3 * Copyright 2006 The Android Open Source Project
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
9 #include "SkBlurMaskFilter.h"
10 #include "SkBlurMask.h"
11 #include "SkGpuBlurUtils.h"
12 #include "SkFlattenableBuffers.h"
13 #include "SkMaskFilter.h"
15 #include "SkStringUtils.h"
16 #include "SkStrokeRec.h"
19 #include "GrContext.h"
20 #include "GrTexture.h"
21 #include "effects/GrSimpleTextureEffect.h"
22 #include "SkGrPixelRef.h"
25 class SkBlurMaskFilterImpl : public SkMaskFilter {
27 SkBlurMaskFilterImpl(SkScalar sigma, SkBlurMaskFilter::BlurStyle, uint32_t flags);
29 // overrides from SkMaskFilter
30 virtual SkMask::Format getFormat() const SK_OVERRIDE;
31 virtual bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&,
32 SkIPoint* margin) const SK_OVERRIDE;
35 virtual bool canFilterMaskGPU(const SkRect& devBounds,
36 const SkIRect& clipBounds,
38 SkRect* maskRect) const SK_OVERRIDE;
39 virtual bool filterMaskGPU(GrTexture* src,
40 const SkRect& maskRect,
42 bool canOverwriteSrc) const;
45 virtual void computeFastBounds(const SkRect&, SkRect*) const SK_OVERRIDE;
47 SkDEVCODE(virtual void toString(SkString* str) const SK_OVERRIDE;)
48 SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkBlurMaskFilterImpl)
51 virtual FilterReturn filterRectsToNine(const SkRect[], int count, const SkMatrix&,
52 const SkIRect& clipBounds,
53 NinePatch*) const SK_OVERRIDE;
55 bool filterRectMask(SkMask* dstM, const SkRect& r, const SkMatrix& matrix,
56 SkIPoint* margin, SkMask::CreateMode createMode) const;
59 // To avoid unseemly allocation requests (esp. for finite platforms like
60 // handset) we limit the radius so something manageable. (as opposed to
61 // a request like 10,000)
62 static const SkScalar kMAX_BLUR_SIGMA;
65 SkBlurMaskFilter::BlurStyle fBlurStyle;
68 SkBlurMaskFilterImpl(SkFlattenableReadBuffer&);
69 virtual void flatten(SkFlattenableWriteBuffer&) const SK_OVERRIDE;
71 SkScalar computeXformedSigma(const SkMatrix& ctm) const {
72 bool ignoreTransform = SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag);
74 SkScalar xformedSigma = ignoreTransform ? fSigma : ctm.mapRadius(fSigma);
75 return SkMinScalar(xformedSigma, kMAX_BLUR_SIGMA);
78 typedef SkMaskFilter INHERITED;
81 const SkScalar SkBlurMaskFilterImpl::kMAX_BLUR_SIGMA = SkIntToScalar(128);
83 SkMaskFilter* SkBlurMaskFilter::Create(SkScalar radius,
84 SkBlurMaskFilter::BlurStyle style,
86 // use !(radius > 0) instead of radius <= 0 to reject NaN values
87 if (!(radius > 0) || (unsigned)style >= SkBlurMaskFilter::kBlurStyleCount
88 || flags > SkBlurMaskFilter::kAll_BlurFlag) {
92 SkScalar sigma = SkBlurMask::ConvertRadiusToSigma(radius);
94 return SkNEW_ARGS(SkBlurMaskFilterImpl, (sigma, style, flags));
97 SkMaskFilter* SkBlurMaskFilter::Create(SkBlurMaskFilter::BlurStyle style,
100 // use !(sigma > 0) instead of sigma <= 0 to reject NaN values
101 if (!(sigma > 0) || (unsigned)style >= SkBlurMaskFilter::kBlurStyleCount
102 || flags > SkBlurMaskFilter::kAll_BlurFlag) {
106 return SkNEW_ARGS(SkBlurMaskFilterImpl, (sigma, style, flags));
109 ///////////////////////////////////////////////////////////////////////////////
111 SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar sigma,
112 SkBlurMaskFilter::BlurStyle style,
114 : fSigma(sigma), fBlurStyle(style), fBlurFlags(flags) {
118 fGamma = new U8[256];
120 SkBlurMask::BuildSqrGamma(fGamma, gammaScale);
122 SkBlurMask::BuildSqrtGamma(fGamma, -gammaScale);
125 SkASSERT(fSigma >= 0);
126 SkASSERT((unsigned)style < SkBlurMaskFilter::kBlurStyleCount);
127 SkASSERT(flags <= SkBlurMaskFilter::kAll_BlurFlag);
130 SkMask::Format SkBlurMaskFilterImpl::getFormat() const {
131 return SkMask::kA8_Format;
134 bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src,
135 const SkMatrix& matrix,
136 SkIPoint* margin) const{
137 SkScalar sigma = this->computeXformedSigma(matrix);
139 SkBlurMask::Quality blurQuality =
140 (fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag) ?
141 SkBlurMask::kHigh_Quality : SkBlurMask::kLow_Quality;
143 return SkBlurMask::BoxBlur(dst, src, sigma, (SkBlurMask::Style)fBlurStyle,
144 blurQuality, margin);
147 bool SkBlurMaskFilterImpl::filterRectMask(SkMask* dst, const SkRect& r,
148 const SkMatrix& matrix,
149 SkIPoint* margin, SkMask::CreateMode createMode) const{
150 SkScalar sigma = computeXformedSigma(matrix);
152 return SkBlurMask::BlurRect(sigma, dst, r, (SkBlurMask::Style)fBlurStyle,
156 #include "SkCanvas.h"
158 static bool drawRectsIntoMask(const SkRect rects[], int count, SkMask* mask) {
159 rects[0].roundOut(&mask->fBounds);
160 mask->fRowBytes = SkAlign4(mask->fBounds.width());
161 mask->fFormat = SkMask::kA8_Format;
162 size_t size = mask->computeImageSize();
163 mask->fImage = SkMask::AllocImage(size);
164 if (NULL == mask->fImage) {
167 sk_bzero(mask->fImage, size);
170 bitmap.setConfig(SkBitmap::kA8_Config,
171 mask->fBounds.width(), mask->fBounds.height(),
173 bitmap.setPixels(mask->fImage);
175 SkCanvas canvas(bitmap);
176 canvas.translate(-SkIntToScalar(mask->fBounds.left()),
177 -SkIntToScalar(mask->fBounds.top()));
180 paint.setAntiAlias(true);
183 canvas.drawRect(rects[0], paint);
185 // todo: do I need a fast way to do this?
187 path.addRect(rects[0]);
188 path.addRect(rects[1]);
189 path.setFillType(SkPath::kEvenOdd_FillType);
190 canvas.drawPath(path, paint);
195 static bool rect_exceeds(const SkRect& r, SkScalar v) {
196 return r.fLeft < -v || r.fTop < -v || r.fRight > v || r.fBottom > v ||
197 r.width() > v || r.height() > v;
200 #ifdef SK_IGNORE_FAST_RECT_BLUR
201 SK_CONF_DECLARE( bool, c_analyticBlurNinepatch, "mask.filter.analyticNinePatch", false, "Use the faster analytic blur approach for ninepatch rects" );
203 SK_CONF_DECLARE( bool, c_analyticBlurNinepatch, "mask.filter.analyticNinePatch", true, "Use the faster analytic blur approach for ninepatch rects" );
206 SkMaskFilter::FilterReturn
207 SkBlurMaskFilterImpl::filterRectsToNine(const SkRect rects[], int count,
208 const SkMatrix& matrix,
209 const SkIRect& clipBounds,
210 NinePatch* patch) const {
211 if (count < 1 || count > 2) {
212 return kUnimplemented_FilterReturn;
215 // TODO: report correct metrics for innerstyle, where we do not grow the
216 // total bounds, but we do need an inset the size of our blur-radius
217 if (SkBlurMaskFilter::kInner_BlurStyle == fBlurStyle) {
218 return kUnimplemented_FilterReturn;
221 // TODO: take clipBounds into account to limit our coordinates up front
222 // for now, just skip too-large src rects (to take the old code path).
223 if (rect_exceeds(rects[0], SkIntToScalar(32767))) {
224 return kUnimplemented_FilterReturn;
229 rects[0].roundOut(&srcM.fBounds);
231 srcM.fFormat = SkMask::kA8_Format;
234 bool filterResult = false;
235 if (count == 1 && c_analyticBlurNinepatch) {
236 // special case for fast rect blur
237 // don't actually do the blur the first time, just compute the correct size
238 filterResult = this->filterRectMask(&dstM, rects[0], matrix, &margin,
239 SkMask::kJustComputeBounds_CreateMode);
241 filterResult = this->filterMask(&dstM, srcM, matrix, &margin);
245 return kFalse_FilterReturn;
249 * smallR is the smallest version of 'rect' that will still guarantee that
250 * we get the same blur results on all edges, plus 1 center row/col that is
251 * representative of the extendible/stretchable edges of the ninepatch.
252 * Since our actual edge may be fractional we inset 1 more to be sure we
253 * don't miss any interior blur.
254 * x is an added pixel of blur, and { and } are the (fractional) edge
255 * pixels from the original rect.
257 * x x { x x .... x x } x x
259 * Thus, in this case, we inset by a total of 5 (on each side) beginning
260 * with our outer-rect (dstM.fBounds)
265 // +2 is from +1 for each edge (to account for possible fractional edges
266 int smallW = dstM.fBounds.width() - srcM.fBounds.width() + 2;
267 int smallH = dstM.fBounds.height() - srcM.fBounds.height() + 2;
271 innerIR = srcM.fBounds;
272 center.set(smallW, smallH);
274 SkASSERT(2 == count);
275 rects[1].roundIn(&innerIR);
276 center.set(smallW + (innerIR.left() - srcM.fBounds.left()),
277 smallH + (innerIR.top() - srcM.fBounds.top()));
280 // +1 so we get a clean, stretchable, center row/col
284 // we want the inset amounts to be integral, so we don't change any
285 // fractional phase on the fRight or fBottom of our smallR.
286 const SkScalar dx = SkIntToScalar(innerIR.width() - smallW);
287 const SkScalar dy = SkIntToScalar(innerIR.height() - smallH);
288 if (dx < 0 || dy < 0) {
289 // we're too small, relative to our blur, to break into nine-patch,
290 // so we ask to have our normal filterMask() be called.
291 return kUnimplemented_FilterReturn;
294 smallR[0].set(rects[0].left(), rects[0].top(), rects[0].right() - dx, rects[0].bottom() - dy);
295 if (smallR[0].width() < 2 || smallR[0].height() < 2) {
296 return kUnimplemented_FilterReturn;
299 smallR[1].set(rects[1].left(), rects[1].top(),
300 rects[1].right() - dx, rects[1].bottom() - dy);
301 SkASSERT(!smallR[1].isEmpty());
304 if (count > 1 || !c_analyticBlurNinepatch) {
305 if (!drawRectsIntoMask(smallR, count, &srcM)) {
306 return kFalse_FilterReturn;
309 SkAutoMaskFreeImage amf(srcM.fImage);
311 if (!this->filterMask(&patch->fMask, srcM, matrix, &margin)) {
312 return kFalse_FilterReturn;
315 if (!this->filterRectMask(&patch->fMask, smallR[0], matrix, &margin,
316 SkMask::kComputeBoundsAndRenderImage_CreateMode)) {
317 return kFalse_FilterReturn;
320 patch->fMask.fBounds.offsetTo(0, 0);
321 patch->fOuterRect = dstM.fBounds;
322 patch->fCenter = center;
323 return kTrue_FilterReturn;
326 void SkBlurMaskFilterImpl::computeFastBounds(const SkRect& src,
328 SkScalar pad = 3.0f * fSigma;
330 dst->set(src.fLeft - pad, src.fTop - pad,
331 src.fRight + pad, src.fBottom + pad);
334 SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkFlattenableReadBuffer& buffer)
335 : SkMaskFilter(buffer) {
336 fSigma = buffer.readScalar();
337 #ifndef DELETE_THIS_CODE_WHEN_SKPS_ARE_REBUILT_AT_V13_AND_ALL_OTHER_INSTANCES_TOO
338 // Fixing this must be done in two stages. When the skps are recaptured in V13,
339 // remove the ConvertRadiusToSigma but retain the absolute value.
340 // At the same time, switch the code in flatten to write a positive value.
341 // When the skps are captured in V14 the absolute value can be removed.
343 fSigma = SkBlurMask::ConvertRadiusToSigma(fSigma);
348 fBlurStyle = (SkBlurMaskFilter::BlurStyle)buffer.readInt();
349 fBlurFlags = buffer.readUInt() & SkBlurMaskFilter::kAll_BlurFlag;
350 SkASSERT(fSigma >= 0);
351 SkASSERT((unsigned)fBlurStyle < SkBlurMaskFilter::kBlurStyleCount);
354 void SkBlurMaskFilterImpl::flatten(SkFlattenableWriteBuffer& buffer) const {
355 this->INHERITED::flatten(buffer);
356 buffer.writeScalar(-fSigma);
357 buffer.writeInt(fBlurStyle);
358 buffer.writeUInt(fBlurFlags);
363 bool SkBlurMaskFilterImpl::canFilterMaskGPU(const SkRect& srcBounds,
364 const SkIRect& clipBounds,
366 SkRect* maskRect) const {
367 SkScalar xformedSigma = this->computeXformedSigma(ctm);
368 if (xformedSigma <= 0) {
372 static const SkScalar kMIN_GPU_BLUR_SIZE = SkIntToScalar(64);
373 static const SkScalar kMIN_GPU_BLUR_SIGMA = SkIntToScalar(32);
375 if (srcBounds.width() <= kMIN_GPU_BLUR_SIZE &&
376 srcBounds.height() <= kMIN_GPU_BLUR_SIZE &&
377 xformedSigma <= kMIN_GPU_BLUR_SIGMA) {
378 // We prefer to blur small rect with small radius via CPU.
382 if (NULL == maskRect) {
383 // don't need to compute maskRect
387 float sigma3 = 3 * SkScalarToFloat(xformedSigma);
389 SkRect clipRect = SkRect::Make(clipBounds);
390 SkRect srcRect(srcBounds);
392 // Outset srcRect and clipRect by 3 * sigma, to compute affected blur area.
393 srcRect.outset(SkFloatToScalar(sigma3), SkFloatToScalar(sigma3));
394 clipRect.outset(SkFloatToScalar(sigma3), SkFloatToScalar(sigma3));
395 srcRect.intersect(clipRect);
400 bool SkBlurMaskFilterImpl::filterMaskGPU(GrTexture* src,
401 const SkRect& maskRect,
403 bool canOverwriteSrc) const {
404 SkRect clipRect = SkRect::MakeWH(maskRect.width(), maskRect.height());
406 GrContext* context = src->getContext();
408 GrContext::AutoWideOpenIdentityDraw awo(context, NULL);
410 SkScalar xformedSigma = this->computeXformedSigma(context->getMatrix());
411 SkASSERT(xformedSigma > 0);
413 // If we're doing a normal blur, we can clobber the pathTexture in the
414 // gaussianBlur. Otherwise, we need to save it for later compositing.
415 bool isNormalBlur = (SkBlurMaskFilter::kNormal_BlurStyle == fBlurStyle);
416 *result = SkGpuBlurUtils::GaussianBlur(context, src, isNormalBlur && canOverwriteSrc,
417 clipRect, false, xformedSigma, xformedSigma);
418 if (NULL == *result) {
423 context->setIdentityMatrix();
426 matrix.setIDiv(src->width(), src->height());
427 // Blend pathTexture over blurTexture.
428 GrContext::AutoRenderTarget art(context, (*result)->asRenderTarget());
429 paint.addColorEffect(GrSimpleTextureEffect::Create(src, matrix))->unref();
430 if (SkBlurMaskFilter::kInner_BlurStyle == fBlurStyle) {
431 // inner: dst = dst * src
432 paint.setBlendFunc(kDC_GrBlendCoeff, kZero_GrBlendCoeff);
433 } else if (SkBlurMaskFilter::kSolid_BlurStyle == fBlurStyle) {
434 // solid: dst = src + dst - src * dst
435 // = (1 - dst) * src + 1 * dst
436 paint.setBlendFunc(kIDC_GrBlendCoeff, kOne_GrBlendCoeff);
437 } else if (SkBlurMaskFilter::kOuter_BlurStyle == fBlurStyle) {
438 // outer: dst = dst * (1 - src)
439 // = 0 * src + (1 - src) * dst
440 paint.setBlendFunc(kZero_GrBlendCoeff, kISC_GrBlendCoeff);
442 context->drawRect(paint, clipRect);
448 #endif // SK_SUPPORT_GPU
452 void SkBlurMaskFilterImpl::toString(SkString* str) const {
453 str->append("SkBlurMaskFilterImpl: (");
455 str->append("sigma: ");
456 str->appendScalar(fSigma);
459 static const char* gStyleName[SkBlurMaskFilter::kBlurStyleCount] = {
460 "normal", "solid", "outer", "inner"
463 str->appendf("style: %s ", gStyleName[fBlurStyle]);
464 str->append("flags: (");
466 bool needSeparator = false;
467 SkAddFlagToString(str,
468 SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag),
469 "IgnoreXform", &needSeparator);
470 SkAddFlagToString(str,
471 SkToBool(fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag),
472 "HighQuality", &needSeparator);
480 SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkBlurMaskFilter)
481 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkBlurMaskFilterImpl)
482 SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END