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