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