1 /*
2 * Copyright 2015 Google Inc.
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 "src/gpu/GrFragmentProcessor.h"
9
10 #include "src/core/SkRuntimeEffectPriv.h"
11 #include "src/gpu/GrPipeline.h"
12 #include "src/gpu/GrProcessorAnalysis.h"
13 #include "src/gpu/GrShaderCaps.h"
14 #include "src/gpu/effects/GrBlendFragmentProcessor.h"
15 #include "src/gpu/effects/GrSkSLFP.h"
16 #include "src/gpu/effects/GrTextureEffect.h"
17 #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
18 #include "src/gpu/glsl/GrGLSLProgramBuilder.h"
19 #include "src/gpu/glsl/GrGLSLProgramDataManager.h"
20 #include "src/gpu/glsl/GrGLSLUniformHandler.h"
21
22 // Advanced Filter
checkAFRecursively() const23 bool GrFragmentProcessor::checkAFRecursively() const
24 {
25 if (isAFEnabled()) {
26 return true;
27 }
28
29 for (int i = 0; i < numChildProcessors(); ++i) {
30 const GrFragmentProcessor* fChildFp = childProcessor(i);
31 if (fChildFp != nullptr && fChildFp->checkAFRecursively()) {
32 return true;
33 }
34 }
35 return false;
36 }
37
isEqual(const GrFragmentProcessor & that) const38 bool GrFragmentProcessor::isEqual(const GrFragmentProcessor& that) const {
39 if (this->classID() != that.classID()) {
40 return false;
41 }
42 if (this->sampleUsage() != that.sampleUsage()) {
43 return false;
44 }
45 if (!this->onIsEqual(that)) {
46 return false;
47 }
48 if (this->numChildProcessors() != that.numChildProcessors()) {
49 return false;
50 }
51 for (int i = 0; i < this->numChildProcessors(); ++i) {
52 auto thisChild = this->childProcessor(i),
53 thatChild = that .childProcessor(i);
54 if (SkToBool(thisChild) != SkToBool(thatChild)) {
55 return false;
56 }
57 if (thisChild && !thisChild->isEqual(*thatChild)) {
58 return false;
59 }
60 }
61 return true;
62 }
63
visitProxies(const GrVisitProxyFunc & func) const64 void GrFragmentProcessor::visitProxies(const GrVisitProxyFunc& func) const {
65 this->visitTextureEffects([&func](const GrTextureEffect& te) {
66 func(te.view().proxy(), te.samplerState().mipmapped());
67 });
68 }
69
visitTextureEffects(const std::function<void (const GrTextureEffect &)> & func) const70 void GrFragmentProcessor::visitTextureEffects(
71 const std::function<void(const GrTextureEffect&)>& func) const {
72 if (auto* te = this->asTextureEffect()) {
73 func(*te);
74 }
75 for (auto& child : fChildProcessors) {
76 if (child) {
77 child->visitTextureEffects(func);
78 }
79 }
80 }
81
visitWithImpls(const std::function<void (const GrFragmentProcessor &,ProgramImpl &)> & f,ProgramImpl & impl) const82 void GrFragmentProcessor::visitWithImpls(
83 const std::function<void(const GrFragmentProcessor&, ProgramImpl&)>& f,
84 ProgramImpl& impl) const {
85 f(*this, impl);
86 SkASSERT(impl.numChildProcessors() == this->numChildProcessors());
87 for (int i = 0; i < this->numChildProcessors(); ++i) {
88 if (const auto* child = this->childProcessor(i)) {
89 child->visitWithImpls(f, *impl.childProcessor(i));
90 }
91 }
92 }
93
asTextureEffect()94 GrTextureEffect* GrFragmentProcessor::asTextureEffect() {
95 if (this->classID() == kGrTextureEffect_ClassID) {
96 return static_cast<GrTextureEffect*>(this);
97 }
98 return nullptr;
99 }
100
asTextureEffect() const101 const GrTextureEffect* GrFragmentProcessor::asTextureEffect() const {
102 if (this->classID() == kGrTextureEffect_ClassID) {
103 return static_cast<const GrTextureEffect*>(this);
104 }
105 return nullptr;
106 }
107
108 #if GR_TEST_UTILS
recursive_dump_tree_info(const GrFragmentProcessor & fp,SkString indent,SkString * text)109 static void recursive_dump_tree_info(const GrFragmentProcessor& fp,
110 SkString indent,
111 SkString* text) {
112 for (int index = 0; index < fp.numChildProcessors(); ++index) {
113 text->appendf("\n%s(#%d) -> ", indent.c_str(), index);
114 if (const GrFragmentProcessor* childFP = fp.childProcessor(index)) {
115 text->append(childFP->dumpInfo());
116 indent.append("\t");
117 recursive_dump_tree_info(*childFP, indent, text);
118 } else {
119 text->append("null");
120 }
121 }
122 }
123
dumpTreeInfo() const124 SkString GrFragmentProcessor::dumpTreeInfo() const {
125 SkString text = this->dumpInfo();
126 recursive_dump_tree_info(*this, SkString("\t"), &text);
127 text.append("\n");
128 return text;
129 }
130 #endif
131
makeProgramImpl() const132 std::unique_ptr<GrFragmentProcessor::ProgramImpl> GrFragmentProcessor::makeProgramImpl() const {
133 std::unique_ptr<ProgramImpl> impl = this->onMakeProgramImpl();
134 impl->fChildProcessors.push_back_n(fChildProcessors.count());
135 for (int i = 0; i < fChildProcessors.count(); ++i) {
136 impl->fChildProcessors[i] = fChildProcessors[i] ? fChildProcessors[i]->makeProgramImpl()
137 : nullptr;
138 }
139 return impl;
140 }
141
numNonNullChildProcessors() const142 int GrFragmentProcessor::numNonNullChildProcessors() const {
143 return std::count_if(fChildProcessors.begin(), fChildProcessors.end(),
144 [](const auto& c) { return c != nullptr; });
145 }
146
147 #ifdef SK_DEBUG
isInstantiated() const148 bool GrFragmentProcessor::isInstantiated() const {
149 bool result = true;
150 this->visitTextureEffects([&result](const GrTextureEffect& te) {
151 if (!te.texture()) {
152 result = false;
153 }
154 });
155 return result;
156 }
157 #endif
158
registerChild(std::unique_ptr<GrFragmentProcessor> child,SkSL::SampleUsage sampleUsage)159 void GrFragmentProcessor::registerChild(std::unique_ptr<GrFragmentProcessor> child,
160 SkSL::SampleUsage sampleUsage) {
161 SkASSERT(sampleUsage.isSampled());
162
163 if (!child) {
164 fChildProcessors.push_back(nullptr);
165 return;
166 }
167
168 // The child should not have been attached to another FP already and not had any sampling
169 // strategy set on it.
170 SkASSERT(!child->fParent && !child->sampleUsage().isSampled());
171
172 // Configure child's sampling state first
173 child->fUsage = sampleUsage;
174
175 // Propagate the "will read dest-color" flag up to parent FPs.
176 if (child->willReadDstColor()) {
177 this->setWillReadDstColor();
178 }
179
180 // If this child receives passthrough or matrix transformed coords from its parent then note
181 // that the parent's coords are used indirectly to ensure that they aren't omitted.
182 if ((sampleUsage.isPassThrough() || sampleUsage.isUniformMatrix()) &&
183 child->usesSampleCoords()) {
184 fFlags |= kUsesSampleCoordsIndirectly_Flag;
185 }
186
187 // Record that the child is attached to us; this FP is the source of any uniform data needed
188 // to evaluate the child sample matrix.
189 child->fParent = this;
190 fChildProcessors.push_back(std::move(child));
191
192 // Validate: our sample strategy comes from a parent we shouldn't have yet.
193 SkASSERT(!fUsage.isSampled() && !fParent);
194 }
195
cloneAndRegisterAllChildProcessors(const GrFragmentProcessor & src)196 void GrFragmentProcessor::cloneAndRegisterAllChildProcessors(const GrFragmentProcessor& src) {
197 for (int i = 0; i < src.numChildProcessors(); ++i) {
198 if (auto fp = src.childProcessor(i)) {
199 this->registerChild(fp->clone(), fp->sampleUsage());
200 } else {
201 this->registerChild(nullptr);
202 }
203 }
204 }
205
MakeColor(SkPMColor4f color)206 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::MakeColor(SkPMColor4f color) {
207 // Use ColorFilter signature/factory to get the constant output for constant input optimization
208 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
209 uniform half4 color;
210 half4 main(half4 inColor) { return color; }
211 )");
212 SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
213 return GrSkSLFP::Make(effect, "color_fp", /*inputFP=*/nullptr,
214 color.isOpaque() ? GrSkSLFP::OptFlags::kPreservesOpaqueInput
215 : GrSkSLFP::OptFlags::kNone,
216 "color", color);
217 }
218
MulInputByChildAlpha(std::unique_ptr<GrFragmentProcessor> fp)219 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::MulInputByChildAlpha(
220 std::unique_ptr<GrFragmentProcessor> fp) {
221 if (!fp) {
222 return nullptr;
223 }
224 return GrBlendFragmentProcessor::Make(/*src=*/nullptr, std::move(fp), SkBlendMode::kSrcIn);
225 }
226
ApplyPaintAlpha(std::unique_ptr<GrFragmentProcessor> child)227 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::ApplyPaintAlpha(
228 std::unique_ptr<GrFragmentProcessor> child) {
229 SkASSERT(child);
230 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
231 uniform colorFilter fp;
232 half4 main(half4 inColor) {
233 return fp.eval(inColor.rgb1) * inColor.a;
234 }
235 )");
236 return GrSkSLFP::Make(effect, "ApplyPaintAlpha", /*inputFP=*/nullptr,
237 GrSkSLFP::OptFlags::kPreservesOpaqueInput |
238 GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
239 "fp", std::move(child));
240 }
241
ModulateRGBA(std::unique_ptr<GrFragmentProcessor> inputFP,const SkPMColor4f & color)242 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::ModulateRGBA(
243 std::unique_ptr<GrFragmentProcessor> inputFP, const SkPMColor4f& color) {
244 auto colorFP = MakeColor(color);
245 return GrBlendFragmentProcessor::Make(std::move(colorFP),
246 std::move(inputFP),
247 SkBlendMode::kModulate);
248 }
249
ClampOutput(std::unique_ptr<GrFragmentProcessor> fp)250 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::ClampOutput(
251 std::unique_ptr<GrFragmentProcessor> fp) {
252 SkASSERT(fp);
253 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
254 half4 main(half4 inColor) {
255 return saturate(inColor);
256 }
257 )");
258 SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
259 return GrSkSLFP::Make(
260 effect, "Clamp", std::move(fp), GrSkSLFP::OptFlags::kPreservesOpaqueInput);
261 }
262
SwizzleOutput(std::unique_ptr<GrFragmentProcessor> fp,const GrSwizzle & swizzle)263 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::SwizzleOutput(
264 std::unique_ptr<GrFragmentProcessor> fp, const GrSwizzle& swizzle) {
265 class SwizzleFragmentProcessor : public GrFragmentProcessor {
266 public:
267 static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> fp,
268 const GrSwizzle& swizzle) {
269 return std::unique_ptr<GrFragmentProcessor>(
270 new SwizzleFragmentProcessor(std::move(fp), swizzle));
271 }
272
273 const char* name() const override { return "Swizzle"; }
274
275 std::unique_ptr<GrFragmentProcessor> clone() const override {
276 return Make(this->childProcessor(0)->clone(), fSwizzle);
277 }
278
279 private:
280 SwizzleFragmentProcessor(std::unique_ptr<GrFragmentProcessor> fp, const GrSwizzle& swizzle)
281 : INHERITED(kSwizzleFragmentProcessor_ClassID, ProcessorOptimizationFlags(fp.get()))
282 , fSwizzle(swizzle) {
283 this->registerChild(std::move(fp));
284 }
285
286 std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
287 class Impl : public ProgramImpl {
288 public:
289 void emitCode(EmitArgs& args) override {
290 SkString childColor = this->invokeChild(0, args);
291
292 const SwizzleFragmentProcessor& sfp = args.fFp.cast<SwizzleFragmentProcessor>();
293 const GrSwizzle& swizzle = sfp.fSwizzle;
294 GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
295
296 fragBuilder->codeAppendf("return %s.%s;",
297 childColor.c_str(), swizzle.asString().c_str());
298 }
299 };
300 return std::make_unique<Impl>();
301 }
302
303 void onAddToKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const override {
304 b->add32(fSwizzle.asKey());
305 }
306
307 bool onIsEqual(const GrFragmentProcessor& other) const override {
308 const SwizzleFragmentProcessor& sfp = other.cast<SwizzleFragmentProcessor>();
309 return fSwizzle == sfp.fSwizzle;
310 }
311
312 SkPMColor4f constantOutputForConstantInput(const SkPMColor4f& input) const override {
313 return fSwizzle.applyTo(ConstantOutputForConstantInput(this->childProcessor(0), input));
314 }
315
316 GrSwizzle fSwizzle;
317
318 using INHERITED = GrFragmentProcessor;
319 };
320
321 if (!fp) {
322 return nullptr;
323 }
324 if (GrSwizzle::RGBA() == swizzle) {
325 return fp;
326 }
327 return SwizzleFragmentProcessor::Make(std::move(fp), swizzle);
328 }
329
330 //////////////////////////////////////////////////////////////////////////////
331
OverrideInput(std::unique_ptr<GrFragmentProcessor> fp,const SkPMColor4f & color)332 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::OverrideInput(
333 std::unique_ptr<GrFragmentProcessor> fp, const SkPMColor4f& color) {
334 if (!fp) {
335 return nullptr;
336 }
337 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
338 uniform colorFilter fp; // Declared as colorFilter so we can pass a color
339 uniform half4 color;
340 half4 main(half4 inColor) {
341 return fp.eval(color);
342 }
343 )");
344 SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
345 return GrSkSLFP::Make(effect, "OverrideInput", /*inputFP=*/nullptr,
346 color.isOpaque() ? GrSkSLFP::OptFlags::kPreservesOpaqueInput
347 : GrSkSLFP::OptFlags::kNone,
348 "fp", std::move(fp),
349 "color", color);
350 }
351
352 //////////////////////////////////////////////////////////////////////////////
353
DisableCoverageAsAlpha(std::unique_ptr<GrFragmentProcessor> fp)354 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::DisableCoverageAsAlpha(
355 std::unique_ptr<GrFragmentProcessor> fp) {
356 if (!fp || !fp->compatibleWithCoverageAsAlpha()) {
357 return fp;
358 }
359 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
360 half4 main(half4 inColor) { return inColor; }
361 )");
362 SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
363 return GrSkSLFP::Make(effect, "DisableCoverageAsAlpha", std::move(fp),
364 GrSkSLFP::OptFlags::kPreservesOpaqueInput);
365 }
366
367 //////////////////////////////////////////////////////////////////////////////
368
UseDestColorAsInput(std::unique_ptr<GrFragmentProcessor> fp)369 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::UseDestColorAsInput(
370 std::unique_ptr<GrFragmentProcessor> fp) {
371 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForBlender, R"(
372 uniform colorFilter fp; // Declared as colorFilter so we can pass a color
373 half4 main(half4 src, half4 dst) {
374 return fp.eval(dst);
375 }
376 )");
377 return GrSkSLFP::Make(effect, "UseDestColorAsInput", /*inputFP=*/nullptr,
378 GrSkSLFP::OptFlags::kNone, "fp", std::move(fp));
379 }
380
381 //////////////////////////////////////////////////////////////////////////////
382
Compose(std::unique_ptr<GrFragmentProcessor> f,std::unique_ptr<GrFragmentProcessor> g)383 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::Compose(
384 std::unique_ptr<GrFragmentProcessor> f, std::unique_ptr<GrFragmentProcessor> g) {
385 class ComposeProcessor : public GrFragmentProcessor {
386 public:
387 static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> f,
388 std::unique_ptr<GrFragmentProcessor> g) {
389 return std::unique_ptr<GrFragmentProcessor>(new ComposeProcessor(std::move(f),
390 std::move(g)));
391 }
392
393 const char* name() const override { return "Compose"; }
394
395 std::unique_ptr<GrFragmentProcessor> clone() const override {
396 return std::unique_ptr<GrFragmentProcessor>(new ComposeProcessor(*this));
397 }
398
399 private:
400 std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
401 class Impl : public ProgramImpl {
402 public:
403 void emitCode(EmitArgs& args) override {
404 SkString result = this->invokeChild(1, args); // g(x)
405 result = this->invokeChild(0, result.c_str(), args); // f(g(x))
406 args.fFragBuilder->codeAppendf("return %s;", result.c_str());
407 }
408 };
409 return std::make_unique<Impl>();
410 }
411
412 ComposeProcessor(std::unique_ptr<GrFragmentProcessor> f,
413 std::unique_ptr<GrFragmentProcessor> g)
414 : INHERITED(kSeriesFragmentProcessor_ClassID,
415 f->optimizationFlags() & g->optimizationFlags()) {
416 this->registerChild(std::move(f));
417 this->registerChild(std::move(g));
418 }
419
420 ComposeProcessor(const ComposeProcessor& that) : INHERITED(that) {}
421
422 void onAddToKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const override {}
423
424 bool onIsEqual(const GrFragmentProcessor&) const override { return true; }
425
426 SkPMColor4f constantOutputForConstantInput(const SkPMColor4f& inColor) const override {
427 SkPMColor4f color = inColor;
428 color = ConstantOutputForConstantInput(this->childProcessor(1), color);
429 color = ConstantOutputForConstantInput(this->childProcessor(0), color);
430 return color;
431 }
432
433 using INHERITED = GrFragmentProcessor;
434 };
435
436 // Allow either of the composed functions to be null.
437 if (f == nullptr) {
438 return g;
439 }
440 if (g == nullptr) {
441 return f;
442 }
443
444 // Run an optimization pass on this composition.
445 GrProcessorAnalysisColor inputColor;
446 inputColor.setToUnknown();
447
448 std::unique_ptr<GrFragmentProcessor> series[2] = {std::move(g), std::move(f)};
449 GrColorFragmentProcessorAnalysis info(inputColor, series, SK_ARRAY_COUNT(series));
450
451 SkPMColor4f knownColor;
452 int leadingFPsToEliminate = info.initialProcessorsToEliminate(&knownColor);
453 switch (leadingFPsToEliminate) {
454 default:
455 // We shouldn't eliminate more than we started with.
456 SkASSERT(leadingFPsToEliminate <= 2);
457 [[fallthrough]];
458 case 0:
459 // Compose the two processors as requested.
460 return ComposeProcessor::Make(/*f=*/std::move(series[1]), /*g=*/std::move(series[0]));
461 case 1:
462 // Replace the first processor with a constant color.
463 return ComposeProcessor::Make(/*f=*/std::move(series[1]),
464 /*g=*/MakeColor(knownColor));
465 case 2:
466 // Replace the entire composition with a constant color.
467 return MakeColor(knownColor);
468 }
469 }
470
471 //////////////////////////////////////////////////////////////////////////////
472
ColorMatrix(std::unique_ptr<GrFragmentProcessor> child,const float matrix[20],bool unpremulInput,bool clampRGBOutput,bool premulOutput)473 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::ColorMatrix(
474 std::unique_ptr<GrFragmentProcessor> child,
475 const float matrix[20],
476 bool unpremulInput,
477 bool clampRGBOutput,
478 bool premulOutput) {
479 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
480 uniform half4x4 m;
481 uniform half4 v;
482 uniform int unpremulInput; // always specialized
483 uniform int clampRGBOutput; // always specialized
484 uniform int premulOutput; // always specialized
485 half4 main(half4 color) {
486 if (bool(unpremulInput)) {
487 color = unpremul(color);
488 }
489 color = m * color + v;
490 if (bool(clampRGBOutput)) {
491 color = saturate(color);
492 } else {
493 color.a = saturate(color.a);
494 }
495 if (bool(premulOutput)) {
496 color.rgb *= color.a;
497 }
498 return color;
499 }
500 )");
501 SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
502
503 SkM44 m44(matrix[ 0], matrix[ 1], matrix[ 2], matrix[ 3],
504 matrix[ 5], matrix[ 6], matrix[ 7], matrix[ 8],
505 matrix[10], matrix[11], matrix[12], matrix[13],
506 matrix[15], matrix[16], matrix[17], matrix[18]);
507 SkV4 v4 = {matrix[4], matrix[9], matrix[14], matrix[19]};
508 return GrSkSLFP::Make(effect, "ColorMatrix", std::move(child), GrSkSLFP::OptFlags::kNone,
509 "m", m44,
510 "v", v4,
511 "unpremulInput", GrSkSLFP::Specialize(unpremulInput ? 1 : 0),
512 "clampRGBOutput", GrSkSLFP::Specialize(clampRGBOutput ? 1 : 0),
513 "premulOutput", GrSkSLFP::Specialize(premulOutput ? 1 : 0));
514 }
515
516 //////////////////////////////////////////////////////////////////////////////
517
SurfaceColor()518 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::SurfaceColor() {
519 class SurfaceColorProcessor : public GrFragmentProcessor {
520 public:
521 static std::unique_ptr<GrFragmentProcessor> Make() {
522 return std::unique_ptr<GrFragmentProcessor>(new SurfaceColorProcessor());
523 }
524
525 std::unique_ptr<GrFragmentProcessor> clone() const override { return Make(); }
526
527 const char* name() const override { return "SurfaceColor"; }
528
529 private:
530 std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
531 class Impl : public ProgramImpl {
532 public:
533 void emitCode(EmitArgs& args) override {
534 const char* dstColor = args.fFragBuilder->dstColor();
535 args.fFragBuilder->codeAppendf("return %s;", dstColor);
536 }
537 };
538 return std::make_unique<Impl>();
539 }
540
541 SurfaceColorProcessor()
542 : INHERITED(kSurfaceColorProcessor_ClassID, kNone_OptimizationFlags) {
543 this->setWillReadDstColor();
544 }
545
546 void onAddToKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const override {}
547
548 bool onIsEqual(const GrFragmentProcessor&) const override { return true; }
549
550 using INHERITED = GrFragmentProcessor;
551 };
552
553 return SurfaceColorProcessor::Make();
554 }
555
556 //////////////////////////////////////////////////////////////////////////////
557
DeviceSpace(std::unique_ptr<GrFragmentProcessor> fp)558 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::DeviceSpace(
559 std::unique_ptr<GrFragmentProcessor> fp) {
560 if (!fp) {
561 return nullptr;
562 }
563
564 class DeviceSpace : GrFragmentProcessor {
565 public:
566 static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> fp) {
567 return std::unique_ptr<GrFragmentProcessor>(new DeviceSpace(std::move(fp)));
568 }
569
570 private:
571 DeviceSpace(std::unique_ptr<GrFragmentProcessor> fp)
572 : GrFragmentProcessor(kDeviceSpace_ClassID, fp->optimizationFlags()) {
573 // Passing FragCoord here is the reason this is a subclass and not a runtime-FP.
574 this->registerChild(std::move(fp), SkSL::SampleUsage::FragCoord());
575 }
576
577 std::unique_ptr<GrFragmentProcessor> clone() const override {
578 auto child = this->childProcessor(0)->clone();
579 return std::unique_ptr<GrFragmentProcessor>(new DeviceSpace(std::move(child)));
580 }
581
582 SkPMColor4f constantOutputForConstantInput(const SkPMColor4f& f) const override {
583 return this->childProcessor(0)->constantOutputForConstantInput(f);
584 }
585
586 std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
587 class Impl : public ProgramImpl {
588 public:
589 Impl() = default;
590 void emitCode(ProgramImpl::EmitArgs& args) override {
591 auto child = this->invokeChild(0, args.fInputColor, args, "sk_FragCoord.xy");
592 args.fFragBuilder->codeAppendf("return %s;", child.c_str());
593 }
594 };
595 return std::make_unique<Impl>();
596 }
597
598 void onAddToKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const override {}
599
600 bool onIsEqual(const GrFragmentProcessor& processor) const override { return true; }
601
602 const char* name() const override { return "DeviceSpace"; }
603 };
604
605 return DeviceSpace::Make(std::move(fp));
606 }
607
608 //////////////////////////////////////////////////////////////////////////////
609
610 #define CLIP_EDGE_SKSL \
611 "const int kFillBW = 0;" \
612 "const int kFillAA = 1;" \
613 "const int kInverseFillBW = 2;" \
614 "const int kInverseFillAA = 3;"
615
616 static_assert(static_cast<int>(GrClipEdgeType::kFillBW) == 0);
617 static_assert(static_cast<int>(GrClipEdgeType::kFillAA) == 1);
618 static_assert(static_cast<int>(GrClipEdgeType::kInverseFillBW) == 2);
619 static_assert(static_cast<int>(GrClipEdgeType::kInverseFillAA) == 3);
620
Rect(std::unique_ptr<GrFragmentProcessor> inputFP,GrClipEdgeType edgeType,SkRect rect)621 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::Rect(
622 std::unique_ptr<GrFragmentProcessor> inputFP, GrClipEdgeType edgeType, SkRect rect) {
623 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader, CLIP_EDGE_SKSL R"(
624 uniform int edgeType; // GrClipEdgeType, specialized
625 uniform float4 rectUniform;
626
627 half4 main(float2 xy, half4 inColor) {
628 half coverage;
629 if (edgeType == kFillBW || edgeType == kInverseFillBW) {
630 // non-AA
631 coverage = all(greaterThan(float4(sk_FragCoord.xy, rectUniform.zw),
632 float4(rectUniform.xy, sk_FragCoord.xy))) ? 1 : 0;
633 } else {
634 // compute coverage relative to left and right edges, add, then subtract 1 to
635 // account for double counting. And similar for top/bottom.
636 half4 dists4 = clamp(half4(1, 1, -1, -1) *
637 half4(sk_FragCoord.xyxy - rectUniform), 0, 1);
638 half2 dists2 = dists4.xy + dists4.zw - 1;
639 coverage = dists2.x * dists2.y;
640 }
641
642 if (edgeType == kInverseFillBW || edgeType == kInverseFillAA) {
643 coverage = 1.0 - coverage;
644 }
645
646 return inColor * coverage;
647 }
648 )");
649
650 SkASSERT(rect.isSorted());
651 // The AA math in the shader evaluates to 0 at the uploaded coordinates, so outset by 0.5
652 // to interpolate from 0 at a half pixel inset and 1 at a half pixel outset of rect.
653 SkRect rectUniform = GrClipEdgeTypeIsAA(edgeType) ? rect.makeOutset(.5f, .5f) : rect;
654
655 return GrSkSLFP::Make(effect, "Rect", std::move(inputFP),
656 GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
657 "edgeType", GrSkSLFP::Specialize(static_cast<int>(edgeType)),
658 "rectUniform", rectUniform);
659 }
660
Circle(std::unique_ptr<GrFragmentProcessor> inputFP,GrClipEdgeType edgeType,SkPoint center,float radius)661 GrFPResult GrFragmentProcessor::Circle(std::unique_ptr<GrFragmentProcessor> inputFP,
662 GrClipEdgeType edgeType,
663 SkPoint center,
664 float radius) {
665 // A radius below half causes the implicit insetting done by this processor to become
666 // inverted. We could handle this case by making the processor code more complicated.
667 if (radius < .5f && GrClipEdgeTypeIsInverseFill(edgeType)) {
668 return GrFPFailure(std::move(inputFP));
669 }
670
671 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader, CLIP_EDGE_SKSL R"(
672 uniform int edgeType; // GrClipEdgeType, specialized
673 // The circle uniform is (center.x, center.y, radius + 0.5, 1 / (radius + 0.5)) for regular
674 // fills and (..., radius - 0.5, 1 / (radius - 0.5)) for inverse fills.
675 uniform float4 circle;
676
677 half4 main(float2 xy, half4 inColor) {
678 // TODO: Right now the distance to circle calculation is performed in a space normalized
679 // to the radius and then denormalized. This is to mitigate overflow on devices that
680 // don't have full float.
681 half d;
682 if (edgeType == kInverseFillBW || edgeType == kInverseFillAA) {
683 d = half((length((circle.xy - sk_FragCoord.xy) * circle.w) - 1.0) * circle.z);
684 } else {
685 d = half((1.0 - length((circle.xy - sk_FragCoord.xy) * circle.w)) * circle.z);
686 }
687 if (edgeType == kFillAA || edgeType == kInverseFillAA) {
688 return inColor * saturate(d);
689 } else {
690 return d > 0.5 ? inColor : half4(0);
691 }
692 }
693 )");
694
695 SkScalar effectiveRadius = radius;
696 if (GrClipEdgeTypeIsInverseFill(edgeType)) {
697 effectiveRadius -= 0.5f;
698 // When the radius is 0.5 effectiveRadius is 0 which causes an inf * 0 in the shader.
699 effectiveRadius = std::max(0.001f, effectiveRadius);
700 } else {
701 effectiveRadius += 0.5f;
702 }
703 SkV4 circle = {center.fX, center.fY, effectiveRadius, SkScalarInvert(effectiveRadius)};
704
705 return GrFPSuccess(GrSkSLFP::Make(effect, "Circle", std::move(inputFP),
706 GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
707 "edgeType", GrSkSLFP::Specialize(static_cast<int>(edgeType)),
708 "circle", circle));
709 }
710
Ellipse(std::unique_ptr<GrFragmentProcessor> inputFP,GrClipEdgeType edgeType,SkPoint center,SkPoint radii,const GrShaderCaps & caps)711 GrFPResult GrFragmentProcessor::Ellipse(std::unique_ptr<GrFragmentProcessor> inputFP,
712 GrClipEdgeType edgeType,
713 SkPoint center,
714 SkPoint radii,
715 const GrShaderCaps& caps) {
716 const bool medPrecision = !caps.floatIs32Bits();
717
718 // Small radii produce bad results on devices without full float.
719 if (medPrecision && (radii.fX < 0.5f || radii.fY < 0.5f)) {
720 return GrFPFailure(std::move(inputFP));
721 }
722 // Very narrow ellipses produce bad results on devices without full float
723 if (medPrecision && (radii.fX > 255*radii.fY || radii.fY > 255*radii.fX)) {
724 return GrFPFailure(std::move(inputFP));
725 }
726 // Very large ellipses produce bad results on devices without full float
727 if (medPrecision && (radii.fX > 16384 || radii.fY > 16384)) {
728 return GrFPFailure(std::move(inputFP));
729 }
730
731 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader, CLIP_EDGE_SKSL R"(
732 uniform int edgeType; // GrClipEdgeType, specialized
733 uniform int medPrecision; // !sk_Caps.floatIs32Bits, specialized
734
735 uniform float4 ellipse;
736 uniform float2 scale; // only for medPrecision
737
738 half4 main(float2 xy, half4 inColor) {
739 // d is the offset to the ellipse center
740 float2 d = sk_FragCoord.xy - ellipse.xy;
741 // If we're on a device with a "real" mediump then we'll do the distance computation in
742 // a space that is normalized by the larger radius or 128, whichever is smaller. The
743 // scale uniform will be scale, 1/scale. The inverse squared radii uniform values are
744 // already in this normalized space. The center is not.
745 if (bool(medPrecision)) {
746 d *= scale.y;
747 }
748 float2 Z = d * ellipse.zw;
749 // implicit is the evaluation of (x/rx)^2 + (y/ry)^2 - 1.
750 float implicit = dot(Z, d) - 1;
751 // grad_dot is the squared length of the gradient of the implicit.
752 float grad_dot = 4 * dot(Z, Z);
753 // Avoid calling inversesqrt on zero.
754 if (bool(medPrecision)) {
755 grad_dot = max(grad_dot, 6.1036e-5);
756 } else {
757 grad_dot = max(grad_dot, 1.1755e-38);
758 }
759 float approx_dist = implicit * inversesqrt(grad_dot);
760 if (bool(medPrecision)) {
761 approx_dist *= scale.x;
762 }
763
764 half alpha;
765 if (edgeType == kFillBW) {
766 alpha = approx_dist > 0.0 ? 0.0 : 1.0;
767 } else if (edgeType == kFillAA) {
768 alpha = saturate(0.5 - half(approx_dist));
769 } else if (edgeType == kInverseFillBW) {
770 alpha = approx_dist > 0.0 ? 1.0 : 0.0;
771 } else { // edgeType == kInverseFillAA
772 alpha = saturate(0.5 + half(approx_dist));
773 }
774 return inColor * alpha;
775 }
776 )");
777
778 float invRXSqd;
779 float invRYSqd;
780 SkV2 scale = {1, 1};
781 // If we're using a scale factor to work around precision issues, choose the larger radius as
782 // the scale factor. The inv radii need to be pre-adjusted by the scale factor.
783 if (medPrecision) {
784 if (radii.fX > radii.fY) {
785 invRXSqd = 1.f;
786 invRYSqd = (radii.fX * radii.fX) / (radii.fY * radii.fY);
787 scale = {radii.fX, 1.f / radii.fX};
788 } else {
789 invRXSqd = (radii.fY * radii.fY) / (radii.fX * radii.fX);
790 invRYSqd = 1.f;
791 scale = {radii.fY, 1.f / radii.fY};
792 }
793 } else {
794 invRXSqd = 1.f / (radii.fX * radii.fX);
795 invRYSqd = 1.f / (radii.fY * radii.fY);
796 }
797 SkV4 ellipse = {center.fX, center.fY, invRXSqd, invRYSqd};
798
799 return GrFPSuccess(GrSkSLFP::Make(effect, "Ellipse", std::move(inputFP),
800 GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
801 "edgeType", GrSkSLFP::Specialize(static_cast<int>(edgeType)),
802 "medPrecision", GrSkSLFP::Specialize<int>(medPrecision),
803 "ellipse", ellipse,
804 "scale", scale));
805 }
806
807 //////////////////////////////////////////////////////////////////////////////
808
HighPrecision(std::unique_ptr<GrFragmentProcessor> fp)809 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::HighPrecision(
810 std::unique_ptr<GrFragmentProcessor> fp) {
811 class HighPrecisionFragmentProcessor : public GrFragmentProcessor {
812 public:
813 static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> fp) {
814 return std::unique_ptr<GrFragmentProcessor>(
815 new HighPrecisionFragmentProcessor(std::move(fp)));
816 }
817
818 const char* name() const override { return "HighPrecision"; }
819
820 std::unique_ptr<GrFragmentProcessor> clone() const override {
821 return Make(this->childProcessor(0)->clone());
822 }
823
824 private:
825 HighPrecisionFragmentProcessor(std::unique_ptr<GrFragmentProcessor> fp)
826 : INHERITED(kHighPrecisionFragmentProcessor_ClassID,
827 ProcessorOptimizationFlags(fp.get())) {
828 this->registerChild(std::move(fp));
829 }
830
831 std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
832 class Impl : public ProgramImpl {
833 public:
834 void emitCode(EmitArgs& args) override {
835 SkString childColor = this->invokeChild(0, args);
836
837 args.fFragBuilder->forceHighPrecision();
838 args.fFragBuilder->codeAppendf("return %s;", childColor.c_str());
839 }
840 };
841 return std::make_unique<Impl>();
842 }
843
844 void onAddToKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const override {}
845 bool onIsEqual(const GrFragmentProcessor& other) const override { return true; }
846
847 SkPMColor4f constantOutputForConstantInput(const SkPMColor4f& input) const override {
848 return ConstantOutputForConstantInput(this->childProcessor(0), input);
849 }
850
851 using INHERITED = GrFragmentProcessor;
852 };
853
854 return HighPrecisionFragmentProcessor::Make(std::move(fp));
855 }
856
857 //////////////////////////////////////////////////////////////////////////////
858
859 using ProgramImpl = GrFragmentProcessor::ProgramImpl;
860
setData(const GrGLSLProgramDataManager & pdman,const GrFragmentProcessor & processor)861 void ProgramImpl::setData(const GrGLSLProgramDataManager& pdman,
862 const GrFragmentProcessor& processor) {
863 this->onSetData(pdman, processor);
864 }
865
invokeChild(int childIndex,const char * inputColor,const char * destColor,EmitArgs & args,SkSL::String skslCoords)866 SkString ProgramImpl::invokeChild(int childIndex,
867 const char* inputColor,
868 const char* destColor,
869 EmitArgs& args,
870 SkSL::String skslCoords) {
871 SkASSERT(childIndex >= 0);
872
873 if (!inputColor) {
874 inputColor = args.fInputColor;
875 }
876
877 const GrFragmentProcessor* childProc = args.fFp.childProcessor(childIndex);
878 if (!childProc) {
879 // If no child processor is provided, return the input color as-is.
880 return SkString(inputColor);
881 }
882
883 auto invocation = SkStringPrintf("%s(%s", this->childProcessor(childIndex)->functionName(),
884 inputColor);
885
886 if (childProc->isBlendFunction()) {
887 if (!destColor) {
888 destColor = args.fFp.isBlendFunction() ? args.fDestColor : "half4(1)";
889 }
890 invocation.appendf(", %s", destColor);
891 }
892
893 // Assert that the child has no sample matrix. A uniform matrix sample call would go through
894 // invokeChildWithMatrix, not here.
895 SkASSERT(!childProc->sampleUsage().isUniformMatrix());
896
897 if (args.fFragBuilder->getProgramBuilder()->fragmentProcessorHasCoordsParam(childProc)) {
898 SkASSERT(!childProc->sampleUsage().isFragCoord() || skslCoords == "sk_FragCoord.xy");
899 // The child's function takes a half4 color and a float2 coordinate
900 invocation.appendf(", %s", skslCoords.empty() ? args.fSampleCoord : skslCoords.c_str());
901 }
902
903 invocation.append(")");
904 return invocation;
905 }
906
invokeChildWithMatrix(int childIndex,const char * inputColor,const char * destColor,EmitArgs & args)907 SkString ProgramImpl::invokeChildWithMatrix(int childIndex,
908 const char* inputColor,
909 const char* destColor,
910 EmitArgs& args) {
911 SkASSERT(childIndex >= 0);
912
913 if (!inputColor) {
914 inputColor = args.fInputColor;
915 }
916
917 const GrFragmentProcessor* childProc = args.fFp.childProcessor(childIndex);
918 if (!childProc) {
919 // If no child processor is provided, return the input color as-is.
920 return SkString(inputColor);
921 }
922
923 SkASSERT(childProc->sampleUsage().isUniformMatrix());
924
925 // Every uniform matrix has the same (initial) name. Resolve that into the mangled name:
926 GrShaderVar uniform = args.fUniformHandler->getUniformMapping(
927 args.fFp, SkString(SkSL::SampleUsage::MatrixUniformName()));
928 SkASSERT(uniform.getType() == kFloat3x3_GrSLType);
929 const SkString& matrixName(uniform.getName());
930
931 auto invocation = SkStringPrintf("%s(%s", this->childProcessor(childIndex)->functionName(),
932 inputColor);
933
934 if (childProc->isBlendFunction()) {
935 if (!destColor) {
936 destColor = args.fFp.isBlendFunction() ? args.fDestColor : "half4(1)";
937 }
938 invocation.appendf(", %s", destColor);
939 }
940
941 // Produce a string containing the call to the helper function. We have a uniform variable
942 // containing our transform (matrixName). If the parent coords were produced by uniform
943 // transforms, then the entire expression (matrixName * coords) is lifted to a vertex shader
944 // and is stored in a varying. In that case, childProc will not be sampled explicitly, so its
945 // function signature will not take in coords.
946 //
947 // In all other cases, we need to insert sksl to compute matrix * parent coords and then invoke
948 // the function.
949 if (args.fFragBuilder->getProgramBuilder()->fragmentProcessorHasCoordsParam(childProc)) {
950 // Only check perspective for this specific matrix transform, not the aggregate FP property.
951 // Any parent perspective will have already been applied when evaluated in the FS.
952 if (childProc->sampleUsage().hasPerspective()) {
953 invocation.appendf(", proj((%s) * %s.xy1)", matrixName.c_str(), args.fSampleCoord);
954 } else if (args.fShaderCaps->nonsquareMatrixSupport()) {
955 invocation.appendf(", float3x2(%s) * %s.xy1", matrixName.c_str(), args.fSampleCoord);
956 } else {
957 invocation.appendf(", ((%s) * %s.xy1).xy", matrixName.c_str(), args.fSampleCoord);
958 }
959 }
960
961 invocation.append(")");
962 return invocation;
963 }
964