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