Debian Codegraph @

src/utils/SkShadowUtils.cpp

raw
1 /*
2 * Copyright 2017 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 "include/utils/SkShadowUtils.h"
9
10 #include "include/core/SkBlendMode.h"
11 #include "include/core/SkBlender.h"
12 #include "include/core/SkBlurTypes.h"
13 #include "include/core/SkCanvas.h"
14 #include "include/core/SkColorFilter.h"
15 #include "include/core/SkM44.h"
16 #include "include/core/SkMaskFilter.h"
17 #include "include/core/SkMatrix.h"
18 #include "include/core/SkPaint.h"
19 #include "include/core/SkPath.h"
20 #include "include/core/SkPoint.h"
21 #include "include/core/SkPoint3.h"
22 #include "include/core/SkRect.h"
23 #include "include/core/SkRefCnt.h"
24 #include "include/core/SkVertices.h"
25 #include "include/private/SkIDChangeListener.h"
26 #include "include/private/base/SkFloatingPoint.h"
27 #include "include/private/base/SkTPin.h"
28 #include "include/private/base/SkTemplates.h"
29 #include "include/private/base/SkTo.h"
30 #include "src/base/SkRandom.h"
31 #include "src/core/SkBlurMask.h"
32 #include "src/core/SkColorFilterPriv.h"
33 #include "src/core/SkDevice.h"
34 #include "src/core/SkDrawShadowInfo.h"
35 #include "src/core/SkPathPriv.h"
36 #include "src/core/SkResourceCache.h"
37 #include "src/core/SkVerticesPriv.h"
38
39 #if !defined(SK_ENABLE_OPTIMIZE_SIZE)
40 #include "src/utils/SkShadowTessellator.h"
41 #endif
42
43 #if defined(SK_GANESH)
44 #include "src/gpu/ganesh/GrStyle.h"
45 #include "src/gpu/ganesh/geometry/GrStyledShape.h"
46 #endif
47
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 #include <memory>
52 #include <new>
53 #include <utility>
54
55 using namespace skia_private;
56
57 class SkRRect;
58
59 ///////////////////////////////////////////////////////////////////////////////////////////////////
60
61 #if !defined(SK_ENABLE_OPTIMIZE_SIZE)
62 namespace {
63
64 uint64_t resource_cache_shared_id() {
65 return 0x2020776f64616873llu; // 'shadow '
66 }
67
68 /** Factory for an ambient shadow mesh with particular shadow properties. */
69 struct AmbientVerticesFactory {
70 SkScalar fOccluderHeight = SK_ScalarNaN; // NaN so that isCompatible will fail until init'ed.
71 bool fTransparent;
72 SkVector fOffset;
73
74 bool isCompatible(const AmbientVerticesFactory& that, SkVector* translate) const {
75 if (fOccluderHeight != that.fOccluderHeight || fTransparent != that.fTransparent) {
76 return false;
77 }
78 *translate = that.fOffset;
79 return true;
80 }
81
82 sk_sp<SkVertices> makeVertices(const SkPath& path, const SkMatrix& ctm,
83 SkVector* translate) const {
84 SkPoint3 zParams = SkPoint3::Make(0, 0, fOccluderHeight);
85 // pick a canonical place to generate shadow
86 SkMatrix noTrans(ctm);
87 if (!ctm.hasPerspective()) {
88 noTrans[SkMatrix::kMTransX] = 0;
89 noTrans[SkMatrix::kMTransY] = 0;
90 }
91 *translate = fOffset;
92 return SkShadowTessellator::MakeAmbient(path, noTrans, zParams, fTransparent);
93 }
94 };
95
96 /** Factory for an spot shadow mesh with particular shadow properties. */
97 struct SpotVerticesFactory {
98 enum class OccluderType {
99 // The umbra cannot be dropped out because either the occluder is not opaque,
100 // or the center of the umbra is visible. Uses point light.
101 kPointTransparent,
102 // The umbra can be dropped where it is occluded. Uses point light.
103 kPointOpaquePartialUmbra,
104 // It is known that the entire umbra is occluded. Uses point light.
105 kPointOpaqueNoUmbra,
106 // Uses directional light.
107 kDirectional,
108 // The umbra can't be dropped out. Uses directional light.
109 kDirectionalTransparent,
110 };
111
112 SkVector fOffset;
113 SkPoint fLocalCenter;
114 SkScalar fOccluderHeight = SK_ScalarNaN; // NaN so that isCompatible will fail until init'ed.
115 SkPoint3 fDevLightPos;
116 SkScalar fLightRadius;
117 OccluderType fOccluderType;
118
119 bool isCompatible(const SpotVerticesFactory& that, SkVector* translate) const {
120 if (fOccluderHeight != that.fOccluderHeight || fDevLightPos.fZ != that.fDevLightPos.fZ ||
121 fLightRadius != that.fLightRadius || fOccluderType != that.fOccluderType) {
122 return false;
123 }
124 switch (fOccluderType) {
125 case OccluderType::kPointTransparent:
126 case OccluderType::kPointOpaqueNoUmbra:
127 // 'this' and 'that' will either both have no umbra removed or both have all the
128 // umbra removed.
129 *translate = that.fOffset;
130 return true;
131 case OccluderType::kPointOpaquePartialUmbra:
132 // In this case we partially remove the umbra differently for 'this' and 'that'
133 // if the offsets don't match.
134 if (fOffset == that.fOffset) {
135 translate->set(0, 0);
136 return true;
137 }
138 return false;
139 case OccluderType::kDirectional:
140 case OccluderType::kDirectionalTransparent:
141 *translate = that.fOffset - fOffset;
142 return true;
143 }
144 SK_ABORT("Uninitialized occluder type?");
145 }
146
147 sk_sp<SkVertices> makeVertices(const SkPath& path, const SkMatrix& ctm,
148 SkVector* translate) const {
149 bool transparent = fOccluderType == OccluderType::kPointTransparent ||
150 fOccluderType == OccluderType::kDirectionalTransparent;
151 bool directional = fOccluderType == OccluderType::kDirectional ||
152 fOccluderType == OccluderType::kDirectionalTransparent;
153 SkPoint3 zParams = SkPoint3::Make(0, 0, fOccluderHeight);
154 if (directional) {
155 translate->set(0, 0);
156 return SkShadowTessellator::MakeSpot(path, ctm, zParams, fDevLightPos, fLightRadius,
157 transparent, true);
158 } else if (ctm.hasPerspective() || OccluderType::kPointOpaquePartialUmbra == fOccluderType) {
159 translate->set(0, 0);
160 return SkShadowTessellator::MakeSpot(path, ctm, zParams, fDevLightPos, fLightRadius,
161 transparent, false);
162 } else {
163 // pick a canonical place to generate shadow, with light centered over path
164 SkMatrix noTrans(ctm);
165 noTrans[SkMatrix::kMTransX] = 0;
166 noTrans[SkMatrix::kMTransY] = 0;
167 SkPoint devCenter(fLocalCenter);
168 devCenter = noTrans.mapPoint(devCenter);
169 SkPoint3 centerLightPos = SkPoint3::Make(devCenter.fX, devCenter.fY, fDevLightPos.fZ);
170 *translate = fOffset;
171 return SkShadowTessellator::MakeSpot(path, noTrans, zParams,
172 centerLightPos, fLightRadius, transparent, false);
173 }
174 }
175 };
176
177 /**
178 * This manages a set of tessellations for a given shape in the cache. Because SkResourceCache
179 * records are immutable this is not itself a Rec. When we need to update it we return this on
180 * the FindVisitor and let the cache destroy the Rec. We'll update the tessellations and then add
181 * a new Rec with an adjusted size for any deletions/additions.
182 */
183 class CachedTessellations : public SkRefCnt {
184 public:
185 size_t size() const { return fAmbientSet.size() + fSpotSet.size(); }
186
187 sk_sp<SkVertices> find(const AmbientVerticesFactory& ambient, const SkMatrix& matrix,
188 SkVector* translate) const {
189 return fAmbientSet.find(ambient, matrix, translate);
190 }
191
192 sk_sp<SkVertices> add(const SkPath& devPath, const AmbientVerticesFactory& ambient,
193 const SkMatrix& matrix, SkVector* translate) {
194 return fAmbientSet.add(devPath, ambient, matrix, translate);
195 }
196
197 sk_sp<SkVertices> find(const SpotVerticesFactory& spot, const SkMatrix& matrix,
198 SkVector* translate) const {
199 return fSpotSet.find(spot, matrix, translate);
200 }
201
202 sk_sp<SkVertices> add(const SkPath& devPath, const SpotVerticesFactory& spot,
203 const SkMatrix& matrix, SkVector* translate) {
204 return fSpotSet.add(devPath, spot, matrix, translate);
205 }
206
207 private:
208 template <typename FACTORY, int MAX_ENTRIES>
209 class Set {
210 public:
211 size_t size() const { return fSize; }
212
213 sk_sp<SkVertices> find(const FACTORY& factory, const SkMatrix& matrix,
214 SkVector* translate) const {
215 for (int i = 0; i < MAX_ENTRIES; ++i) {
216 if (fEntries[i].fFactory.isCompatible(factory, translate)) {
217 const SkMatrix& m = fEntries[i].fMatrix;
218 if (matrix.hasPerspective() || m.hasPerspective()) {
219 if (matrix != fEntries[i].fMatrix) {
220 continue;
221 }
222 } else if (matrix.getScaleX() != m.getScaleX() ||
223 matrix.getSkewX() != m.getSkewX() ||
224 matrix.getScaleY() != m.getScaleY() ||
225 matrix.getSkewY() != m.getSkewY()) {
226 continue;
227 }
228 return fEntries[i].fVertices;
229 }
230 }
231 return nullptr;
232 }
233
234 sk_sp<SkVertices> add(const SkPath& path, const FACTORY& factory, const SkMatrix& matrix,
235 SkVector* translate) {
236 sk_sp<SkVertices> vertices = factory.makeVertices(path, matrix, translate);
237 if (!vertices) {
238 return nullptr;
239 }
240 int i;
241 if (fCount < MAX_ENTRIES) {
242 i = fCount++;
243 } else {
244 i = fRandom.nextULessThan(MAX_ENTRIES);
245 fSize -= fEntries[i].fVertices->approximateSize();
246 }
247 fEntries[i].fFactory = factory;
248 fEntries[i].fVertices = vertices;
249 fEntries[i].fMatrix = matrix;
250 fSize += vertices->approximateSize();
251 return vertices;
252 }
253
254 private:
255 struct Entry {
256 FACTORY fFactory;
257 sk_sp<SkVertices> fVertices;
258 SkMatrix fMatrix;
259 };
260 Entry fEntries[MAX_ENTRIES];
261 int fCount = 0;
262 size_t fSize = 0;
263 SkRandom fRandom;
264 };
265
266 Set<AmbientVerticesFactory, 4> fAmbientSet;
267 Set<SpotVerticesFactory, 4> fSpotSet;
268 };
269
270 /**
271 * A record of shadow vertices stored in SkResourceCache of CachedTessellations for a particular
272 * path. The key represents the path's geometry and not any shadow params.
273 */
274 class CachedTessellationsRec : public SkResourceCache::Rec {
275 public:
276 CachedTessellationsRec(const SkResourceCache::Key& key,
277 sk_sp<CachedTessellations> tessellations)
278 : fTessellations(std::move(tessellations)) {
279 fKey.reset(new uint8_t[key.size()]);
280 memcpy(fKey.get(), &key, key.size());
281 }
282
283 const Key& getKey() const override {
284 return *reinterpret_cast<SkResourceCache::Key*>(fKey.get());
285 }
286
287 size_t bytesUsed() const override { return fTessellations->size(); }
288
289 const char* getCategory() const override { return "tessellated shadow masks"; }
290
291 sk_sp<CachedTessellations> refTessellations() const { return fTessellations; }
292
293 template <typename FACTORY>
294 sk_sp<SkVertices> find(const FACTORY& factory, const SkMatrix& matrix,
295 SkVector* translate) const {
296 return fTessellations->find(factory, matrix, translate);
297 }
298
299 private:
300 std::unique_ptr<uint8_t[]> fKey;
301 sk_sp<CachedTessellations> fTessellations;
302 };
303
304 /**
305 * Used by FindVisitor to determine whether a cache entry can be reused and if so returns the
306 * vertices and a translation vector. If the CachedTessellations does not contain a suitable
307 * mesh then we inform SkResourceCache to destroy the Rec and we return the CachedTessellations
308 * to the caller. The caller will update it and reinsert it back into the cache.
309 */
310 template <typename FACTORY>
311 struct FindContext {
312 FindContext(const SkMatrix* viewMatrix, const FACTORY* factory)
313 : fViewMatrix(viewMatrix), fFactory(factory) {}
314 const SkMatrix* const fViewMatrix;
315 // If this is valid after Find is called then we found the vertices and they should be drawn
316 // with fTranslate applied.
317 sk_sp<SkVertices> fVertices;
318 SkVector fTranslate = {0, 0};
319
320 // If this is valid after Find then the caller should add the vertices to the tessellation set
321 // and create a new CachedTessellationsRec and insert it into SkResourceCache.
322 sk_sp<CachedTessellations> fTessellationsOnFailure;
323
324 const FACTORY* fFactory;
325 };
326
327 /**
328 * Function called by SkResourceCache when a matching cache key is found. The FACTORY and matrix of
329 * the FindContext are used to determine if the vertices are reusable. If so the vertices and
330 * necessary translation vector are set on the FindContext.
331 */
332 template <typename FACTORY>
333 bool FindVisitor(const SkResourceCache::Rec& baseRec, void* ctx) {
334 FindContext<FACTORY>* findContext = (FindContext<FACTORY>*)ctx;
335 const CachedTessellationsRec& rec = static_cast<const CachedTessellationsRec&>(baseRec);
336 findContext->fVertices =
337 rec.find(*findContext->fFactory, *findContext->fViewMatrix, &findContext->fTranslate);
338 if (findContext->fVertices) {
339 return true;
340 }
341 // We ref the tessellations and let the cache destroy the Rec. Once the tessellations have been
342 // manipulated we will add a new Rec.
343 findContext->fTessellationsOnFailure = rec.refTessellations();
344 return false;
345 }
346
347 class ShadowedPath {
348 public:
349 ShadowedPath(const SkPath* path, const SkMatrix* viewMatrix)
350 : fPath(path)
351 , fViewMatrix(viewMatrix)
352 #if defined(SK_GANESH)
353 , fShapeForKey(*path, GrStyle::SimpleFill())
354 #endif
355 {}
356
357 const SkPath& path() const { return *fPath; }
358 const SkMatrix& viewMatrix() const { return *fViewMatrix; }
359 #if defined(SK_GANESH)
360 /** Negative means the vertices should not be cached for this path. */
361 int keyBytes() const {
362 return fShapeForKey.hasUnstyledKey() ? fShapeForKey.unstyledKeySize() * sizeof(uint32_t)
363 : -1;
364 }
365 void writeKey(void* key) const {
366 fShapeForKey.writeUnstyledKey(reinterpret_cast<uint32_t*>(key));
367 }
368 bool isRRect(SkRRect* rrect) { return fShapeForKey.asRRect(rrect, nullptr); }
369 #else
370 int keyBytes() const { return -1; }
371 void writeKey(void* key) const { SK_ABORT("Should never be called"); }
372 bool isRRect(SkRRect* rrect) { return false; }
373 #endif
374
375 private:
376 const SkPath* fPath;
377 const SkMatrix* fViewMatrix;
378 #if defined(SK_GANESH)
379 GrStyledShape fShapeForKey;
380 #endif
381 };
382
383 // This creates a domain of keys in SkResourceCache used by this file.
384 static void* kNamespace;
385
386 // When the SkPathRef genID changes, invalidate a corresponding GrResource described by key.
387 class ShadowInvalidator : public SkIDChangeListener {
388 public:
389 ShadowInvalidator(const SkResourceCache::Key& key) {
390 fKey.reset(new uint8_t[key.size()]);
391 memcpy(fKey.get(), &key, key.size());
392 }
393
394 private:
395 const SkResourceCache::Key& getKey() const {
396 return *reinterpret_cast<SkResourceCache::Key*>(fKey.get());
397 }
398
399 // always purge
400 static bool FindVisitor(const SkResourceCache::Rec&, void*) {
401 return false;
402 }
403
404 void changed() override {
405 SkResourceCache::Find(this->getKey(), ShadowInvalidator::FindVisitor, nullptr);
406 }
407
408 std::unique_ptr<uint8_t[]> fKey;
409 };
410
411 /**
412 * Draws a shadow to 'canvas'. The vertices used to draw the shadow are created by 'factory' unless
413 * they are first found in SkResourceCache.
414 */
415 template <typename FACTORY>
416 bool draw_shadow(const FACTORY& factory,
417 std::function<void(const SkVertices*, SkBlendMode, const SkPaint&,
418 SkScalar tx, SkScalar ty, bool)> drawProc, ShadowedPath& path, SkColor color) {
419 FindContext<FACTORY> context(&path.viewMatrix(), &factory);
420
421 SkResourceCache::Key* key = nullptr;
422 constexpr int kMinBytes = 128;
423 // We need to make this array be of the cache's Key so the memory we create the Key in
424 // is properly aligned.
425 AutoSTArray<kMinBytes / sizeof(SkResourceCache::Key), SkResourceCache::Key> keyStorage;
426 int keyDataBytes = path.keyBytes();
427 if (keyDataBytes >= 0) {
428 // Store the key...
429 keyStorage.reset(keyDataBytes + sizeof(SkResourceCache::Key));
430 key = new (keyStorage.begin()) SkResourceCache::Key();
431 // ... followed by the bytes from path.
432 path.writeKey((uint32_t*)(((uint8_t*)keyStorage.begin()) + sizeof(SkResourceCache::Key)));
433 key->init(&kNamespace, resource_cache_shared_id(), keyDataBytes);
434 SkResourceCache::Find(*key, FindVisitor<FACTORY>, &context);
435 }
436
437 sk_sp<SkVertices> vertices;
438 bool foundInCache = SkToBool(context.fVertices);
439 if (foundInCache) {
440 vertices = std::move(context.fVertices);
441 } else {
442 // TODO: handle transforming the path as part of the tessellator
443 if (key) {
444 // Update or initialize a tessellation set and add it to the cache.
445 sk_sp<CachedTessellations> tessellations;
446 if (context.fTessellationsOnFailure) {
447 tessellations = std::move(context.fTessellationsOnFailure);
448 } else {
449 tessellations.reset(new CachedTessellations());
450 }
451 vertices = tessellations->add(path.path(), factory, path.viewMatrix(),
452 &context.fTranslate);
453 if (!vertices) {
454 return false;
455 }
456 auto rec = new CachedTessellationsRec(*key, std::move(tessellations));
457 SkPathPriv::AddGenIDChangeListener(path.path(), sk_make_sp<ShadowInvalidator>(*key));
458 SkResourceCache::Add(rec);
459 } else {
460 vertices = factory.makeVertices(path.path(), path.viewMatrix(),
461 &context.fTranslate);
462 if (!vertices) {
463 return false;
464 }
465 }
466 }
467
468 SkPaint paint;
469 // Run the vertex color through a GaussianColorFilter and then modulate the grayscale result of
470 // that against our 'color' param.
471 paint.setColorFilter(
472 SkColorFilters::Blend(color, SkBlendMode::kModulate)->makeComposed(
473 SkColorFilterPriv::MakeGaussian()));
474
475 drawProc(vertices.get(), SkBlendMode::kDst, paint,
476 context.fTranslate.fX, context.fTranslate.fY, path.viewMatrix().hasPerspective());
477
478 return true;
479 }
480 } // namespace
481
482 static bool tilted(const SkPoint3& zPlaneParams) {
483 return !SkScalarNearlyZero(zPlaneParams.fX) || !SkScalarNearlyZero(zPlaneParams.fY);
484 }
485 #endif // SK_ENABLE_OPTIMIZE_SIZE
486
487 void SkShadowUtils::ComputeTonalColors(SkColor inAmbientColor, SkColor inSpotColor,
488 SkColor* outAmbientColor, SkColor* outSpotColor) {
489 // For tonal color we only compute color values for the spot shadow.
490 // The ambient shadow is greyscale only.
491
492 // Ambient
493 *outAmbientColor = SkColorSetARGB(SkColorGetA(inAmbientColor), 0, 0, 0);
494
495 // Spot
496 int spotR = SkColorGetR(inSpotColor);
497 int spotG = SkColorGetG(inSpotColor);
498 int spotB = SkColorGetB(inSpotColor);
499 int max = std::max(std::max(spotR, spotG), spotB);
500 int min = std::min(std::min(spotR, spotG), spotB);
501 SkScalar luminance = 0.5f*(max + min)/255.f;
502 SkScalar origA = SkColorGetA(inSpotColor)/255.f;
503
504 // We compute a color alpha value based on the luminance of the color, scaled by an
505 // adjusted alpha value. We want the following properties to match the UX examples
506 // (assuming a = 0.25) and to ensure that we have reasonable results when the color
507 // is black and/or the alpha is 0:
508 // f(0, a) = 0
509 // f(luminance, 0) = 0
510 // f(1, 0.25) = .5
511 // f(0.5, 0.25) = .4
512 // f(1, 1) = 1
513 // The following functions match this as closely as possible.
514 SkScalar alphaAdjust = (2.6f + (-2.66667f + 1.06667f*origA)*origA)*origA;
515 SkScalar colorAlpha = (3.544762f + (-4.891428f + 2.3466f*luminance)*luminance)*luminance;
516 colorAlpha = SkTPin(alphaAdjust*colorAlpha, 0.0f, 1.0f);
517
518 // Similarly, we set the greyscale alpha based on luminance and alpha so that
519 // f(0, a) = a
520 // f(luminance, 0) = 0
521 // f(1, 0.25) = 0.15
522 SkScalar greyscaleAlpha = SkTPin(origA*(1 - 0.4f*luminance), 0.0f, 1.0f);
523
524 // The final color we want to emulate is generated by rendering a color shadow (C_rgb) using an
525 // alpha computed from the color's luminance (C_a), and then a black shadow with alpha (S_a)
526 // which is an adjusted value of 'a'. Assuming SrcOver, a background color of B_rgb, and
527 // ignoring edge falloff, this becomes
528 //
529 // (C_a - S_a*C_a)*C_rgb + (1 - (S_a + C_a - S_a*C_a))*B_rgb
530 //
531 // Assuming premultiplied alpha, this means we scale the color by (C_a - S_a*C_a) and
532 // set the alpha to (S_a + C_a - S_a*C_a).
533 SkScalar colorScale = colorAlpha*(SK_Scalar1 - greyscaleAlpha);
534 SkScalar tonalAlpha = colorScale + greyscaleAlpha;
535 SkScalar unPremulScale = colorScale / tonalAlpha;
536 *outSpotColor = SkColorSetARGB(tonalAlpha*255.999f,
537 unPremulScale*spotR,
538 unPremulScale*spotG,
539 unPremulScale*spotB);
540 }
541
542 static bool fill_shadow_rec(const SkPath& path, const SkPoint3& zPlaneParams,
543 const SkPoint3& lightPos, SkScalar lightRadius,
544 SkColor ambientColor, SkColor spotColor,
545 uint32_t flags, const SkMatrix& ctm, SkDrawShadowRec* rec) {
546 SkPoint pt = { lightPos.fX, lightPos.fY };
547 if (!SkToBool(flags & kDirectionalLight_ShadowFlag)) {
548 // If light position is in device space, need to transform to local space
549 // before applying to SkCanvas.
550 SkMatrix inverse;
551 if (!ctm.invert(&inverse)) {
552 return false;
553 }
554 pt = inverse.mapPoint(pt);
555 }
556
557 rec->fZPlaneParams = zPlaneParams;
558 rec->fLightPos = { pt.fX, pt.fY, lightPos.fZ };
559 rec->fLightRadius = lightRadius;
560 rec->fAmbientColor = ambientColor;
561 rec->fSpotColor = spotColor;
562 rec->fFlags = flags;
563
564 return true;
565 }
566
567 // Draw an offset spot shadow and outlining ambient shadow for the given path.
568 void SkShadowUtils::DrawShadow(SkCanvas* canvas, const SkPath& path, const SkPoint3& zPlaneParams,
569 const SkPoint3& lightPos, SkScalar lightRadius,
570 SkColor ambientColor, SkColor spotColor,
571 uint32_t flags) {
572 SkDrawShadowRec rec;
573 if (!fill_shadow_rec(path, zPlaneParams, lightPos, lightRadius, ambientColor, spotColor,
574 flags, canvas->getTotalMatrix(), &rec)) {
575 return;
576 }
577
578 canvas->private_draw_shadow_rec(path, rec);
579 }
580
581 bool SkShadowUtils::GetLocalBounds(const SkMatrix& ctm, const SkPath& path,
582 const SkPoint3& zPlaneParams, const SkPoint3& lightPos,
583 SkScalar lightRadius, uint32_t flags, SkRect* bounds) {
584 SkDrawShadowRec rec;
585 if (!fill_shadow_rec(path, zPlaneParams, lightPos, lightRadius, SK_ColorBLACK, SK_ColorBLACK,
586 flags, ctm, &rec)) {
587 return false;
588 }
589
590 SkDrawShadowMetrics::GetLocalBounds(path, rec, ctm, bounds);
591
592 return true;
593 }
594
595 //////////////////////////////////////////////////////////////////////////////////////////////
596
597 static bool validate_rec(const SkDrawShadowRec& rec) {
598 return rec.fLightPos.isFinite() && rec.fZPlaneParams.isFinite() &&
599 SkIsFinite(rec.fLightRadius);
600 }
601
602 void SkDevice::drawShadow(SkCanvas* canvas, const SkPath& path, const SkDrawShadowRec& rec) {
603 if (!validate_rec(rec)) {
604 return;
605 }
606
607 SkMatrix viewMatrix = this->localToDevice();
608
609 #if !defined(SK_ENABLE_OPTIMIZE_SIZE)
610 auto drawVertsProc = [this](const SkVertices* vertices, SkBlendMode mode, const SkPaint& paint,
611 SkScalar tx, SkScalar ty, bool hasPerspective) {
612 if (vertices->priv().vertexCount()) {
613 // For perspective shadows we've already computed the shadow in world space,
614 // and we can't translate it without changing it. Otherwise we concat the
615 // change in translation from the cached version.
616 SkAutoDeviceTransformRestore adr(
617 this,
618 hasPerspective ? SkM44()
619 : this->localToDevice44() * SkM44::Translate(tx, ty));
620 // The vertex colors for a tesselated shadow polygon are always either opaque black
621 // or transparent and their real contribution to the final blended color is via
622 // their alpha. We can skip expensive per-vertex color conversion for this.
623 this->drawVertices(vertices, SkBlender::Mode(mode), paint, /*skipColorXform=*/true);
624 }
625 };
626
627 ShadowedPath shadowedPath(&path, &viewMatrix);
628
629 bool tiltZPlane = tilted(rec.fZPlaneParams);
630 bool transparent = SkToBool(rec.fFlags & SkShadowFlags::kTransparentOccluder_ShadowFlag);
631 bool useBlur = SkToBool(rec.fFlags & SkShadowFlags::kConcaveBlurOnly_ShadowFlag) &&
632 !path.isConvex();
633 bool uncached = tiltZPlane || path.isVolatile();
634 #endif
635 bool directional = SkToBool(rec.fFlags & SkShadowFlags::kDirectionalLight_ShadowFlag);
636
637 SkPoint3 zPlaneParams = rec.fZPlaneParams;
638 SkPoint3 devLightPos = rec.fLightPos;
639 if (!directional) {
640 viewMatrix.mapPoints({(SkPoint*)&devLightPos.fX, 1});
641 }
642 float lightRadius = rec.fLightRadius;
643
644 if (SkColorGetA(rec.fAmbientColor) > 0) {
645 SkAutoDeviceTransformRestore adr(this, SkM44());
646
647 bool success = false;
648 #if !defined(SK_ENABLE_OPTIMIZE_SIZE)
649 if (uncached && !useBlur) {
650 sk_sp<SkVertices> vertices = SkShadowTessellator::MakeAmbient(path, viewMatrix,
651 zPlaneParams,
652 transparent);
653 if (vertices) {
654 SkPaint paint;
655 // Run the vertex color through a GaussianColorFilter and then modulate the
656 // grayscale result of that against our 'color' param.
657 paint.setColorFilter(
658 SkColorFilters::Blend(rec.fAmbientColor,
659 SkBlendMode::kModulate)->makeComposed(
660 SkColorFilterPriv::MakeGaussian()));
661 // The vertex colors for a tesselated shadow polygon are always either opaque black
662 // or transparent and their real contribution to the final blended color is via
663 // their alpha. We can skip expensive per-vertex color conversion for this.
664 this->drawVertices(vertices.get(),
665 SkBlender::Mode(SkBlendMode::kDst),
666 paint,
667 /*skipColorXform=*/true);
668 success = true;
669 }
670 }
671
672 if (!success && !useBlur) {
673 AmbientVerticesFactory factory;
674 factory.fOccluderHeight = zPlaneParams.fZ;
675 factory.fTransparent = transparent;
676 if (viewMatrix.hasPerspective()) {
677 factory.fOffset.set(0, 0);
678 } else {
679 factory.fOffset.fX = viewMatrix.getTranslateX();
680 factory.fOffset.fY = viewMatrix.getTranslateY();
681 }
682
683 success = draw_shadow(factory, drawVertsProc, shadowedPath, rec.fAmbientColor);
684 }
685 #endif // !defined(SK_ENABLE_OPTIMIZE_SIZE)
686
687 // All else has failed, draw with blur
688 if (!success) {
689 // Pretransform the path to avoid transforming the stroke, below.
690 SkPath devSpacePath = path.makeTransform(canvas->getLocalToDeviceAs3x3());
691 devSpacePath.setIsVolatile(true);
692
693 // The tesselator outsets by AmbientBlurRadius (or 'r') to get the outer ring of
694 // the tesselation, and sets the alpha on the path to 1/AmbientRecipAlpha (or 'a').
695 //
696 // We want to emulate this with a blur. The full blur width (2*blurRadius or 'f')
697 // can be calculated by interpolating:
698 //
699 // original edge outer edge
700 // | |<---------- r ------>|
701 // |<------|--- f -------------->|
702 // | | |
703 // alpha = 1 alpha = a alpha = 0
704 //
705 // Taking ratios, f/1 = r/a, so f = r/a and blurRadius = f/2.
706 //
707 // We now need to outset the path to place the new edge in the center of the
708 // blur region:
709 //
710 // original new
711 // | |<------|--- r ------>|
712 // |<------|--- f -|------------>|
713 // | |<- o ->|<--- f/2 --->|
714 //
715 // r = o + f/2, so o = r - f/2
716 //
717 // We outset by using the stroker, so the strokeWidth is o/2.
718 //
719 SkScalar devSpaceOutset = SkDrawShadowMetrics::AmbientBlurRadius(zPlaneParams.fZ);
720 SkScalar oneOverA = SkDrawShadowMetrics::AmbientRecipAlpha(zPlaneParams.fZ);
721 SkScalar blurRadius = 0.5f*devSpaceOutset*oneOverA;
722 SkScalar strokeWidth = 0.5f*(devSpaceOutset - blurRadius);
723
724 // Now draw with blur
725 SkAutoCanvasRestore autoRestore(canvas, /*doSave=*/true);
726 canvas->setMatrix(SkM44());
727 SkPaint paint;
728 paint.setColor(rec.fAmbientColor);
729 paint.setStrokeWidth(strokeWidth);
730 paint.setStyle(SkPaint::kStrokeAndFill_Style);
731 SkScalar sigma = SkBlurMask::ConvertRadiusToSigma(blurRadius);
732 paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, sigma,
733 /*respectCTM=*/false));
734 canvas->drawPath(devSpacePath, paint);
735 }
736 }
737
738 if (SkColorGetA(rec.fSpotColor) > 0) {
739 SkAutoDeviceTransformRestore adr(this, SkM44());
740
741 bool success = false;
742 #if !defined(SK_ENABLE_OPTIMIZE_SIZE)
743 if (uncached && !useBlur) {
744 sk_sp<SkVertices> vertices = SkShadowTessellator::MakeSpot(path, viewMatrix,
745 zPlaneParams,
746 devLightPos, lightRadius,
747 transparent,
748 directional);
749 if (vertices) {
750 SkPaint paint;
751 // Run the vertex color through a GaussianColorFilter and then modulate the
752 // grayscale result of that against our 'color' param.
753 paint.setColorFilter(
754 SkColorFilters::Blend(rec.fSpotColor,
755 SkBlendMode::kModulate)->makeComposed(
756 SkColorFilterPriv::MakeGaussian()));
757 // The vertex colors for a tesselated shadow polygon are always either opaque black
758 // or transparent and their real contribution to the final blended color is via
759 // their alpha. We can skip expensive per-vertex color conversion for this.
760 this->drawVertices(vertices.get(),
761 SkBlender::Mode(SkBlendMode::kDst),
762 paint,
763 /*skipColorXform=*/true);
764 success = true;
765 }
766 }
767
768 if (!success && !useBlur) {
769 SpotVerticesFactory factory;
770 factory.fOccluderHeight = zPlaneParams.fZ;
771 factory.fDevLightPos = devLightPos;
772 factory.fLightRadius = lightRadius;
773
774 SkPoint center = SkPoint::Make(path.getBounds().centerX(), path.getBounds().centerY());
775 factory.fLocalCenter = center;
776 center = viewMatrix.mapPoint(center);
777 SkScalar radius, scale;
778 if (SkToBool(rec.fFlags & kDirectionalLight_ShadowFlag)) {
779 SkDrawShadowMetrics::GetDirectionalParams(zPlaneParams.fZ, devLightPos.fX,
780 devLightPos.fY, devLightPos.fZ,
781 lightRadius, &radius, &scale,
782 &factory.fOffset);
783 } else {
784 SkDrawShadowMetrics::GetSpotParams(zPlaneParams.fZ, devLightPos.fX - center.fX,
785 devLightPos.fY - center.fY, devLightPos.fZ,
786 lightRadius, &radius, &scale, &factory.fOffset);
787 }
788
789 SkRect devBounds;
790 viewMatrix.mapRect(&devBounds, path.getBounds());
791 if (transparent ||
792 SkTAbs(factory.fOffset.fX) > 0.5f*devBounds.width() ||
793 SkTAbs(factory.fOffset.fY) > 0.5f*devBounds.height()) {
794 // if the translation of the shadow is big enough we're going to end up
795 // filling the entire umbra, we can treat these as all the same
796 if (directional) {
797 factory.fOccluderType =
798 SpotVerticesFactory::OccluderType::kDirectionalTransparent;
799 } else {
800 factory.fOccluderType = SpotVerticesFactory::OccluderType::kPointTransparent;
801 }
802 } else if (directional) {
803 factory.fOccluderType = SpotVerticesFactory::OccluderType::kDirectional;
804 } else if (factory.fOffset.length()*scale + scale < radius) {
805 // if we don't translate more than the blur distance, can assume umbra is covered
806 factory.fOccluderType = SpotVerticesFactory::OccluderType::kPointOpaqueNoUmbra;
807 } else if (path.isConvex()) {
808 factory.fOccluderType = SpotVerticesFactory::OccluderType::kPointOpaquePartialUmbra;
809 } else {
810 factory.fOccluderType = SpotVerticesFactory::OccluderType::kPointTransparent;
811 }
812 // need to add this after we classify the shadow
813 factory.fOffset.fX += viewMatrix.getTranslateX();
814 factory.fOffset.fY += viewMatrix.getTranslateY();
815
816 SkColor color = rec.fSpotColor;
817 #ifdef DEBUG_SHADOW_CHECKS
818 switch (factory.fOccluderType) {
819 case SpotVerticesFactory::OccluderType::kPointTransparent:
820 color = 0xFFD2B48C; // tan for transparent
821 break;
822 case SpotVerticesFactory::OccluderType::kPointOpaquePartialUmbra:
823 color = 0xFFFFA500; // orange for opaque
824 break;
825 case SpotVerticesFactory::OccluderType::kPointOpaqueNoUmbra:
826 color = 0xFFE5E500; // corn yellow for covered
827 break;
828 case SpotVerticesFactory::OccluderType::kDirectional:
829 case SpotVerticesFactory::OccluderType::kDirectionalTransparent:
830 color = 0xFF550000; // dark red for directional
831 break;
832 }
833 #endif
834 success = draw_shadow(factory, drawVertsProc, shadowedPath, color);
835 }
836 #endif // !defined(SK_ENABLE_OPTIMIZE_SIZE)
837
838 // All else has failed, draw with blur
839 if (!success) {
840 SkMatrix shadowMatrix;
841 SkScalar radius;
842 if (!SkDrawShadowMetrics::GetSpotShadowTransform(devLightPos, lightRadius,
843 canvas->getLocalToDeviceAs3x3(),
844 zPlaneParams,
845 path.getBounds(), directional,
846 &shadowMatrix, &radius)) {
847 return;
848 }
849 SkAutoCanvasRestore autoRestore(canvas, /*doSave=*/true);
850
851 // And draw with blur
852 canvas->setMatrix(shadowMatrix);
853 SkPaint paint;
854 paint.setColor(rec.fSpotColor);
855 SkScalar sigma = SkBlurMask::ConvertRadiusToSigma(radius);
856 paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, sigma,
857 /*respectCTM=*/false));
858 canvas->drawPath(path, paint);
859 }
860 }
861 }