1 /*
2 * Copyright 2011 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "src/core/SkDevice.h"
9
10 #include "include/core/SkColorFilter.h"
11 #include "include/core/SkDrawable.h"
12 #include "include/core/SkImageFilter.h"
13 #include "include/core/SkPathMeasure.h"
14 #include "include/core/SkRSXform.h"
15 #include "include/core/SkShader.h"
16 #include "include/core/SkVertices.h"
17 #include "include/private/SkTo.h"
18 #include "src/core/SkDraw.h"
19 #include "src/core/SkGlyphRun.h"
20 #include "src/core/SkImageFilterCache.h"
21 #include "src/core/SkImageFilter_Base.h"
22 #include "src/core/SkImagePriv.h"
23 #include "src/core/SkLatticeIter.h"
24 #include "src/core/SkMarkerStack.h"
25 #include "src/core/SkMatrixPriv.h"
26 #include "src/core/SkPathPriv.h"
27 #include "src/core/SkRasterClip.h"
28 #include "src/core/SkSpecialImage.h"
29 #include "src/core/SkTLazy.h"
30 #include "src/core/SkTextBlobPriv.h"
31 #include "src/core/SkUtils.h"
32 #include "src/image/SkImage_Base.h"
33 #include "src/shaders/SkLocalMatrixShader.h"
34 #include "src/utils/SkPatchUtils.h"
35
SkBaseDevice(const SkImageInfo & info,const SkSurfaceProps & surfaceProps)36 SkBaseDevice::SkBaseDevice(const SkImageInfo& info, const SkSurfaceProps& surfaceProps)
37 : SkMatrixProvider(/* localToDevice = */ SkMatrix::I())
38 , fInfo(info)
39 , fSurfaceProps(surfaceProps) {
40 fDeviceToGlobal.reset();
41 fGlobalToDevice.reset();
42 }
43
setDeviceCoordinateSystem(const SkMatrix & deviceToGlobal,const SkM44 & localToDevice,int bufferOriginX,int bufferOriginY)44 void SkBaseDevice::setDeviceCoordinateSystem(const SkMatrix& deviceToGlobal,
45 const SkM44& localToDevice,
46 int bufferOriginX,
47 int bufferOriginY) {
48 fDeviceToGlobal = deviceToGlobal;
49 fDeviceToGlobal.normalizePerspective();
50 SkAssertResult(deviceToGlobal.invert(&fGlobalToDevice));
51
52 fLocalToDevice = localToDevice;
53 fLocalToDevice.normalizePerspective();
54 if (bufferOriginX | bufferOriginY) {
55 fDeviceToGlobal.preTranslate(bufferOriginX, bufferOriginY);
56 fGlobalToDevice.postTranslate(-bufferOriginX, -bufferOriginY);
57 fLocalToDevice.postTranslate(-bufferOriginX, -bufferOriginY);
58 }
59 fLocalToDevice33 = fLocalToDevice.asM33();
60 }
61
setGlobalCTM(const SkM44 & ctm)62 void SkBaseDevice::setGlobalCTM(const SkM44& ctm) {
63 fLocalToDevice = ctm;
64 fLocalToDevice.normalizePerspective();
65 if (!fGlobalToDevice.isIdentity()) {
66 // Map from the global CTM state to this device's coordinate system.
67 fLocalToDevice.postConcat(SkM44(fGlobalToDevice));
68 }
69 fLocalToDevice33 = fLocalToDevice.asM33();
70 }
71
isPixelAlignedToGlobal() const72 bool SkBaseDevice::isPixelAlignedToGlobal() const {
73 return fDeviceToGlobal.isTranslate() &&
74 SkScalarIsInt(fDeviceToGlobal.getTranslateX()) &&
75 SkScalarIsInt(fDeviceToGlobal.getTranslateY());
76 }
77
getOrigin() const78 SkIPoint SkBaseDevice::getOrigin() const {
79 // getOrigin() is deprecated, the old origin has been moved into the fDeviceToGlobal matrix.
80 // This extracts the origin from the matrix, but asserts that a more complicated coordinate
81 // space hasn't been set of the device. This function can be removed once existing use cases
82 // have been updated to use the device-to-global matrix instead or have themselves been removed
83 // (e.g. Android's device-space clip regions are going away, and are not compatible with the
84 // generalized device coordinate system).
85 SkASSERT(this->isPixelAlignedToGlobal());
86 return SkIPoint::Make(SkScalarFloorToInt(fDeviceToGlobal.getTranslateX()),
87 SkScalarFloorToInt(fDeviceToGlobal.getTranslateY()));
88 }
89
getRelativeTransform(const SkBaseDevice & dstDevice) const90 SkMatrix SkBaseDevice::getRelativeTransform(const SkBaseDevice& dstDevice) const {
91 // To get the transform from this space to the other device's, transform from our space to
92 // global and then from global to the other device.
93 return SkMatrix::Concat(dstDevice.fGlobalToDevice, fDeviceToGlobal);
94 }
95
getLocalToMarker(uint32_t id,SkM44 * localToMarker) const96 bool SkBaseDevice::getLocalToMarker(uint32_t id, SkM44* localToMarker) const {
97 // The marker stack stores CTM snapshots, which are "marker to global" matrices.
98 // We ask for the (cached) inverse, which is a "global to marker" matrix.
99 SkM44 globalToMarker;
100 // ID 0 is special, and refers to the CTM (local-to-global)
101 if (fMarkerStack && (id == 0 || fMarkerStack->findMarkerInverse(id, &globalToMarker))) {
102 if (localToMarker) {
103 // globalToMarker will still be the identity if id is zero
104 *localToMarker = globalToMarker * SkM44(fDeviceToGlobal) * fLocalToDevice;
105 }
106 return true;
107 }
108 return false;
109 }
110
is_int(float x)111 static inline bool is_int(float x) {
112 return x == (float) sk_float_round2int(x);
113 }
114
drawRegion(const SkRegion & region,const SkPaint & paint)115 void SkBaseDevice::drawRegion(const SkRegion& region, const SkPaint& paint) {
116 const SkMatrix& localToDevice = this->localToDevice();
117 bool isNonTranslate = localToDevice.getType() & ~(SkMatrix::kTranslate_Mask);
118 bool complexPaint = paint.getStyle() != SkPaint::kFill_Style || paint.getMaskFilter() ||
119 paint.getPathEffect();
120 bool antiAlias = paint.isAntiAlias() && (!is_int(localToDevice.getTranslateX()) ||
121 !is_int(localToDevice.getTranslateY()));
122 if (isNonTranslate || complexPaint || antiAlias) {
123 SkPath path;
124 region.getBoundaryPath(&path);
125 path.setIsVolatile(true);
126 return this->drawPath(path, paint, true);
127 }
128
129 SkRegion::Iterator it(region);
130 while (!it.done()) {
131 this->drawRect(SkRect::Make(it.rect()), paint);
132 it.next();
133 }
134 }
135
drawArc(const SkRect & oval,SkScalar startAngle,SkScalar sweepAngle,bool useCenter,const SkPaint & paint)136 void SkBaseDevice::drawArc(const SkRect& oval, SkScalar startAngle,
137 SkScalar sweepAngle, bool useCenter, const SkPaint& paint) {
138 SkPath path;
139 bool isFillNoPathEffect = SkPaint::kFill_Style == paint.getStyle() && !paint.getPathEffect();
140 SkPathPriv::CreateDrawArcPath(&path, oval, startAngle, sweepAngle, useCenter,
141 isFillNoPathEffect);
142 this->drawPath(path, paint);
143 }
144
drawDRRect(const SkRRect & outer,const SkRRect & inner,const SkPaint & paint)145 void SkBaseDevice::drawDRRect(const SkRRect& outer,
146 const SkRRect& inner, const SkPaint& paint) {
147 SkPath path;
148 path.addRRect(outer);
149 path.addRRect(inner);
150 path.setFillType(SkPathFillType::kEvenOdd);
151 path.setIsVolatile(true);
152
153 this->drawPath(path, paint, true);
154 }
155
drawPatch(const SkPoint cubics[12],const SkColor colors[4],const SkPoint texCoords[4],SkBlendMode bmode,const SkPaint & paint)156 void SkBaseDevice::drawPatch(const SkPoint cubics[12], const SkColor colors[4],
157 const SkPoint texCoords[4], SkBlendMode bmode, const SkPaint& paint) {
158 SkISize lod = SkPatchUtils::GetLevelOfDetail(cubics, &this->localToDevice());
159 auto vertices = SkPatchUtils::MakeVertices(cubics, colors, texCoords, lod.width(), lod.height(),
160 this->imageInfo().colorSpace());
161 if (vertices) {
162 this->drawVertices(vertices.get(), bmode, paint);
163 }
164 }
165
drawImageNine(const SkImage * image,const SkIRect & center,const SkRect & dst,const SkPaint & paint)166 void SkBaseDevice::drawImageNine(const SkImage* image, const SkIRect& center,
167 const SkRect& dst, const SkPaint& paint) {
168 SkLatticeIter iter(image->width(), image->height(), center, dst);
169
170 SkRect srcR, dstR;
171 while (iter.next(&srcR, &dstR)) {
172 this->drawImageRect(image, &srcR, dstR, paint, SkCanvas::kStrict_SrcRectConstraint);
173 }
174 }
175
drawImageLattice(const SkImage * image,const SkCanvas::Lattice & lattice,const SkRect & dst,const SkPaint & paint)176 void SkBaseDevice::drawImageLattice(const SkImage* image,
177 const SkCanvas::Lattice& lattice, const SkRect& dst,
178 const SkPaint& paint) {
179 SkLatticeIter iter(lattice, dst);
180
181 SkRect srcR, dstR;
182 SkColor c;
183 bool isFixedColor = false;
184 const SkImageInfo info = SkImageInfo::Make(1, 1, kBGRA_8888_SkColorType, kUnpremul_SkAlphaType);
185
186 while (iter.next(&srcR, &dstR, &isFixedColor, &c)) {
187 // TODO: support this fast-path for GPU images
188 if (isFixedColor || (srcR.width() <= 1.0f && srcR.height() <= 1.0f &&
189 image->readPixels(nullptr, info, &c, 4, srcR.fLeft, srcR.fTop))) {
190 // Fast draw with drawRect, if this is a patch containing a single color
191 // or if this is a patch containing a single pixel.
192 if (0 != c || !paint.isSrcOver()) {
193 SkPaint paintCopy(paint);
194 int alpha = SkAlphaMul(SkColorGetA(c), SkAlpha255To256(paint.getAlpha()));
195 paintCopy.setColor(SkColorSetA(c, alpha));
196 this->drawRect(dstR, paintCopy);
197 }
198 } else {
199 this->drawImageRect(image, &srcR, dstR, paint, SkCanvas::kStrict_SrcRectConstraint);
200 }
201 }
202 }
203
quad_to_tris(SkPoint tris[6],const SkPoint quad[4])204 static SkPoint* quad_to_tris(SkPoint tris[6], const SkPoint quad[4]) {
205 tris[0] = quad[0];
206 tris[1] = quad[1];
207 tris[2] = quad[2];
208
209 tris[3] = quad[0];
210 tris[4] = quad[2];
211 tris[5] = quad[3];
212
213 return tris + 6;
214 }
215
drawAtlas(const SkImage * atlas,const SkRSXform xform[],const SkRect tex[],const SkColor colors[],int quadCount,SkBlendMode mode,const SkPaint & paint)216 void SkBaseDevice::drawAtlas(const SkImage* atlas, const SkRSXform xform[],
217 const SkRect tex[], const SkColor colors[], int quadCount,
218 SkBlendMode mode, const SkPaint& paint) {
219 const int triCount = quadCount << 1;
220 const int vertexCount = triCount * 3;
221 uint32_t flags = SkVertices::kHasTexCoords_BuilderFlag;
222 if (colors) {
223 flags |= SkVertices::kHasColors_BuilderFlag;
224 }
225 SkVertices::Builder builder(SkVertices::kTriangles_VertexMode, vertexCount, 0, flags);
226
227 SkPoint* vPos = builder.positions();
228 SkPoint* vTex = builder.texCoords();
229 SkColor* vCol = builder.colors();
230 for (int i = 0; i < quadCount; ++i) {
231 SkPoint tmp[4];
232 xform[i].toQuad(tex[i].width(), tex[i].height(), tmp);
233 vPos = quad_to_tris(vPos, tmp);
234
235 tex[i].toQuad(tmp);
236 vTex = quad_to_tris(vTex, tmp);
237
238 if (colors) {
239 sk_memset32(vCol, colors[i], 6);
240 vCol += 6;
241 }
242 }
243 SkPaint p(paint);
244 p.setShader(atlas->makeShader());
245 this->drawVertices(builder.detach().get(), mode, p);
246 }
247
248
drawEdgeAAQuad(const SkRect & r,const SkPoint clip[4],SkCanvas::QuadAAFlags aa,const SkColor4f & color,SkBlendMode mode)249 void SkBaseDevice::drawEdgeAAQuad(const SkRect& r, const SkPoint clip[4], SkCanvas::QuadAAFlags aa,
250 const SkColor4f& color, SkBlendMode mode) {
251 SkPaint paint;
252 paint.setColor4f(color);
253 paint.setBlendMode(mode);
254 paint.setAntiAlias(aa == SkCanvas::kAll_QuadAAFlags);
255
256 if (clip) {
257 // Draw the clip directly as a quad since it's a filled color with no local coords
258 SkPath clipPath;
259 clipPath.addPoly(clip, 4, true);
260 this->drawPath(clipPath, paint);
261 } else {
262 this->drawRect(r, paint);
263 }
264 }
265
drawEdgeAAImageSet(const SkCanvas::ImageSetEntry images[],int count,const SkPoint dstClips[],const SkMatrix preViewMatrices[],const SkPaint & paint,SkCanvas::SrcRectConstraint constraint)266 void SkBaseDevice::drawEdgeAAImageSet(const SkCanvas::ImageSetEntry images[], int count,
267 const SkPoint dstClips[], const SkMatrix preViewMatrices[],
268 const SkPaint& paint,
269 SkCanvas::SrcRectConstraint constraint) {
270 SkASSERT(paint.getStyle() == SkPaint::kFill_Style);
271 SkASSERT(!paint.getPathEffect());
272
273 SkPaint entryPaint = paint;
274 const SkM44 baseLocalToDevice = this->localToDevice44();
275 int clipIndex = 0;
276 for (int i = 0; i < count; ++i) {
277 // TODO: Handle per-edge AA. Right now this mirrors the SkiaRenderer component of Chrome
278 // which turns off antialiasing unless all four edges should be antialiased. This avoids
279 // seaming in tiled composited layers.
280 entryPaint.setAntiAlias(images[i].fAAFlags == SkCanvas::kAll_QuadAAFlags);
281 entryPaint.setAlphaf(paint.getAlphaf() * images[i].fAlpha);
282
283 bool needsRestore = false;
284 SkASSERT(images[i].fMatrixIndex < 0 || preViewMatrices);
285 if (images[i].fMatrixIndex >= 0) {
286 this->save();
287 this->setLocalToDevice(baseLocalToDevice *
288 SkM44(preViewMatrices[images[i].fMatrixIndex]));
289 needsRestore = true;
290 }
291
292 SkASSERT(!images[i].fHasClip || dstClips);
293 if (images[i].fHasClip) {
294 // Since drawImageRect requires a srcRect, the dst clip is implemented as a true clip
295 if (!needsRestore) {
296 this->save();
297 needsRestore = true;
298 }
299 SkPath clipPath;
300 clipPath.addPoly(dstClips + clipIndex, 4, true);
301 this->clipPath(clipPath, SkClipOp::kIntersect, entryPaint.isAntiAlias());
302 clipIndex += 4;
303 }
304 this->drawImageRect(images[i].fImage.get(), &images[i].fSrcRect, images[i].fDstRect,
305 entryPaint, constraint);
306 if (needsRestore) {
307 this->restoreLocal(baseLocalToDevice);
308 }
309 }
310 }
311
312 ///////////////////////////////////////////////////////////////////////////////////////////////////
313
drawDrawable(SkDrawable * drawable,const SkMatrix * matrix,SkCanvas * canvas)314 void SkBaseDevice::drawDrawable(SkDrawable* drawable, const SkMatrix* matrix, SkCanvas* canvas) {
315 drawable->draw(canvas, matrix);
316 }
317
318 ///////////////////////////////////////////////////////////////////////////////////////////////////
319
drawSpecial(SkSpecialImage *,const SkMatrix &,const SkPaint &)320 void SkBaseDevice::drawSpecial(SkSpecialImage*, const SkMatrix&, const SkPaint&) {}
makeSpecial(const SkBitmap &)321 sk_sp<SkSpecialImage> SkBaseDevice::makeSpecial(const SkBitmap&) { return nullptr; }
makeSpecial(const SkImage *)322 sk_sp<SkSpecialImage> SkBaseDevice::makeSpecial(const SkImage*) { return nullptr; }
snapSpecial(const SkIRect &,bool)323 sk_sp<SkSpecialImage> SkBaseDevice::snapSpecial(const SkIRect&, bool) { return nullptr; }
snapSpecial()324 sk_sp<SkSpecialImage> SkBaseDevice::snapSpecial() {
325 return this->snapSpecial(SkIRect::MakeWH(this->width(), this->height()));
326 }
327
drawDevice(SkBaseDevice * device,const SkPaint & paint)328 void SkBaseDevice::drawDevice(SkBaseDevice* device, const SkPaint& paint) {
329 sk_sp<SkSpecialImage> deviceImage = device->snapSpecial();
330 if (deviceImage) {
331 this->drawSpecial(deviceImage.get(), device->getRelativeTransform(*this), paint);
332 }
333 }
334
drawFilteredImage(const skif::Mapping & mapping,SkSpecialImage * src,const SkImageFilter * filter,const SkPaint & paint)335 void SkBaseDevice::drawFilteredImage(const skif::Mapping& mapping, SkSpecialImage* src,
336 const SkImageFilter* filter, const SkPaint& paint) {
337 SkASSERT(!paint.getImageFilter() && !paint.getMaskFilter());
338 using For = skif::Usage;
339
340 skif::LayerSpace<SkIRect> targetOutput = mapping.deviceToLayer(
341 skif::DeviceSpace<SkIRect>(this->devClipBounds()));
342
343 // FIXME If the saved layer (so src) was created to use F16, should we do all image filtering
344 // in F16 and then only flatten to the destination color encoding at the end?
345 // Currently, this context converts everything to the dst color type ASAP.
346 SkColorType colorType = this->imageInfo().colorType();
347 if (colorType == kUnknown_SkColorType) {
348 colorType = kRGBA_8888_SkColorType;
349 }
350
351 // getImageFilterCache returns a bare image filter cache pointer that must be ref'ed until the
352 // filter's filterImage(ctx) function returns.
353 sk_sp<SkImageFilterCache> cache(this->getImageFilterCache());
354 skif::Context ctx(mapping, targetOutput, cache.get(), colorType, this->imageInfo().colorSpace(),
355 skif::FilterResult<For::kInput>(sk_ref_sp(src)));
356
357 SkIPoint offset;
358 sk_sp<SkSpecialImage> result = as_IFB(filter)->filterImage(ctx).imageAndOffset(&offset);
359 if (result) {
360 SkMatrix deviceMatrixWithOffset = mapping.deviceMatrix();
361 deviceMatrixWithOffset.preTranslate(offset.fX, offset.fY);
362 this->drawSpecial(result.get(), deviceMatrixWithOffset, paint);
363 }
364 }
365
366 ///////////////////////////////////////////////////////////////////////////////////////////////////
367
readPixels(const SkPixmap & pm,int x,int y)368 bool SkBaseDevice::readPixels(const SkPixmap& pm, int x, int y) {
369 return this->onReadPixels(pm, x, y);
370 }
371
writePixels(const SkPixmap & pm,int x,int y)372 bool SkBaseDevice::writePixels(const SkPixmap& pm, int x, int y) {
373 return this->onWritePixels(pm, x, y);
374 }
375
onWritePixels(const SkPixmap &,int,int)376 bool SkBaseDevice::onWritePixels(const SkPixmap&, int, int) {
377 return false;
378 }
379
onReadPixels(const SkPixmap &,int x,int y)380 bool SkBaseDevice::onReadPixels(const SkPixmap&, int x, int y) {
381 return false;
382 }
383
accessPixels(SkPixmap * pmap)384 bool SkBaseDevice::accessPixels(SkPixmap* pmap) {
385 SkPixmap tempStorage;
386 if (nullptr == pmap) {
387 pmap = &tempStorage;
388 }
389 return this->onAccessPixels(pmap);
390 }
391
peekPixels(SkPixmap * pmap)392 bool SkBaseDevice::peekPixels(SkPixmap* pmap) {
393 SkPixmap tempStorage;
394 if (nullptr == pmap) {
395 pmap = &tempStorage;
396 }
397 return this->onPeekPixels(pmap);
398 }
399
400 //////////////////////////////////////////////////////////////////////////////////////////
401
402 #include "src/core/SkUtils.h"
403
drawGlyphRunRSXform(const SkFont & font,const SkGlyphID glyphs[],const SkRSXform xform[],int count,SkPoint origin,const SkPaint & paint)404 void SkBaseDevice::drawGlyphRunRSXform(const SkFont& font, const SkGlyphID glyphs[],
405 const SkRSXform xform[], int count, SkPoint origin,
406 const SkPaint& paint) {
407 const SkM44 originalLocalToDevice = this->localToDevice44();
408 if (!originalLocalToDevice.isFinite() || !SkScalarIsFinite(font.getSize()) ||
409 !SkScalarIsFinite(font.getScaleX()) ||
410 !SkScalarIsFinite(font.getSkewX())) {
411 return;
412 }
413
414 SkPoint sharedPos{0, 0}; // we're at the origin
415 SkGlyphID glyphID;
416 SkGlyphRun glyphRun{
417 font,
418 SkSpan<const SkPoint>{&sharedPos, 1},
419 SkSpan<const SkGlyphID>{&glyphID, 1},
420 SkSpan<const char>{},
421 SkSpan<const uint32_t>{}
422 };
423
424 for (int i = 0; i < count; i++) {
425 glyphID = glyphs[i];
426 // now "glyphRun" is pointing at the current glyphID
427
428 SkMatrix glyphToDevice;
429 glyphToDevice.setRSXform(xform[i]).postTranslate(origin.fX, origin.fY);
430
431 // We want to rotate each glyph by the rsxform, but we don't want to rotate "space"
432 // (i.e. the shader that cares about the ctm) so we have to undo our little ctm trick
433 // with a localmatrixshader so that the shader draws as if there was no change to the ctm.
434 SkPaint transformingPaint{paint};
435 auto shader = transformingPaint.getShader();
436 if (shader) {
437 SkMatrix inverse;
438 if (glyphToDevice.invert(&inverse)) {
439 transformingPaint.setShader(shader->makeWithLocalMatrix(inverse));
440 } else {
441 transformingPaint.setShader(nullptr); // can't handle this xform
442 }
443 }
444
445 this->setLocalToDevice(originalLocalToDevice * SkM44(glyphToDevice));
446
447 this->drawGlyphRunList(SkGlyphRunList{glyphRun, transformingPaint});
448 }
449 this->setLocalToDevice(originalLocalToDevice);
450 }
451
452 //////////////////////////////////////////////////////////////////////////////////////////
453
makeSurface(SkImageInfo const &,SkSurfaceProps const &)454 sk_sp<SkSurface> SkBaseDevice::makeSurface(SkImageInfo const&, SkSurfaceProps const&) {
455 return nullptr;
456 }
457
458