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