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