• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2006 The Android Open Source Project
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/core/SkBitmap.h"
9 #include "include/core/SkMaskFilter.h"
10 #include "include/core/SkPathBuilder.h"
11 #include "include/core/SkRRect.h"
12 #include "include/core/SkStrokeRec.h"
13 #include "include/core/SkVertices.h"
14 #include "src/core/SkBlurMask.h"
15 #include "src/core/SkGpuBlurUtils.h"
16 #include "src/core/SkMaskFilterBase.h"
17 #include "src/core/SkMathPriv.h"
18 #include "src/core/SkMatrixProvider.h"
19 #include "src/core/SkRRectPriv.h"
20 #include "src/core/SkReadBuffer.h"
21 #include "src/core/SkStringUtils.h"
22 #include "src/core/SkSDFFilter.h"
23 #include "src/core/SkWriteBuffer.h"
24 
25 #if SK_SUPPORT_GPU
26 #include "include/gpu/GrRecordingContext.h"
27 #include "src/core/SkRuntimeEffectPriv.h"
28 #include "src/gpu/GrFragmentProcessor.h"
29 #include "src/gpu/GrRecordingContextPriv.h"
30 #include "src/gpu/GrResourceProvider.h"
31 #include "src/gpu/GrShaderCaps.h"
32 #include "src/gpu/GrStyle.h"
33 #include "src/gpu/GrTextureProxy.h"
34 #include "src/gpu/GrThreadSafeCache.h"
35 #include "src/gpu/SkGr.h"
36 #include "src/gpu/effects/GrMatrixEffect.h"
37 #include "src/gpu/effects/GrSkSLFP.h"
38 #include "src/gpu/effects/GrTextureEffect.h"
39 #include "src/gpu/geometry/GrStyledShape.h"
40 #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
41 #include "src/gpu/glsl/GrGLSLProgramDataManager.h"
42 #include "src/gpu/glsl/GrGLSLUniformHandler.h"
43 #if SK_GPU_V1
44 #include "src/gpu/v1/SurfaceDrawContext_v1.h"
45 #endif // SK_GPU_V1
46 #endif // SK_SUPPORT_GPU
47 
48 class SkBlurMaskFilterImpl : public SkMaskFilterBase {
49 public:
50     SkBlurMaskFilterImpl(SkScalar sigma, SkBlurStyle, bool respectCTM);
51 
52     // overrides from SkMaskFilter
53     SkMask::Format getFormat() const override;
54     bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&,
55                     SkIPoint* margin) const override;
56 
57 #if SK_SUPPORT_GPU && SK_GPU_V1
58     bool canFilterMaskGPU(const GrStyledShape& shape,
59                           const SkIRect& devSpaceShapeBounds,
60                           const SkIRect& clipBounds,
61                           const SkMatrix& ctm,
62                           SkIRect* maskRect,
63                           const bool canUseSDFBlur = false) const override;
64     bool directFilterMaskGPU(GrRecordingContext*,
65                              skgpu::v1::SurfaceDrawContext*,
66                              GrPaint&&,
67                              const GrClip*,
68                              const SkMatrix& viewMatrix,
69                              const GrStyledShape&) const override;
70     GrSurfaceProxyView filterMaskGPU(GrRecordingContext*,
71                                      GrSurfaceProxyView srcView,
72                                      GrColorType srcColorType,
73                                      SkAlphaType srcAlphaType,
74                                      const SkMatrix& ctm,
75                                      const SkIRect& maskRect) const override;
76 
77     float getNoxFormedSigma3() const override;
78 
79     GrSurfaceProxyView filterMaskGPUNoxFormed(GrRecordingContext*, GrSurfaceProxyView srcView,
80         GrColorType srcColorType, SkAlphaType srcAlphaType, const SkMatrix& viewMatrix, const SkIRect& maskRect,
81         const SkRRect& srcRRect) const override;
82 #endif
83 
84     void computeFastBounds(const SkRect&, SkRect*) const override;
85     bool asABlur(BlurRec*) const override;
86 
87 
88 protected:
89     FilterReturn filterRectsToNine(const SkRect[], int count, const SkMatrix&,
90                                    const SkIRect& clipBounds,
91                                    NinePatch*) const override;
92 
93     FilterReturn filterRRectToNine(const SkRRect&, const SkMatrix&,
94                                    const SkIRect& clipBounds,
95                                    NinePatch*) const override;
96 
97     bool filterRectMask(SkMask* dstM, const SkRect& r, const SkMatrix& matrix,
98                         SkIPoint* margin, SkMask::CreateMode createMode) const;
99     bool filterRRectMask(SkMask* dstM, const SkRRect& r, const SkMatrix& matrix,
100                         SkIPoint* margin, SkMask::CreateMode createMode) const;
101 
ignoreXform() const102     bool ignoreXform() const { return !fRespectCTM; }
103 
104 private:
105     SK_FLATTENABLE_HOOKS(SkBlurMaskFilterImpl)
106     // To avoid unseemly allocation requests (esp. for finite platforms like
107     // handset) we limit the radius so something manageable. (as opposed to
108     // a request like 10,000)
109     static const SkScalar kMAX_BLUR_SIGMA;
110 
111     SkScalar    fSigma;
112     SkBlurStyle fBlurStyle;
113     bool        fRespectCTM;
114 
115     SkBlurMaskFilterImpl(SkReadBuffer&);
116     void flatten(SkWriteBuffer&) const override;
117 
computeXformedSigma(const SkMatrix & ctm) const118     SkScalar computeXformedSigma(const SkMatrix& ctm) const {
119         SkScalar xformedSigma = this->ignoreXform() ? fSigma : ctm.mapRadius(fSigma);
120         return std::min(xformedSigma, kMAX_BLUR_SIGMA);
121     }
122 
123     friend class SkBlurMaskFilter;
124 
125     using INHERITED = SkMaskFilter;
126     friend void sk_register_blur_maskfilter_createproc();
127 };
128 
129 const SkScalar SkBlurMaskFilterImpl::kMAX_BLUR_SIGMA = SkIntToScalar(128);
130 
131 ///////////////////////////////////////////////////////////////////////////////
132 
SkBlurMaskFilterImpl(SkScalar sigma,SkBlurStyle style,bool respectCTM)133 SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar sigma, SkBlurStyle style, bool respectCTM)
134     : fSigma(sigma)
135     , fBlurStyle(style)
136     , fRespectCTM(respectCTM) {
137     SkASSERT(fSigma > 0);
138     SkASSERT((unsigned)style <= kLastEnum_SkBlurStyle);
139 }
140 
getFormat() const141 SkMask::Format SkBlurMaskFilterImpl::getFormat() const {
142     return SkMask::kA8_Format;
143 }
144 
asABlur(BlurRec * rec) const145 bool SkBlurMaskFilterImpl::asABlur(BlurRec* rec) const {
146     if (this->ignoreXform()) {
147         return false;
148     }
149 
150     if (rec) {
151         rec->fSigma = fSigma;
152         rec->fStyle = fBlurStyle;
153     }
154     return true;
155 }
156 
filterMask(SkMask * dst,const SkMask & src,const SkMatrix & matrix,SkIPoint * margin) const157 bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src,
158                                       const SkMatrix& matrix,
159                                       SkIPoint* margin) const {
160     SkScalar sigma = this->computeXformedSigma(matrix);
161     return SkBlurMask::BoxBlur(dst, src, sigma, fBlurStyle, margin);
162 }
163 
filterRectMask(SkMask * dst,const SkRect & r,const SkMatrix & matrix,SkIPoint * margin,SkMask::CreateMode createMode) const164 bool SkBlurMaskFilterImpl::filterRectMask(SkMask* dst, const SkRect& r,
165                                           const SkMatrix& matrix,
166                                           SkIPoint* margin, SkMask::CreateMode createMode) const {
167     SkScalar sigma = computeXformedSigma(matrix);
168 
169     return SkBlurMask::BlurRect(sigma, dst, r, fBlurStyle, margin, createMode);
170 }
171 
filterRRectMask(SkMask * dst,const SkRRect & r,const SkMatrix & matrix,SkIPoint * margin,SkMask::CreateMode createMode) const172 bool SkBlurMaskFilterImpl::filterRRectMask(SkMask* dst, const SkRRect& r,
173                                           const SkMatrix& matrix,
174                                           SkIPoint* margin, SkMask::CreateMode createMode) const {
175     SkScalar sigma = computeXformedSigma(matrix);
176 
177     return SkBlurMask::BlurRRect(sigma, dst, r, fBlurStyle, margin, createMode);
178 }
179 
180 #include "include/core/SkCanvas.h"
181 
prepare_to_draw_into_mask(const SkRect & bounds,SkMask * mask)182 static bool prepare_to_draw_into_mask(const SkRect& bounds, SkMask* mask) {
183     SkASSERT(mask != nullptr);
184 
185     mask->fBounds = bounds.roundOut();
186     mask->fRowBytes = SkAlign4(mask->fBounds.width());
187     mask->fFormat = SkMask::kA8_Format;
188     const size_t size = mask->computeImageSize();
189     mask->fImage = SkMask::AllocImage(size, SkMask::kZeroInit_Alloc);
190     if (nullptr == mask->fImage) {
191         return false;
192     }
193     return true;
194 }
195 
draw_rrect_into_mask(const SkRRect rrect,SkMask * mask)196 static bool draw_rrect_into_mask(const SkRRect rrect, SkMask* mask) {
197     if (!prepare_to_draw_into_mask(rrect.rect(), mask)) {
198         return false;
199     }
200 
201     // FIXME: This code duplicates code in draw_rects_into_mask, below. Is there a
202     // clean way to share more code?
203     SkBitmap bitmap;
204     bitmap.installMaskPixels(*mask);
205 
206     SkCanvas canvas(bitmap);
207     canvas.translate(-SkIntToScalar(mask->fBounds.left()),
208                      -SkIntToScalar(mask->fBounds.top()));
209 
210     SkPaint paint;
211     paint.setAntiAlias(true);
212     canvas.drawRRect(rrect, paint);
213     return true;
214 }
215 
draw_rects_into_mask(const SkRect rects[],int count,SkMask * mask)216 static bool draw_rects_into_mask(const SkRect rects[], int count, SkMask* mask) {
217     if (!prepare_to_draw_into_mask(rects[0], mask)) {
218         return false;
219     }
220 
221     SkBitmap bitmap;
222     bitmap.installPixels(SkImageInfo::Make(mask->fBounds.width(),
223                                            mask->fBounds.height(),
224                                            kAlpha_8_SkColorType,
225                                            kPremul_SkAlphaType),
226                          mask->fImage, mask->fRowBytes);
227 
228     SkCanvas canvas(bitmap);
229     canvas.translate(-SkIntToScalar(mask->fBounds.left()),
230                      -SkIntToScalar(mask->fBounds.top()));
231 
232     SkPaint paint;
233     paint.setAntiAlias(true);
234 
235     if (1 == count) {
236         canvas.drawRect(rects[0], paint);
237     } else {
238         // todo: do I need a fast way to do this?
239         SkPath path = SkPathBuilder().addRect(rects[0])
240                                      .addRect(rects[1])
241                                      .setFillType(SkPathFillType::kEvenOdd)
242                                      .detach();
243         canvas.drawPath(path, paint);
244     }
245     return true;
246 }
247 
rect_exceeds(const SkRect & r,SkScalar v)248 static bool rect_exceeds(const SkRect& r, SkScalar v) {
249     return r.fLeft < -v || r.fTop < -v || r.fRight > v || r.fBottom > v ||
250            r.width() > v || r.height() > v;
251 }
252 
253 #include "src/core/SkMaskCache.h"
254 
copy_mask_to_cacheddata(SkMask * mask)255 static SkCachedData* copy_mask_to_cacheddata(SkMask* mask) {
256     const size_t size = mask->computeTotalImageSize();
257     SkCachedData* data = SkResourceCache::NewCachedData(size);
258     if (data) {
259         memcpy(data->writable_data(), mask->fImage, size);
260         SkMask::FreeImage(mask->fImage);
261         mask->fImage = (uint8_t*)data->data();
262     }
263     return data;
264 }
265 
find_cached_rrect(SkMask * mask,SkScalar sigma,SkBlurStyle style,const SkRRect & rrect)266 static SkCachedData* find_cached_rrect(SkMask* mask, SkScalar sigma, SkBlurStyle style,
267                                        const SkRRect& rrect) {
268     return SkMaskCache::FindAndRef(sigma, style, rrect, mask);
269 }
270 
add_cached_rrect(SkMask * mask,SkScalar sigma,SkBlurStyle style,const SkRRect & rrect)271 static SkCachedData* add_cached_rrect(SkMask* mask, SkScalar sigma, SkBlurStyle style,
272                                       const SkRRect& rrect) {
273     SkCachedData* cache = copy_mask_to_cacheddata(mask);
274     if (cache) {
275         SkMaskCache::Add(sigma, style, rrect, *mask, cache);
276     }
277     return cache;
278 }
279 
find_cached_rects(SkMask * mask,SkScalar sigma,SkBlurStyle style,const SkRect rects[],int count)280 static SkCachedData* find_cached_rects(SkMask* mask, SkScalar sigma, SkBlurStyle style,
281                                        const SkRect rects[], int count) {
282     return SkMaskCache::FindAndRef(sigma, style, rects, count, mask);
283 }
284 
add_cached_rects(SkMask * mask,SkScalar sigma,SkBlurStyle style,const SkRect rects[],int count)285 static SkCachedData* add_cached_rects(SkMask* mask, SkScalar sigma, SkBlurStyle style,
286                                       const SkRect rects[], int count) {
287     SkCachedData* cache = copy_mask_to_cacheddata(mask);
288     if (cache) {
289         SkMaskCache::Add(sigma, style, rects, count, *mask, cache);
290     }
291     return cache;
292 }
293 
294 static const bool c_analyticBlurRRect{true};
295 
296 SkMaskFilterBase::FilterReturn
filterRRectToNine(const SkRRect & rrect,const SkMatrix & matrix,const SkIRect & clipBounds,NinePatch * patch) const297 SkBlurMaskFilterImpl::filterRRectToNine(const SkRRect& rrect, const SkMatrix& matrix,
298                                         const SkIRect& clipBounds,
299                                         NinePatch* patch) const {
300     SkASSERT(patch != nullptr);
301     switch (rrect.getType()) {
302         case SkRRect::kEmpty_Type:
303             // Nothing to draw.
304             return kFalse_FilterReturn;
305 
306         case SkRRect::kRect_Type:
307             // We should have caught this earlier.
308             SkASSERT(false);
309             [[fallthrough]];
310         case SkRRect::kOval_Type:
311             // The nine patch special case does not handle ovals, and we
312             // already have code for rectangles.
313             return kUnimplemented_FilterReturn;
314 
315         // These three can take advantage of this fast path.
316         case SkRRect::kSimple_Type:
317         case SkRRect::kNinePatch_Type:
318         case SkRRect::kComplex_Type:
319             break;
320     }
321 
322     // TODO: report correct metrics for innerstyle, where we do not grow the
323     // total bounds, but we do need an inset the size of our blur-radius
324     if (kInner_SkBlurStyle == fBlurStyle) {
325         return kUnimplemented_FilterReturn;
326     }
327 
328     // TODO: take clipBounds into account to limit our coordinates up front
329     // for now, just skip too-large src rects (to take the old code path).
330     if (rect_exceeds(rrect.rect(), SkIntToScalar(32767))) {
331         return kUnimplemented_FilterReturn;
332     }
333 
334     SkIPoint margin;
335     SkMask  srcM, dstM;
336     srcM.fBounds = rrect.rect().roundOut();
337     srcM.fFormat = SkMask::kA8_Format;
338     srcM.fRowBytes = 0;
339 
340     bool filterResult = false;
341     if (c_analyticBlurRRect) {
342         // special case for fast round rect blur
343         // don't actually do the blur the first time, just compute the correct size
344         filterResult = this->filterRRectMask(&dstM, rrect, matrix, &margin,
345                                             SkMask::kJustComputeBounds_CreateMode);
346     }
347 
348     if (!filterResult) {
349         filterResult = this->filterMask(&dstM, srcM, matrix, &margin);
350     }
351 
352     if (!filterResult) {
353         return kFalse_FilterReturn;
354     }
355 
356     // Now figure out the appropriate width and height of the smaller round rectangle
357     // to stretch. It will take into account the larger radius per side as well as double
358     // the margin, to account for inner and outer blur.
359     const SkVector& UL = rrect.radii(SkRRect::kUpperLeft_Corner);
360     const SkVector& UR = rrect.radii(SkRRect::kUpperRight_Corner);
361     const SkVector& LR = rrect.radii(SkRRect::kLowerRight_Corner);
362     const SkVector& LL = rrect.radii(SkRRect::kLowerLeft_Corner);
363 
364     const SkScalar leftUnstretched = std::max(UL.fX, LL.fX) + SkIntToScalar(2 * margin.fX);
365     const SkScalar rightUnstretched = std::max(UR.fX, LR.fX) + SkIntToScalar(2 * margin.fX);
366 
367     // Extra space in the middle to ensure an unchanging piece for stretching. Use 3 to cover
368     // any fractional space on either side plus 1 for the part to stretch.
369     const SkScalar stretchSize = SkIntToScalar(3);
370 
371     const SkScalar totalSmallWidth = leftUnstretched + rightUnstretched + stretchSize;
372     if (totalSmallWidth >= rrect.rect().width()) {
373         // There is no valid piece to stretch.
374         return kUnimplemented_FilterReturn;
375     }
376 
377     const SkScalar topUnstretched = std::max(UL.fY, UR.fY) + SkIntToScalar(2 * margin.fY);
378     const SkScalar bottomUnstretched = std::max(LL.fY, LR.fY) + SkIntToScalar(2 * margin.fY);
379 
380     const SkScalar totalSmallHeight = topUnstretched + bottomUnstretched + stretchSize;
381     if (totalSmallHeight >= rrect.rect().height()) {
382         // There is no valid piece to stretch.
383         return kUnimplemented_FilterReturn;
384     }
385 
386     SkRect smallR = SkRect::MakeWH(totalSmallWidth, totalSmallHeight);
387 
388     SkRRect smallRR;
389     SkVector radii[4];
390     radii[SkRRect::kUpperLeft_Corner] = UL;
391     radii[SkRRect::kUpperRight_Corner] = UR;
392     radii[SkRRect::kLowerRight_Corner] = LR;
393     radii[SkRRect::kLowerLeft_Corner] = LL;
394     smallRR.setRectRadii(smallR, radii);
395 
396     const SkScalar sigma = this->computeXformedSigma(matrix);
397     SkCachedData* cache = find_cached_rrect(&patch->fMask, sigma, fBlurStyle, smallRR);
398     if (!cache) {
399         bool analyticBlurWorked = false;
400         if (c_analyticBlurRRect) {
401             analyticBlurWorked =
402                 this->filterRRectMask(&patch->fMask, smallRR, matrix, &margin,
403                                       SkMask::kComputeBoundsAndRenderImage_CreateMode);
404         }
405 
406         if (!analyticBlurWorked) {
407             if (!draw_rrect_into_mask(smallRR, &srcM)) {
408                 return kFalse_FilterReturn;
409             }
410 
411             SkAutoMaskFreeImage amf(srcM.fImage);
412 
413             if (!this->filterMask(&patch->fMask, srcM, matrix, &margin)) {
414                 return kFalse_FilterReturn;
415             }
416         }
417         cache = add_cached_rrect(&patch->fMask, sigma, fBlurStyle, smallRR);
418     }
419 
420     patch->fMask.fBounds.offsetTo(0, 0);
421     patch->fOuterRect = dstM.fBounds;
422     patch->fCenter.fX = SkScalarCeilToInt(leftUnstretched) + 1;
423     patch->fCenter.fY = SkScalarCeilToInt(topUnstretched) + 1;
424     SkASSERT(nullptr == patch->fCache);
425     patch->fCache = cache;  // transfer ownership to patch
426     return kTrue_FilterReturn;
427 }
428 
429 // Use the faster analytic blur approach for ninepatch rects
430 static const bool c_analyticBlurNinepatch{true};
431 
432 SkMaskFilterBase::FilterReturn
filterRectsToNine(const SkRect rects[],int count,const SkMatrix & matrix,const SkIRect & clipBounds,NinePatch * patch) const433 SkBlurMaskFilterImpl::filterRectsToNine(const SkRect rects[], int count,
434                                         const SkMatrix& matrix,
435                                         const SkIRect& clipBounds,
436                                         NinePatch* patch) const {
437     if (count < 1 || count > 2) {
438         return kUnimplemented_FilterReturn;
439     }
440 
441     // TODO: report correct metrics for innerstyle, where we do not grow the
442     // total bounds, but we do need an inset the size of our blur-radius
443     if (kInner_SkBlurStyle == fBlurStyle || kOuter_SkBlurStyle == fBlurStyle) {
444         return kUnimplemented_FilterReturn;
445     }
446 
447     // TODO: take clipBounds into account to limit our coordinates up front
448     // for now, just skip too-large src rects (to take the old code path).
449     if (rect_exceeds(rects[0], SkIntToScalar(32767))) {
450         return kUnimplemented_FilterReturn;
451     }
452 
453     SkIPoint margin;
454     SkMask  srcM, dstM;
455     srcM.fBounds = rects[0].roundOut();
456     srcM.fFormat = SkMask::kA8_Format;
457     srcM.fRowBytes = 0;
458 
459     bool filterResult = false;
460     if (count == 1 && c_analyticBlurNinepatch) {
461         // special case for fast rect blur
462         // don't actually do the blur the first time, just compute the correct size
463         filterResult = this->filterRectMask(&dstM, rects[0], matrix, &margin,
464                                             SkMask::kJustComputeBounds_CreateMode);
465     } else {
466         filterResult = this->filterMask(&dstM, srcM, matrix, &margin);
467     }
468 
469     if (!filterResult) {
470         return kFalse_FilterReturn;
471     }
472 
473     /*
474      *  smallR is the smallest version of 'rect' that will still guarantee that
475      *  we get the same blur results on all edges, plus 1 center row/col that is
476      *  representative of the extendible/stretchable edges of the ninepatch.
477      *  Since our actual edge may be fractional we inset 1 more to be sure we
478      *  don't miss any interior blur.
479      *  x is an added pixel of blur, and { and } are the (fractional) edge
480      *  pixels from the original rect.
481      *
482      *   x x { x x .... x x } x x
483      *
484      *  Thus, in this case, we inset by a total of 5 (on each side) beginning
485      *  with our outer-rect (dstM.fBounds)
486      */
487     SkRect smallR[2];
488     SkIPoint center;
489 
490     // +2 is from +1 for each edge (to account for possible fractional edges
491     int smallW = dstM.fBounds.width() - srcM.fBounds.width() + 2;
492     int smallH = dstM.fBounds.height() - srcM.fBounds.height() + 2;
493     SkIRect innerIR;
494 
495     if (1 == count) {
496         innerIR = srcM.fBounds;
497         center.set(smallW, smallH);
498     } else {
499         SkASSERT(2 == count);
500         rects[1].roundIn(&innerIR);
501         center.set(smallW + (innerIR.left() - srcM.fBounds.left()),
502                    smallH + (innerIR.top() - srcM.fBounds.top()));
503     }
504 
505     // +1 so we get a clean, stretchable, center row/col
506     smallW += 1;
507     smallH += 1;
508 
509     // we want the inset amounts to be integral, so we don't change any
510     // fractional phase on the fRight or fBottom of our smallR.
511     const SkScalar dx = SkIntToScalar(innerIR.width() - smallW);
512     const SkScalar dy = SkIntToScalar(innerIR.height() - smallH);
513     if (dx < 0 || dy < 0) {
514         // we're too small, relative to our blur, to break into nine-patch,
515         // so we ask to have our normal filterMask() be called.
516         return kUnimplemented_FilterReturn;
517     }
518 
519     smallR[0].setLTRB(rects[0].left(),       rects[0].top(),
520                       rects[0].right() - dx, rects[0].bottom() - dy);
521     if (smallR[0].width() < 2 || smallR[0].height() < 2) {
522         return kUnimplemented_FilterReturn;
523     }
524     if (2 == count) {
525         smallR[1].setLTRB(rects[1].left(), rects[1].top(),
526                           rects[1].right() - dx, rects[1].bottom() - dy);
527         SkASSERT(!smallR[1].isEmpty());
528     }
529 
530     const SkScalar sigma = this->computeXformedSigma(matrix);
531     SkCachedData* cache = find_cached_rects(&patch->fMask, sigma, fBlurStyle, smallR, count);
532     if (!cache) {
533         if (count > 1 || !c_analyticBlurNinepatch) {
534             if (!draw_rects_into_mask(smallR, count, &srcM)) {
535                 return kFalse_FilterReturn;
536             }
537 
538             SkAutoMaskFreeImage amf(srcM.fImage);
539 
540             if (!this->filterMask(&patch->fMask, srcM, matrix, &margin)) {
541                 return kFalse_FilterReturn;
542             }
543         } else {
544             if (!this->filterRectMask(&patch->fMask, smallR[0], matrix, &margin,
545                                       SkMask::kComputeBoundsAndRenderImage_CreateMode)) {
546                 return kFalse_FilterReturn;
547             }
548         }
549         cache = add_cached_rects(&patch->fMask, sigma, fBlurStyle, smallR, count);
550     }
551     patch->fMask.fBounds.offsetTo(0, 0);
552     patch->fOuterRect = dstM.fBounds;
553     patch->fCenter = center;
554     SkASSERT(nullptr == patch->fCache);
555     patch->fCache = cache;  // transfer ownership to patch
556     return kTrue_FilterReturn;
557 }
558 
computeFastBounds(const SkRect & src,SkRect * dst) const559 void SkBlurMaskFilterImpl::computeFastBounds(const SkRect& src,
560                                              SkRect* dst) const {
561     // TODO: if we're doing kInner blur, should we return a different outset?
562     //       i.e. pad == 0 ?
563 
564     SkScalar pad = 3.0f * fSigma;
565 
566     dst->setLTRB(src.fLeft  - pad, src.fTop    - pad,
567                  src.fRight + pad, src.fBottom + pad);
568 }
569 
CreateProc(SkReadBuffer & buffer)570 sk_sp<SkFlattenable> SkBlurMaskFilterImpl::CreateProc(SkReadBuffer& buffer) {
571     const SkScalar sigma = buffer.readScalar();
572     SkBlurStyle style = buffer.read32LE(kLastEnum_SkBlurStyle);
573 
574     uint32_t flags = buffer.read32LE(0x3);  // historically we only recorded 2 bits
575     bool respectCTM = !(flags & 1); // historically we stored ignoreCTM in low bit
576 
577     return SkMaskFilter::MakeBlur((SkBlurStyle)style, sigma, respectCTM);
578 }
579 
flatten(SkWriteBuffer & buffer) const580 void SkBlurMaskFilterImpl::flatten(SkWriteBuffer& buffer) const {
581     buffer.writeScalar(fSigma);
582     buffer.writeUInt(fBlurStyle);
583     buffer.writeUInt(!fRespectCTM); // historically we recorded ignoreCTM
584 }
585 
586 
587 #if SK_SUPPORT_GPU && SK_GPU_V1
588 
589 ///////////////////////////////////////////////////////////////////////////////
590 //  Circle Blur
591 ///////////////////////////////////////////////////////////////////////////////
592 
593 // Computes an unnormalized half kernel (right side). Returns the summation of all the half
594 // kernel values.
make_unnormalized_half_kernel(float * halfKernel,int halfKernelSize,float sigma)595 static float make_unnormalized_half_kernel(float* halfKernel, int halfKernelSize, float sigma) {
596     const float invSigma = 1.f / sigma;
597     const float b = -0.5f * invSigma * invSigma;
598     float tot = 0.0f;
599     // Compute half kernel values at half pixel steps out from the center.
600     float t = 0.5f;
601     for (int i = 0; i < halfKernelSize; ++i) {
602         float value = expf(t * t * b);
603         tot += value;
604         halfKernel[i] = value;
605         t += 1.f;
606     }
607     return tot;
608 }
609 
610 // Create a Gaussian half-kernel (right side) and a summed area table given a sigma and number
611 // of discrete steps. The half kernel is normalized to sum to 0.5.
make_half_kernel_and_summed_table(float * halfKernel,float * summedHalfKernel,int halfKernelSize,float sigma)612 static void make_half_kernel_and_summed_table(float* halfKernel,
613                                               float* summedHalfKernel,
614                                               int halfKernelSize,
615                                               float sigma) {
616     // The half kernel should sum to 0.5 not 1.0.
617     const float tot = 2.f * make_unnormalized_half_kernel(halfKernel, halfKernelSize, sigma);
618     float sum = 0.f;
619     for (int i = 0; i < halfKernelSize; ++i) {
620         halfKernel[i] /= tot;
621         sum += halfKernel[i];
622         summedHalfKernel[i] = sum;
623     }
624 }
625 
626 // Applies the 1D half kernel vertically at points along the x axis to a circle centered at the
627 // origin with radius circleR.
apply_kernel_in_y(float * results,int numSteps,float firstX,float circleR,int halfKernelSize,const float * summedHalfKernelTable)628 void apply_kernel_in_y(float* results,
629                        int numSteps,
630                        float firstX,
631                        float circleR,
632                        int halfKernelSize,
633                        const float* summedHalfKernelTable) {
634     float x = firstX;
635     for (int i = 0; i < numSteps; ++i, x += 1.f) {
636         if (x < -circleR || x > circleR) {
637             results[i] = 0;
638             continue;
639         }
640         float y = sqrtf(circleR * circleR - x * x);
641         // In the column at x we exit the circle at +y and -y
642         // The summed table entry j is actually reflects an offset of j + 0.5.
643         y -= 0.5f;
644         int yInt = SkScalarFloorToInt(y);
645         SkASSERT(yInt >= -1);
646         if (y < 0) {
647             results[i] = (y + 0.5f) * summedHalfKernelTable[0];
648         } else if (yInt >= halfKernelSize - 1) {
649             results[i] = 0.5f;
650         } else {
651             float yFrac = y - yInt;
652             results[i] = (1.f - yFrac) * summedHalfKernelTable[yInt] +
653                          yFrac * summedHalfKernelTable[yInt + 1];
654         }
655     }
656 }
657 
658 // Apply a Gaussian at point (evalX, 0) to a circle centered at the origin with radius circleR.
659 // This relies on having a half kernel computed for the Gaussian and a table of applications of
660 // the half kernel in y to columns at (evalX - halfKernel, evalX - halfKernel + 1, ..., evalX +
661 // halfKernel) passed in as yKernelEvaluations.
eval_at(float evalX,float circleR,const float * halfKernel,int halfKernelSize,const float * yKernelEvaluations)662 static uint8_t eval_at(float evalX,
663                        float circleR,
664                        const float* halfKernel,
665                        int halfKernelSize,
666                        const float* yKernelEvaluations) {
667     float acc = 0;
668 
669     float x = evalX - halfKernelSize;
670     for (int i = 0; i < halfKernelSize; ++i, x += 1.f) {
671         if (x < -circleR || x > circleR) {
672             continue;
673         }
674         float verticalEval = yKernelEvaluations[i];
675         acc += verticalEval * halfKernel[halfKernelSize - i - 1];
676     }
677     for (int i = 0; i < halfKernelSize; ++i, x += 1.f) {
678         if (x < -circleR || x > circleR) {
679             continue;
680         }
681         float verticalEval = yKernelEvaluations[i + halfKernelSize];
682         acc += verticalEval * halfKernel[i];
683     }
684     // Since we applied a half kernel in y we multiply acc by 2 (the circle is symmetric about
685     // the x axis).
686     return SkUnitScalarClampToByte(2.f * acc);
687 }
688 
689 // This function creates a profile of a blurred circle. It does this by computing a kernel for
690 // half the Gaussian and a matching summed area table. The summed area table is used to compute
691 // an array of vertical applications of the half kernel to the circle along the x axis. The
692 // table of y evaluations has 2 * k + n entries where k is the size of the half kernel and n is
693 // the size of the profile being computed. Then for each of the n profile entries we walk out k
694 // steps in each horizontal direction multiplying the corresponding y evaluation by the half
695 // kernel entry and sum these values to compute the profile entry.
create_circle_profile(uint8_t * weights,float sigma,float circleR,int profileTextureWidth)696 static void create_circle_profile(uint8_t* weights,
697                                   float sigma,
698                                   float circleR,
699                                   int profileTextureWidth) {
700     const int numSteps = profileTextureWidth;
701 
702     // The full kernel is 6 sigmas wide.
703     int halfKernelSize = SkScalarCeilToInt(6.0f * sigma);
704     // round up to next multiple of 2 and then divide by 2
705     halfKernelSize = ((halfKernelSize + 1) & ~1) >> 1;
706 
707     // Number of x steps at which to apply kernel in y to cover all the profile samples in x.
708     int numYSteps = numSteps + 2 * halfKernelSize;
709 
710     SkAutoTArray<float> bulkAlloc(halfKernelSize + halfKernelSize + numYSteps);
711     float* halfKernel = bulkAlloc.get();
712     float* summedKernel = bulkAlloc.get() + halfKernelSize;
713     float* yEvals = bulkAlloc.get() + 2 * halfKernelSize;
714     make_half_kernel_and_summed_table(halfKernel, summedKernel, halfKernelSize, sigma);
715 
716     float firstX = -halfKernelSize + 0.5f;
717     apply_kernel_in_y(yEvals, numYSteps, firstX, circleR, halfKernelSize, summedKernel);
718 
719     for (int i = 0; i < numSteps - 1; ++i) {
720         float evalX = i + 0.5f;
721         weights[i] = eval_at(evalX, circleR, halfKernel, halfKernelSize, yEvals + i);
722     }
723     // Ensure the tail of the Gaussian goes to zero.
724     weights[numSteps - 1] = 0;
725 }
726 
create_half_plane_profile(uint8_t * profile,int profileWidth)727 static void create_half_plane_profile(uint8_t* profile, int profileWidth) {
728     SkASSERT(!(profileWidth & 0x1));
729     // The full kernel is 6 sigmas wide.
730     float sigma = profileWidth / 6.f;
731     int halfKernelSize = profileWidth / 2;
732 
733     SkAutoTArray<float> halfKernel(halfKernelSize);
734 
735     // The half kernel should sum to 0.5.
736     const float tot = 2.f * make_unnormalized_half_kernel(halfKernel.get(), halfKernelSize, sigma);
737     float sum = 0.f;
738     // Populate the profile from the right edge to the middle.
739     for (int i = 0; i < halfKernelSize; ++i) {
740         halfKernel[halfKernelSize - i - 1] /= tot;
741         sum += halfKernel[halfKernelSize - i - 1];
742         profile[profileWidth - i - 1] = SkUnitScalarClampToByte(sum);
743     }
744     // Populate the profile from the middle to the left edge (by flipping the half kernel and
745     // continuing the summation).
746     for (int i = 0; i < halfKernelSize; ++i) {
747         sum += halfKernel[i];
748         profile[halfKernelSize - i - 1] = SkUnitScalarClampToByte(sum);
749     }
750     // Ensure tail goes to 0.
751     profile[profileWidth - 1] = 0;
752 }
753 
create_profile_effect(GrRecordingContext * rContext,const SkRect & circle,float sigma,float * solidRadius,float * textureRadius)754 static std::unique_ptr<GrFragmentProcessor> create_profile_effect(GrRecordingContext* rContext,
755                                                                   const SkRect& circle,
756                                                                   float sigma,
757                                                                   float* solidRadius,
758                                                                   float* textureRadius) {
759     float circleR = circle.width() / 2.0f;
760     if (!sk_float_isfinite(circleR) || circleR < SK_ScalarNearlyZero) {
761         return nullptr;
762     }
763 
764     auto threadSafeCache = rContext->priv().threadSafeCache();
765 
766     // Profile textures are cached by the ratio of sigma to circle radius and by the size of the
767     // profile texture (binned by powers of 2).
768     SkScalar sigmaToCircleRRatio = sigma / circleR;
769     // When sigma is really small this becomes a equivalent to convolving a Gaussian with a
770     // half-plane. Similarly, in the extreme high ratio cases circle becomes a point WRT to the
771     // Guassian and the profile texture is a just a Gaussian evaluation. However, we haven't yet
772     // implemented this latter optimization.
773     sigmaToCircleRRatio = std::min(sigmaToCircleRRatio, 8.f);
774     SkFixed sigmaToCircleRRatioFixed;
775     static const SkScalar kHalfPlaneThreshold = 0.1f;
776     bool useHalfPlaneApprox = false;
777     if (sigmaToCircleRRatio <= kHalfPlaneThreshold) {
778         useHalfPlaneApprox = true;
779         sigmaToCircleRRatioFixed = 0;
780         *solidRadius = circleR - 3 * sigma;
781         *textureRadius = 6 * sigma;
782     } else {
783         // Convert to fixed point for the key.
784         sigmaToCircleRRatioFixed = SkScalarToFixed(sigmaToCircleRRatio);
785         // We shave off some bits to reduce the number of unique entries. We could probably
786         // shave off more than we do.
787         sigmaToCircleRRatioFixed &= ~0xff;
788         sigmaToCircleRRatio = SkFixedToScalar(sigmaToCircleRRatioFixed);
789         sigma = circleR * sigmaToCircleRRatio;
790         *solidRadius = 0;
791         *textureRadius = circleR + 3 * sigma;
792     }
793 
794     static constexpr int kProfileTextureWidth = 512;
795     // This would be kProfileTextureWidth/textureRadius if it weren't for the fact that we do
796     // the calculation of the profile coord in a coord space that has already been scaled by
797     // 1 / textureRadius. This is done to avoid overflow in length().
798     SkMatrix texM = SkMatrix::Scale(kProfileTextureWidth, 1.f);
799 
800     static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
801     GrUniqueKey key;
802     GrUniqueKey::Builder builder(&key, kDomain, 1, "1-D Circular Blur");
803     builder[0] = sigmaToCircleRRatioFixed;
804     builder.finish();
805 
806     GrSurfaceProxyView profileView = threadSafeCache->find(key);
807     if (profileView) {
808         SkASSERT(profileView.asTextureProxy());
809         SkASSERT(profileView.origin() == kTopLeft_GrSurfaceOrigin);
810         return GrTextureEffect::Make(std::move(profileView), kPremul_SkAlphaType, texM);
811     }
812 
813     SkBitmap bm;
814     if (!bm.tryAllocPixels(SkImageInfo::MakeA8(kProfileTextureWidth, 1))) {
815         return nullptr;
816     }
817 
818     if (useHalfPlaneApprox) {
819         create_half_plane_profile(bm.getAddr8(0, 0), kProfileTextureWidth);
820     } else {
821         // Rescale params to the size of the texture we're creating.
822         SkScalar scale = kProfileTextureWidth / *textureRadius;
823         create_circle_profile(
824                 bm.getAddr8(0, 0), sigma * scale, circleR * scale, kProfileTextureWidth);
825     }
826     bm.setImmutable();
827 
828     profileView = std::get<0>(GrMakeUncachedBitmapProxyView(rContext, bm));
829     if (!profileView) {
830         return nullptr;
831     }
832 
833     profileView = threadSafeCache->add(key, profileView);
834     return GrTextureEffect::Make(std::move(profileView), kPremul_SkAlphaType, texM);
835 }
836 
make_circle_blur(GrRecordingContext * context,const SkRect & circle,float sigma)837 static std::unique_ptr<GrFragmentProcessor> make_circle_blur(GrRecordingContext* context,
838                                                              const SkRect& circle,
839                                                              float sigma) {
840     if (SkGpuBlurUtils::IsEffectivelyZeroSigma(sigma)) {
841         return nullptr;
842     }
843 
844     float solidRadius;
845     float textureRadius;
846     std::unique_ptr<GrFragmentProcessor> profile =
847             create_profile_effect(context, circle, sigma, &solidRadius, &textureRadius);
848     if (!profile) {
849         return nullptr;
850     }
851 
852     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader, R"(
853         uniform shader blurProfile;
854         uniform float4 circleData;
855 
856         half4 main(float2 xy, half4 inColor) {
857             // We just want to compute "(length(vec) - circleData.z + 0.5) * circleData.w" but need
858             // to rearrange to avoid passing large values to length() that would overflow.
859             half4 halfCircleData = circleData;
860             half2 vec = (sk_FragCoord.xy - halfCircleData.xy) * circleData.w;
861             half dist = length(vec) + (0.5 - halfCircleData.z) * halfCircleData.w;
862             return inColor * blurProfile.eval(half2(dist, 0.5)).a;
863         }
864     )");
865 
866     SkV4 circleData = {circle.centerX(), circle.centerY(), solidRadius, 1.f / textureRadius};
867     return GrSkSLFP::Make(effect, "CircleBlur", /*inputFP=*/nullptr,
868                           GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
869                           "blurProfile", GrSkSLFP::IgnoreOptFlags(std::move(profile)),
870                           "circleData", circleData);
871 }
872 
873 ///////////////////////////////////////////////////////////////////////////////
874 //  Rect Blur
875 ///////////////////////////////////////////////////////////////////////////////
876 
make_rect_integral_fp(GrRecordingContext * rContext,float sixSigma)877 static std::unique_ptr<GrFragmentProcessor> make_rect_integral_fp(GrRecordingContext* rContext,
878                                                                   float sixSigma) {
879     SkASSERT(!SkGpuBlurUtils::IsEffectivelyZeroSigma(sixSigma / 6.f));
880     auto threadSafeCache = rContext->priv().threadSafeCache();
881 
882     int width = SkGpuBlurUtils::CreateIntegralTable(sixSigma, nullptr);
883 
884     static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
885     GrUniqueKey key;
886     GrUniqueKey::Builder builder(&key, kDomain, 1, "Rect Blur Mask");
887     builder[0] = width;
888     builder.finish();
889 
890     SkMatrix m = SkMatrix::Scale(width / sixSigma, 1.f);
891 
892     GrSurfaceProxyView view = threadSafeCache->find(key);
893 
894     if (view) {
895         SkASSERT(view.origin() == kTopLeft_GrSurfaceOrigin);
896         return GrTextureEffect::Make(
897                 std::move(view), kPremul_SkAlphaType, m, GrSamplerState::Filter::kLinear);
898     }
899 
900     SkBitmap bitmap;
901     if (!SkGpuBlurUtils::CreateIntegralTable(sixSigma, &bitmap)) {
902         return {};
903     }
904 
905     view = std::get<0>(GrMakeUncachedBitmapProxyView(rContext, bitmap));
906     if (!view) {
907         return {};
908     }
909 
910     view = threadSafeCache->add(key, view);
911 
912     SkASSERT(view.origin() == kTopLeft_GrSurfaceOrigin);
913     return GrTextureEffect::Make(
914             std::move(view), kPremul_SkAlphaType, m, GrSamplerState::Filter::kLinear);
915 }
916 
make_rect_blur(GrRecordingContext * context,const GrShaderCaps & caps,const SkRect & srcRect,const SkMatrix & viewMatrix,float transformedSigma)917 static std::unique_ptr<GrFragmentProcessor> make_rect_blur(GrRecordingContext* context,
918                                                            const GrShaderCaps& caps,
919                                                            const SkRect& srcRect,
920                                                            const SkMatrix& viewMatrix,
921                                                            float transformedSigma) {
922     SkASSERT(viewMatrix.preservesRightAngles());
923     SkASSERT(srcRect.isSorted());
924 
925     if (SkGpuBlurUtils::IsEffectivelyZeroSigma(transformedSigma)) {
926         // No need to blur the rect
927         return nullptr;
928     }
929 
930     SkMatrix invM;
931     SkRect rect;
932     if (viewMatrix.rectStaysRect()) {
933         invM = SkMatrix::I();
934         // We can do everything in device space when the src rect projects to a rect in device space
935         SkAssertResult(viewMatrix.mapRect(&rect, srcRect));
936     } else {
937         // The view matrix may scale, perhaps anisotropically. But we want to apply our device space
938         // "transformedSigma" to the delta of frag coord from the rect edges. Factor out the scaling
939         // to define a space that is purely rotation/translation from device space (and scale from
940         // src space) We'll meet in the middle: pre-scale the src rect to be in this space and then
941         // apply the inverse of the rotation/translation portion to the frag coord.
942         SkMatrix m;
943         SkSize scale;
944         if (!viewMatrix.decomposeScale(&scale, &m)) {
945             return nullptr;
946         }
947         if (!m.invert(&invM)) {
948             return nullptr;
949         }
950         rect = {srcRect.left() * scale.width(),
951                 srcRect.top() * scale.height(),
952                 srcRect.right() * scale.width(),
953                 srcRect.bottom() * scale.height()};
954     }
955 
956     if (!caps.floatIs32Bits()) {
957         // We promote the math that gets us into the Gaussian space to full float when the rect
958         // coords are large. If we don't have full float then fail. We could probably clip the rect
959         // to an outset device bounds instead.
960         if (SkScalarAbs(rect.fLeft) > 16000.f || SkScalarAbs(rect.fTop) > 16000.f ||
961             SkScalarAbs(rect.fRight) > 16000.f || SkScalarAbs(rect.fBottom) > 16000.f) {
962             return nullptr;
963         }
964     }
965 
966     const float sixSigma = 6 * transformedSigma;
967     std::unique_ptr<GrFragmentProcessor> integral = make_rect_integral_fp(context, sixSigma);
968     if (!integral) {
969         return nullptr;
970     }
971 
972     // In the fast variant we think of the midpoint of the integral texture as aligning with the
973     // closest rect edge both in x and y. To simplify texture coord calculation we inset the rect so
974     // that the edge of the inset rect corresponds to t = 0 in the texture. It actually simplifies
975     // things a bit in the !isFast case, too.
976     float threeSigma = sixSigma / 2;
977     SkRect insetRect = {rect.left() + threeSigma,
978                         rect.top() + threeSigma,
979                         rect.right() - threeSigma,
980                         rect.bottom() - threeSigma};
981 
982     // In our fast variant we find the nearest horizontal and vertical edges and for each do a
983     // lookup in the integral texture for each and multiply them. When the rect is less than 6 sigma
984     // wide then things aren't so simple and we have to consider both the left and right edge of the
985     // rectangle (and similar in y).
986     bool isFast = insetRect.isSorted();
987 
988     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader, R"(
989         // Effect that is a LUT for integral of normal distribution. The value at x:[0,6*sigma] is
990         // the integral from -inf to (3*sigma - x). I.e. x is mapped from [0, 6*sigma] to
991         // [3*sigma to -3*sigma]. The flip saves a reversal in the shader.
992         uniform shader integral;
993 
994         uniform float4 rect;
995         uniform int isFast;  // specialized
996 
997         half4 main(float2 pos, half4 inColor) {
998             half xCoverage, yCoverage;
999             if (bool(isFast)) {
1000                 // Get the smaller of the signed distance from the frag coord to the left and right
1001                 // edges and similar for y.
1002                 // The integral texture goes "backwards" (from 3*sigma to -3*sigma), So, the below
1003                 // computations align the left edge of the integral texture with the inset rect's
1004                 // edge extending outward 6 * sigma from the inset rect.
1005                 half2 xy = max(half2(rect.LT - pos), half2(pos - rect.RB));
1006                 xCoverage = integral.eval(half2(xy.x, 0.5)).a;
1007                 yCoverage = integral.eval(half2(xy.y, 0.5)).a;
1008             } else {
1009                 // We just consider just the x direction here. In practice we compute x and y
1010                 // separately and multiply them together.
1011                 // We define our coord system so that the point at which we're evaluating a kernel
1012                 // defined by the normal distribution (K) at 0. In this coord system let L be left
1013                 // edge and R be the right edge of the rectangle.
1014                 // We can calculate C by integrating K with the half infinite ranges outside the
1015                 // L to R range and subtracting from 1:
1016                 //   C = 1 - <integral of K from from -inf to  L> - <integral of K from R to inf>
1017                 // K is symmetric about x=0 so:
1018                 //   C = 1 - <integral of K from from -inf to  L> - <integral of K from -inf to -R>
1019 
1020                 // The integral texture goes "backwards" (from 3*sigma to -3*sigma) which is
1021                 // factored in to the below calculations.
1022                 // Also, our rect uniform was pre-inset by 3 sigma from the actual rect being
1023                 // blurred, also factored in.
1024                 half4 rect = half4(half2(rect.LT - pos), half2(pos - rect.RB));
1025                 xCoverage = 1 - integral.eval(half2(rect.L, 0.5)).a
1026                               - integral.eval(half2(rect.R, 0.5)).a;
1027                 yCoverage = 1 - integral.eval(half2(rect.T, 0.5)).a
1028                               - integral.eval(half2(rect.B, 0.5)).a;
1029             }
1030             return inColor * xCoverage * yCoverage;
1031         }
1032     )");
1033 
1034     std::unique_ptr<GrFragmentProcessor> fp =
1035             GrSkSLFP::Make(effect, "RectBlur", /*inputFP=*/nullptr,
1036                            GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
1037                            "integral", GrSkSLFP::IgnoreOptFlags(std::move(integral)),
1038                            "rect", insetRect,
1039                            "isFast", GrSkSLFP::Specialize<int>(isFast));
1040     if (!invM.isIdentity()) {
1041         fp = GrMatrixEffect::Make(invM, std::move(fp));
1042     }
1043     return GrFragmentProcessor::DeviceSpace(std::move(fp));
1044 }
1045 
1046 ///////////////////////////////////////////////////////////////////////////////
1047 //  RRect Blur
1048 ///////////////////////////////////////////////////////////////////////////////
1049 
1050 static constexpr auto kBlurredRRectMaskOrigin = kTopLeft_GrSurfaceOrigin;
1051 
make_blurred_rrect_key(GrUniqueKey * key,const SkRRect & rrectToDraw,float xformedSigma)1052 static void make_blurred_rrect_key(GrUniqueKey* key,
1053                                    const SkRRect& rrectToDraw,
1054                                    float xformedSigma) {
1055     SkASSERT(!SkGpuBlurUtils::IsEffectivelyZeroSigma(xformedSigma));
1056     static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
1057 
1058     GrUniqueKey::Builder builder(key, kDomain, 9, "RoundRect Blur Mask");
1059     builder[0] = SkScalarCeilToInt(xformedSigma - 1 / 6.0f);
1060 
1061     int index = 1;
1062     // TODO: this is overkill for _simple_ circular rrects
1063     for (auto c : {SkRRect::kUpperLeft_Corner,
1064                    SkRRect::kUpperRight_Corner,
1065                    SkRRect::kLowerRight_Corner,
1066                    SkRRect::kLowerLeft_Corner}) {
1067         SkASSERT(SkScalarIsInt(rrectToDraw.radii(c).fX) && SkScalarIsInt(rrectToDraw.radii(c).fY));
1068         builder[index++] = SkScalarCeilToInt(rrectToDraw.radii(c).fX);
1069         builder[index++] = SkScalarCeilToInt(rrectToDraw.radii(c).fY);
1070     }
1071     builder.finish();
1072 }
1073 
fillin_view_on_gpu(GrDirectContext * dContext,const GrSurfaceProxyView & lazyView,sk_sp<GrThreadSafeCache::Trampoline> trampoline,const SkRRect & rrectToDraw,const SkISize & dimensions,float xformedSigma)1074 static bool fillin_view_on_gpu(GrDirectContext* dContext,
1075                                const GrSurfaceProxyView& lazyView,
1076                                sk_sp<GrThreadSafeCache::Trampoline> trampoline,
1077                                const SkRRect& rrectToDraw,
1078                                const SkISize& dimensions,
1079                                float xformedSigma) {
1080 #if SK_GPU_V1
1081     SkASSERT(!SkGpuBlurUtils::IsEffectivelyZeroSigma(xformedSigma));
1082 
1083     // We cache blur masks. Use default surface props here so we can use the same cached mask
1084     // regardless of the final dst surface.
1085     SkSurfaceProps defaultSurfaceProps;
1086 
1087     std::unique_ptr<skgpu::v1::SurfaceDrawContext> sdc =
1088             skgpu::v1::SurfaceDrawContext::MakeWithFallback(dContext,
1089                                                             GrColorType::kAlpha_8,
1090                                                             nullptr,
1091                                                             SkBackingFit::kExact,
1092                                                             dimensions,
1093                                                             defaultSurfaceProps,
1094                                                             1,
1095                                                             GrMipmapped::kNo,
1096                                                             GrProtected::kNo,
1097                                                             kBlurredRRectMaskOrigin);
1098     if (!sdc) {
1099         return false;
1100     }
1101 
1102     GrPaint paint;
1103 
1104     sdc->clear(SK_PMColor4fTRANSPARENT);
1105     sdc->drawRRect(nullptr,
1106                    std::move(paint),
1107                    GrAA::kYes,
1108                    SkMatrix::I(),
1109                    rrectToDraw,
1110                    GrStyle::SimpleFill());
1111 
1112     GrSurfaceProxyView srcView = sdc->readSurfaceView();
1113     SkASSERT(srcView.asTextureProxy());
1114     auto rtc2 = SkGpuBlurUtils::GaussianBlur(dContext,
1115                                              std::move(srcView),
1116                                              sdc->colorInfo().colorType(),
1117                                              sdc->colorInfo().alphaType(),
1118                                              nullptr,
1119                                              SkIRect::MakeSize(dimensions),
1120                                              SkIRect::MakeSize(dimensions),
1121                                              xformedSigma,
1122                                              xformedSigma,
1123                                              SkTileMode::kClamp,
1124                                              SkBackingFit::kExact);
1125     if (!rtc2 || !rtc2->readSurfaceView()) {
1126         return false;
1127     }
1128 
1129     auto view = rtc2->readSurfaceView();
1130     SkASSERT(view.swizzle() == lazyView.swizzle());
1131     SkASSERT(view.origin() == lazyView.origin());
1132     trampoline->fProxy = view.asTextureProxyRef();
1133 
1134     return true;
1135 #else
1136     return false;
1137 #endif
1138 }
1139 
1140 // Evaluate the vertical blur at the specified 'y' value given the location of the top of the
1141 // rrect.
eval_V(float top,int y,const uint8_t * integral,int integralSize,float sixSigma)1142 static uint8_t eval_V(float top, int y, const uint8_t* integral, int integralSize, float sixSigma) {
1143     if (top < 0) {
1144         return 0;  // an empty column
1145     }
1146 
1147     float fT = (top - y - 0.5f) * (integralSize / sixSigma);
1148     if (fT < 0) {
1149         return 255;
1150     } else if (fT >= integralSize - 1) {
1151         return 0;
1152     }
1153 
1154     int lower = (int)fT;
1155     float frac = fT - lower;
1156 
1157     SkASSERT(lower + 1 < integralSize);
1158 
1159     return integral[lower] * (1.0f - frac) + integral[lower + 1] * frac;
1160 }
1161 
1162 // Apply a gaussian 'kernel' horizontally at the specified 'x', 'y' location.
eval_H(int x,int y,const std::vector<float> & topVec,const float * kernel,int kernelSize,const uint8_t * integral,int integralSize,float sixSigma)1163 static uint8_t eval_H(int x,
1164                       int y,
1165                       const std::vector<float>& topVec,
1166                       const float* kernel,
1167                       int kernelSize,
1168                       const uint8_t* integral,
1169                       int integralSize,
1170                       float sixSigma) {
1171     SkASSERT(0 <= x && x < (int)topVec.size());
1172     SkASSERT(kernelSize % 2);
1173 
1174     float accum = 0.0f;
1175 
1176     int xSampleLoc = x - (kernelSize / 2);
1177     for (int i = 0; i < kernelSize; ++i, ++xSampleLoc) {
1178         if (xSampleLoc < 0 || xSampleLoc >= (int)topVec.size()) {
1179             continue;
1180         }
1181 
1182         accum += kernel[i] * eval_V(topVec[xSampleLoc], y, integral, integralSize, sixSigma);
1183     }
1184 
1185     return accum + 0.5f;
1186 }
1187 
1188 // Create a cpu-side blurred-rrect mask that is close to the version the gpu would've produced.
1189 // The match needs to be close bc the cpu- and gpu-generated version must be interchangeable.
create_mask_on_cpu(GrRecordingContext * rContext,const SkRRect & rrectToDraw,const SkISize & dimensions,float xformedSigma)1190 static GrSurfaceProxyView create_mask_on_cpu(GrRecordingContext* rContext,
1191                                              const SkRRect& rrectToDraw,
1192                                              const SkISize& dimensions,
1193                                              float xformedSigma) {
1194     SkASSERT(!SkGpuBlurUtils::IsEffectivelyZeroSigma(xformedSigma));
1195     int radius = SkGpuBlurUtils::SigmaRadius(xformedSigma);
1196     int kernelSize = 2 * radius + 1;
1197 
1198     SkASSERT(kernelSize % 2);
1199     SkASSERT(dimensions.width() % 2);
1200     SkASSERT(dimensions.height() % 2);
1201 
1202     SkVector radii = rrectToDraw.getSimpleRadii();
1203     SkASSERT(SkScalarNearlyEqual(radii.fX, radii.fY));
1204 
1205     const int halfWidthPlus1 = (dimensions.width() / 2) + 1;
1206     const int halfHeightPlus1 = (dimensions.height() / 2) + 1;
1207 
1208     std::unique_ptr<float[]> kernel(new float[kernelSize]);
1209 
1210     SkGpuBlurUtils::Compute1DGaussianKernel(kernel.get(), xformedSigma, radius);
1211 
1212     SkBitmap integral;
1213     if (!SkGpuBlurUtils::CreateIntegralTable(6 * xformedSigma, &integral)) {
1214         return {};
1215     }
1216 
1217     SkBitmap result;
1218     if (!result.tryAllocPixels(SkImageInfo::MakeA8(dimensions.width(), dimensions.height()))) {
1219         return {};
1220     }
1221 
1222     std::vector<float> topVec;
1223     topVec.reserve(dimensions.width());
1224     for (int x = 0; x < dimensions.width(); ++x) {
1225         if (x < rrectToDraw.rect().fLeft || x > rrectToDraw.rect().fRight) {
1226             topVec.push_back(-1);
1227         } else {
1228             if (x + 0.5f < rrectToDraw.rect().fLeft + radii.fX) {  // in the circular section
1229                 float xDist = rrectToDraw.rect().fLeft + radii.fX - x - 0.5f;
1230                 float h = sqrtf(radii.fX * radii.fX - xDist * xDist);
1231                 SkASSERT(0 <= h && h < radii.fY);
1232                 topVec.push_back(rrectToDraw.rect().fTop + radii.fX - h + 3 * xformedSigma);
1233             } else {
1234                 topVec.push_back(rrectToDraw.rect().fTop + 3 * xformedSigma);
1235             }
1236         }
1237     }
1238 
1239     for (int y = 0; y < halfHeightPlus1; ++y) {
1240         uint8_t* scanline = result.getAddr8(0, y);
1241 
1242         for (int x = 0; x < halfWidthPlus1; ++x) {
1243             scanline[x] = eval_H(x,
1244                                  y,
1245                                  topVec,
1246                                  kernel.get(),
1247                                  kernelSize,
1248                                  integral.getAddr8(0, 0),
1249                                  integral.width(),
1250                                  6 * xformedSigma);
1251             scanline[dimensions.width() - x - 1] = scanline[x];
1252         }
1253 
1254         memcpy(result.getAddr8(0, dimensions.height() - y - 1), scanline, result.rowBytes());
1255     }
1256 
1257     result.setImmutable();
1258 
1259     auto view = std::get<0>(GrMakeUncachedBitmapProxyView(rContext, result));
1260     if (!view) {
1261         return {};
1262     }
1263 
1264     SkASSERT(view.origin() == kBlurredRRectMaskOrigin);
1265     return view;
1266 }
1267 
find_or_create_rrect_blur_mask_fp(GrRecordingContext * rContext,const SkRRect & rrectToDraw,const SkISize & dimensions,float xformedSigma)1268 static std::unique_ptr<GrFragmentProcessor> find_or_create_rrect_blur_mask_fp(
1269         GrRecordingContext* rContext,
1270         const SkRRect& rrectToDraw,
1271         const SkISize& dimensions,
1272         float xformedSigma) {
1273     SkASSERT(!SkGpuBlurUtils::IsEffectivelyZeroSigma(xformedSigma));
1274     GrUniqueKey key;
1275     make_blurred_rrect_key(&key, rrectToDraw, xformedSigma);
1276 
1277     auto threadSafeCache = rContext->priv().threadSafeCache();
1278 
1279     // It seems like we could omit this matrix and modify the shader code to not normalize
1280     // the coords used to sample the texture effect. However, the "proxyDims" value in the
1281     // shader is not always the actual the proxy dimensions. This is because 'dimensions' here
1282     // was computed using integer corner radii as determined in
1283     // SkComputeBlurredRRectParams whereas the shader code uses the float radius to compute
1284     // 'proxyDims'. Why it draws correctly with these unequal values is a mystery for the ages.
1285     auto m = SkMatrix::Scale(dimensions.width(), dimensions.height());
1286 
1287     GrSurfaceProxyView view;
1288 
1289     if (GrDirectContext* dContext = rContext->asDirectContext()) {
1290         // The gpu thread gets priority over the recording threads. If the gpu thread is first,
1291         // it crams a lazy proxy into the cache and then fills it in later.
1292         auto [lazyView, trampoline] = GrThreadSafeCache::CreateLazyView(dContext,
1293                                                                         GrColorType::kAlpha_8,
1294                                                                         dimensions,
1295                                                                         kBlurredRRectMaskOrigin,
1296                                                                         SkBackingFit::kExact);
1297         if (!lazyView) {
1298             return nullptr;
1299         }
1300 
1301         view = threadSafeCache->findOrAdd(key, lazyView);
1302         if (view != lazyView) {
1303             SkASSERT(view.asTextureProxy());
1304             SkASSERT(view.origin() == kBlurredRRectMaskOrigin);
1305             return GrTextureEffect::Make(std::move(view), kPremul_SkAlphaType, m);
1306         }
1307 
1308         if (!fillin_view_on_gpu(dContext,
1309                                 lazyView,
1310                                 std::move(trampoline),
1311                                 rrectToDraw,
1312                                 dimensions,
1313                                 xformedSigma)) {
1314             // In this case something has gone disastrously wrong so set up to drop the draw
1315             // that needed this resource and reduce future pollution of the cache.
1316             threadSafeCache->remove(key);
1317             return nullptr;
1318         }
1319     } else {
1320         view = threadSafeCache->find(key);
1321         if (view) {
1322             SkASSERT(view.asTextureProxy());
1323             SkASSERT(view.origin() == kBlurredRRectMaskOrigin);
1324             return GrTextureEffect::Make(std::move(view), kPremul_SkAlphaType, m);
1325         }
1326 
1327         view = create_mask_on_cpu(rContext, rrectToDraw, dimensions, xformedSigma);
1328         if (!view) {
1329             return nullptr;
1330         }
1331 
1332         view = threadSafeCache->add(key, view);
1333     }
1334 
1335     SkASSERT(view.asTextureProxy());
1336     SkASSERT(view.origin() == kBlurredRRectMaskOrigin);
1337     return GrTextureEffect::Make(std::move(view), kPremul_SkAlphaType, m);
1338 }
1339 
make_rrect_blur(GrRecordingContext * context,float sigma,float xformedSigma,const SkRRect & srcRRect,const SkRRect & devRRect)1340 static std::unique_ptr<GrFragmentProcessor> make_rrect_blur(GrRecordingContext* context,
1341                                                             float sigma,
1342                                                             float xformedSigma,
1343                                                             const SkRRect& srcRRect,
1344                                                             const SkRRect& devRRect) {
1345     // Should've been caught up-stream
1346 #ifdef SK_DEBUG
1347     SkASSERTF(!SkRRectPriv::IsCircle(devRRect),
1348               "Unexpected circle. %d\n\t%s\n\t%s",
1349               SkRRectPriv::IsCircle(srcRRect),
1350               srcRRect.dumpToString(true).c_str(),
1351               devRRect.dumpToString(true).c_str());
1352     SkASSERTF(!devRRect.isRect(),
1353               "Unexpected rect. %d\n\t%s\n\t%s",
1354               srcRRect.isRect(),
1355               srcRRect.dumpToString(true).c_str(),
1356               devRRect.dumpToString(true).c_str());
1357 #endif
1358 
1359     // TODO: loosen this up
1360     if (!SkRRectPriv::IsSimpleCircular(devRRect)) {
1361         return nullptr;
1362     }
1363 
1364     if (SkGpuBlurUtils::IsEffectivelyZeroSigma(xformedSigma)) {
1365         return nullptr;
1366     }
1367 
1368     // Make sure we can successfully ninepatch this rrect -- the blur sigma has to be sufficiently
1369     // small relative to both the size of the corner radius and the width (and height) of the rrect.
1370     SkRRect rrectToDraw;
1371     SkISize dimensions;
1372     SkScalar ignored[SkGpuBlurUtils::kBlurRRectMaxDivisions];
1373 
1374     bool ninePatchable = SkGpuBlurUtils::ComputeBlurredRRectParams(srcRRect,
1375                                                                    devRRect,
1376                                                                    sigma,
1377                                                                    xformedSigma,
1378                                                                    &rrectToDraw,
1379                                                                    &dimensions,
1380                                                                    ignored,
1381                                                                    ignored,
1382                                                                    ignored,
1383                                                                    ignored);
1384     if (!ninePatchable) {
1385         return nullptr;
1386     }
1387 
1388     std::unique_ptr<GrFragmentProcessor> maskFP =
1389             find_or_create_rrect_blur_mask_fp(context, rrectToDraw, dimensions, xformedSigma);
1390     if (!maskFP) {
1391         return nullptr;
1392     }
1393 
1394     static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader, R"(
1395         uniform shader ninePatchFP;
1396 
1397         uniform half cornerRadius;
1398         uniform float4 proxyRect;
1399         uniform half blurRadius;
1400 
1401         half4 main(float2 xy, half4 inColor) {
1402             // Warp the fragment position to the appropriate part of the 9-patch blur texture by
1403             // snipping out the middle section of the proxy rect.
1404             float2 translatedFragPosFloat = sk_FragCoord.xy - proxyRect.LT;
1405             float2 proxyCenter = (proxyRect.RB - proxyRect.LT) * 0.5;
1406             half edgeSize = 2.0 * blurRadius + cornerRadius + 0.5;
1407 
1408             // Position the fragment so that (0, 0) marks the center of the proxy rectangle.
1409             // Negative coordinates are on the left/top side and positive numbers are on the
1410             // right/bottom.
1411             translatedFragPosFloat -= proxyCenter;
1412 
1413             // Temporarily strip off the fragment's sign. x/y are now strictly increasing as we
1414             // move away from the center.
1415             half2 fragDirection = half2(sign(translatedFragPosFloat));
1416             translatedFragPosFloat = abs(translatedFragPosFloat);
1417 
1418             // Our goal is to snip out the "middle section" of the proxy rect (everything but the
1419             // edge). We've repositioned our fragment position so that (0, 0) is the centerpoint
1420             // and x/y are always positive, so we can subtract here and interpret negative results
1421             // as being within the middle section.
1422             half2 translatedFragPosHalf = half2(translatedFragPosFloat - (proxyCenter - edgeSize));
1423 
1424             // Remove the middle section by clamping to zero.
1425             translatedFragPosHalf = max(translatedFragPosHalf, 0);
1426 
1427             // Reapply the fragment's sign, so that negative coordinates once again mean left/top
1428             // side and positive means bottom/right side.
1429             translatedFragPosHalf *= fragDirection;
1430 
1431             // Offset the fragment so that (0, 0) marks the upper-left again, instead of the center
1432             // point.
1433             translatedFragPosHalf += half2(edgeSize);
1434 
1435             half2 proxyDims = half2(2.0 * edgeSize);
1436             half2 texCoord = translatedFragPosHalf / proxyDims;
1437 
1438             return inColor * ninePatchFP.eval(texCoord).a;
1439         }
1440     )");
1441 
1442     float cornerRadius = SkRRectPriv::GetSimpleRadii(devRRect).fX;
1443     float blurRadius = 3.f * SkScalarCeilToScalar(xformedSigma - 1 / 6.0f);
1444     SkRect proxyRect = devRRect.getBounds().makeOutset(blurRadius, blurRadius);
1445 
1446     return GrSkSLFP::Make(effect, "RRectBlur", /*inputFP=*/nullptr,
1447                           GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
1448                           "ninePatchFP", GrSkSLFP::IgnoreOptFlags(std::move(maskFP)),
1449                           "cornerRadius", cornerRadius,
1450                           "proxyRect", proxyRect,
1451                           "blurRadius", blurRadius);
1452 }
1453 
1454 ///////////////////////////////////////////////////////////////////////////////
1455 
directFilterMaskGPU(GrRecordingContext * context,skgpu::v1::SurfaceDrawContext * sdc,GrPaint && paint,const GrClip * clip,const SkMatrix & viewMatrix,const GrStyledShape & shape) const1456 bool SkBlurMaskFilterImpl::directFilterMaskGPU(GrRecordingContext* context,
1457                                                skgpu::v1::SurfaceDrawContext* sdc,
1458                                                GrPaint&& paint,
1459                                                const GrClip* clip,
1460                                                const SkMatrix& viewMatrix,
1461                                                const GrStyledShape& shape) const {
1462     SkASSERT(sdc);
1463 
1464     if (fBlurStyle != kNormal_SkBlurStyle) {
1465         return false;
1466     }
1467 
1468     // TODO: we could handle blurred stroked circles
1469     if (!shape.style().isSimpleFill()) {
1470         return false;
1471     }
1472 
1473     SkScalar xformedSigma = this->computeXformedSigma(viewMatrix);
1474     if (SkGpuBlurUtils::IsEffectivelyZeroSigma(xformedSigma)) {
1475         sdc->drawShape(clip, std::move(paint), GrAA::kYes, viewMatrix, GrStyledShape(shape));
1476         return true;
1477     }
1478 
1479     SkRRect srcRRect;
1480     bool inverted;
1481     if (!shape.asRRect(&srcRRect, nullptr, nullptr, &inverted) || inverted) {
1482         return false;
1483     }
1484 
1485     std::unique_ptr<GrFragmentProcessor> fp;
1486 
1487     SkRRect devRRect;
1488     bool devRRectIsValid = srcRRect.transform(viewMatrix, &devRRect);
1489 
1490     bool devRRectIsCircle = devRRectIsValid && SkRRectPriv::IsCircle(devRRect);
1491 
1492     bool canBeRect = srcRRect.isRect() && viewMatrix.preservesRightAngles();
1493     bool canBeCircle = (SkRRectPriv::IsCircle(srcRRect) && viewMatrix.isSimilarity()) ||
1494                        devRRectIsCircle;
1495 
1496     if (canBeRect || canBeCircle) {
1497         if (canBeRect) {
1498             fp = make_rect_blur(context, *context->priv().caps()->shaderCaps(),
1499                                 srcRRect.rect(), viewMatrix, xformedSigma);
1500         } else {
1501             SkRect devBounds;
1502             if (devRRectIsCircle) {
1503                 devBounds = devRRect.getBounds();
1504             } else {
1505                 SkPoint center = {srcRRect.getBounds().centerX(), srcRRect.getBounds().centerY()};
1506                 viewMatrix.mapPoints(&center, 1);
1507                 SkScalar radius = viewMatrix.mapVector(0, srcRRect.width()/2.f).length();
1508                 devBounds = {center.x() - radius,
1509                              center.y() - radius,
1510                              center.x() + radius,
1511                              center.y() + radius};
1512             }
1513             fp = make_circle_blur(context, devBounds, xformedSigma);
1514         }
1515 
1516         if (!fp) {
1517             return false;
1518         }
1519 
1520         SkRect srcProxyRect = srcRRect.rect();
1521         // Determine how much to outset the src rect to ensure we hit pixels within three sigma.
1522         SkScalar outsetX = 3.0f*xformedSigma;
1523         SkScalar outsetY = 3.0f*xformedSigma;
1524         if (viewMatrix.isScaleTranslate()) {
1525             outsetX /= SkScalarAbs(viewMatrix.getScaleX());
1526             outsetY /= SkScalarAbs(viewMatrix.getScaleY());
1527         } else {
1528             SkSize scale;
1529             if (!viewMatrix.decomposeScale(&scale, nullptr)) {
1530                 return false;
1531             }
1532             outsetX /= scale.width();
1533             outsetY /= scale.height();
1534         }
1535         srcProxyRect.outset(outsetX, outsetY);
1536 
1537         paint.setCoverageFragmentProcessor(std::move(fp));
1538         sdc->drawRect(clip, std::move(paint), GrAA::kNo, viewMatrix, srcProxyRect);
1539         return true;
1540     }
1541     if (!viewMatrix.isScaleTranslate()) {
1542         return false;
1543     }
1544     if (!devRRectIsValid || !SkRRectPriv::AllCornersCircular(devRRect)) {
1545         return false;
1546     }
1547 
1548     fp = make_rrect_blur(context, fSigma, xformedSigma, srcRRect, devRRect);
1549     if (!fp) {
1550         return false;
1551     }
1552 
1553     if (!this->ignoreXform()) {
1554         SkRect srcProxyRect = srcRRect.rect();
1555         srcProxyRect.outset(3.0f*fSigma, 3.0f*fSigma);
1556         paint.setCoverageFragmentProcessor(std::move(fp));
1557         sdc->drawRect(clip, std::move(paint), GrAA::kNo, viewMatrix, srcProxyRect);
1558     } else {
1559         SkMatrix inverse;
1560         if (!viewMatrix.invert(&inverse)) {
1561             return false;
1562         }
1563 
1564         SkIRect proxyBounds;
1565         float extra=3.f*SkScalarCeilToScalar(xformedSigma-1/6.0f);
1566         devRRect.rect().makeOutset(extra, extra).roundOut(&proxyBounds);
1567 
1568         paint.setCoverageFragmentProcessor(std::move(fp));
1569         sdc->fillPixelsWithLocalMatrix(clip, std::move(paint), proxyBounds, inverse);
1570     }
1571 
1572     return true;
1573 }
1574 
canFilterMaskGPU(const GrStyledShape & shape,const SkIRect & devSpaceShapeBounds,const SkIRect & clipBounds,const SkMatrix & ctm,SkIRect * maskRect,const bool canUseSDFBlur) const1575 bool SkBlurMaskFilterImpl::canFilterMaskGPU(const GrStyledShape& shape,
1576                                             const SkIRect& devSpaceShapeBounds,
1577                                             const SkIRect& clipBounds,
1578                                             const SkMatrix& ctm,
1579                                             SkIRect* maskRect,
1580                                             const bool canUseSDFBlur) const {
1581     SkScalar xformedSigma = this->computeXformedSigma(ctm);
1582     if (SkGpuBlurUtils::IsEffectivelyZeroSigma(xformedSigma)) {
1583         *maskRect = devSpaceShapeBounds;
1584         return maskRect->intersect(clipBounds);
1585     }
1586 
1587     if (maskRect) {
1588         float sigma3 = 3 * SkScalarToFloat(xformedSigma);
1589 
1590         // Outset srcRect and clipRect by 3 * sigma, to compute affected blur area.
1591         SkIRect clipRect = clipBounds.makeOutset(sigma3, sigma3);
1592         SkIRect srcRect = devSpaceShapeBounds.makeOutset(sigma3, sigma3);
1593 
1594         if (!canUseSDFBlur && !srcRect.intersect(clipRect)) {
1595             srcRect.setEmpty();
1596         }
1597         SkRRect srcRRect;
1598         bool inverted;
1599         if (canUseSDFBlur && shape.asRRect(&srcRRect, nullptr, nullptr, &inverted)) {
1600             SkScalar sx = ctm.getScaleX();
1601             SkScalar sy = ctm.getScaleY();
1602             float noxFormedSigma3 = this->getNoxFormedSigma3();
1603             int sigmaX = noxFormedSigma3 * sx;
1604             int sigmaY = noxFormedSigma3 * sy;
1605             srcRect = devSpaceShapeBounds.makeOutset(sigmaX, sigmaY);
1606             srcRect = SkIRect::MakeXYWH(srcRect.fLeft, srcRect.fTop,
1607                 srcRect.width() + srcRRect.rect().fLeft * sx,
1608                 srcRect.height() + srcRRect.rect().fTop * sy);
1609         }
1610         *maskRect = srcRect;
1611     }
1612 
1613     // We prefer to blur paths with small blur radii on the CPU.
1614     static const SkScalar kMIN_GPU_BLUR_SIZE  = SkIntToScalar(64);
1615     static const SkScalar kMIN_GPU_BLUR_SIGMA = SkIntToScalar(32);
1616 
1617     if (devSpaceShapeBounds.width() <= kMIN_GPU_BLUR_SIZE &&
1618         devSpaceShapeBounds.height() <= kMIN_GPU_BLUR_SIZE &&
1619         xformedSigma <= kMIN_GPU_BLUR_SIGMA) {
1620         return false;
1621     }
1622 
1623     return true;
1624 }
1625 
filterMaskGPU(GrRecordingContext * context,GrSurfaceProxyView srcView,GrColorType srcColorType,SkAlphaType srcAlphaType,const SkMatrix & ctm,const SkIRect & maskRect) const1626 GrSurfaceProxyView SkBlurMaskFilterImpl::filterMaskGPU(GrRecordingContext* context,
1627                                                        GrSurfaceProxyView srcView,
1628                                                        GrColorType srcColorType,
1629                                                        SkAlphaType srcAlphaType,
1630                                                        const SkMatrix& ctm,
1631                                                        const SkIRect& maskRect) const {
1632     // 'maskRect' isn't snapped to the UL corner but the mask in 'src' is.
1633     const SkIRect clipRect = SkIRect::MakeWH(maskRect.width(), maskRect.height());
1634 
1635     SkScalar xformedSigma = this->computeXformedSigma(ctm);
1636 
1637     // If we're doing a normal blur, we can clobber the pathTexture in the
1638     // gaussianBlur.  Otherwise, we need to save it for later compositing.
1639     bool isNormalBlur = (kNormal_SkBlurStyle == fBlurStyle);
1640     auto srcBounds = SkIRect::MakeSize(srcView.proxy()->dimensions());
1641     auto surfaceDrawContext = SkGpuBlurUtils::GaussianBlur(context,
1642                                                             srcView,
1643                                                             srcColorType,
1644                                                             srcAlphaType,
1645                                                             nullptr,
1646                                                             clipRect,
1647                                                             srcBounds,
1648                                                             xformedSigma,
1649                                                             xformedSigma,
1650                                                             SkTileMode::kClamp);
1651     if (!surfaceDrawContext || !surfaceDrawContext->asTextureProxy()) {
1652         return {};
1653     }
1654 
1655     if (!isNormalBlur) {
1656         GrPaint paint;
1657         // Blend pathTexture over blurTexture.
1658         paint.setCoverageFragmentProcessor(GrTextureEffect::Make(std::move(srcView), srcAlphaType));
1659         if (kInner_SkBlurStyle == fBlurStyle) {
1660             // inner:  dst = dst * src
1661             paint.setCoverageSetOpXPFactory(SkRegion::kIntersect_Op);
1662         } else if (kSolid_SkBlurStyle == fBlurStyle) {
1663             // solid:  dst = src + dst - src * dst
1664             //             = src + (1 - src) * dst
1665             paint.setCoverageSetOpXPFactory(SkRegion::kUnion_Op);
1666         } else if (kOuter_SkBlurStyle == fBlurStyle) {
1667             // outer:  dst = dst * (1 - src)
1668             //             = 0 * src + (1 - src) * dst
1669             paint.setCoverageSetOpXPFactory(SkRegion::kDifference_Op);
1670         } else {
1671             paint.setCoverageSetOpXPFactory(SkRegion::kReplace_Op);
1672         }
1673 
1674         surfaceDrawContext->fillPixelsWithLocalMatrix(nullptr, std::move(paint), clipRect,
1675                                                       SkMatrix::I());
1676     }
1677 
1678     return surfaceDrawContext->readSurfaceView();
1679 }
1680 
getNoxFormedSigma3() const1681 float SkBlurMaskFilterImpl::getNoxFormedSigma3() const
1682 {
1683     constexpr float kSigma_Factor = 3.f;
1684     return kSigma_Factor * fSigma;
1685 }
1686 
filterMaskGPUNoxFormed(GrRecordingContext * context,GrSurfaceProxyView srcView,GrColorType srcColorType,SkAlphaType srcAlphaType,const SkMatrix & viewMatrix,const SkIRect & maskRect,const SkRRect & srcRRect) const1687 GrSurfaceProxyView SkBlurMaskFilterImpl::filterMaskGPUNoxFormed(GrRecordingContext* context,
1688     GrSurfaceProxyView srcView, GrColorType srcColorType, SkAlphaType srcAlphaType, const SkMatrix& viewMatrix,
1689     const SkIRect& maskRect, const SkRRect& srcRRect) const
1690 {
1691     const SkIRect clipRect = SkIRect::MakeWH(maskRect.width(), maskRect.height());
1692 
1693     float noxFormedSigma = this->getNoxFormedSigma3();
1694 
1695     bool isNormalBlur = (kNormal_SkBlurStyle == fBlurStyle);
1696     if (!isNormalBlur) {
1697         return {};
1698     }
1699     auto srcBounds = SkIRect::MakeSize(srcView.proxy()->dimensions());
1700     auto surfaceDrawContext = SDFBlur::SDFBlur(context, srcView, srcColorType, srcAlphaType, nullptr,
1701         clipRect, srcBounds, noxFormedSigma, SkTileMode::kClamp, viewMatrix, srcRRect);
1702     if (!surfaceDrawContext || !surfaceDrawContext->asTextureProxy()) {
1703         return {};
1704     }
1705 
1706     return surfaceDrawContext->readSurfaceView();
1707 }
1708 
1709 #endif // SK_SUPPORT_GPU && SK_GPU_V1
1710 
sk_register_blur_maskfilter_createproc()1711 void sk_register_blur_maskfilter_createproc() { SK_REGISTER_FLATTENABLE(SkBlurMaskFilterImpl); }
1712 
MakeBlur(SkBlurStyle style,SkScalar sigma,bool respectCTM)1713 sk_sp<SkMaskFilter> SkMaskFilter::MakeBlur(SkBlurStyle style, SkScalar sigma, bool respectCTM) {
1714     if (SkScalarIsFinite(sigma) && sigma > 0) {
1715         return sk_sp<SkMaskFilter>(new SkBlurMaskFilterImpl(sigma, style, respectCTM));
1716     }
1717     return nullptr;
1718 }
1719