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