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