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/SkCanvasMatrix.h"
19#include "src/core/SkDraw.h"
20#include "src/core/SkGlyphRun.h"
21#include "src/core/SkImageFilterCache.h"
22#include "src/core/SkImagePriv.h"
23#include "src/core/SkLatticeIter.h"
24#include "src/core/SkMatrixPriv.h"
25#include "src/core/SkPathPriv.h"
26#include "src/core/SkRasterClip.h"
27#include "src/core/SkSpecialImage.h"
28#include "src/core/SkTLazy.h"
29#include "src/core/SkTextBlobPriv.h"
30#include "src/core/SkUtils.h"
31#include "src/image/SkImage_Base.h"
32#include "src/shaders/SkLocalMatrixShader.h"
33#include "src/utils/SkPatchUtils.h"
34
35SkBaseDevice::SkBaseDevice(const SkImageInfo& info, const SkSurfaceProps& surfaceProps)
36 : fInfo(info)
37 , fSurfaceProps(surfaceProps) {
38 fDeviceToGlobal.reset();
39 fGlobalToDevice.reset();
40 fLocalToDevice.reset();
41}
42
43void SkBaseDevice::setDeviceCoordinateSystem(const SkMatrix& deviceToGlobal,
44 const SkMatrix& localToDevice,
45 int bufferOriginX,
46 int bufferOriginY) {
47 fDeviceToGlobal = deviceToGlobal;
48 fDeviceToGlobal.normalizePerspective();
49 SkAssertResult(deviceToGlobal.invert(&fGlobalToDevice));
50
51 fLocalToDevice = localToDevice;
52 fLocalToDevice.normalizePerspective();
53 if (bufferOriginX | bufferOriginY) {
54 fDeviceToGlobal.preTranslate(bufferOriginX, bufferOriginY);
55 fGlobalToDevice.postTranslate(-bufferOriginX, -bufferOriginY);
56 fLocalToDevice.postTranslate(-bufferOriginX, -bufferOriginY);
57 }
58}
59
60void SkBaseDevice::setGlobalCTM(const SkCanvasMatrix& ctm) {
61 fLocalToDevice = ctm;
62 fLocalToDevice.normalizePerspective();
63 if (!fGlobalToDevice.isIdentity()) {
64 // Map from the global CTM state to this device's coordinate system.
65 fLocalToDevice.postConcat(fGlobalToDevice);
66 }
67}
68
69bool SkBaseDevice::isPixelAlignedToGlobal() const {
70 return fDeviceToGlobal.isTranslate() &&
71 SkScalarIsInt(fDeviceToGlobal.getTranslateX()) &&
72 SkScalarIsInt(fDeviceToGlobal.getTranslateY());
73}
74
75SkIPoint SkBaseDevice::getOrigin() const {
76 // getOrigin() is deprecated, the old origin has been moved into the fDeviceToGlobal matrix.
77 // This extracts the origin from the matrix, but asserts that a more complicated coordinate
78 // space hasn't been set of the device. This function can be removed once existing use cases
79 // have been updated to use the device-to-global matrix instead or have themselves been removed
80 // (e.g. Android's device-space clip regions are going away, and are not compatible with the
81 // generalized device coordinate system).
82 SkASSERT(this->isPixelAlignedToGlobal());
83 return SkIPoint::Make(SkScalarFloorToInt(fDeviceToGlobal.getTranslateX()),
84 SkScalarFloorToInt(fDeviceToGlobal.getTranslateY()));
85}
86
87SkMatrix SkBaseDevice::getRelativeTransform(const SkBaseDevice& inputDevice) const {
88 // To get the transform from the input's space to this space, transform from the input space to
89 // the global space, and then from the global space back to this space.
90 return SkMatrix::Concat(fGlobalToDevice, inputDevice.fDeviceToGlobal);
91}
92
93SkM44 SkBaseDevice::localToWorld() const {
94 // fInvCamera == GlobalToWorld
95 return fInvCamera * SkMatrix::Concat(fDeviceToGlobal, fLocalToDevice);
96}
97
98SkPixelGeometry SkBaseDevice::CreateInfo::AdjustGeometry(TileUsage tileUsage, SkPixelGeometry geo) {
99 switch (tileUsage) {
100 case kPossible_TileUsage:
101 // (we think) for compatibility with old clients, we assume this layer can support LCD
102 // even though they may not have marked it as opaque... seems like we should update
103 // our callers (reed/robertphilips).
104 break;
105 case kNever_TileUsage:
106 geo = kUnknown_SkPixelGeometry;
107 break;
108 }
109 return geo;
110}
111
112static inline bool is_int(float x) {
113 return x == (float) sk_float_round2int(x);
114}
115
116void SkBaseDevice::drawRegion(const SkRegion& region, const SkPaint& paint) {
117 const SkMatrix& localToDevice = this->localToDevice();
118 bool isNonTranslate = localToDevice.getType() & ~(SkMatrix::kTranslate_Mask);
119 bool complexPaint = paint.getStyle() != SkPaint::kFill_Style || paint.getMaskFilter() ||
120 paint.getPathEffect();
121 bool antiAlias = paint.isAntiAlias() && (!is_int(localToDevice.getTranslateX()) ||
122 !is_int(localToDevice.getTranslateY()));
123 if (isNonTranslate || complexPaint || antiAlias) {
124 SkPath path;
125 region.getBoundaryPath(&path);
126 path.setIsVolatile(true);
127 return this->drawPath(path, paint, true);
128 }
129
130 SkRegion::Iterator it(region);
131 while (!it.done()) {
132 this->drawRect(SkRect::Make(it.rect()), paint);
133 it.next();
134 }
135}
136
137void SkBaseDevice::drawArc(const SkRect& oval, SkScalar startAngle,
138 SkScalar sweepAngle, bool useCenter, const SkPaint& paint) {
139 SkPath path;
140 bool isFillNoPathEffect = SkPaint::kFill_Style == paint.getStyle() && !paint.getPathEffect();
141 SkPathPriv::CreateDrawArcPath(&path, oval, startAngle, sweepAngle, useCenter,
142 isFillNoPathEffect);
143 this->drawPath(path, paint);
144}
145
146void SkBaseDevice::drawDRRect(const SkRRect& outer,
147 const SkRRect& inner, const SkPaint& paint) {
148 SkPath path;
149 path.addRRect(outer);
150 path.addRRect(inner);
151 path.setFillType(SkPathFillType::kEvenOdd);
152 path.setIsVolatile(true);
153
154 this->drawPath(path, paint, true);
155}
156
157void SkBaseDevice::drawPatch(const SkPoint cubics[12], const SkColor colors[4],
158 const SkPoint texCoords[4], SkBlendMode bmode, const SkPaint& paint) {
159 SkISize lod = SkPatchUtils::GetLevelOfDetail(cubics, &this->localToDevice());
160 auto vertices = SkPatchUtils::MakeVertices(cubics, colors, texCoords, lod.width(), lod.height(),
161 this->imageInfo().colorSpace());
162 if (vertices) {
163 this->drawVertices(vertices.get(), bmode, paint);
164 }
165}
166
167void SkBaseDevice::drawImageNine(const SkImage* image, const SkIRect& center,
168 const SkRect& dst, const SkPaint& paint) {
169 SkLatticeIter iter(image->width(), image->height(), center, dst);
170
171 SkRect srcR, dstR;
172 while (iter.next(&srcR, &dstR)) {
173 this->drawImageRect(image, &srcR, dstR, paint, SkCanvas::kStrict_SrcRectConstraint);
174 }
175}
176
177void SkBaseDevice::drawImageLattice(const SkImage* image,
178 const SkCanvas::Lattice& lattice, const SkRect& dst,
179 const SkPaint& paint) {
180 SkLatticeIter iter(lattice, dst);
181
182 SkRect srcR, dstR;
183 SkColor c;
184 bool isFixedColor = false;
185 const SkImageInfo info = SkImageInfo::Make(1, 1, kBGRA_8888_SkColorType, kUnpremul_SkAlphaType);
186
187 while (iter.next(&srcR, &dstR, &isFixedColor, &c)) {
188 if (isFixedColor || (srcR.width() <= 1.0f && srcR.height() <= 1.0f &&
189 image->readPixels(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
204static 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
216void 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
249void 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
266void 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 SkMatrix baseLocalToDevice = this->localToDevice();
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(SkMatrix::Concat(
288 baseLocalToDevice, 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
314void SkBaseDevice::drawDrawable(SkDrawable* drawable, const SkMatrix* matrix, SkCanvas* canvas) {
315 drawable->draw(canvas, matrix);
316}
317
318///////////////////////////////////////////////////////////////////////////////////////////////////
319
320void SkBaseDevice::drawSpecial(SkSpecialImage*, int x, int y, const SkPaint&,
321 SkImage*, const SkMatrix&) {}
322sk_sp<SkSpecialImage> SkBaseDevice::makeSpecial(const SkBitmap&) { return nullptr; }
323sk_sp<SkSpecialImage> SkBaseDevice::makeSpecial(const SkImage*) { return nullptr; }
324sk_sp<SkSpecialImage> SkBaseDevice::snapSpecial(const SkIRect&, bool) { return nullptr; }
325sk_sp<SkSpecialImage> SkBaseDevice::snapSpecial() {
326 return this->snapSpecial(SkIRect::MakeWH(this->width(), this->height()));
327}
328
329///////////////////////////////////////////////////////////////////////////////////////////////////
330
331bool SkBaseDevice::readPixels(const SkPixmap& pm, int x, int y) {
332 return this->onReadPixels(pm, x, y);
333}
334
335bool SkBaseDevice::writePixels(const SkPixmap& pm, int x, int y) {
336 return this->onWritePixels(pm, x, y);
337}
338
339bool SkBaseDevice::onWritePixels(const SkPixmap&, int, int) {
340 return false;
341}
342
343bool SkBaseDevice::onReadPixels(const SkPixmap&, int x, int y) {
344 return false;
345}
346
347bool SkBaseDevice::accessPixels(SkPixmap* pmap) {
348 SkPixmap tempStorage;
349 if (nullptr == pmap) {
350 pmap = &tempStorage;
351 }
352 return this->onAccessPixels(pmap);
353}
354
355bool SkBaseDevice::peekPixels(SkPixmap* pmap) {
356 SkPixmap tempStorage;
357 if (nullptr == pmap) {
358 pmap = &tempStorage;
359 }
360 return this->onPeekPixels(pmap);
361}
362
363//////////////////////////////////////////////////////////////////////////////////////////
364
365#include "src/core/SkUtils.h"
366
367void SkBaseDevice::drawGlyphRunRSXform(const SkFont& font, const SkGlyphID glyphs[],
368 const SkRSXform xform[], int count, SkPoint origin,
369 const SkPaint& paint) {
370 const SkMatrix originalLocalToDevice = this->localToDevice();
371 if (!originalLocalToDevice.isFinite() || !SkScalarIsFinite(font.getSize()) ||
372 !SkScalarIsFinite(font.getScaleX()) ||
373 !SkScalarIsFinite(font.getSkewX())) {
374 return;
375 }
376
377 SkPoint sharedPos{0, 0}; // we're at the origin
378 SkGlyphID glyphID;
379 SkGlyphRun glyphRun{
380 font,
381 SkSpan<const SkPoint>{&sharedPos, 1},
382 SkSpan<const SkGlyphID>{&glyphID, 1},
383 SkSpan<const char>{},
384 SkSpan<const uint32_t>{}
385 };
386
387 for (int i = 0; i < count; i++) {
388 glyphID = glyphs[i];
389 // now "glyphRun" is pointing at the current glyphID
390
391 SkMatrix glyphToDevice;
392 glyphToDevice.setRSXform(xform[i]).postTranslate(origin.fX, origin.fY);
393
394 // We want to rotate each glyph by the rsxform, but we don't want to rotate "space"
395 // (i.e. the shader that cares about the ctm) so we have to undo our little ctm trick
396 // with a localmatrixshader so that the shader draws as if there was no change to the ctm.
397 SkPaint transformingPaint{paint};
398 auto shader = transformingPaint.getShader();
399 if (shader) {
400 SkMatrix inverse;
401 if (glyphToDevice.invert(&inverse)) {
402 transformingPaint.setShader(shader->makeWithLocalMatrix(inverse));
403 } else {
404 transformingPaint.setShader(nullptr); // can't handle this xform
405 }
406 }
407
408 glyphToDevice.postConcat(originalLocalToDevice);
409 this->setLocalToDevice(glyphToDevice);
410
411 this->drawGlyphRunList(SkGlyphRunList{glyphRun, transformingPaint});
412 }
413 this->setLocalToDevice(originalLocalToDevice);
414}
415
416//////////////////////////////////////////////////////////////////////////////////////////
417
418sk_sp<SkSurface> SkBaseDevice::makeSurface(SkImageInfo const&, SkSurfaceProps const&) {
419 return nullptr;
420}
421
422//////////////////////////////////////////////////////////////////////////////////////////
423
424void SkBaseDevice::LogDrawScaleFactor(const SkMatrix& view, const SkMatrix& srcToDst,
425 SkFilterQuality filterQuality) {
426#if SK_HISTOGRAMS_ENABLED
427 SkMatrix matrix = SkMatrix::Concat(view, srcToDst);
428 enum ScaleFactor {
429 kUpscale_ScaleFactor,
430 kNoScale_ScaleFactor,
431 kDownscale_ScaleFactor,
432 kLargeDownscale_ScaleFactor,
433
434 kLast_ScaleFactor = kLargeDownscale_ScaleFactor
435 };
436
437 float rawScaleFactor = matrix.getMinScale();
438
439 ScaleFactor scaleFactor;
440 if (rawScaleFactor < 0.5f) {
441 scaleFactor = kLargeDownscale_ScaleFactor;
442 } else if (rawScaleFactor < 1.0f) {
443 scaleFactor = kDownscale_ScaleFactor;
444 } else if (rawScaleFactor > 1.0f) {
445 scaleFactor = kUpscale_ScaleFactor;
446 } else {
447 scaleFactor = kNoScale_ScaleFactor;
448 }
449
450 switch (filterQuality) {
451 case kNone_SkFilterQuality:
452 SK_HISTOGRAM_ENUMERATION("DrawScaleFactor.NoneFilterQuality", scaleFactor,
453 kLast_ScaleFactor + 1);
454 break;
455 case kLow_SkFilterQuality:
456 SK_HISTOGRAM_ENUMERATION("DrawScaleFactor.LowFilterQuality", scaleFactor,
457 kLast_ScaleFactor + 1);
458 break;
459 case kMedium_SkFilterQuality:
460 SK_HISTOGRAM_ENUMERATION("DrawScaleFactor.MediumFilterQuality", scaleFactor,
461 kLast_ScaleFactor + 1);
462 break;
463 case kHigh_SkFilterQuality:
464 SK_HISTOGRAM_ENUMERATION("DrawScaleFactor.HighFilterQuality", scaleFactor,
465 kLast_ScaleFactor + 1);
466 break;
467 }
468
469 // Also log filter quality independent scale factor.
470 SK_HISTOGRAM_ENUMERATION("DrawScaleFactor.AnyFilterQuality", scaleFactor,
471 kLast_ScaleFactor + 1);
472
473 // Also log an overall histogram of filter quality.
474 SK_HISTOGRAM_ENUMERATION("FilterQuality", filterQuality, kLast_SkFilterQuality + 1);
475#endif
476}
477