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"
16 #include "SkStringUtils.h"
17 #include "SkStrokeRec.h"
20 #include "GrContext.h"
21 #include "GrTexture.h"
22 #include "effects/GrSimpleTextureEffect.h"
23 #include "SkGrPixelRef.h"
26 class SkBlurMaskFilterImpl : public SkMaskFilter {
28 SkBlurMaskFilterImpl(SkScalar sigma, SkBlurMaskFilter::BlurStyle, uint32_t flags);
30 // overrides from SkMaskFilter
31 virtual SkMask::Format getFormat() const SK_OVERRIDE;
32 virtual bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&,
33 SkIPoint* margin) const SK_OVERRIDE;
36 virtual bool canFilterMaskGPU(const SkRect& devBounds,
37 const SkIRect& clipBounds,
39 SkRect* maskRect) const SK_OVERRIDE;
40 virtual bool filterMaskGPU(GrTexture* src,
42 const SkRect& maskRect,
44 bool canOverwriteSrc) const SK_OVERRIDE;
47 virtual void computeFastBounds(const SkRect&, SkRect*) const SK_OVERRIDE;
49 SkDEVCODE(virtual void toString(SkString* str) const SK_OVERRIDE;)
50 SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkBlurMaskFilterImpl)
53 virtual FilterReturn filterRectsToNine(const SkRect[], int count, const SkMatrix&,
54 const SkIRect& clipBounds,
55 NinePatch*) const SK_OVERRIDE;
57 virtual FilterReturn filterRRectToNine(const SkRRect&, const SkMatrix&,
58 const SkIRect& clipBounds,
59 NinePatch*) const SK_OVERRIDE;
61 bool filterRectMask(SkMask* dstM, const SkRect& r, const SkMatrix& matrix,
62 SkIPoint* margin, SkMask::CreateMode createMode) const;
65 // To avoid unseemly allocation requests (esp. for finite platforms like
66 // handset) we limit the radius so something manageable. (as opposed to
67 // a request like 10,000)
68 static const SkScalar kMAX_BLUR_SIGMA;
71 SkBlurMaskFilter::BlurStyle fBlurStyle;
74 SkBlurMaskFilterImpl(SkFlattenableReadBuffer&);
75 virtual void flatten(SkFlattenableWriteBuffer&) const SK_OVERRIDE;
77 SkScalar computeXformedSigma(const SkMatrix& ctm) const {
78 bool ignoreTransform = SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag);
80 SkScalar xformedSigma = ignoreTransform ? fSigma : ctm.mapRadius(fSigma);
81 return SkMinScalar(xformedSigma, kMAX_BLUR_SIGMA);
84 typedef SkMaskFilter INHERITED;
87 const SkScalar SkBlurMaskFilterImpl::kMAX_BLUR_SIGMA = SkIntToScalar(128);
89 SkMaskFilter* SkBlurMaskFilter::Create(SkScalar radius,
90 SkBlurMaskFilter::BlurStyle style,
92 // use !(radius > 0) instead of radius <= 0 to reject NaN values
93 if (!(radius > 0) || (unsigned)style >= SkBlurMaskFilter::kBlurStyleCount
94 || flags > SkBlurMaskFilter::kAll_BlurFlag) {
98 SkScalar sigma = SkBlurMask::ConvertRadiusToSigma(radius);
100 return SkNEW_ARGS(SkBlurMaskFilterImpl, (sigma, style, flags));
103 SkMaskFilter* SkBlurMaskFilter::Create(SkBlurMaskFilter::BlurStyle style,
106 // use !(sigma > 0) instead of sigma <= 0 to reject NaN values
107 if (!(sigma > 0) || (unsigned)style >= SkBlurMaskFilter::kBlurStyleCount
108 || flags > SkBlurMaskFilter::kAll_BlurFlag) {
112 return SkNEW_ARGS(SkBlurMaskFilterImpl, (sigma, style, flags));
115 ///////////////////////////////////////////////////////////////////////////////
117 SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar sigma,
118 SkBlurMaskFilter::BlurStyle style,
120 : fSigma(sigma), fBlurStyle(style), fBlurFlags(flags) {
124 fGamma = new U8[256];
126 SkBlurMask::BuildSqrGamma(fGamma, gammaScale);
128 SkBlurMask::BuildSqrtGamma(fGamma, -gammaScale);
131 SkASSERT(fSigma >= 0);
132 SkASSERT((unsigned)style < SkBlurMaskFilter::kBlurStyleCount);
133 SkASSERT(flags <= SkBlurMaskFilter::kAll_BlurFlag);
136 SkMask::Format SkBlurMaskFilterImpl::getFormat() const {
137 return SkMask::kA8_Format;
140 bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src,
141 const SkMatrix& matrix,
142 SkIPoint* margin) const{
143 SkScalar sigma = this->computeXformedSigma(matrix);
145 SkBlurMask::Quality blurQuality =
146 (fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag) ?
147 SkBlurMask::kHigh_Quality : SkBlurMask::kLow_Quality;
149 return SkBlurMask::BoxBlur(dst, src, sigma, (SkBlurMask::Style)fBlurStyle,
150 blurQuality, margin);
153 bool SkBlurMaskFilterImpl::filterRectMask(SkMask* dst, const SkRect& r,
154 const SkMatrix& matrix,
155 SkIPoint* margin, SkMask::CreateMode createMode) const{
156 SkScalar sigma = computeXformedSigma(matrix);
158 return SkBlurMask::BlurRect(sigma, dst, r, (SkBlurMask::Style)fBlurStyle,
162 #include "SkCanvas.h"
164 static bool prepare_to_draw_into_mask(const SkRect& bounds, SkMask* mask) {
165 SkASSERT(mask != NULL);
167 bounds.roundOut(&mask->fBounds);
168 mask->fRowBytes = SkAlign4(mask->fBounds.width());
169 mask->fFormat = SkMask::kA8_Format;
170 const size_t size = mask->computeImageSize();
171 mask->fImage = SkMask::AllocImage(size);
172 if (NULL == mask->fImage) {
176 // FIXME: use sk_calloc in AllocImage?
177 sk_bzero(mask->fImage, size);
181 static bool draw_rrect_into_mask(const SkRRect rrect, SkMask* mask) {
182 if (!prepare_to_draw_into_mask(rrect.rect(), mask)) {
186 // FIXME: This code duplicates code in draw_rects_into_mask, below. Is there a
187 // clean way to share more code?
189 bitmap.setConfig(SkBitmap::kA8_Config,
190 mask->fBounds.width(), mask->fBounds.height(),
192 bitmap.setPixels(mask->fImage);
194 SkCanvas canvas(bitmap);
195 canvas.translate(-SkIntToScalar(mask->fBounds.left()),
196 -SkIntToScalar(mask->fBounds.top()));
199 paint.setAntiAlias(true);
200 canvas.drawRRect(rrect, paint);
204 static bool draw_rects_into_mask(const SkRect rects[], int count, SkMask* mask) {
205 if (!prepare_to_draw_into_mask(rects[0], mask)) {
210 bitmap.setConfig(SkBitmap::kA8_Config,
211 mask->fBounds.width(), mask->fBounds.height(),
213 bitmap.setPixels(mask->fImage);
215 SkCanvas canvas(bitmap);
216 canvas.translate(-SkIntToScalar(mask->fBounds.left()),
217 -SkIntToScalar(mask->fBounds.top()));
220 paint.setAntiAlias(true);
223 canvas.drawRect(rects[0], paint);
225 // todo: do I need a fast way to do this?
227 path.addRect(rects[0]);
228 path.addRect(rects[1]);
229 path.setFillType(SkPath::kEvenOdd_FillType);
230 canvas.drawPath(path, paint);
235 static bool rect_exceeds(const SkRect& r, SkScalar v) {
236 return r.fLeft < -v || r.fTop < -v || r.fRight > v || r.fBottom > v ||
237 r.width() > v || r.height() > v;
240 SkMaskFilter::FilterReturn
241 SkBlurMaskFilterImpl::filterRRectToNine(const SkRRect& rrect, const SkMatrix& matrix,
242 const SkIRect& clipBounds,
243 NinePatch* patch) const {
244 SkASSERT(patch != NULL);
245 switch (rrect.getType()) {
246 case SkRRect::kUnknown_Type:
247 // Unknown should never be returned.
250 case SkRRect::kEmpty_Type:
252 return kFalse_FilterReturn;
254 case SkRRect::kRect_Type:
255 // We should have caught this earlier.
258 case SkRRect::kOval_Type:
259 // The nine patch special case does not handle ovals, and we
260 // already have code for rectangles.
261 return kUnimplemented_FilterReturn;
263 case SkRRect::kSimple_Type:
265 case SkRRect::kComplex_Type:
266 // These can take advantage of this fast path.
270 // TODO: report correct metrics for innerstyle, where we do not grow the
271 // total bounds, but we do need an inset the size of our blur-radius
272 if (SkBlurMaskFilter::kInner_BlurStyle == fBlurStyle) {
273 return kUnimplemented_FilterReturn;
276 // TODO: take clipBounds into account to limit our coordinates up front
277 // for now, just skip too-large src rects (to take the old code path).
278 if (rect_exceeds(rrect.rect(), SkIntToScalar(32767))) {
279 return kUnimplemented_FilterReturn;
284 rrect.rect().roundOut(&srcM.fBounds);
286 srcM.fFormat = SkMask::kA8_Format;
289 if (!this->filterMask(&dstM, srcM, matrix, &margin)) {
290 return kFalse_FilterReturn;
293 // Now figure out the appropriate width and height of the smaller round rectangle
294 // to stretch. It will take into account the larger radius per side as well as double
295 // the margin, to account for inner and outer blur.
296 const SkVector& UL = rrect.radii(SkRRect::kUpperLeft_Corner);
297 const SkVector& UR = rrect.radii(SkRRect::kUpperRight_Corner);
298 const SkVector& LR = rrect.radii(SkRRect::kLowerRight_Corner);
299 const SkVector& LL = rrect.radii(SkRRect::kLowerLeft_Corner);
301 const SkScalar leftUnstretched = SkTMax(UL.fX, LL.fX) + SkIntToScalar(2 * margin.fX);
302 const SkScalar rightUnstretched = SkTMax(UR.fX, LR.fX) + SkIntToScalar(2 * margin.fX);
304 // Extra space in the middle to ensure an unchanging piece for stretching. Use 3 to cover
305 // any fractional space on either side plus 1 for the part to stretch.
306 const SkScalar stretchSize = SkIntToScalar(3);
308 const SkScalar totalSmallWidth = leftUnstretched + rightUnstretched + stretchSize;
309 if (totalSmallWidth >= rrect.rect().width()) {
310 // There is no valid piece to stretch.
311 return kUnimplemented_FilterReturn;
314 const SkScalar topUnstretched = SkTMax(UL.fY, UR.fY) + SkIntToScalar(2 * margin.fY);
315 const SkScalar bottomUnstretched = SkTMax(LL.fY, LR.fY) + SkIntToScalar(2 * margin.fY);
317 const SkScalar totalSmallHeight = topUnstretched + bottomUnstretched + stretchSize;
318 if (totalSmallHeight >= rrect.rect().height()) {
319 // There is no valid piece to stretch.
320 return kUnimplemented_FilterReturn;
323 SkRect smallR = SkRect::MakeWH(totalSmallWidth, totalSmallHeight);
327 radii[SkRRect::kUpperLeft_Corner] = UL;
328 radii[SkRRect::kUpperRight_Corner] = UR;
329 radii[SkRRect::kLowerRight_Corner] = LR;
330 radii[SkRRect::kLowerLeft_Corner] = LL;
331 smallRR.setRectRadii(smallR, radii);
333 if (!draw_rrect_into_mask(smallRR, &srcM)) {
334 return kFalse_FilterReturn;
337 SkAutoMaskFreeImage amf(srcM.fImage);
339 if (!this->filterMask(&patch->fMask, srcM, matrix, &margin)) {
340 return kFalse_FilterReturn;
343 patch->fMask.fBounds.offsetTo(0, 0);
344 patch->fOuterRect = dstM.fBounds;
345 patch->fCenter.fX = SkScalarCeilToInt(leftUnstretched) + 1;
346 patch->fCenter.fY = SkScalarCeilToInt(topUnstretched) + 1;
347 return kTrue_FilterReturn;
350 #ifdef SK_IGNORE_FAST_RECT_BLUR
351 SK_CONF_DECLARE( bool, c_analyticBlurNinepatch, "mask.filter.analyticNinePatch", false, "Use the faster analytic blur approach for ninepatch rects" );
353 SK_CONF_DECLARE( bool, c_analyticBlurNinepatch, "mask.filter.analyticNinePatch", true, "Use the faster analytic blur approach for ninepatch rects" );
356 SkMaskFilter::FilterReturn
357 SkBlurMaskFilterImpl::filterRectsToNine(const SkRect rects[], int count,
358 const SkMatrix& matrix,
359 const SkIRect& clipBounds,
360 NinePatch* patch) const {
361 if (count < 1 || count > 2) {
362 return kUnimplemented_FilterReturn;
365 // TODO: report correct metrics for innerstyle, where we do not grow the
366 // total bounds, but we do need an inset the size of our blur-radius
367 if (SkBlurMaskFilter::kInner_BlurStyle == fBlurStyle ||
368 SkBlurMaskFilter::kOuter_BlurStyle == fBlurStyle) {
369 return kUnimplemented_FilterReturn;
372 // TODO: take clipBounds into account to limit our coordinates up front
373 // for now, just skip too-large src rects (to take the old code path).
374 if (rect_exceeds(rects[0], SkIntToScalar(32767))) {
375 return kUnimplemented_FilterReturn;
380 rects[0].roundOut(&srcM.fBounds);
382 srcM.fFormat = SkMask::kA8_Format;
385 bool filterResult = false;
386 if (count == 1 && c_analyticBlurNinepatch) {
387 // special case for fast rect blur
388 // don't actually do the blur the first time, just compute the correct size
389 filterResult = this->filterRectMask(&dstM, rects[0], matrix, &margin,
390 SkMask::kJustComputeBounds_CreateMode);
392 filterResult = this->filterMask(&dstM, srcM, matrix, &margin);
396 return kFalse_FilterReturn;
400 * smallR is the smallest version of 'rect' that will still guarantee that
401 * we get the same blur results on all edges, plus 1 center row/col that is
402 * representative of the extendible/stretchable edges of the ninepatch.
403 * Since our actual edge may be fractional we inset 1 more to be sure we
404 * don't miss any interior blur.
405 * x is an added pixel of blur, and { and } are the (fractional) edge
406 * pixels from the original rect.
408 * x x { x x .... x x } x x
410 * Thus, in this case, we inset by a total of 5 (on each side) beginning
411 * with our outer-rect (dstM.fBounds)
416 // +2 is from +1 for each edge (to account for possible fractional edges
417 int smallW = dstM.fBounds.width() - srcM.fBounds.width() + 2;
418 int smallH = dstM.fBounds.height() - srcM.fBounds.height() + 2;
422 innerIR = srcM.fBounds;
423 center.set(smallW, smallH);
425 SkASSERT(2 == count);
426 rects[1].roundIn(&innerIR);
427 center.set(smallW + (innerIR.left() - srcM.fBounds.left()),
428 smallH + (innerIR.top() - srcM.fBounds.top()));
431 // +1 so we get a clean, stretchable, center row/col
435 // we want the inset amounts to be integral, so we don't change any
436 // fractional phase on the fRight or fBottom of our smallR.
437 const SkScalar dx = SkIntToScalar(innerIR.width() - smallW);
438 const SkScalar dy = SkIntToScalar(innerIR.height() - smallH);
439 if (dx < 0 || dy < 0) {
440 // we're too small, relative to our blur, to break into nine-patch,
441 // so we ask to have our normal filterMask() be called.
442 return kUnimplemented_FilterReturn;
445 smallR[0].set(rects[0].left(), rects[0].top(), rects[0].right() - dx, rects[0].bottom() - dy);
446 if (smallR[0].width() < 2 || smallR[0].height() < 2) {
447 return kUnimplemented_FilterReturn;
450 smallR[1].set(rects[1].left(), rects[1].top(),
451 rects[1].right() - dx, rects[1].bottom() - dy);
452 SkASSERT(!smallR[1].isEmpty());
455 if (count > 1 || !c_analyticBlurNinepatch) {
456 if (!draw_rects_into_mask(smallR, count, &srcM)) {
457 return kFalse_FilterReturn;
460 SkAutoMaskFreeImage amf(srcM.fImage);
462 if (!this->filterMask(&patch->fMask, srcM, matrix, &margin)) {
463 return kFalse_FilterReturn;
466 if (!this->filterRectMask(&patch->fMask, smallR[0], matrix, &margin,
467 SkMask::kComputeBoundsAndRenderImage_CreateMode)) {
468 return kFalse_FilterReturn;
471 patch->fMask.fBounds.offsetTo(0, 0);
472 patch->fOuterRect = dstM.fBounds;
473 patch->fCenter = center;
474 return kTrue_FilterReturn;
477 void SkBlurMaskFilterImpl::computeFastBounds(const SkRect& src,
479 SkScalar pad = 3.0f * fSigma;
481 dst->set(src.fLeft - pad, src.fTop - pad,
482 src.fRight + pad, src.fBottom + pad);
485 SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkFlattenableReadBuffer& buffer)
486 : SkMaskFilter(buffer) {
487 fSigma = buffer.readScalar();
488 fBlurStyle = (SkBlurMaskFilter::BlurStyle)buffer.readInt();
489 fBlurFlags = buffer.readUInt() & SkBlurMaskFilter::kAll_BlurFlag;
490 SkASSERT(fSigma >= 0);
491 SkASSERT((unsigned)fBlurStyle < SkBlurMaskFilter::kBlurStyleCount);
494 void SkBlurMaskFilterImpl::flatten(SkFlattenableWriteBuffer& buffer) const {
495 this->INHERITED::flatten(buffer);
496 buffer.writeScalar(fSigma);
497 buffer.writeInt(fBlurStyle);
498 buffer.writeUInt(fBlurFlags);
503 bool SkBlurMaskFilterImpl::canFilterMaskGPU(const SkRect& srcBounds,
504 const SkIRect& clipBounds,
506 SkRect* maskRect) const {
507 SkScalar xformedSigma = this->computeXformedSigma(ctm);
508 if (xformedSigma <= 0) {
512 static const SkScalar kMIN_GPU_BLUR_SIZE = SkIntToScalar(64);
513 static const SkScalar kMIN_GPU_BLUR_SIGMA = SkIntToScalar(32);
515 if (srcBounds.width() <= kMIN_GPU_BLUR_SIZE &&
516 srcBounds.height() <= kMIN_GPU_BLUR_SIZE &&
517 xformedSigma <= kMIN_GPU_BLUR_SIGMA) {
518 // We prefer to blur small rect with small radius via CPU.
522 if (NULL == maskRect) {
523 // don't need to compute maskRect
527 float sigma3 = 3 * SkScalarToFloat(xformedSigma);
529 SkRect clipRect = SkRect::Make(clipBounds);
530 SkRect srcRect(srcBounds);
532 // Outset srcRect and clipRect by 3 * sigma, to compute affected blur area.
533 srcRect.outset(sigma3, sigma3);
534 clipRect.outset(sigma3, sigma3);
535 srcRect.intersect(clipRect);
540 bool SkBlurMaskFilterImpl::filterMaskGPU(GrTexture* src,
542 const SkRect& maskRect,
544 bool canOverwriteSrc) const {
545 SkRect clipRect = SkRect::MakeWH(maskRect.width(), maskRect.height());
547 GrContext* context = src->getContext();
549 GrContext::AutoWideOpenIdentityDraw awo(context, NULL);
551 SkScalar xformedSigma = this->computeXformedSigma(ctm);
552 SkASSERT(xformedSigma > 0);
554 // If we're doing a normal blur, we can clobber the pathTexture in the
555 // gaussianBlur. Otherwise, we need to save it for later compositing.
556 bool isNormalBlur = (SkBlurMaskFilter::kNormal_BlurStyle == fBlurStyle);
557 *result = SkGpuBlurUtils::GaussianBlur(context, src, isNormalBlur && canOverwriteSrc,
558 clipRect, false, xformedSigma, xformedSigma);
559 if (NULL == *result) {
564 context->setIdentityMatrix();
567 matrix.setIDiv(src->width(), src->height());
568 // Blend pathTexture over blurTexture.
569 GrContext::AutoRenderTarget art(context, (*result)->asRenderTarget());
570 paint.addColorEffect(GrSimpleTextureEffect::Create(src, matrix))->unref();
571 if (SkBlurMaskFilter::kInner_BlurStyle == fBlurStyle) {
572 // inner: dst = dst * src
573 paint.setBlendFunc(kDC_GrBlendCoeff, kZero_GrBlendCoeff);
574 } else if (SkBlurMaskFilter::kSolid_BlurStyle == fBlurStyle) {
575 // solid: dst = src + dst - src * dst
576 // = (1 - dst) * src + 1 * dst
577 paint.setBlendFunc(kIDC_GrBlendCoeff, kOne_GrBlendCoeff);
578 } else if (SkBlurMaskFilter::kOuter_BlurStyle == fBlurStyle) {
579 // outer: dst = dst * (1 - src)
580 // = 0 * src + (1 - src) * dst
581 paint.setBlendFunc(kZero_GrBlendCoeff, kISC_GrBlendCoeff);
583 context->drawRect(paint, clipRect);
589 #endif // SK_SUPPORT_GPU
593 void SkBlurMaskFilterImpl::toString(SkString* str) const {
594 str->append("SkBlurMaskFilterImpl: (");
596 str->append("sigma: ");
597 str->appendScalar(fSigma);
600 static const char* gStyleName[SkBlurMaskFilter::kBlurStyleCount] = {
601 "normal", "solid", "outer", "inner"
604 str->appendf("style: %s ", gStyleName[fBlurStyle]);
605 str->append("flags: (");
607 bool needSeparator = false;
608 SkAddFlagToString(str,
609 SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag),
610 "IgnoreXform", &needSeparator);
611 SkAddFlagToString(str,
612 SkToBool(fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag),
613 "HighQuality", &needSeparator);
621 SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkBlurMaskFilter)
622 SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkBlurMaskFilterImpl)
623 SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END