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 "SkShadowUtils.h"
9 #include "SkBlurMaskFilter.h"
10 #include "SkCanvas.h"
11 #include "SkColorFilter.h"
12 #include "SkColorData.h"
13 #include "SkDevice.h"
14 #include "SkDrawShadowInfo.h"
15 #include "SkPath.h"
16 #include "SkPM4f.h"
17 #include "SkRandom.h"
18 #include "SkRasterPipeline.h"
19 #include "SkResourceCache.h"
20 #include "SkShadowTessellator.h"
21 #include "SkString.h"
22 #include "SkTLazy.h"
23 #include "SkVertices.h"
24 #if SK_SUPPORT_GPU
25 #include "GrShape.h"
26 #include "effects/GrBlurredEdgeFragmentProcessor.h"
27 #endif
28
29 /**
30 * Gaussian color filter -- produces a Gaussian ramp based on the color's B value,
31 * then blends with the color's G value.
32 * Final result is black with alpha of Gaussian(B)*G.
33 * The assumption is that the original color's alpha is 1.
34 */
35 class SkGaussianColorFilter : public SkColorFilter {
36 public:
Make()37 static sk_sp<SkColorFilter> Make() {
38 return sk_sp<SkColorFilter>(new SkGaussianColorFilter);
39 }
40
41 #if SK_SUPPORT_GPU
42 std::unique_ptr<GrFragmentProcessor> asFragmentProcessor(
43 GrContext*, const GrColorSpaceInfo&) const override;
44 #endif
45
46 SK_TO_STRING_OVERRIDE()
47 SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkGaussianColorFilter)
48
49 protected:
flatten(SkWriteBuffer &) const50 void flatten(SkWriteBuffer&) const override {}
onAppendStages(SkRasterPipeline * pipeline,SkColorSpace * dstCS,SkArenaAlloc * alloc,bool shaderIsOpaque) const51 void onAppendStages(SkRasterPipeline* pipeline, SkColorSpace* dstCS, SkArenaAlloc* alloc,
52 bool shaderIsOpaque) const override {
53 pipeline->append(SkRasterPipeline::gauss_a_to_rgba);
54 }
55 private:
SkGaussianColorFilter()56 SkGaussianColorFilter() : INHERITED() {}
57
58 typedef SkColorFilter INHERITED;
59 };
60
CreateProc(SkReadBuffer &)61 sk_sp<SkFlattenable> SkGaussianColorFilter::CreateProc(SkReadBuffer&) {
62 return Make();
63 }
64
65 #ifndef SK_IGNORE_TO_STRING
toString(SkString * str) const66 void SkGaussianColorFilter::toString(SkString* str) const {
67 str->append("SkGaussianColorFilter ");
68 }
69 #endif
70
71 #if SK_SUPPORT_GPU
72
asFragmentProcessor(GrContext *,const GrColorSpaceInfo &) const73 std::unique_ptr<GrFragmentProcessor> SkGaussianColorFilter::asFragmentProcessor(
74 GrContext*, const GrColorSpaceInfo&) const {
75 return GrBlurredEdgeFragmentProcessor::Make(GrBlurredEdgeFragmentProcessor::Mode::kGaussian);
76 }
77 #endif
78
79 ///////////////////////////////////////////////////////////////////////////////////////////////////
80
81 namespace {
82
resource_cache_shared_id()83 uint64_t resource_cache_shared_id() {
84 return 0x2020776f64616873llu; // 'shadow '
85 }
86
87 /** Factory for an ambient shadow mesh with particular shadow properties. */
88 struct AmbientVerticesFactory {
89 SkScalar fOccluderHeight = SK_ScalarNaN; // NaN so that isCompatible will fail until init'ed.
90 bool fTransparent;
91 SkVector fOffset;
92
isCompatible__anon565577e20111::AmbientVerticesFactory93 bool isCompatible(const AmbientVerticesFactory& that, SkVector* translate) const {
94 if (fOccluderHeight != that.fOccluderHeight || fTransparent != that.fTransparent) {
95 return false;
96 }
97 *translate = that.fOffset;
98 return true;
99 }
100
makeVertices__anon565577e20111::AmbientVerticesFactory101 sk_sp<SkVertices> makeVertices(const SkPath& path, const SkMatrix& ctm,
102 SkVector* translate) const {
103 SkPoint3 zParams = SkPoint3::Make(0, 0, fOccluderHeight);
104 // pick a canonical place to generate shadow
105 SkMatrix noTrans(ctm);
106 if (!ctm.hasPerspective()) {
107 noTrans[SkMatrix::kMTransX] = 0;
108 noTrans[SkMatrix::kMTransY] = 0;
109 }
110 *translate = fOffset;
111 return SkShadowTessellator::MakeAmbient(path, noTrans, zParams, fTransparent);
112 }
113 };
114
115 /** Factory for an spot shadow mesh with particular shadow properties. */
116 struct SpotVerticesFactory {
117 enum class OccluderType {
118 // The umbra cannot be dropped out because either the occluder is not opaque,
119 // or the center of the umbra is visible.
120 kTransparent,
121 // The umbra can be dropped where it is occluded.
122 kOpaquePartialUmbra,
123 // It is known that the entire umbra is occluded.
124 kOpaqueNoUmbra
125 };
126
127 SkVector fOffset;
128 SkPoint fLocalCenter;
129 SkScalar fOccluderHeight = SK_ScalarNaN; // NaN so that isCompatible will fail until init'ed.
130 SkPoint3 fDevLightPos;
131 SkScalar fLightRadius;
132 OccluderType fOccluderType;
133
isCompatible__anon565577e20111::SpotVerticesFactory134 bool isCompatible(const SpotVerticesFactory& that, SkVector* translate) const {
135 if (fOccluderHeight != that.fOccluderHeight || fDevLightPos.fZ != that.fDevLightPos.fZ ||
136 fLightRadius != that.fLightRadius || fOccluderType != that.fOccluderType) {
137 return false;
138 }
139 switch (fOccluderType) {
140 case OccluderType::kTransparent:
141 case OccluderType::kOpaqueNoUmbra:
142 // 'this' and 'that' will either both have no umbra removed or both have all the
143 // umbra removed.
144 *translate = that.fOffset;
145 return true;
146 case OccluderType::kOpaquePartialUmbra:
147 // In this case we partially remove the umbra differently for 'this' and 'that'
148 // if the offsets don't match.
149 if (fOffset == that.fOffset) {
150 translate->set(0, 0);
151 return true;
152 }
153 return false;
154 }
155 SK_ABORT("Uninitialized occluder type?");
156 return false;
157 }
158
makeVertices__anon565577e20111::SpotVerticesFactory159 sk_sp<SkVertices> makeVertices(const SkPath& path, const SkMatrix& ctm,
160 SkVector* translate) const {
161 bool transparent = OccluderType::kTransparent == fOccluderType;
162 SkPoint3 zParams = SkPoint3::Make(0, 0, fOccluderHeight);
163 if (ctm.hasPerspective() || OccluderType::kOpaquePartialUmbra == fOccluderType) {
164 translate->set(0, 0);
165 return SkShadowTessellator::MakeSpot(path, ctm, zParams,
166 fDevLightPos, fLightRadius, transparent);
167 } else {
168 // pick a canonical place to generate shadow, with light centered over path
169 SkMatrix noTrans(ctm);
170 noTrans[SkMatrix::kMTransX] = 0;
171 noTrans[SkMatrix::kMTransY] = 0;
172 SkPoint devCenter(fLocalCenter);
173 noTrans.mapPoints(&devCenter, 1);
174 SkPoint3 centerLightPos = SkPoint3::Make(devCenter.fX, devCenter.fY, fDevLightPos.fZ);
175 *translate = fOffset;
176 return SkShadowTessellator::MakeSpot(path, noTrans, zParams,
177 centerLightPos, fLightRadius, transparent);
178 }
179 }
180 };
181
182 /**
183 * This manages a set of tessellations for a given shape in the cache. Because SkResourceCache
184 * records are immutable this is not itself a Rec. When we need to update it we return this on
185 * the FindVisitor and let the cache destroy the Rec. We'll update the tessellations and then add
186 * a new Rec with an adjusted size for any deletions/additions.
187 */
188 class CachedTessellations : public SkRefCnt {
189 public:
size() const190 size_t size() const { return fAmbientSet.size() + fSpotSet.size(); }
191
find(const AmbientVerticesFactory & ambient,const SkMatrix & matrix,SkVector * translate) const192 sk_sp<SkVertices> find(const AmbientVerticesFactory& ambient, const SkMatrix& matrix,
193 SkVector* translate) const {
194 return fAmbientSet.find(ambient, matrix, translate);
195 }
196
add(const SkPath & devPath,const AmbientVerticesFactory & ambient,const SkMatrix & matrix,SkVector * translate)197 sk_sp<SkVertices> add(const SkPath& devPath, const AmbientVerticesFactory& ambient,
198 const SkMatrix& matrix, SkVector* translate) {
199 return fAmbientSet.add(devPath, ambient, matrix, translate);
200 }
201
find(const SpotVerticesFactory & spot,const SkMatrix & matrix,SkVector * translate) const202 sk_sp<SkVertices> find(const SpotVerticesFactory& spot, const SkMatrix& matrix,
203 SkVector* translate) const {
204 return fSpotSet.find(spot, matrix, translate);
205 }
206
add(const SkPath & devPath,const SpotVerticesFactory & spot,const SkMatrix & matrix,SkVector * translate)207 sk_sp<SkVertices> add(const SkPath& devPath, const SpotVerticesFactory& spot,
208 const SkMatrix& matrix, SkVector* translate) {
209 return fSpotSet.add(devPath, spot, matrix, translate);
210 }
211
212 private:
213 template <typename FACTORY, int MAX_ENTRIES>
214 class Set {
215 public:
size() const216 size_t size() const { return fSize; }
217
find(const FACTORY & factory,const SkMatrix & matrix,SkVector * translate) const218 sk_sp<SkVertices> find(const FACTORY& factory, const SkMatrix& matrix,
219 SkVector* translate) const {
220 for (int i = 0; i < MAX_ENTRIES; ++i) {
221 if (fEntries[i].fFactory.isCompatible(factory, translate)) {
222 const SkMatrix& m = fEntries[i].fMatrix;
223 if (matrix.hasPerspective() || m.hasPerspective()) {
224 if (matrix != fEntries[i].fMatrix) {
225 continue;
226 }
227 } else if (matrix.getScaleX() != m.getScaleX() ||
228 matrix.getSkewX() != m.getSkewX() ||
229 matrix.getScaleY() != m.getScaleY() ||
230 matrix.getSkewY() != m.getSkewY()) {
231 continue;
232 }
233 return fEntries[i].fVertices;
234 }
235 }
236 return nullptr;
237 }
238
add(const SkPath & path,const FACTORY & factory,const SkMatrix & matrix,SkVector * translate)239 sk_sp<SkVertices> add(const SkPath& path, const FACTORY& factory, const SkMatrix& matrix,
240 SkVector* translate) {
241 sk_sp<SkVertices> vertices = factory.makeVertices(path, matrix, translate);
242 if (!vertices) {
243 return nullptr;
244 }
245 int i;
246 if (fCount < MAX_ENTRIES) {
247 i = fCount++;
248 } else {
249 i = fRandom.nextULessThan(MAX_ENTRIES);
250 fSize -= fEntries[i].fVertices->approximateSize();
251 }
252 fEntries[i].fFactory = factory;
253 fEntries[i].fVertices = vertices;
254 fEntries[i].fMatrix = matrix;
255 fSize += vertices->approximateSize();
256 return vertices;
257 }
258
259 private:
260 struct Entry {
261 FACTORY fFactory;
262 sk_sp<SkVertices> fVertices;
263 SkMatrix fMatrix;
264 };
265 Entry fEntries[MAX_ENTRIES];
266 int fCount = 0;
267 size_t fSize = 0;
268 SkRandom fRandom;
269 };
270
271 Set<AmbientVerticesFactory, 4> fAmbientSet;
272 Set<SpotVerticesFactory, 4> fSpotSet;
273 };
274
275 /**
276 * A record of shadow vertices stored in SkResourceCache of CachedTessellations for a particular
277 * path. The key represents the path's geometry and not any shadow params.
278 */
279 class CachedTessellationsRec : public SkResourceCache::Rec {
280 public:
CachedTessellationsRec(const SkResourceCache::Key & key,sk_sp<CachedTessellations> tessellations)281 CachedTessellationsRec(const SkResourceCache::Key& key,
282 sk_sp<CachedTessellations> tessellations)
283 : fTessellations(std::move(tessellations)) {
284 fKey.reset(new uint8_t[key.size()]);
285 memcpy(fKey.get(), &key, key.size());
286 }
287
getKey() const288 const Key& getKey() const override {
289 return *reinterpret_cast<SkResourceCache::Key*>(fKey.get());
290 }
291
bytesUsed() const292 size_t bytesUsed() const override { return fTessellations->size(); }
293
getCategory() const294 const char* getCategory() const override { return "tessellated shadow masks"; }
295
refTessellations() const296 sk_sp<CachedTessellations> refTessellations() const { return fTessellations; }
297
298 template <typename FACTORY>
find(const FACTORY & factory,const SkMatrix & matrix,SkVector * translate) const299 sk_sp<SkVertices> find(const FACTORY& factory, const SkMatrix& matrix,
300 SkVector* translate) const {
301 return fTessellations->find(factory, matrix, translate);
302 }
303
304 private:
305 std::unique_ptr<uint8_t[]> fKey;
306 sk_sp<CachedTessellations> fTessellations;
307 };
308
309 /**
310 * Used by FindVisitor to determine whether a cache entry can be reused and if so returns the
311 * vertices and a translation vector. If the CachedTessellations does not contain a suitable
312 * mesh then we inform SkResourceCache to destroy the Rec and we return the CachedTessellations
313 * to the caller. The caller will update it and reinsert it back into the cache.
314 */
315 template <typename FACTORY>
316 struct FindContext {
FindContext__anon565577e20111::FindContext317 FindContext(const SkMatrix* viewMatrix, const FACTORY* factory)
318 : fViewMatrix(viewMatrix), fFactory(factory) {}
319 const SkMatrix* const fViewMatrix;
320 // If this is valid after Find is called then we found the vertices and they should be drawn
321 // with fTranslate applied.
322 sk_sp<SkVertices> fVertices;
323 SkVector fTranslate = {0, 0};
324
325 // If this is valid after Find then the caller should add the vertices to the tessellation set
326 // and create a new CachedTessellationsRec and insert it into SkResourceCache.
327 sk_sp<CachedTessellations> fTessellationsOnFailure;
328
329 const FACTORY* fFactory;
330 };
331
332 /**
333 * Function called by SkResourceCache when a matching cache key is found. The FACTORY and matrix of
334 * the FindContext are used to determine if the vertices are reusable. If so the vertices and
335 * necessary translation vector are set on the FindContext.
336 */
337 template <typename FACTORY>
FindVisitor(const SkResourceCache::Rec & baseRec,void * ctx)338 bool FindVisitor(const SkResourceCache::Rec& baseRec, void* ctx) {
339 FindContext<FACTORY>* findContext = (FindContext<FACTORY>*)ctx;
340 const CachedTessellationsRec& rec = static_cast<const CachedTessellationsRec&>(baseRec);
341 findContext->fVertices =
342 rec.find(*findContext->fFactory, *findContext->fViewMatrix, &findContext->fTranslate);
343 if (findContext->fVertices) {
344 return true;
345 }
346 // We ref the tessellations and let the cache destroy the Rec. Once the tessellations have been
347 // manipulated we will add a new Rec.
348 findContext->fTessellationsOnFailure = rec.refTessellations();
349 return false;
350 }
351
352 class ShadowedPath {
353 public:
ShadowedPath(const SkPath * path,const SkMatrix * viewMatrix)354 ShadowedPath(const SkPath* path, const SkMatrix* viewMatrix)
355 : fPath(path)
356 , fViewMatrix(viewMatrix)
357 #if SK_SUPPORT_GPU
358 , fShapeForKey(*path, GrStyle::SimpleFill())
359 #endif
360 {}
361
path() const362 const SkPath& path() const { return *fPath; }
viewMatrix() const363 const SkMatrix& viewMatrix() const { return *fViewMatrix; }
364 #if SK_SUPPORT_GPU
365 /** Negative means the vertices should not be cached for this path. */
keyBytes() const366 int keyBytes() const { return fShapeForKey.unstyledKeySize() * sizeof(uint32_t); }
writeKey(void * key) const367 void writeKey(void* key) const {
368 fShapeForKey.writeUnstyledKey(reinterpret_cast<uint32_t*>(key));
369 }
isRRect(SkRRect * rrect)370 bool isRRect(SkRRect* rrect) { return fShapeForKey.asRRect(rrect, nullptr, nullptr, nullptr); }
371 #else
keyBytes() const372 int keyBytes() const { return -1; }
writeKey(void * key) const373 void writeKey(void* key) const { SK_ABORT("Should never be called"); }
isRRect(SkRRect * rrect)374 bool isRRect(SkRRect* rrect) { return false; }
375 #endif
376
377 private:
378 const SkPath* fPath;
379 const SkMatrix* fViewMatrix;
380 #if SK_SUPPORT_GPU
381 GrShape fShapeForKey;
382 #endif
383 };
384
385 // This creates a domain of keys in SkResourceCache used by this file.
386 static void* kNamespace;
387
388 /**
389 * Draws a shadow to 'canvas'. The vertices used to draw the shadow are created by 'factory' unless
390 * they are first found in SkResourceCache.
391 */
392 template <typename FACTORY>
draw_shadow(const FACTORY & factory,std::function<void (const SkVertices *,SkBlendMode,const SkPaint &,SkScalar tx,SkScalar ty)> drawProc,ShadowedPath & path,SkColor color)393 bool draw_shadow(const FACTORY& factory,
394 std::function<void(const SkVertices*, SkBlendMode, const SkPaint&,
395 SkScalar tx, SkScalar ty)> drawProc, ShadowedPath& path, SkColor color) {
396 FindContext<FACTORY> context(&path.viewMatrix(), &factory);
397
398 SkResourceCache::Key* key = nullptr;
399 SkAutoSTArray<32 * 4, uint8_t> keyStorage;
400 int keyDataBytes = path.keyBytes();
401 if (keyDataBytes >= 0) {
402 keyStorage.reset(keyDataBytes + sizeof(SkResourceCache::Key));
403 key = new (keyStorage.begin()) SkResourceCache::Key();
404 path.writeKey((uint32_t*)(keyStorage.begin() + sizeof(*key)));
405 key->init(&kNamespace, resource_cache_shared_id(), keyDataBytes);
406 SkResourceCache::Find(*key, FindVisitor<FACTORY>, &context);
407 }
408
409 sk_sp<SkVertices> vertices;
410 bool foundInCache = SkToBool(context.fVertices);
411 if (foundInCache) {
412 vertices = std::move(context.fVertices);
413 } else {
414 // TODO: handle transforming the path as part of the tessellator
415 if (key) {
416 // Update or initialize a tessellation set and add it to the cache.
417 sk_sp<CachedTessellations> tessellations;
418 if (context.fTessellationsOnFailure) {
419 tessellations = std::move(context.fTessellationsOnFailure);
420 } else {
421 tessellations.reset(new CachedTessellations());
422 }
423 vertices = tessellations->add(path.path(), factory, path.viewMatrix(),
424 &context.fTranslate);
425 if (!vertices) {
426 return false;
427 }
428 auto rec = new CachedTessellationsRec(*key, std::move(tessellations));
429 SkResourceCache::Add(rec);
430 } else {
431 vertices = factory.makeVertices(path.path(), path.viewMatrix(),
432 &context.fTranslate);
433 if (!vertices) {
434 return false;
435 }
436 }
437 }
438
439 SkPaint paint;
440 // Run the vertex color through a GaussianColorFilter and then modulate the grayscale result of
441 // that against our 'color' param.
442 paint.setColorFilter(
443 SkColorFilter::MakeModeFilter(color, SkBlendMode::kModulate)->makeComposed(
444 SkGaussianColorFilter::Make()));
445
446 drawProc(vertices.get(), SkBlendMode::kModulate, paint,
447 context.fTranslate.fX, context.fTranslate.fY);
448
449 return true;
450 }
451 }
452
tilted(const SkPoint3 & zPlaneParams)453 static bool tilted(const SkPoint3& zPlaneParams) {
454 return !SkScalarNearlyZero(zPlaneParams.fX) || !SkScalarNearlyZero(zPlaneParams.fY);
455 }
456
map(const SkMatrix & m,const SkPoint3 & pt)457 static SkPoint3 map(const SkMatrix& m, const SkPoint3& pt) {
458 SkPoint3 result;
459 m.mapXY(pt.fX, pt.fY, (SkPoint*)&result.fX);
460 result.fZ = pt.fZ;
461 return result;
462 }
463
ComputeTonalColors(SkColor inAmbientColor,SkColor inSpotColor,SkColor * outAmbientColor,SkColor * outSpotColor)464 void SkShadowUtils::ComputeTonalColors(SkColor inAmbientColor, SkColor inSpotColor,
465 SkColor* outAmbientColor, SkColor* outSpotColor) {
466 // For tonal color we only compute color values for the spot shadow.
467 // The ambient shadow is greyscale only.
468
469 // Ambient
470 *outAmbientColor = SkColorSetARGB(SkColorGetA(inAmbientColor), 0, 0, 0);
471
472 // Spot
473 int spotR = SkColorGetR(inSpotColor);
474 int spotG = SkColorGetG(inSpotColor);
475 int spotB = SkColorGetB(inSpotColor);
476 int max = SkTMax(SkTMax(spotR, spotG), spotB);
477 int min = SkTMin(SkTMin(spotR, spotG), spotB);
478 SkScalar luminance = 0.5f*(max + min)/255.f;
479 SkScalar origA = SkColorGetA(inSpotColor)/255.f;
480
481 // We compute a color alpha value based on the luminance of the color, scaled by an
482 // adjusted alpha value. We want the following properties to match the UX examples
483 // (assuming a = 0.25) and to ensure that we have reasonable results when the color
484 // is black and/or the alpha is 0:
485 // f(0, a) = 0
486 // f(luminance, 0) = 0
487 // f(1, 0.25) = .5
488 // f(0.5, 0.25) = .4
489 // f(1, 1) = 1
490 // The following functions match this as closely as possible.
491 SkScalar alphaAdjust = (2.6f + (-2.66667f + 1.06667f*origA)*origA)*origA;
492 SkScalar colorAlpha = (3.544762f + (-4.891428f + 2.3466f*luminance)*luminance)*luminance;
493 colorAlpha = SkTPin(alphaAdjust*colorAlpha, 0.0f, 1.0f);
494
495 // Similarly, we set the greyscale alpha based on luminance and alpha so that
496 // f(0, a) = a
497 // f(luminance, 0) = 0
498 // f(1, 0.25) = 0.15
499 SkScalar greyscaleAlpha = SkTPin(origA*(1 - 0.4f*luminance), 0.0f, 1.0f);
500
501 // The final color we want to emulate is generated by rendering a color shadow (C_rgb) using an
502 // alpha computed from the color's luminance (C_a), and then a black shadow with alpha (S_a)
503 // which is an adjusted value of 'a'. Assuming SrcOver, a background color of B_rgb, and
504 // ignoring edge falloff, this becomes
505 //
506 // (C_a - S_a*C_a)*C_rgb + (1 - (S_a + C_a - S_a*C_a))*B_rgb
507 //
508 // Assuming premultiplied alpha, this means we scale the color by (C_a - S_a*C_a) and
509 // set the alpha to (S_a + C_a - S_a*C_a).
510 SkScalar colorScale = colorAlpha*(SK_Scalar1 - greyscaleAlpha);
511 SkScalar tonalAlpha = colorScale + greyscaleAlpha;
512 SkScalar unPremulScale = colorScale / tonalAlpha;
513 *outSpotColor = SkColorSetARGB(tonalAlpha*255.999f,
514 unPremulScale*spotR,
515 unPremulScale*spotG,
516 unPremulScale*spotB);
517 }
518
519 // Draw an offset spot shadow and outlining ambient shadow for the given path.
DrawShadow(SkCanvas * canvas,const SkPath & path,const SkPoint3 & zPlaneParams,const SkPoint3 & devLightPos,SkScalar lightRadius,SkColor ambientColor,SkColor spotColor,uint32_t flags)520 void SkShadowUtils::DrawShadow(SkCanvas* canvas, const SkPath& path, const SkPoint3& zPlaneParams,
521 const SkPoint3& devLightPos, SkScalar lightRadius,
522 SkColor ambientColor, SkColor spotColor,
523 uint32_t flags) {
524 SkMatrix inverse;
525 if (!canvas->getTotalMatrix().invert(&inverse)) {
526 return;
527 }
528 SkPoint pt = inverse.mapXY(devLightPos.fX, devLightPos.fY);
529
530 SkDrawShadowRec rec;
531 rec.fZPlaneParams = zPlaneParams;
532 rec.fLightPos = { pt.fX, pt.fY, devLightPos.fZ };
533 rec.fLightRadius = lightRadius;
534 rec.fAmbientColor = ambientColor;
535 rec.fSpotColor = spotColor;
536 rec.fFlags = flags;
537
538 canvas->private_draw_shadow_rec(path, rec);
539 }
540
validate_rec(const SkDrawShadowRec & rec)541 static bool validate_rec(const SkDrawShadowRec& rec) {
542 return rec.fLightPos.isFinite() && rec.fZPlaneParams.isFinite() &&
543 SkScalarIsFinite(rec.fLightRadius);
544 }
545
drawShadow(const SkPath & path,const SkDrawShadowRec & rec)546 void SkBaseDevice::drawShadow(const SkPath& path, const SkDrawShadowRec& rec) {
547 auto drawVertsProc = [this](const SkVertices* vertices, SkBlendMode mode, const SkPaint& paint,
548 SkScalar tx, SkScalar ty) {
549 SkAutoDeviceCTMRestore adr(this, SkMatrix::Concat(this->ctm(),
550 SkMatrix::MakeTrans(tx, ty)));
551 this->drawVertices(vertices, mode, paint);
552 };
553
554 if (!validate_rec(rec)) {
555 return;
556 }
557
558 SkMatrix viewMatrix = this->ctm();
559 SkAutoDeviceCTMRestore adr(this, SkMatrix::I());
560
561 ShadowedPath shadowedPath(&path, &viewMatrix);
562
563 bool tiltZPlane = tilted(rec.fZPlaneParams);
564 bool transparent = SkToBool(rec.fFlags & SkShadowFlags::kTransparentOccluder_ShadowFlag);
565 bool uncached = tiltZPlane || path.isVolatile();
566
567 SkPoint3 zPlaneParams = rec.fZPlaneParams;
568 SkPoint3 devLightPos = map(viewMatrix, rec.fLightPos);
569 float lightRadius = rec.fLightRadius;
570
571 if (SkColorGetA(rec.fAmbientColor) > 0) {
572 bool success = false;
573 if (uncached) {
574 sk_sp<SkVertices> vertices = SkShadowTessellator::MakeAmbient(path, viewMatrix,
575 zPlaneParams,
576 transparent);
577 if (vertices) {
578 SkPaint paint;
579 // Run the vertex color through a GaussianColorFilter and then modulate the
580 // grayscale result of that against our 'color' param.
581 paint.setColorFilter(
582 SkColorFilter::MakeModeFilter(rec.fAmbientColor,
583 SkBlendMode::kModulate)->makeComposed(
584 SkGaussianColorFilter::Make()));
585 this->drawVertices(vertices.get(), SkBlendMode::kModulate, paint);
586 success = true;
587 }
588 }
589
590 if (!success) {
591 AmbientVerticesFactory factory;
592 factory.fOccluderHeight = zPlaneParams.fZ;
593 factory.fTransparent = transparent;
594 if (viewMatrix.hasPerspective()) {
595 factory.fOffset.set(0, 0);
596 } else {
597 factory.fOffset.fX = viewMatrix.getTranslateX();
598 factory.fOffset.fY = viewMatrix.getTranslateY();
599 }
600
601 if (!draw_shadow(factory, drawVertsProc, shadowedPath, rec.fAmbientColor)) {
602 // Pretransform the path to avoid transforming the stroke, below.
603 SkPath devSpacePath;
604 path.transform(viewMatrix, &devSpacePath);
605
606 // The tesselator outsets by AmbientBlurRadius (or 'r') to get the outer ring of
607 // the tesselation, uses the original path as the inner ring, and sets the alpha
608 // of the inner ring to 1/AmbientRecipAlpha (or 'a').
609 //
610 // We want to emulate this with a blur. The full blur width (2*blurRadius or 'f')
611 // can be calculated by interpolating:
612 //
613 // original edge outer edge
614 // | |<---------- r ------>|
615 // |<------|--- f -------------->|
616 // | | |
617 // alpha = 1 alpha = a alpha = 0
618 //
619 // Taking ratios, f/1 = r/a, so f = r/a and blurRadius = f/2.
620 //
621 // We now need to outset the path to place the new edge in the center of the
622 // blur region:
623 //
624 // original new
625 // | |<------|--- r ------>|
626 // |<------|--- f -|------------>|
627 // | |<- o ->|<--- f/2 --->|
628 //
629 // r = o + f/2, so o = r - f/2
630 //
631 // We outset by using the stroker, so the strokeWidth is o/2.
632 //
633 SkScalar devSpaceOutset = SkDrawShadowMetrics::AmbientBlurRadius(zPlaneParams.fZ);
634 SkScalar oneOverA = SkDrawShadowMetrics::AmbientRecipAlpha(zPlaneParams.fZ);
635 SkScalar blurRadius = 0.5f*devSpaceOutset*oneOverA;
636 SkScalar strokeWidth = 0.5f*(devSpaceOutset - blurRadius);
637
638 // Now draw with blur
639 SkPaint paint;
640 paint.setColor(rec.fAmbientColor);
641 paint.setStrokeWidth(strokeWidth);
642 paint.setStyle(SkPaint::kStrokeAndFill_Style);
643 SkScalar sigma = SkBlurMaskFilter::ConvertRadiusToSigma(blurRadius);
644 uint32_t flags = SkBlurMaskFilter::kIgnoreTransform_BlurFlag;
645 paint.setMaskFilter(SkBlurMaskFilter::Make(kNormal_SkBlurStyle, sigma, flags));
646 this->drawPath(devSpacePath, paint);
647 }
648 }
649 }
650
651 if (SkColorGetA(rec.fSpotColor) > 0) {
652 bool success = false;
653 if (uncached) {
654 sk_sp<SkVertices> vertices = SkShadowTessellator::MakeSpot(path, viewMatrix,
655 zPlaneParams,
656 devLightPos, lightRadius,
657 transparent);
658 if (vertices) {
659 SkPaint paint;
660 // Run the vertex color through a GaussianColorFilter and then modulate the
661 // grayscale result of that against our 'color' param.
662 paint.setColorFilter(
663 SkColorFilter::MakeModeFilter(rec.fSpotColor,
664 SkBlendMode::kModulate)->makeComposed(
665 SkGaussianColorFilter::Make()));
666 this->drawVertices(vertices.get(), SkBlendMode::kModulate, paint);
667 success = true;
668 }
669 }
670
671 if (!success) {
672 SpotVerticesFactory factory;
673 factory.fOccluderHeight = zPlaneParams.fZ;
674 factory.fDevLightPos = devLightPos;
675 factory.fLightRadius = lightRadius;
676
677 SkPoint center = SkPoint::Make(path.getBounds().centerX(), path.getBounds().centerY());
678 factory.fLocalCenter = center;
679 viewMatrix.mapPoints(¢er, 1);
680 SkScalar radius, scale;
681 SkDrawShadowMetrics::GetSpotParams(zPlaneParams.fZ, devLightPos.fX - center.fX,
682 devLightPos.fY - center.fY, devLightPos.fZ,
683 lightRadius, &radius, &scale, &factory.fOffset);
684 SkRect devBounds;
685 viewMatrix.mapRect(&devBounds, path.getBounds());
686 if (transparent ||
687 SkTAbs(factory.fOffset.fX) > 0.5f*devBounds.width() ||
688 SkTAbs(factory.fOffset.fY) > 0.5f*devBounds.height()) {
689 // if the translation of the shadow is big enough we're going to end up
690 // filling the entire umbra, so we can treat these as all the same
691 factory.fOccluderType = SpotVerticesFactory::OccluderType::kTransparent;
692 } else if (factory.fOffset.length()*scale + scale < radius) {
693 // if we don't translate more than the blur distance, can assume umbra is covered
694 factory.fOccluderType = SpotVerticesFactory::OccluderType::kOpaqueNoUmbra;
695 } else {
696 factory.fOccluderType = SpotVerticesFactory::OccluderType::kOpaquePartialUmbra;
697 }
698 // need to add this after we classify the shadow
699 factory.fOffset.fX += viewMatrix.getTranslateX();
700 factory.fOffset.fY += viewMatrix.getTranslateY();
701
702 SkColor color = rec.fSpotColor;
703 #ifdef DEBUG_SHADOW_CHECKS
704 switch (factory.fOccluderType) {
705 case SpotVerticesFactory::OccluderType::kTransparent:
706 color = 0xFFD2B48C; // tan for transparent
707 break;
708 case SpotVerticesFactory::OccluderType::kOpaquePartialUmbra:
709 color = 0xFFFFA500; // orange for opaque
710 break;
711 case SpotVerticesFactory::OccluderType::kOpaqueNoUmbra:
712 color = 0xFFE5E500; // corn yellow for covered
713 break;
714 }
715 #endif
716 if (!draw_shadow(factory, drawVertsProc, shadowedPath, color)) {
717 // draw with blur
718 SkVector translate;
719 SkDrawShadowMetrics::GetSpotParams(zPlaneParams.fZ, devLightPos.fX,
720 devLightPos.fY, devLightPos.fZ,
721 lightRadius, &radius, &scale, &translate);
722 SkMatrix shadowMatrix;
723 shadowMatrix.setScaleTranslate(scale, scale, translate.fX, translate.fY);
724 SkAutoDeviceCTMRestore adr(this, SkMatrix::Concat(shadowMatrix, viewMatrix));
725
726 SkPaint paint;
727 paint.setColor(rec.fSpotColor);
728 SkScalar sigma = SkBlurMaskFilter::ConvertRadiusToSigma(radius);
729 uint32_t flags = SkBlurMaskFilter::kIgnoreTransform_BlurFlag;
730 paint.setMaskFilter(SkBlurMaskFilter::Make(kNormal_SkBlurStyle, sigma, flags));
731 this->drawPath(path, paint);
732 }
733 }
734 }
735 }
736