1 /*
2 * Copyright 2012 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/effects/SkMorphologyImageFilter.h"
9
10 #include "include/core/SkBitmap.h"
11 #include "include/core/SkRect.h"
12 #include "include/private/SkColorData.h"
13 #include "src/core/SkImageFilter_Base.h"
14 #include "src/core/SkReadBuffer.h"
15 #include "src/core/SkSpecialImage.h"
16 #include "src/core/SkWriteBuffer.h"
17
18 #if SK_SUPPORT_GPU
19 #include "include/gpu/GrContext.h"
20 #include "include/gpu/GrTexture.h"
21 #include "include/private/GrRecordingContext.h"
22 #include "src/gpu/GrContextPriv.h"
23 #include "src/gpu/GrCoordTransform.h"
24 #include "src/gpu/GrFixedClip.h"
25 #include "src/gpu/GrRecordingContextPriv.h"
26 #include "src/gpu/GrRenderTargetContext.h"
27 #include "src/gpu/GrTextureProxy.h"
28 #include "src/gpu/SkGr.h"
29 #include "src/gpu/glsl/GrGLSLFragmentProcessor.h"
30 #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
31 #include "src/gpu/glsl/GrGLSLProgramDataManager.h"
32 #include "src/gpu/glsl/GrGLSLUniformHandler.h"
33 #endif
34
35 namespace {
36
37 enum class MorphType {
38 kErode,
39 kDilate,
40 kLastType = kDilate
41 };
42
43 enum class MorphDirection { kX, kY };
44
45 class SkMorphologyImageFilterImpl final : public SkImageFilter_Base {
46 public:
SkMorphologyImageFilterImpl(MorphType type,int radiusX,int radiusY,sk_sp<SkImageFilter> input,const CropRect * cropRect)47 SkMorphologyImageFilterImpl(MorphType type, int radiusX, int radiusY,
48 sk_sp<SkImageFilter> input, const CropRect* cropRect)
49 : INHERITED(&input, 1, cropRect)
50 , fType(type)
51 , fRadius(SkISize::Make(radiusX, radiusY)) {}
52
53 SkRect computeFastBounds(const SkRect& src) const override;
54 SkIRect onFilterNodeBounds(const SkIRect& src, const SkMatrix& ctm,
55 MapDirection, const SkIRect* inputRect) const override;
56
57 /**
58 * All morphology procs have the same signature: src is the source buffer, dst the
59 * destination buffer, radius is the morphology radius, width and height are the bounds
60 * of the destination buffer (in pixels), and srcStride and dstStride are the
61 * number of pixels per row in each buffer. All buffers are 8888.
62 */
63
64 typedef void (*Proc)(const SkPMColor* src, SkPMColor* dst, int radius,
65 int width, int height, int srcStride, int dstStride);
66
67 protected:
68 sk_sp<SkSpecialImage> onFilterImage(const Context&, SkIPoint* offset) const override;
69 void flatten(SkWriteBuffer&) const override;
70
radius() const71 SkISize radius() const { return fRadius; }
mappedRadius(const SkMatrix & ctm) const72 SkSize mappedRadius(const SkMatrix& ctm) const {
73 SkVector radiusVector = SkVector::Make(SkIntToScalar(fRadius.width()),
74 SkIntToScalar(fRadius.height()));
75 ctm.mapVectors(&radiusVector, 1);
76 radiusVector.setAbs(radiusVector);
77 return SkSize::Make(radiusVector.x(), radiusVector.y());
78 }
79
80 private:
81 friend void SkDilateImageFilter::RegisterFlattenables();
82
83 SK_FLATTENABLE_HOOKS(SkMorphologyImageFilterImpl)
84 // Historically the morphology op was implicitly encoded in the factory type used to decode
85 // the image filter, so provide backwards compatible functions for old SKPs.
86 static sk_sp<SkFlattenable> CreateProcWithType(SkReadBuffer&, const MorphType*);
DilateCreateProc(SkReadBuffer & buffer)87 static sk_sp<SkFlattenable> DilateCreateProc(SkReadBuffer& buffer) {
88 static const MorphType kType = MorphType::kDilate;
89 return CreateProcWithType(buffer, &kType);
90 }
ErodeCreateProc(SkReadBuffer & buffer)91 static sk_sp<SkFlattenable> ErodeCreateProc(SkReadBuffer& buffer) {
92 static const MorphType kType = MorphType::kErode;
93 return CreateProcWithType(buffer, &kType);
94 }
95
96 MorphType fType;
97 SkISize fRadius;
98
99 typedef SkImageFilter_Base INHERITED;
100 };
101
102 } // end namespace
103
Make(int radiusX,int radiusY,sk_sp<SkImageFilter> input,const SkImageFilter::CropRect * cropRect)104 sk_sp<SkImageFilter> SkDilateImageFilter::Make(int radiusX, int radiusY,
105 sk_sp<SkImageFilter> input,
106 const SkImageFilter::CropRect* cropRect) {
107 if (radiusX < 0 || radiusY < 0) {
108 return nullptr;
109 }
110 return sk_sp<SkImageFilter>(new SkMorphologyImageFilterImpl(
111 MorphType::kDilate, radiusX, radiusY, std::move(input), cropRect));
112 }
113
Make(int radiusX,int radiusY,sk_sp<SkImageFilter> input,const SkImageFilter::CropRect * cropRect)114 sk_sp<SkImageFilter> SkErodeImageFilter::Make(int radiusX, int radiusY,
115 sk_sp<SkImageFilter> input,
116 const SkImageFilter::CropRect* cropRect) {
117 if (radiusX < 0 || radiusY < 0) {
118 return nullptr;
119 }
120 return sk_sp<SkImageFilter>(new SkMorphologyImageFilterImpl(
121 MorphType::kErode, radiusX, radiusY, std::move(input), cropRect));
122 }
123
RegisterFlattenables()124 void SkDilateImageFilter::RegisterFlattenables() {
125 SK_REGISTER_FLATTENABLE(SkMorphologyImageFilterImpl);
126 // TODO (michaelludwig) - Remove after grace period for SKPs to stop using old names
127 SkFlattenable::Register("SkDilateImageFilter", SkMorphologyImageFilterImpl::DilateCreateProc);
128 SkFlattenable::Register(
129 "SkDilateImageFilterImpl", SkMorphologyImageFilterImpl::DilateCreateProc);
130 SkFlattenable::Register("SkErodeImageFilter", SkMorphologyImageFilterImpl::ErodeCreateProc);
131 SkFlattenable::Register("SkErodeImageFilterImpl", SkMorphologyImageFilterImpl::ErodeCreateProc);
132 }
133
134 ///////////////////////////////////////////////////////////////////////////////
135
136 // 'type' acts as a signal that old-style deserialization is required. It is temporary.
CreateProcWithType(SkReadBuffer & buffer,const MorphType * type)137 sk_sp<SkFlattenable> SkMorphologyImageFilterImpl::CreateProcWithType(SkReadBuffer& buffer,
138 const MorphType* type) {
139 SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1);
140 const int width = buffer.readInt();
141 const int height = buffer.readInt();
142
143 MorphType filterType;
144 if (type) {
145 // The old create procs that have an associated op should only be used on old SKPs
146 SkASSERT(buffer.isVersionLT(SkPicturePriv::kUnifyErodeDilateImpls_Version));
147 filterType = *type;
148 } else {
149 filterType = buffer.read32LE(MorphType::kLastType);
150 }
151
152 if (filterType == MorphType::kDilate) {
153 return SkDilateImageFilter::Make(width, height, common.getInput(0), &common.cropRect());
154 } else if (filterType == MorphType::kErode) {
155 return SkErodeImageFilter::Make(width, height, common.getInput(0), &common.cropRect());
156 } else {
157 return nullptr;
158 }
159 }
160
CreateProc(SkReadBuffer & buffer)161 sk_sp<SkFlattenable> SkMorphologyImageFilterImpl::CreateProc(SkReadBuffer& buffer) {
162 // Pass null to have the create proc read the op from the buffer
163 return CreateProcWithType(buffer, nullptr);
164 }
165
flatten(SkWriteBuffer & buffer) const166 void SkMorphologyImageFilterImpl::flatten(SkWriteBuffer& buffer) const {
167 this->INHERITED::flatten(buffer);
168 buffer.writeInt(fRadius.fWidth);
169 buffer.writeInt(fRadius.fHeight);
170 buffer.writeInt(static_cast<int>(fType));
171 }
172
call_proc_X(SkMorphologyImageFilterImpl::Proc procX,const SkBitmap & src,SkBitmap * dst,int radiusX,const SkIRect & bounds)173 static void call_proc_X(SkMorphologyImageFilterImpl::Proc procX,
174 const SkBitmap& src, SkBitmap* dst,
175 int radiusX, const SkIRect& bounds) {
176 procX(src.getAddr32(bounds.left(), bounds.top()), dst->getAddr32(0, 0),
177 radiusX, bounds.width(), bounds.height(),
178 src.rowBytesAsPixels(), dst->rowBytesAsPixels());
179 }
180
call_proc_Y(SkMorphologyImageFilterImpl::Proc procY,const SkPMColor * src,int srcRowBytesAsPixels,SkBitmap * dst,int radiusY,const SkIRect & bounds)181 static void call_proc_Y(SkMorphologyImageFilterImpl::Proc procY,
182 const SkPMColor* src, int srcRowBytesAsPixels, SkBitmap* dst,
183 int radiusY, const SkIRect& bounds) {
184 procY(src, dst->getAddr32(0, 0),
185 radiusY, bounds.height(), bounds.width(),
186 srcRowBytesAsPixels, dst->rowBytesAsPixels());
187 }
188
computeFastBounds(const SkRect & src) const189 SkRect SkMorphologyImageFilterImpl::computeFastBounds(const SkRect& src) const {
190 SkRect bounds = this->getInput(0) ? this->getInput(0)->computeFastBounds(src) : src;
191 bounds.outset(SkIntToScalar(fRadius.width()), SkIntToScalar(fRadius.height()));
192 return bounds;
193 }
194
onFilterNodeBounds(const SkIRect & src,const SkMatrix & ctm,MapDirection,const SkIRect * inputRect) const195 SkIRect SkMorphologyImageFilterImpl::onFilterNodeBounds(
196 const SkIRect& src, const SkMatrix& ctm, MapDirection, const SkIRect* inputRect) const {
197 SkSize radius = mappedRadius(ctm);
198 return src.makeOutset(SkScalarCeilToInt(radius.width()), SkScalarCeilToInt(radius.height()));
199 }
200
201 #if SK_SUPPORT_GPU
202
203 ///////////////////////////////////////////////////////////////////////////////
204 /**
205 * Morphology effects. Depending upon the type of morphology, either the
206 * component-wise min (Erode_Type) or max (Dilate_Type) of all pixels in the
207 * kernel is selected as the new color. The new color is modulated by the input
208 * color.
209 */
210 class GrMorphologyEffect : public GrFragmentProcessor {
211 public:
Make(sk_sp<GrTextureProxy> proxy,GrColorType srcColorType,MorphDirection dir,int radius,MorphType type)212 static std::unique_ptr<GrFragmentProcessor> Make(sk_sp<GrTextureProxy> proxy,
213 GrColorType srcColorType,
214 MorphDirection dir,
215 int radius, MorphType type) {
216 return std::unique_ptr<GrFragmentProcessor>(
217 new GrMorphologyEffect(std::move(proxy), srcColorType, dir, radius, type, nullptr));
218 }
219
Make(sk_sp<GrTextureProxy> proxy,GrColorType srcColorType,MorphDirection dir,int radius,MorphType type,const float bounds[2])220 static std::unique_ptr<GrFragmentProcessor> Make(sk_sp<GrTextureProxy> proxy,
221 GrColorType srcColorType,
222 MorphDirection dir,
223 int radius, MorphType type,
224 const float bounds[2]) {
225 return std::unique_ptr<GrFragmentProcessor>(
226 new GrMorphologyEffect(std::move(proxy), srcColorType, dir, radius, type, bounds));
227 }
228
type() const229 MorphType type() const { return fType; }
useRange() const230 bool useRange() const { return fUseRange; }
range() const231 const float* range() const { return fRange; }
direction() const232 MorphDirection direction() const { return fDirection; }
radius() const233 int radius() const { return fRadius; }
width() const234 int width() const { return 2 * fRadius + 1; }
235
name() const236 const char* name() const override { return "Morphology"; }
237
clone() const238 std::unique_ptr<GrFragmentProcessor> clone() const override {
239 return std::unique_ptr<GrFragmentProcessor>(new GrMorphologyEffect(*this));
240 }
241
242 private:
243 GrCoordTransform fCoordTransform;
244 TextureSampler fTextureSampler;
245 MorphDirection fDirection;
246 int fRadius;
247 MorphType fType;
248 bool fUseRange;
249 float fRange[2];
250
251 GrGLSLFragmentProcessor* onCreateGLSLInstance() const override;
252
253 void onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const override;
254
255 bool onIsEqual(const GrFragmentProcessor&) const override;
256
onTextureSampler(int i) const257 const TextureSampler& onTextureSampler(int i) const override { return fTextureSampler; }
258
259 GrMorphologyEffect(sk_sp<GrTextureProxy>, GrColorType srcColorType, MorphDirection, int radius,
260 MorphType, const float range[2]);
261 explicit GrMorphologyEffect(const GrMorphologyEffect&);
262
263 GR_DECLARE_FRAGMENT_PROCESSOR_TEST
264
265 typedef GrFragmentProcessor INHERITED;
266 };
267
268 ///////////////////////////////////////////////////////////////////////////////
269
270 class GrGLMorphologyEffect : public GrGLSLFragmentProcessor {
271 public:
272 void emitCode(EmitArgs&) override;
273
274 static inline void GenKey(const GrProcessor&, const GrShaderCaps&, GrProcessorKeyBuilder*);
275
276 protected:
277 void onSetData(const GrGLSLProgramDataManager&, const GrFragmentProcessor&) override;
278
279 private:
280 GrGLSLProgramDataManager::UniformHandle fPixelSizeUni;
281 GrGLSLProgramDataManager::UniformHandle fRangeUni;
282
283 typedef GrGLSLFragmentProcessor INHERITED;
284 };
285
emitCode(EmitArgs & args)286 void GrGLMorphologyEffect::emitCode(EmitArgs& args) {
287 const GrMorphologyEffect& me = args.fFp.cast<GrMorphologyEffect>();
288
289 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
290 fPixelSizeUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kHalf_GrSLType, "PixelSize");
291 const char* pixelSizeInc = uniformHandler->getUniformCStr(fPixelSizeUni);
292 fRangeUni = uniformHandler->addUniform(kFragment_GrShaderFlag, kFloat2_GrSLType, "Range");
293 const char* range = uniformHandler->getUniformCStr(fRangeUni);
294
295 GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
296 SkString coords2D = fragBuilder->ensureCoords2D(args.fTransformedCoords[0].fVaryingPoint);
297 const char* func;
298 switch (me.type()) {
299 case MorphType::kErode:
300 fragBuilder->codeAppendf("\t\t%s = half4(1, 1, 1, 1);\n", args.fOutputColor);
301 func = "min";
302 break;
303 case MorphType::kDilate:
304 fragBuilder->codeAppendf("\t\t%s = half4(0, 0, 0, 0);\n", args.fOutputColor);
305 func = "max";
306 break;
307 default:
308 SK_ABORT("Unexpected type");
309 func = ""; // suppress warning
310 break;
311 }
312
313 const char* dir;
314 switch (me.direction()) {
315 case MorphDirection::kX:
316 dir = "x";
317 break;
318 case MorphDirection::kY:
319 dir = "y";
320 break;
321 default:
322 SK_ABORT("Unknown filter direction.");
323 dir = ""; // suppress warning
324 }
325
326 int width = me.width();
327
328 // float2 coord = coord2D;
329 fragBuilder->codeAppendf("\t\tfloat2 coord = %s;\n", coords2D.c_str());
330 // coord.x -= radius * pixelSize;
331 fragBuilder->codeAppendf("\t\tcoord.%s -= %d.0 * %s; \n", dir, me.radius(), pixelSizeInc);
332 if (me.useRange()) {
333 // highBound = min(highBound, coord.x + (width-1) * pixelSize);
334 fragBuilder->codeAppendf("\t\tfloat highBound = min(%s.y, coord.%s + %f * %s);",
335 range, dir, float(width - 1), pixelSizeInc);
336 // coord.x = max(lowBound, coord.x);
337 fragBuilder->codeAppendf("\t\tcoord.%s = max(%s.x, coord.%s);", dir, range, dir);
338 }
339 fragBuilder->codeAppendf("\t\tfor (int i = 0; i < %d; i++) {\n", width);
340 fragBuilder->codeAppendf("\t\t\t%s = %s(%s, ", args.fOutputColor, func, args.fOutputColor);
341 fragBuilder->appendTextureLookup(args.fTexSamplers[0], "coord");
342 fragBuilder->codeAppend(");\n");
343 // coord.x += pixelSize;
344 fragBuilder->codeAppendf("\t\t\tcoord.%s += %s;\n", dir, pixelSizeInc);
345 if (me.useRange()) {
346 // coord.x = min(highBound, coord.x);
347 fragBuilder->codeAppendf("\t\t\tcoord.%s = min(highBound, coord.%s);", dir, dir);
348 }
349 fragBuilder->codeAppend("\t\t}\n");
350 fragBuilder->codeAppendf("%s *= %s;\n", args.fOutputColor, args.fInputColor);
351 }
352
GenKey(const GrProcessor & proc,const GrShaderCaps &,GrProcessorKeyBuilder * b)353 void GrGLMorphologyEffect::GenKey(const GrProcessor& proc,
354 const GrShaderCaps&, GrProcessorKeyBuilder* b) {
355 const GrMorphologyEffect& m = proc.cast<GrMorphologyEffect>();
356 uint32_t key = static_cast<uint32_t>(m.radius());
357 key |= (static_cast<uint32_t>(m.type()) << 8);
358 key |= (static_cast<uint32_t>(m.direction()) << 9);
359 if (m.useRange()) {
360 key |= 1 << 10;
361 }
362 b->add32(key);
363 }
364
onSetData(const GrGLSLProgramDataManager & pdman,const GrFragmentProcessor & proc)365 void GrGLMorphologyEffect::onSetData(const GrGLSLProgramDataManager& pdman,
366 const GrFragmentProcessor& proc) {
367 const GrMorphologyEffect& m = proc.cast<GrMorphologyEffect>();
368 GrSurfaceProxy* proxy = m.textureSampler(0).proxy();
369 GrTexture& texture = *proxy->peekTexture();
370
371 float pixelSize = 0.0f;
372 switch (m.direction()) {
373 case MorphDirection::kX:
374 pixelSize = 1.0f / texture.width();
375 break;
376 case MorphDirection::kY:
377 pixelSize = 1.0f / texture.height();
378 break;
379 default:
380 SK_ABORT("Unknown filter direction.");
381 }
382 pdman.set1f(fPixelSizeUni, pixelSize);
383
384 if (m.useRange()) {
385 const float* range = m.range();
386 if (MorphDirection::kY == m.direction() &&
387 proxy->origin() == kBottomLeft_GrSurfaceOrigin) {
388 pdman.set2f(fRangeUni, 1.0f - (range[1]*pixelSize), 1.0f - (range[0]*pixelSize));
389 } else {
390 pdman.set2f(fRangeUni, range[0] * pixelSize, range[1] * pixelSize);
391 }
392 }
393 }
394
395 ///////////////////////////////////////////////////////////////////////////////
396
GrMorphologyEffect(sk_sp<GrTextureProxy> proxy,GrColorType srcColorType,MorphDirection direction,int radius,MorphType type,const float range[2])397 GrMorphologyEffect::GrMorphologyEffect(sk_sp<GrTextureProxy> proxy,
398 GrColorType srcColorType,
399 MorphDirection direction,
400 int radius,
401 MorphType type,
402 const float range[2])
403 : INHERITED(kGrMorphologyEffect_ClassID,
404 ModulateForClampedSamplerOptFlags(srcColorType))
405 , fCoordTransform(proxy.get())
406 , fTextureSampler(std::move(proxy))
407 , fDirection(direction)
408 , fRadius(radius)
409 , fType(type)
410 , fUseRange(SkToBool(range)) {
411 // Make sure the sampler's ctor uses the clamp wrap mode
412 SkASSERT(fTextureSampler.samplerState().wrapModeX() == GrSamplerState::WrapMode::kClamp &&
413 fTextureSampler.samplerState().wrapModeY() == GrSamplerState::WrapMode::kClamp);
414 this->addCoordTransform(&fCoordTransform);
415 this->setTextureSamplerCnt(1);
416 if (fUseRange) {
417 fRange[0] = range[0];
418 fRange[1] = range[1];
419 }
420 }
421
GrMorphologyEffect(const GrMorphologyEffect & that)422 GrMorphologyEffect::GrMorphologyEffect(const GrMorphologyEffect& that)
423 : INHERITED(kGrMorphologyEffect_ClassID, that.optimizationFlags())
424 , fCoordTransform(that.fCoordTransform)
425 , fTextureSampler(that.fTextureSampler)
426 , fDirection(that.fDirection)
427 , fRadius(that.fRadius)
428 , fType(that.fType)
429 , fUseRange(that.fUseRange) {
430 this->addCoordTransform(&fCoordTransform);
431 this->setTextureSamplerCnt(1);
432 if (that.fUseRange) {
433 fRange[0] = that.fRange[0];
434 fRange[1] = that.fRange[1];
435 }
436 }
437
onGetGLSLProcessorKey(const GrShaderCaps & caps,GrProcessorKeyBuilder * b) const438 void GrMorphologyEffect::onGetGLSLProcessorKey(const GrShaderCaps& caps,
439 GrProcessorKeyBuilder* b) const {
440 GrGLMorphologyEffect::GenKey(*this, caps, b);
441 }
442
onCreateGLSLInstance() const443 GrGLSLFragmentProcessor* GrMorphologyEffect::onCreateGLSLInstance() const {
444 return new GrGLMorphologyEffect;
445 }
onIsEqual(const GrFragmentProcessor & sBase) const446 bool GrMorphologyEffect::onIsEqual(const GrFragmentProcessor& sBase) const {
447 const GrMorphologyEffect& s = sBase.cast<GrMorphologyEffect>();
448 return (this->radius() == s.radius() &&
449 this->direction() == s.direction() &&
450 this->useRange() == s.useRange() &&
451 this->type() == s.type());
452 }
453
454 ///////////////////////////////////////////////////////////////////////////////
455
456 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrMorphologyEffect);
457
458 #if GR_TEST_UTILS
TestCreate(GrProcessorTestData * d)459 std::unique_ptr<GrFragmentProcessor> GrMorphologyEffect::TestCreate(GrProcessorTestData* d) {
460 int texIdx = d->fRandom->nextBool() ? GrProcessorUnitTest::kSkiaPMTextureIdx
461 : GrProcessorUnitTest::kAlphaTextureIdx;
462 sk_sp<GrTextureProxy> proxy = d->textureProxy(texIdx);
463
464 MorphDirection dir = d->fRandom->nextBool() ? MorphDirection::kX : MorphDirection::kY;
465 static const int kMaxRadius = 10;
466 int radius = d->fRandom->nextRangeU(1, kMaxRadius);
467 MorphType type = d->fRandom->nextBool() ? MorphType::kErode : MorphType::kDilate;
468
469 return GrMorphologyEffect::Make(std::move(proxy), d->textureProxyColorType(texIdx), dir, radius,
470 type);
471 }
472 #endif
473
apply_morphology_rect(GrRenderTargetContext * renderTargetContext,const GrClip & clip,sk_sp<GrTextureProxy> proxy,GrColorType srcColorType,const SkIRect & srcRect,const SkIRect & dstRect,int radius,MorphType morphType,const float bounds[2],MorphDirection direction)474 static void apply_morphology_rect(GrRenderTargetContext* renderTargetContext,
475 const GrClip& clip,
476 sk_sp<GrTextureProxy> proxy,
477 GrColorType srcColorType,
478 const SkIRect& srcRect,
479 const SkIRect& dstRect,
480 int radius,
481 MorphType morphType,
482 const float bounds[2],
483 MorphDirection direction) {
484 GrPaint paint;
485 paint.addColorFragmentProcessor(GrMorphologyEffect::Make(std::move(proxy), srcColorType,
486 direction, radius, morphType,
487 bounds));
488 paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
489 renderTargetContext->fillRectToRect(clip, std::move(paint), GrAA::kNo, SkMatrix::I(),
490 SkRect::Make(dstRect), SkRect::Make(srcRect));
491 }
492
apply_morphology_rect_no_bounds(GrRenderTargetContext * renderTargetContext,const GrClip & clip,sk_sp<GrTextureProxy> proxy,GrColorType srcColorType,const SkIRect & srcRect,const SkIRect & dstRect,int radius,MorphType morphType,MorphDirection direction)493 static void apply_morphology_rect_no_bounds(GrRenderTargetContext* renderTargetContext,
494 const GrClip& clip,
495 sk_sp<GrTextureProxy> proxy,
496 GrColorType srcColorType,
497 const SkIRect& srcRect,
498 const SkIRect& dstRect,
499 int radius,
500 MorphType morphType,
501 MorphDirection direction) {
502 GrPaint paint;
503 paint.addColorFragmentProcessor(GrMorphologyEffect::Make(std::move(proxy), srcColorType,
504 direction, radius, morphType));
505 paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
506 renderTargetContext->fillRectToRect(clip, std::move(paint), GrAA::kNo, SkMatrix::I(),
507 SkRect::Make(dstRect), SkRect::Make(srcRect));
508 }
509
apply_morphology_pass(GrRenderTargetContext * renderTargetContext,const GrClip & clip,sk_sp<GrTextureProxy> textureProxy,GrColorType srcColorType,const SkIRect & srcRect,const SkIRect & dstRect,int radius,MorphType morphType,MorphDirection direction)510 static void apply_morphology_pass(GrRenderTargetContext* renderTargetContext,
511 const GrClip& clip,
512 sk_sp<GrTextureProxy> textureProxy,
513 GrColorType srcColorType,
514 const SkIRect& srcRect,
515 const SkIRect& dstRect,
516 int radius,
517 MorphType morphType,
518 MorphDirection direction) {
519 float bounds[2] = { 0.0f, 1.0f };
520 SkIRect lowerSrcRect = srcRect, lowerDstRect = dstRect;
521 SkIRect middleSrcRect = srcRect, middleDstRect = dstRect;
522 SkIRect upperSrcRect = srcRect, upperDstRect = dstRect;
523 if (direction == MorphDirection::kX) {
524 bounds[0] = SkIntToScalar(srcRect.left()) + 0.5f;
525 bounds[1] = SkIntToScalar(srcRect.right()) - 0.5f;
526 lowerSrcRect.fRight = srcRect.left() + radius;
527 lowerDstRect.fRight = dstRect.left() + radius;
528 upperSrcRect.fLeft = srcRect.right() - radius;
529 upperDstRect.fLeft = dstRect.right() - radius;
530 middleSrcRect.inset(radius, 0);
531 middleDstRect.inset(radius, 0);
532 } else {
533 bounds[0] = SkIntToScalar(srcRect.top()) + 0.5f;
534 bounds[1] = SkIntToScalar(srcRect.bottom()) - 0.5f;
535 lowerSrcRect.fBottom = srcRect.top() + radius;
536 lowerDstRect.fBottom = dstRect.top() + radius;
537 upperSrcRect.fTop = srcRect.bottom() - radius;
538 upperDstRect.fTop = dstRect.bottom() - radius;
539 middleSrcRect.inset(0, radius);
540 middleDstRect.inset(0, radius);
541 }
542 if (middleSrcRect.width() <= 0) {
543 // radius covers srcRect; use bounds over entire draw
544 apply_morphology_rect(renderTargetContext, clip, std::move(textureProxy), srcColorType,
545 srcRect, dstRect, radius, morphType, bounds, direction);
546 } else {
547 // Draw upper and lower margins with bounds; middle without.
548 apply_morphology_rect(renderTargetContext, clip, textureProxy, srcColorType,
549 lowerSrcRect, lowerDstRect, radius, morphType, bounds, direction);
550 apply_morphology_rect(renderTargetContext, clip, textureProxy, srcColorType,
551 upperSrcRect, upperDstRect, radius, morphType, bounds, direction);
552 apply_morphology_rect_no_bounds(renderTargetContext, clip, std::move(textureProxy),
553 srcColorType, middleSrcRect, middleDstRect, radius,
554 morphType, direction);
555 }
556 }
557
apply_morphology(GrRecordingContext * context,SkSpecialImage * input,const SkIRect & rect,MorphType morphType,SkISize radius,const SkImageFilter_Base::Context & ctx)558 static sk_sp<SkSpecialImage> apply_morphology(
559 GrRecordingContext* context, SkSpecialImage* input, const SkIRect& rect,
560 MorphType morphType, SkISize radius, const SkImageFilter_Base::Context& ctx) {
561 sk_sp<GrTextureProxy> srcTexture(input->asTextureProxyRef(context));
562 GrColorType srcColorType = SkColorTypeToGrColorType(input->colorType());
563 SkASSERT(srcTexture);
564 sk_sp<SkColorSpace> colorSpace = ctx.refColorSpace();
565 GrColorType colorType = ctx.grColorType();
566
567 // setup new clip
568 const GrFixedClip clip(SkIRect::MakeWH(srcTexture->width(), srcTexture->height()));
569
570 const SkIRect dstRect = SkIRect::MakeWH(rect.width(), rect.height());
571 SkIRect srcRect = rect;
572 // Map into proxy space
573 srcRect.offset(input->subset().x(), input->subset().y());
574 SkASSERT(radius.width() > 0 || radius.height() > 0);
575
576 if (radius.fWidth > 0) {
577 auto dstRTContext = context->priv().makeDeferredRenderTargetContext(
578 SkBackingFit::kApprox,
579 rect.width(),
580 rect.height(),
581 colorType,
582 colorSpace,
583 1,
584 GrMipMapped::kNo,
585 kBottomLeft_GrSurfaceOrigin,
586 nullptr,
587 SkBudgeted::kYes,
588 srcTexture->isProtected() ? GrProtected::kYes : GrProtected::kNo);
589 if (!dstRTContext) {
590 return nullptr;
591 }
592
593 apply_morphology_pass(dstRTContext.get(), clip, std::move(srcTexture), srcColorType,
594 srcRect, dstRect, radius.fWidth, morphType, MorphDirection::kX);
595 SkIRect clearRect = SkIRect::MakeXYWH(dstRect.fLeft, dstRect.fBottom,
596 dstRect.width(), radius.fHeight);
597 SkPMColor4f clearColor = MorphType::kErode == morphType
598 ? SK_PMColor4fWHITE : SK_PMColor4fTRANSPARENT;
599 dstRTContext->clear(&clearRect, clearColor, GrRenderTargetContext::CanClearFullscreen::kNo);
600
601 srcTexture = dstRTContext->asTextureProxyRef();
602 srcColorType = colorType;
603 srcRect = dstRect;
604 }
605 if (radius.fHeight > 0) {
606 auto dstRTContext = context->priv().makeDeferredRenderTargetContext(
607 SkBackingFit::kApprox,
608 rect.width(),
609 rect.height(),
610 colorType,
611 colorSpace,
612 1,
613 GrMipMapped::kNo,
614 kBottomLeft_GrSurfaceOrigin,
615 nullptr,
616 SkBudgeted::kYes,
617 srcTexture->isProtected() ? GrProtected::kYes : GrProtected::kNo);
618 if (!dstRTContext) {
619 return nullptr;
620 }
621
622 apply_morphology_pass(dstRTContext.get(), clip, std::move(srcTexture), srcColorType,
623 srcRect, dstRect, radius.fHeight, morphType, MorphDirection::kY);
624
625 srcTexture = dstRTContext->asTextureProxyRef();
626 }
627
628 return SkSpecialImage::MakeDeferredFromGpu(context,
629 SkIRect::MakeWH(rect.width(), rect.height()),
630 kNeedNewImageUniqueID_SpecialImage,
631 std::move(srcTexture), colorType,
632 std::move(colorSpace), &input->props());
633 }
634 #endif
635
636 namespace {
637
638 #if SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE2
639 template<MorphType type, MorphDirection direction>
morph(const SkPMColor * src,SkPMColor * dst,int radius,int width,int height,int srcStride,int dstStride)640 static void morph(const SkPMColor* src, SkPMColor* dst,
641 int radius, int width, int height, int srcStride, int dstStride) {
642 const int srcStrideX = direction == MorphDirection::kX ? 1 : srcStride;
643 const int dstStrideX = direction == MorphDirection::kX ? 1 : dstStride;
644 const int srcStrideY = direction == MorphDirection::kX ? srcStride : 1;
645 const int dstStrideY = direction == MorphDirection::kX ? dstStride : 1;
646 radius = SkMin32(radius, width - 1);
647 const SkPMColor* upperSrc = src + radius * srcStrideX;
648 for (int x = 0; x < width; ++x) {
649 const SkPMColor* lp = src;
650 const SkPMColor* up = upperSrc;
651 SkPMColor* dptr = dst;
652 for (int y = 0; y < height; ++y) {
653 __m128i extreme = (type == MorphType::kDilate) ? _mm_setzero_si128()
654 : _mm_set1_epi32(0xFFFFFFFF);
655 for (const SkPMColor* p = lp; p <= up; p += srcStrideX) {
656 __m128i src_pixel = _mm_cvtsi32_si128(*p);
657 extreme = (type == MorphType::kDilate) ? _mm_max_epu8(src_pixel, extreme)
658 : _mm_min_epu8(src_pixel, extreme);
659 }
660 *dptr = _mm_cvtsi128_si32(extreme);
661 dptr += dstStrideY;
662 lp += srcStrideY;
663 up += srcStrideY;
664 }
665 if (x >= radius) { src += srcStrideX; }
666 if (x + radius < width - 1) { upperSrc += srcStrideX; }
667 dst += dstStrideX;
668 }
669 }
670
671 #elif defined(SK_ARM_HAS_NEON)
672 template<MorphType type, MorphDirection direction>
673 static void morph(const SkPMColor* src, SkPMColor* dst,
674 int radius, int width, int height, int srcStride, int dstStride) {
675 const int srcStrideX = direction == MorphDirection::kX ? 1 : srcStride;
676 const int dstStrideX = direction == MorphDirection::kX ? 1 : dstStride;
677 const int srcStrideY = direction == MorphDirection::kX ? srcStride : 1;
678 const int dstStrideY = direction == MorphDirection::kX ? dstStride : 1;
679 radius = SkMin32(radius, width - 1);
680 const SkPMColor* upperSrc = src + radius * srcStrideX;
681 for (int x = 0; x < width; ++x) {
682 const SkPMColor* lp = src;
683 const SkPMColor* up = upperSrc;
684 SkPMColor* dptr = dst;
685 for (int y = 0; y < height; ++y) {
686 uint8x8_t extreme = vdup_n_u8(type == MorphType::kDilate ? 0 : 255);
687 for (const SkPMColor* p = lp; p <= up; p += srcStrideX) {
688 uint8x8_t src_pixel = vreinterpret_u8_u32(vdup_n_u32(*p));
689 extreme = (type == MorphType::kDilate) ? vmax_u8(src_pixel, extreme)
690 : vmin_u8(src_pixel, extreme);
691 }
692 *dptr = vget_lane_u32(vreinterpret_u32_u8(extreme), 0);
693 dptr += dstStrideY;
694 lp += srcStrideY;
695 up += srcStrideY;
696 }
697 if (x >= radius) src += srcStrideX;
698 if (x + radius < width - 1) upperSrc += srcStrideX;
699 dst += dstStrideX;
700 }
701 }
702
703 #else
704 template<MorphType type, MorphDirection direction>
705 static void morph(const SkPMColor* src, SkPMColor* dst,
706 int radius, int width, int height, int srcStride, int dstStride) {
707 const int srcStrideX = direction == MorphDirection::kX ? 1 : srcStride;
708 const int dstStrideX = direction == MorphDirection::kX ? 1 : dstStride;
709 const int srcStrideY = direction == MorphDirection::kX ? srcStride : 1;
710 const int dstStrideY = direction == MorphDirection::kX ? dstStride : 1;
711 radius = SkMin32(radius, width - 1);
712 const SkPMColor* upperSrc = src + radius * srcStrideX;
713 for (int x = 0; x < width; ++x) {
714 const SkPMColor* lp = src;
715 const SkPMColor* up = upperSrc;
716 SkPMColor* dptr = dst;
717 for (int y = 0; y < height; ++y) {
718 // If we're maxing (dilate), start from 0; if minning (erode), start from 255.
719 const int start = (type == MorphType::kDilate) ? 0 : 255;
720 int B = start, G = start, R = start, A = start;
721 for (const SkPMColor* p = lp; p <= up; p += srcStrideX) {
722 int b = SkGetPackedB32(*p),
723 g = SkGetPackedG32(*p),
724 r = SkGetPackedR32(*p),
725 a = SkGetPackedA32(*p);
726 if (type == MorphType::kDilate) {
727 B = SkTMax(b, B);
728 G = SkTMax(g, G);
729 R = SkTMax(r, R);
730 A = SkTMax(a, A);
731 } else {
732 B = SkTMin(b, B);
733 G = SkTMin(g, G);
734 R = SkTMin(r, R);
735 A = SkTMin(a, A);
736 }
737 }
738 *dptr = SkPackARGB32(A, R, G, B);
739 dptr += dstStrideY;
740 lp += srcStrideY;
741 up += srcStrideY;
742 }
743 if (x >= radius) { src += srcStrideX; }
744 if (x + radius < width - 1) { upperSrc += srcStrideX; }
745 dst += dstStrideX;
746 }
747 }
748 #endif
749 } // namespace
750
onFilterImage(const Context & ctx,SkIPoint * offset) const751 sk_sp<SkSpecialImage> SkMorphologyImageFilterImpl::onFilterImage(const Context& ctx,
752 SkIPoint* offset) const {
753 SkIPoint inputOffset = SkIPoint::Make(0, 0);
754 sk_sp<SkSpecialImage> input(this->filterInput(0, ctx, &inputOffset));
755 if (!input) {
756 return nullptr;
757 }
758
759 SkIRect bounds;
760 input = this->applyCropRectAndPad(this->mapContext(ctx), input.get(), &inputOffset, &bounds);
761 if (!input) {
762 return nullptr;
763 }
764
765 SkSize radius = mappedRadius(ctx.ctm());
766 int width = SkScalarFloorToInt(radius.width());
767 int height = SkScalarFloorToInt(radius.height());
768
769 if (width < 0 || height < 0) {
770 return nullptr;
771 }
772
773 SkIRect srcBounds = bounds;
774 srcBounds.offset(-inputOffset);
775
776 if (0 == width && 0 == height) {
777 offset->fX = bounds.left();
778 offset->fY = bounds.top();
779 return input->makeSubset(srcBounds);
780 }
781
782 #if SK_SUPPORT_GPU
783 if (ctx.gpuBacked()) {
784 auto context = ctx.getContext();
785
786 // Ensure the input is in the destination color space. Typically applyCropRect will have
787 // called pad_image to account for our dilation of bounds, so the result will already be
788 // moved to the destination color space. If a filter DAG avoids that, then we use this
789 // fall-back, which saves us from having to do the xform during the filter itself.
790 input = ImageToColorSpace(input.get(), ctx.colorType(), ctx.colorSpace());
791
792 sk_sp<SkSpecialImage> result(apply_morphology(context, input.get(), srcBounds, fType,
793 SkISize::Make(width, height), ctx));
794 if (result) {
795 offset->fX = bounds.left();
796 offset->fY = bounds.top();
797 }
798 return result;
799 }
800 #endif
801
802 SkBitmap inputBM;
803
804 if (!input->getROPixels(&inputBM)) {
805 return nullptr;
806 }
807
808 if (inputBM.colorType() != kN32_SkColorType) {
809 return nullptr;
810 }
811
812 SkImageInfo info = SkImageInfo::Make(bounds.size(), inputBM.colorType(), inputBM.alphaType());
813
814 SkBitmap dst;
815 if (!dst.tryAllocPixels(info)) {
816 return nullptr;
817 }
818
819 SkMorphologyImageFilterImpl::Proc procX, procY;
820
821 if (MorphType::kDilate == fType) {
822 procX = &morph<MorphType::kDilate, MorphDirection::kX>;
823 procY = &morph<MorphType::kDilate, MorphDirection::kY>;
824 } else {
825 procX = &morph<MorphType::kErode, MorphDirection::kX>;
826 procY = &morph<MorphType::kErode, MorphDirection::kY>;
827 }
828
829 if (width > 0 && height > 0) {
830 SkBitmap tmp;
831 if (!tmp.tryAllocPixels(info)) {
832 return nullptr;
833 }
834
835 call_proc_X(procX, inputBM, &tmp, width, srcBounds);
836 SkIRect tmpBounds = SkIRect::MakeWH(srcBounds.width(), srcBounds.height());
837 call_proc_Y(procY,
838 tmp.getAddr32(tmpBounds.left(), tmpBounds.top()), tmp.rowBytesAsPixels(),
839 &dst, height, tmpBounds);
840 } else if (width > 0) {
841 call_proc_X(procX, inputBM, &dst, width, srcBounds);
842 } else if (height > 0) {
843 call_proc_Y(procY,
844 inputBM.getAddr32(srcBounds.left(), srcBounds.top()),
845 inputBM.rowBytesAsPixels(),
846 &dst, height, srcBounds);
847 }
848 offset->fX = bounds.left();
849 offset->fY = bounds.top();
850
851 return SkSpecialImage::MakeFromRaster(SkIRect::MakeWH(bounds.width(), bounds.height()),
852 dst, ctx.surfaceProps());
853 }
854