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
resource_cache_shared_id()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
isCompatible__anondd4375fb0111::AmbientVerticesFactory74 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
makeVertices__anondd4375fb0111::AmbientVerticesFactory82 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
isCompatible__anondd4375fb0111::SpotVerticesFactory119 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
makeVertices__anondd4375fb0111::SpotVerticesFactory147 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 noTrans.mapPoints(&devCenter, 1);
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:
size() const185 size_t size() const { return fAmbientSet.size() + fSpotSet.size(); }
186
find(const AmbientVerticesFactory & ambient,const SkMatrix & matrix,SkVector * translate) const187 sk_sp<SkVertices> find(const AmbientVerticesFactory& ambient, const SkMatrix& matrix,
188 SkVector* translate) const {
189 return fAmbientSet.find(ambient, matrix, translate);
190 }
191
add(const SkPath & devPath,const AmbientVerticesFactory & ambient,const SkMatrix & matrix,SkVector * translate)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
find(const SpotVerticesFactory & spot,const SkMatrix & matrix,SkVector * translate) const197 sk_sp<SkVertices> find(const SpotVerticesFactory& spot, const SkMatrix& matrix,
198 SkVector* translate) const {
199 return fSpotSet.find(spot, matrix, translate);
200 }
201
add(const SkPath & devPath,const SpotVerticesFactory & spot,const SkMatrix & matrix,SkVector * translate)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:
size() const211 size_t size() const { return fSize; }
212
find(const FACTORY & factory,const SkMatrix & matrix,SkVector * translate) const213 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
add(const SkPath & path,const FACTORY & factory,const SkMatrix & matrix,SkVector * translate)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:
CachedTessellationsRec(const SkResourceCache::Key & key,sk_sp<CachedTessellations> tessellations)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
getKey() const283 const Key& getKey() const override {
284 return *reinterpret_cast<SkResourceCache::Key*>(fKey.get());
285 }
286
bytesUsed() const287 size_t bytesUsed() const override { return fTessellations->size(); }
288
getCategory() const289 const char* getCategory() const override { return "tessellated shadow masks"; }
290
refTessellations() const291 sk_sp<CachedTessellations> refTessellations() const { return fTessellations; }
292
293 template <typename FACTORY>
find(const FACTORY & factory,const SkMatrix & matrix,SkVector * translate) const294 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 {
FindContext__anondd4375fb0111::FindContext312 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>
FindVisitor(const SkResourceCache::Rec & baseRec,void * ctx)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:
ShadowedPath(const SkPath * path,const SkMatrix * viewMatrix)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
path() const357 const SkPath& path() const { return *fPath; }
viewMatrix() const358 const SkMatrix& viewMatrix() const { return *fViewMatrix; }
359 #if defined(SK_GANESH)
360 /** Negative means the vertices should not be cached for this path. */
keyBytes() const361 int keyBytes() const { return fShapeForKey.unstyledKeySize() * sizeof(uint32_t); }
writeKey(void * key) const362 void writeKey(void* key) const {
363 fShapeForKey.writeUnstyledKey(reinterpret_cast<uint32_t*>(key));
364 }
isRRect(SkRRect * rrect)365 bool isRRect(SkRRect* rrect) { return fShapeForKey.asRRect(rrect, nullptr); }
366 #else
keyBytes() const367 int keyBytes() const { return -1; }
writeKey(void * key) const368 void writeKey(void* key) const { SK_ABORT("Should never be called"); }
isRRect(SkRRect * rrect)369 bool isRRect(SkRRect* rrect) { return false; }
370 #endif
371
372 private:
373 const SkPath* fPath;
374 const SkMatrix* fViewMatrix;
375 #if defined(SK_GANESH)
376 GrStyledShape fShapeForKey;
377 #endif
378 };
379
380 // This creates a domain of keys in SkResourceCache used by this file.
381 static void* kNamespace;
382
383 // When the SkPathRef genID changes, invalidate a corresponding GrResource described by key.
384 class ShadowInvalidator : public SkIDChangeListener {
385 public:
ShadowInvalidator(const SkResourceCache::Key & key)386 ShadowInvalidator(const SkResourceCache::Key& key) {
387 fKey.reset(new uint8_t[key.size()]);
388 memcpy(fKey.get(), &key, key.size());
389 }
390
391 private:
getKey() const392 const SkResourceCache::Key& getKey() const {
393 return *reinterpret_cast<SkResourceCache::Key*>(fKey.get());
394 }
395
396 // always purge
FindVisitor(const SkResourceCache::Rec &,void *)397 static bool FindVisitor(const SkResourceCache::Rec&, void*) {
398 return false;
399 }
400
changed()401 void changed() override {
402 SkResourceCache::Find(this->getKey(), ShadowInvalidator::FindVisitor, nullptr);
403 }
404
405 std::unique_ptr<uint8_t[]> fKey;
406 };
407
408 /**
409 * Draws a shadow to 'canvas'. The vertices used to draw the shadow are created by 'factory' unless
410 * they are first found in SkResourceCache.
411 */
412 template <typename FACTORY>
draw_shadow(const FACTORY & factory,std::function<void (const SkVertices *,SkBlendMode,const SkPaint &,SkScalar tx,SkScalar ty,bool)> drawProc,ShadowedPath & path,SkColor color)413 bool draw_shadow(const FACTORY& factory,
414 std::function<void(const SkVertices*, SkBlendMode, const SkPaint&,
415 SkScalar tx, SkScalar ty, bool)> drawProc, ShadowedPath& path, SkColor color) {
416 FindContext<FACTORY> context(&path.viewMatrix(), &factory);
417
418 SkResourceCache::Key* key = nullptr;
419 constexpr int kMinBytes = 128;
420 // We need to make this array be of the cache's Key so the memory we create the Key in
421 // is properly aligned.
422 AutoSTArray<kMinBytes / sizeof(SkResourceCache::Key), SkResourceCache::Key> keyStorage;
423 int keyDataBytes = path.keyBytes();
424 if (keyDataBytes >= 0) {
425 // Store the key...
426 keyStorage.reset(keyDataBytes + sizeof(SkResourceCache::Key));
427 key = new (keyStorage.begin()) SkResourceCache::Key();
428 // ... followed by the bytes from path.
429 path.writeKey((uint32_t*)(((uint8_t*)keyStorage.begin()) + sizeof(SkResourceCache::Key)));
430 key->init(&kNamespace, resource_cache_shared_id(), keyDataBytes);
431 SkResourceCache::Find(*key, FindVisitor<FACTORY>, &context);
432 }
433
434 sk_sp<SkVertices> vertices;
435 bool foundInCache = SkToBool(context.fVertices);
436 if (foundInCache) {
437 vertices = std::move(context.fVertices);
438 } else {
439 // TODO: handle transforming the path as part of the tessellator
440 if (key) {
441 // Update or initialize a tessellation set and add it to the cache.
442 sk_sp<CachedTessellations> tessellations;
443 if (context.fTessellationsOnFailure) {
444 tessellations = std::move(context.fTessellationsOnFailure);
445 } else {
446 tessellations.reset(new CachedTessellations());
447 }
448 vertices = tessellations->add(path.path(), factory, path.viewMatrix(),
449 &context.fTranslate);
450 if (!vertices) {
451 return false;
452 }
453 auto rec = new CachedTessellationsRec(*key, std::move(tessellations));
454 SkPathPriv::AddGenIDChangeListener(path.path(), sk_make_sp<ShadowInvalidator>(*key));
455 SkResourceCache::Add(rec);
456 } else {
457 vertices = factory.makeVertices(path.path(), path.viewMatrix(),
458 &context.fTranslate);
459 if (!vertices) {
460 return false;
461 }
462 }
463 }
464
465 SkPaint paint;
466 // Run the vertex color through a GaussianColorFilter and then modulate the grayscale result of
467 // that against our 'color' param.
468 paint.setColorFilter(
469 SkColorFilters::Blend(color, SkBlendMode::kModulate)->makeComposed(
470 SkColorFilterPriv::MakeGaussian()));
471
472 drawProc(vertices.get(), SkBlendMode::kModulate, paint,
473 context.fTranslate.fX, context.fTranslate.fY, path.viewMatrix().hasPerspective());
474
475 return true;
476 }
477 } // namespace
478
tilted(const SkPoint3 & zPlaneParams)479 static bool tilted(const SkPoint3& zPlaneParams) {
480 return !SkScalarNearlyZero(zPlaneParams.fX) || !SkScalarNearlyZero(zPlaneParams.fY);
481 }
482 #endif // SK_ENABLE_OPTIMIZE_SIZE
483
ComputeTonalColors(SkColor inAmbientColor,SkColor inSpotColor,SkColor * outAmbientColor,SkColor * outSpotColor)484 void SkShadowUtils::ComputeTonalColors(SkColor inAmbientColor, SkColor inSpotColor,
485 SkColor* outAmbientColor, SkColor* outSpotColor) {
486 // For tonal color we only compute color values for the spot shadow.
487 // The ambient shadow is greyscale only.
488
489 // Ambient
490 *outAmbientColor = SkColorSetARGB(SkColorGetA(inAmbientColor), 0, 0, 0);
491
492 // Spot
493 int spotR = SkColorGetR(inSpotColor);
494 int spotG = SkColorGetG(inSpotColor);
495 int spotB = SkColorGetB(inSpotColor);
496 int max = std::max(std::max(spotR, spotG), spotB);
497 int min = std::min(std::min(spotR, spotG), spotB);
498 SkScalar luminance = 0.5f*(max + min)/255.f;
499 SkScalar origA = SkColorGetA(inSpotColor)/255.f;
500
501 // We compute a color alpha value based on the luminance of the color, scaled by an
502 // adjusted alpha value. We want the following properties to match the UX examples
503 // (assuming a = 0.25) and to ensure that we have reasonable results when the color
504 // is black and/or the alpha is 0:
505 // f(0, a) = 0
506 // f(luminance, 0) = 0
507 // f(1, 0.25) = .5
508 // f(0.5, 0.25) = .4
509 // f(1, 1) = 1
510 // The following functions match this as closely as possible.
511 SkScalar alphaAdjust = (2.6f + (-2.66667f + 1.06667f*origA)*origA)*origA;
512 SkScalar colorAlpha = (3.544762f + (-4.891428f + 2.3466f*luminance)*luminance)*luminance;
513 colorAlpha = SkTPin(alphaAdjust*colorAlpha, 0.0f, 1.0f);
514
515 // Similarly, we set the greyscale alpha based on luminance and alpha so that
516 // f(0, a) = a
517 // f(luminance, 0) = 0
518 // f(1, 0.25) = 0.15
519 SkScalar greyscaleAlpha = SkTPin(origA*(1 - 0.4f*luminance), 0.0f, 1.0f);
520
521 // The final color we want to emulate is generated by rendering a color shadow (C_rgb) using an
522 // alpha computed from the color's luminance (C_a), and then a black shadow with alpha (S_a)
523 // which is an adjusted value of 'a'. Assuming SrcOver, a background color of B_rgb, and
524 // ignoring edge falloff, this becomes
525 //
526 // (C_a - S_a*C_a)*C_rgb + (1 - (S_a + C_a - S_a*C_a))*B_rgb
527 //
528 // Assuming premultiplied alpha, this means we scale the color by (C_a - S_a*C_a) and
529 // set the alpha to (S_a + C_a - S_a*C_a).
530 SkScalar colorScale = colorAlpha*(SK_Scalar1 - greyscaleAlpha);
531 SkScalar tonalAlpha = colorScale + greyscaleAlpha;
532 SkScalar unPremulScale = colorScale / tonalAlpha;
533 *outSpotColor = SkColorSetARGB(tonalAlpha*255.999f,
534 unPremulScale*spotR,
535 unPremulScale*spotG,
536 unPremulScale*spotB);
537 }
538
fill_shadow_rec(const SkPath & path,const SkPoint3 & zPlaneParams,const SkPoint3 & lightPos,SkScalar lightRadius,SkColor ambientColor,SkColor spotColor,uint32_t flags,const SkMatrix & ctm,SkDrawShadowRec * rec)539 static bool fill_shadow_rec(const SkPath& path, const SkPoint3& zPlaneParams,
540 const SkPoint3& lightPos, SkScalar lightRadius,
541 SkColor ambientColor, SkColor spotColor,
542 uint32_t flags, const SkMatrix& ctm, SkDrawShadowRec* rec) {
543 SkPoint pt = { lightPos.fX, lightPos.fY };
544 if (!SkToBool(flags & kDirectionalLight_ShadowFlag)) {
545 // If light position is in device space, need to transform to local space
546 // before applying to SkCanvas.
547 SkMatrix inverse;
548 if (!ctm.invert(&inverse)) {
549 return false;
550 }
551 inverse.mapPoints(&pt, 1);
552 }
553
554 rec->fZPlaneParams = zPlaneParams;
555 rec->fLightPos = { pt.fX, pt.fY, lightPos.fZ };
556 rec->fLightRadius = lightRadius;
557 rec->fAmbientColor = ambientColor;
558 rec->fSpotColor = spotColor;
559 rec->fFlags = flags;
560
561 return true;
562 }
563
564 // Draw an offset spot shadow and outlining ambient shadow for the given path.
DrawShadow(SkCanvas * canvas,const SkPath & path,const SkPoint3 & zPlaneParams,const SkPoint3 & lightPos,SkScalar lightRadius,SkColor ambientColor,SkColor spotColor,uint32_t flags)565 void SkShadowUtils::DrawShadow(SkCanvas* canvas, const SkPath& path, const SkPoint3& zPlaneParams,
566 const SkPoint3& lightPos, SkScalar lightRadius,
567 SkColor ambientColor, SkColor spotColor,
568 uint32_t flags) {
569 SkDrawShadowRec rec;
570 if (!fill_shadow_rec(path, zPlaneParams, lightPos, lightRadius, ambientColor, spotColor,
571 flags, canvas->getTotalMatrix(), &rec)) {
572 return;
573 }
574
575 canvas->private_draw_shadow_rec(path, rec);
576 }
577
GetLocalBounds(const SkMatrix & ctm,const SkPath & path,const SkPoint3 & zPlaneParams,const SkPoint3 & lightPos,SkScalar lightRadius,uint32_t flags,SkRect * bounds)578 bool SkShadowUtils::GetLocalBounds(const SkMatrix& ctm, const SkPath& path,
579 const SkPoint3& zPlaneParams, const SkPoint3& lightPos,
580 SkScalar lightRadius, uint32_t flags, SkRect* bounds) {
581 SkDrawShadowRec rec;
582 if (!fill_shadow_rec(path, zPlaneParams, lightPos, lightRadius, SK_ColorBLACK, SK_ColorBLACK,
583 flags, ctm, &rec)) {
584 return false;
585 }
586
587 SkDrawShadowMetrics::GetLocalBounds(path, rec, ctm, bounds);
588
589 return true;
590 }
591
592 //////////////////////////////////////////////////////////////////////////////////////////////
593
validate_rec(const SkDrawShadowRec & rec)594 static bool validate_rec(const SkDrawShadowRec& rec) {
595 return rec.fLightPos.isFinite() && rec.fZPlaneParams.isFinite() &&
596 SkIsFinite(rec.fLightRadius);
597 }
598
drawShadow(const SkPath & path,const SkDrawShadowRec & rec)599 void SkDevice::drawShadow(const SkPath& path, const SkDrawShadowRec& rec) {
600 if (!validate_rec(rec)) {
601 return;
602 }
603
604 SkMatrix viewMatrix = this->localToDevice();
605 SkAutoDeviceTransformRestore adr(this, SkM44());
606
607 #if !defined(SK_ENABLE_OPTIMIZE_SIZE)
608 auto drawVertsProc = [this](const SkVertices* vertices, SkBlendMode mode, const SkPaint& paint,
609 SkScalar tx, SkScalar ty, bool hasPerspective) {
610 if (vertices->priv().vertexCount()) {
611 // For perspective shadows we've already computed the shadow in world space,
612 // and we can't translate it without changing it. Otherwise we concat the
613 // change in translation from the cached version.
614 SkAutoDeviceTransformRestore adr(
615 this,
616 hasPerspective ? SkM44()
617 : this->localToDevice44() * SkM44::Translate(tx, ty));
618 // The vertex colors for a tesselated shadow polygon are always either opaque black
619 // or transparent and their real contribution to the final blended color is via
620 // their alpha. We can skip expensive per-vertex color conversion for this.
621 this->drawVertices(vertices, SkBlender::Mode(mode), paint, /*skipColorXform=*/true);
622 }
623 };
624
625 ShadowedPath shadowedPath(&path, &viewMatrix);
626
627 bool tiltZPlane = tilted(rec.fZPlaneParams);
628 bool transparent = SkToBool(rec.fFlags & SkShadowFlags::kTransparentOccluder_ShadowFlag);
629 bool useBlur = SkToBool(rec.fFlags & SkShadowFlags::kConcaveBlurOnly_ShadowFlag) &&
630 !path.isConvex();
631 bool uncached = tiltZPlane || path.isVolatile();
632 #endif
633 bool directional = SkToBool(rec.fFlags & SkShadowFlags::kDirectionalLight_ShadowFlag);
634
635 SkPoint3 zPlaneParams = rec.fZPlaneParams;
636 SkPoint3 devLightPos = rec.fLightPos;
637 if (!directional) {
638 viewMatrix.mapPoints((SkPoint*)&devLightPos.fX, 1);
639 }
640 float lightRadius = rec.fLightRadius;
641
642 if (SkColorGetA(rec.fAmbientColor) > 0) {
643 bool success = false;
644 #if !defined(SK_ENABLE_OPTIMIZE_SIZE)
645 if (uncached && !useBlur) {
646 sk_sp<SkVertices> vertices = SkShadowTessellator::MakeAmbient(path, viewMatrix,
647 zPlaneParams,
648 transparent);
649 if (vertices) {
650 SkPaint paint;
651 // Run the vertex color through a GaussianColorFilter and then modulate the
652 // grayscale result of that against our 'color' param.
653 paint.setColorFilter(
654 SkColorFilters::Blend(rec.fAmbientColor,
655 SkBlendMode::kModulate)->makeComposed(
656 SkColorFilterPriv::MakeGaussian()));
657 // The vertex colors for a tesselated shadow polygon are always either opaque black
658 // or transparent and their real contribution to the final blended color is via
659 // their alpha. We can skip expensive per-vertex color conversion for this.
660 this->drawVertices(vertices.get(),
661 SkBlender::Mode(SkBlendMode::kModulate),
662 paint,
663 /*skipColorXform=*/true);
664 success = true;
665 }
666 }
667
668 if (!success && !useBlur) {
669 AmbientVerticesFactory factory;
670 factory.fOccluderHeight = zPlaneParams.fZ;
671 factory.fTransparent = transparent;
672 if (viewMatrix.hasPerspective()) {
673 factory.fOffset.set(0, 0);
674 } else {
675 factory.fOffset.fX = viewMatrix.getTranslateX();
676 factory.fOffset.fY = viewMatrix.getTranslateY();
677 }
678
679 success = draw_shadow(factory, drawVertsProc, shadowedPath, rec.fAmbientColor);
680 }
681 #endif // !defined(SK_ENABLE_OPTIMIZE_SIZE)
682
683 // All else has failed, draw with blur
684 if (!success) {
685 // Pretransform the path to avoid transforming the stroke, below.
686 SkPath devSpacePath;
687 path.transform(viewMatrix, &devSpacePath);
688 devSpacePath.setIsVolatile(true);
689
690 // The tesselator outsets by AmbientBlurRadius (or 'r') to get the outer ring of
691 // the tesselation, and sets the alpha on the path to 1/AmbientRecipAlpha (or 'a').
692 //
693 // We want to emulate this with a blur. The full blur width (2*blurRadius or 'f')
694 // can be calculated by interpolating:
695 //
696 // original edge outer edge
697 // | |<---------- r ------>|
698 // |<------|--- f -------------->|
699 // | | |
700 // alpha = 1 alpha = a alpha = 0
701 //
702 // Taking ratios, f/1 = r/a, so f = r/a and blurRadius = f/2.
703 //
704 // We now need to outset the path to place the new edge in the center of the
705 // blur region:
706 //
707 // original new
708 // | |<------|--- r ------>|
709 // |<------|--- f -|------------>|
710 // | |<- o ->|<--- f/2 --->|
711 //
712 // r = o + f/2, so o = r - f/2
713 //
714 // We outset by using the stroker, so the strokeWidth is o/2.
715 //
716 SkScalar devSpaceOutset = SkDrawShadowMetrics::AmbientBlurRadius(zPlaneParams.fZ);
717 SkScalar oneOverA = SkDrawShadowMetrics::AmbientRecipAlpha(zPlaneParams.fZ);
718 SkScalar blurRadius = 0.5f*devSpaceOutset*oneOverA;
719 SkScalar strokeWidth = 0.5f*(devSpaceOutset - blurRadius);
720
721 // Now draw with blur
722 SkPaint paint;
723 paint.setColor(rec.fAmbientColor);
724 paint.setStrokeWidth(strokeWidth);
725 paint.setStyle(SkPaint::kStrokeAndFill_Style);
726 SkScalar sigma = SkBlurMask::ConvertRadiusToSigma(blurRadius);
727 bool respectCTM = false;
728 paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, sigma, respectCTM));
729 this->drawPath(devSpacePath, paint, true);
730 }
731 }
732
733 if (SkColorGetA(rec.fSpotColor) > 0) {
734 bool success = false;
735 #if !defined(SK_ENABLE_OPTIMIZE_SIZE)
736 if (uncached && !useBlur) {
737 sk_sp<SkVertices> vertices = SkShadowTessellator::MakeSpot(path, viewMatrix,
738 zPlaneParams,
739 devLightPos, lightRadius,
740 transparent,
741 directional);
742 if (vertices) {
743 SkPaint paint;
744 // Run the vertex color through a GaussianColorFilter and then modulate the
745 // grayscale result of that against our 'color' param.
746 paint.setColorFilter(
747 SkColorFilters::Blend(rec.fSpotColor,
748 SkBlendMode::kModulate)->makeComposed(
749 SkColorFilterPriv::MakeGaussian()));
750 // The vertex colors for a tesselated shadow polygon are always either opaque black
751 // or transparent and their real contribution to the final blended color is via
752 // their alpha. We can skip expensive per-vertex color conversion for this.
753 this->drawVertices(vertices.get(),
754 SkBlender::Mode(SkBlendMode::kModulate),
755 paint,
756 /*skipColorXform=*/true);
757 success = true;
758 }
759 }
760
761 if (!success && !useBlur) {
762 SpotVerticesFactory factory;
763 factory.fOccluderHeight = zPlaneParams.fZ;
764 factory.fDevLightPos = devLightPos;
765 factory.fLightRadius = lightRadius;
766
767 SkPoint center = SkPoint::Make(path.getBounds().centerX(), path.getBounds().centerY());
768 factory.fLocalCenter = center;
769 viewMatrix.mapPoints(¢er, 1);
770 SkScalar radius, scale;
771 if (SkToBool(rec.fFlags & kDirectionalLight_ShadowFlag)) {
772 SkDrawShadowMetrics::GetDirectionalParams(zPlaneParams.fZ, devLightPos.fX,
773 devLightPos.fY, devLightPos.fZ,
774 lightRadius, &radius, &scale,
775 &factory.fOffset);
776 } else {
777 SkDrawShadowMetrics::GetSpotParams(zPlaneParams.fZ, devLightPos.fX - center.fX,
778 devLightPos.fY - center.fY, devLightPos.fZ,
779 lightRadius, &radius, &scale, &factory.fOffset);
780 }
781
782 SkRect devBounds;
783 viewMatrix.mapRect(&devBounds, path.getBounds());
784 if (transparent ||
785 SkTAbs(factory.fOffset.fX) > 0.5f*devBounds.width() ||
786 SkTAbs(factory.fOffset.fY) > 0.5f*devBounds.height()) {
787 // if the translation of the shadow is big enough we're going to end up
788 // filling the entire umbra, we can treat these as all the same
789 if (directional) {
790 factory.fOccluderType =
791 SpotVerticesFactory::OccluderType::kDirectionalTransparent;
792 } else {
793 factory.fOccluderType = SpotVerticesFactory::OccluderType::kPointTransparent;
794 }
795 } else if (directional) {
796 factory.fOccluderType = SpotVerticesFactory::OccluderType::kDirectional;
797 } else if (factory.fOffset.length()*scale + scale < radius) {
798 // if we don't translate more than the blur distance, can assume umbra is covered
799 factory.fOccluderType = SpotVerticesFactory::OccluderType::kPointOpaqueNoUmbra;
800 } else if (path.isConvex()) {
801 factory.fOccluderType = SpotVerticesFactory::OccluderType::kPointOpaquePartialUmbra;
802 } else {
803 factory.fOccluderType = SpotVerticesFactory::OccluderType::kPointTransparent;
804 }
805 // need to add this after we classify the shadow
806 factory.fOffset.fX += viewMatrix.getTranslateX();
807 factory.fOffset.fY += viewMatrix.getTranslateY();
808
809 SkColor color = rec.fSpotColor;
810 #ifdef DEBUG_SHADOW_CHECKS
811 switch (factory.fOccluderType) {
812 case SpotVerticesFactory::OccluderType::kPointTransparent:
813 color = 0xFFD2B48C; // tan for transparent
814 break;
815 case SpotVerticesFactory::OccluderType::kPointOpaquePartialUmbra:
816 color = 0xFFFFA500; // orange for opaque
817 break;
818 case SpotVerticesFactory::OccluderType::kPointOpaqueNoUmbra:
819 color = 0xFFE5E500; // corn yellow for covered
820 break;
821 case SpotVerticesFactory::OccluderType::kDirectional:
822 case SpotVerticesFactory::OccluderType::kDirectionalTransparent:
823 color = 0xFF550000; // dark red for directional
824 break;
825 }
826 #endif
827 success = draw_shadow(factory, drawVertsProc, shadowedPath, color);
828 }
829 #endif // !defined(SK_ENABLE_OPTIMIZE_SIZE)
830
831 // All else has failed, draw with blur
832 if (!success) {
833 SkMatrix shadowMatrix;
834 SkScalar radius;
835 if (!SkDrawShadowMetrics::GetSpotShadowTransform(devLightPos, lightRadius,
836 viewMatrix, zPlaneParams,
837 path.getBounds(), directional,
838 &shadowMatrix, &radius)) {
839 return;
840 }
841 SkAutoDeviceTransformRestore adr2(this, SkM44(shadowMatrix));
842
843 SkPaint paint;
844 paint.setColor(rec.fSpotColor);
845 SkScalar sigma = SkBlurMask::ConvertRadiusToSigma(radius);
846 bool respectCTM = false;
847 paint.setMaskFilter(SkMaskFilter::MakeBlur(kNormal_SkBlurStyle, sigma, respectCTM));
848 this->drawPath(path, paint, false);
849 }
850 }
851 }
852