2 * Copyright 2015 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "src/gpu/ganesh/GrFragmentProcessor.h"
10 #include "src/core/SkRuntimeEffectPriv.h"
11 #include "src/gpu/KeyBuilder.h"
12 #include "src/gpu/ganesh/GrPipeline.h"
13 #include "src/gpu/ganesh/GrProcessorAnalysis.h"
14 #include "src/gpu/ganesh/GrShaderCaps.h"
15 #include "src/gpu/ganesh/effects/GrBlendFragmentProcessor.h"
16 #include "src/gpu/ganesh/effects/GrSkSLFP.h"
17 #include "src/gpu/ganesh/effects/GrTextureEffect.h"
18 #include "src/gpu/ganesh/glsl/GrGLSLFragmentShaderBuilder.h"
19 #include "src/gpu/ganesh/glsl/GrGLSLProgramBuilder.h"
20 #include "src/gpu/ganesh/glsl/GrGLSLProgramDataManager.h"
21 #include "src/gpu/ganesh/glsl/GrGLSLUniformHandler.h"
23 bool GrFragmentProcessor::isEqual(const GrFragmentProcessor& that) const {
24 if (this->classID() != that.classID()) {
27 if (this->sampleUsage() != that.sampleUsage()) {
30 if (!this->onIsEqual(that)) {
33 if (this->numChildProcessors() != that.numChildProcessors()) {
36 for (int i = 0; i < this->numChildProcessors(); ++i) {
37 auto thisChild = this->childProcessor(i),
38 thatChild = that .childProcessor(i);
39 if (SkToBool(thisChild) != SkToBool(thatChild)) {
42 if (thisChild && !thisChild->isEqual(*thatChild)) {
49 void GrFragmentProcessor::visitProxies(const GrVisitProxyFunc& func) const {
50 this->visitTextureEffects([&func](const GrTextureEffect& te) {
51 func(te.view().proxy(), te.samplerState().mipmapped());
55 void GrFragmentProcessor::visitTextureEffects(
56 const std::function<void(const GrTextureEffect&)>& func) const {
57 if (auto* te = this->asTextureEffect()) {
60 for (auto& child : fChildProcessors) {
62 child->visitTextureEffects(func);
67 void GrFragmentProcessor::visitWithImpls(
68 const std::function<void(const GrFragmentProcessor&, ProgramImpl&)>& f,
69 ProgramImpl& impl) const {
71 SkASSERT(impl.numChildProcessors() == this->numChildProcessors());
72 for (int i = 0; i < this->numChildProcessors(); ++i) {
73 if (const auto* child = this->childProcessor(i)) {
74 child->visitWithImpls(f, *impl.childProcessor(i));
79 GrTextureEffect* GrFragmentProcessor::asTextureEffect() {
80 if (this->classID() == kGrTextureEffect_ClassID) {
81 return static_cast<GrTextureEffect*>(this);
86 const GrTextureEffect* GrFragmentProcessor::asTextureEffect() const {
87 if (this->classID() == kGrTextureEffect_ClassID) {
88 return static_cast<const GrTextureEffect*>(this);
94 static void recursive_dump_tree_info(const GrFragmentProcessor& fp,
97 for (int index = 0; index < fp.numChildProcessors(); ++index) {
98 text->appendf("\n%s(#%d) -> ", indent.c_str(), index);
99 if (const GrFragmentProcessor* childFP = fp.childProcessor(index)) {
100 text->append(childFP->dumpInfo());
102 recursive_dump_tree_info(*childFP, indent, text);
104 text->append("null");
109 SkString GrFragmentProcessor::dumpTreeInfo() const {
110 SkString text = this->dumpInfo();
111 recursive_dump_tree_info(*this, SkString("\t"), &text);
117 std::unique_ptr<GrFragmentProcessor::ProgramImpl> GrFragmentProcessor::makeProgramImpl() const {
118 std::unique_ptr<ProgramImpl> impl = this->onMakeProgramImpl();
119 impl->fChildProcessors.push_back_n(fChildProcessors.count());
120 for (int i = 0; i < fChildProcessors.count(); ++i) {
121 impl->fChildProcessors[i] = fChildProcessors[i] ? fChildProcessors[i]->makeProgramImpl()
127 int GrFragmentProcessor::numNonNullChildProcessors() const {
128 return std::count_if(fChildProcessors.begin(), fChildProcessors.end(),
129 [](const auto& c) { return c != nullptr; });
133 bool GrFragmentProcessor::isInstantiated() const {
135 this->visitTextureEffects([&result](const GrTextureEffect& te) {
144 void GrFragmentProcessor::registerChild(std::unique_ptr<GrFragmentProcessor> child,
145 SkSL::SampleUsage sampleUsage) {
146 SkASSERT(sampleUsage.isSampled());
149 fChildProcessors.push_back(nullptr);
153 // The child should not have been attached to another FP already and not had any sampling
154 // strategy set on it.
155 SkASSERT(!child->fParent && !child->sampleUsage().isSampled());
157 // Configure child's sampling state first
158 child->fUsage = sampleUsage;
160 // Propagate the "will read dest-color" flag up to parent FPs.
161 if (child->willReadDstColor()) {
162 this->setWillReadDstColor();
165 // If this child receives passthrough or matrix transformed coords from its parent then note
166 // that the parent's coords are used indirectly to ensure that they aren't omitted.
167 if ((sampleUsage.isPassThrough() || sampleUsage.isUniformMatrix()) &&
168 child->usesSampleCoords()) {
169 fFlags |= kUsesSampleCoordsIndirectly_Flag;
172 // Record that the child is attached to us; this FP is the source of any uniform data needed
173 // to evaluate the child sample matrix.
174 child->fParent = this;
175 fChildProcessors.push_back(std::move(child));
177 // Validate: our sample strategy comes from a parent we shouldn't have yet.
178 SkASSERT(!fUsage.isSampled() && !fParent);
181 void GrFragmentProcessor::cloneAndRegisterAllChildProcessors(const GrFragmentProcessor& src) {
182 for (int i = 0; i < src.numChildProcessors(); ++i) {
183 if (auto fp = src.childProcessor(i)) {
184 this->registerChild(fp->clone(), fp->sampleUsage());
186 this->registerChild(nullptr);
191 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::MakeColor(SkPMColor4f color) {
192 // Use ColorFilter signature/factory to get the constant output for constant input optimization
193 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
195 half4 main(half4 inColor) { return color; }
197 SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
198 return GrSkSLFP::Make(effect, "color_fp", /*inputFP=*/nullptr,
199 color.isOpaque() ? GrSkSLFP::OptFlags::kPreservesOpaqueInput
200 : GrSkSLFP::OptFlags::kNone,
204 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::MulInputByChildAlpha(
205 std::unique_ptr<GrFragmentProcessor> fp) {
209 return GrBlendFragmentProcessor::Make<SkBlendMode::kSrcIn>(/*src=*/nullptr, std::move(fp));
212 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::ApplyPaintAlpha(
213 std::unique_ptr<GrFragmentProcessor> child) {
215 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
216 uniform colorFilter fp;
217 half4 main(half4 inColor) {
218 return fp.eval(inColor.rgb1) * inColor.a;
221 return GrSkSLFP::Make(effect, "ApplyPaintAlpha", /*inputFP=*/nullptr,
222 GrSkSLFP::OptFlags::kPreservesOpaqueInput |
223 GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
224 "fp", std::move(child));
227 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::ModulateRGBA(
228 std::unique_ptr<GrFragmentProcessor> inputFP, const SkPMColor4f& color) {
229 auto colorFP = MakeColor(color);
230 return GrBlendFragmentProcessor::Make<SkBlendMode::kModulate>(std::move(colorFP),
234 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::ClampOutput(
235 std::unique_ptr<GrFragmentProcessor> fp) {
237 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
238 half4 main(half4 inColor) {
239 return saturate(inColor);
242 SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
243 return GrSkSLFP::Make(
244 effect, "Clamp", std::move(fp), GrSkSLFP::OptFlags::kPreservesOpaqueInput);
247 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::SwizzleOutput(
248 std::unique_ptr<GrFragmentProcessor> fp, const skgpu::Swizzle& swizzle) {
249 class SwizzleFragmentProcessor : public GrFragmentProcessor {
251 static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> fp,
252 const skgpu::Swizzle& swizzle) {
253 return std::unique_ptr<GrFragmentProcessor>(
254 new SwizzleFragmentProcessor(std::move(fp), swizzle));
257 const char* name() const override { return "Swizzle"; }
259 std::unique_ptr<GrFragmentProcessor> clone() const override {
260 return Make(this->childProcessor(0)->clone(), fSwizzle);
264 SwizzleFragmentProcessor(std::unique_ptr<GrFragmentProcessor> fp,
265 const skgpu::Swizzle& swizzle)
266 : INHERITED(kSwizzleFragmentProcessor_ClassID, ProcessorOptimizationFlags(fp.get()))
267 , fSwizzle(swizzle) {
268 this->registerChild(std::move(fp));
271 std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
272 class Impl : public ProgramImpl {
274 void emitCode(EmitArgs& args) override {
275 SkString childColor = this->invokeChild(0, args);
277 const SwizzleFragmentProcessor& sfp = args.fFp.cast<SwizzleFragmentProcessor>();
278 const skgpu::Swizzle& swizzle = sfp.fSwizzle;
279 GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
281 fragBuilder->codeAppendf("return %s.%s;",
282 childColor.c_str(), swizzle.asString().c_str());
285 return std::make_unique<Impl>();
288 void onAddToKey(const GrShaderCaps&, skgpu::KeyBuilder* b) const override {
289 b->add32(fSwizzle.asKey());
292 bool onIsEqual(const GrFragmentProcessor& other) const override {
293 const SwizzleFragmentProcessor& sfp = other.cast<SwizzleFragmentProcessor>();
294 return fSwizzle == sfp.fSwizzle;
297 SkPMColor4f constantOutputForConstantInput(const SkPMColor4f& input) const override {
298 return fSwizzle.applyTo(ConstantOutputForConstantInput(this->childProcessor(0), input));
301 skgpu::Swizzle fSwizzle;
303 using INHERITED = GrFragmentProcessor;
309 if (skgpu::Swizzle::RGBA() == swizzle) {
312 return SwizzleFragmentProcessor::Make(std::move(fp), swizzle);
315 //////////////////////////////////////////////////////////////////////////////
317 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::OverrideInput(
318 std::unique_ptr<GrFragmentProcessor> fp, const SkPMColor4f& color) {
322 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
323 uniform colorFilter fp; // Declared as colorFilter so we can pass a color
325 half4 main(half4 inColor) {
326 return fp.eval(color);
329 SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
330 return GrSkSLFP::Make(effect, "OverrideInput", /*inputFP=*/nullptr,
331 color.isOpaque() ? GrSkSLFP::OptFlags::kPreservesOpaqueInput
332 : GrSkSLFP::OptFlags::kNone,
337 //////////////////////////////////////////////////////////////////////////////
339 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::DisableCoverageAsAlpha(
340 std::unique_ptr<GrFragmentProcessor> fp) {
341 if (!fp || !fp->compatibleWithCoverageAsAlpha()) {
344 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
345 half4 main(half4 inColor) { return inColor; }
347 SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
348 return GrSkSLFP::Make(effect, "DisableCoverageAsAlpha", std::move(fp),
349 GrSkSLFP::OptFlags::kPreservesOpaqueInput);
352 //////////////////////////////////////////////////////////////////////////////
354 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::UseDestColorAsInput(
355 std::unique_ptr<GrFragmentProcessor> fp) {
356 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForBlender, R"(
357 uniform colorFilter fp; // Declared as colorFilter so we can pass a color
358 half4 main(half4 src, half4 dst) {
362 return GrSkSLFP::Make(effect, "UseDestColorAsInput", /*inputFP=*/nullptr,
363 GrSkSLFP::OptFlags::kNone, "fp", std::move(fp));
366 //////////////////////////////////////////////////////////////////////////////
368 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::Compose(
369 std::unique_ptr<GrFragmentProcessor> f, std::unique_ptr<GrFragmentProcessor> g) {
370 class ComposeProcessor : public GrFragmentProcessor {
372 static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> f,
373 std::unique_ptr<GrFragmentProcessor> g) {
374 return std::unique_ptr<GrFragmentProcessor>(new ComposeProcessor(std::move(f),
378 const char* name() const override { return "Compose"; }
380 std::unique_ptr<GrFragmentProcessor> clone() const override {
381 return std::unique_ptr<GrFragmentProcessor>(new ComposeProcessor(*this));
385 std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
386 class Impl : public ProgramImpl {
388 void emitCode(EmitArgs& args) override {
389 SkString result = this->invokeChild(1, args); // g(x)
390 result = this->invokeChild(0, result.c_str(), args); // f(g(x))
391 args.fFragBuilder->codeAppendf("return %s;", result.c_str());
394 return std::make_unique<Impl>();
397 ComposeProcessor(std::unique_ptr<GrFragmentProcessor> f,
398 std::unique_ptr<GrFragmentProcessor> g)
399 : INHERITED(kSeriesFragmentProcessor_ClassID,
400 f->optimizationFlags() & g->optimizationFlags()) {
401 this->registerChild(std::move(f));
402 this->registerChild(std::move(g));
405 ComposeProcessor(const ComposeProcessor& that) : INHERITED(that) {}
407 void onAddToKey(const GrShaderCaps&, skgpu::KeyBuilder*) const override {}
409 bool onIsEqual(const GrFragmentProcessor&) const override { return true; }
411 SkPMColor4f constantOutputForConstantInput(const SkPMColor4f& inColor) const override {
412 SkPMColor4f color = inColor;
413 color = ConstantOutputForConstantInput(this->childProcessor(1), color);
414 color = ConstantOutputForConstantInput(this->childProcessor(0), color);
418 using INHERITED = GrFragmentProcessor;
421 // Allow either of the composed functions to be null.
429 // Run an optimization pass on this composition.
430 GrProcessorAnalysisColor inputColor;
431 inputColor.setToUnknown();
433 std::unique_ptr<GrFragmentProcessor> series[2] = {std::move(g), std::move(f)};
434 GrColorFragmentProcessorAnalysis info(inputColor, series, SK_ARRAY_COUNT(series));
436 SkPMColor4f knownColor;
437 int leadingFPsToEliminate = info.initialProcessorsToEliminate(&knownColor);
438 switch (leadingFPsToEliminate) {
440 // We shouldn't eliminate more than we started with.
441 SkASSERT(leadingFPsToEliminate <= 2);
444 // Compose the two processors as requested.
445 return ComposeProcessor::Make(/*f=*/std::move(series[1]), /*g=*/std::move(series[0]));
447 // Replace the first processor with a constant color.
448 return ComposeProcessor::Make(/*f=*/std::move(series[1]),
449 /*g=*/MakeColor(knownColor));
451 // Replace the entire composition with a constant color.
452 return MakeColor(knownColor);
456 //////////////////////////////////////////////////////////////////////////////
458 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::ColorMatrix(
459 std::unique_ptr<GrFragmentProcessor> child,
460 const float matrix[20],
464 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForColorFilter, R"(
467 uniform int unpremulInput; // always specialized
468 uniform int clampRGBOutput; // always specialized
469 uniform int premulOutput; // always specialized
470 half4 main(half4 color) {
471 if (bool(unpremulInput)) {
472 color = unpremul(color);
474 color = m * color + v;
475 if (bool(clampRGBOutput)) {
476 color = saturate(color);
478 color.a = saturate(color.a);
480 if (bool(premulOutput)) {
481 color.rgb *= color.a;
486 SkASSERT(SkRuntimeEffectPriv::SupportsConstantOutputForConstantInput(effect));
488 SkM44 m44(matrix[ 0], matrix[ 1], matrix[ 2], matrix[ 3],
489 matrix[ 5], matrix[ 6], matrix[ 7], matrix[ 8],
490 matrix[10], matrix[11], matrix[12], matrix[13],
491 matrix[15], matrix[16], matrix[17], matrix[18]);
492 SkV4 v4 = {matrix[4], matrix[9], matrix[14], matrix[19]};
493 return GrSkSLFP::Make(effect, "ColorMatrix", std::move(child), GrSkSLFP::OptFlags::kNone,
496 "unpremulInput", GrSkSLFP::Specialize(unpremulInput ? 1 : 0),
497 "clampRGBOutput", GrSkSLFP::Specialize(clampRGBOutput ? 1 : 0),
498 "premulOutput", GrSkSLFP::Specialize(premulOutput ? 1 : 0));
501 //////////////////////////////////////////////////////////////////////////////
503 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::SurfaceColor() {
504 class SurfaceColorProcessor : public GrFragmentProcessor {
506 static std::unique_ptr<GrFragmentProcessor> Make() {
507 return std::unique_ptr<GrFragmentProcessor>(new SurfaceColorProcessor());
510 std::unique_ptr<GrFragmentProcessor> clone() const override { return Make(); }
512 const char* name() const override { return "SurfaceColor"; }
515 std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
516 class Impl : public ProgramImpl {
518 void emitCode(EmitArgs& args) override {
519 const char* dstColor = args.fFragBuilder->dstColor();
520 args.fFragBuilder->codeAppendf("return %s;", dstColor);
523 return std::make_unique<Impl>();
526 SurfaceColorProcessor()
527 : INHERITED(kSurfaceColorProcessor_ClassID, kNone_OptimizationFlags) {
528 this->setWillReadDstColor();
531 void onAddToKey(const GrShaderCaps&, skgpu::KeyBuilder*) const override {}
533 bool onIsEqual(const GrFragmentProcessor&) const override { return true; }
535 using INHERITED = GrFragmentProcessor;
538 return SurfaceColorProcessor::Make();
541 //////////////////////////////////////////////////////////////////////////////
543 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::DeviceSpace(
544 std::unique_ptr<GrFragmentProcessor> fp) {
549 class DeviceSpace : GrFragmentProcessor {
551 static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> fp) {
552 return std::unique_ptr<GrFragmentProcessor>(new DeviceSpace(std::move(fp)));
556 DeviceSpace(std::unique_ptr<GrFragmentProcessor> fp)
557 : GrFragmentProcessor(kDeviceSpace_ClassID, fp->optimizationFlags()) {
558 // Passing FragCoord here is the reason this is a subclass and not a runtime-FP.
559 this->registerChild(std::move(fp), SkSL::SampleUsage::FragCoord());
562 std::unique_ptr<GrFragmentProcessor> clone() const override {
563 auto child = this->childProcessor(0)->clone();
564 return std::unique_ptr<GrFragmentProcessor>(new DeviceSpace(std::move(child)));
567 SkPMColor4f constantOutputForConstantInput(const SkPMColor4f& f) const override {
568 return this->childProcessor(0)->constantOutputForConstantInput(f);
571 std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
572 class Impl : public ProgramImpl {
575 void emitCode(ProgramImpl::EmitArgs& args) override {
576 auto child = this->invokeChild(0, args.fInputColor, args, "sk_FragCoord.xy");
577 args.fFragBuilder->codeAppendf("return %s;", child.c_str());
580 return std::make_unique<Impl>();
583 void onAddToKey(const GrShaderCaps&, skgpu::KeyBuilder*) const override {}
585 bool onIsEqual(const GrFragmentProcessor& processor) const override { return true; }
587 const char* name() const override { return "DeviceSpace"; }
590 return DeviceSpace::Make(std::move(fp));
593 //////////////////////////////////////////////////////////////////////////////
595 #define CLIP_EDGE_SKSL \
596 "const int kFillBW = 0;" \
597 "const int kFillAA = 1;" \
598 "const int kInverseFillBW = 2;" \
599 "const int kInverseFillAA = 3;"
601 static_assert(static_cast<int>(GrClipEdgeType::kFillBW) == 0);
602 static_assert(static_cast<int>(GrClipEdgeType::kFillAA) == 1);
603 static_assert(static_cast<int>(GrClipEdgeType::kInverseFillBW) == 2);
604 static_assert(static_cast<int>(GrClipEdgeType::kInverseFillAA) == 3);
606 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::Rect(
607 std::unique_ptr<GrFragmentProcessor> inputFP, GrClipEdgeType edgeType, SkRect rect) {
608 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader, CLIP_EDGE_SKSL R"(
609 uniform int edgeType; // GrClipEdgeType, specialized
610 uniform float4 rectUniform;
612 half4 main(float2 xy, half4 inColor) {
614 if (edgeType == kFillBW || edgeType == kInverseFillBW) {
616 coverage = all(greaterThan(float4(sk_FragCoord.xy, rectUniform.zw),
617 float4(rectUniform.xy, sk_FragCoord.xy))) ? 1 : 0;
619 // compute coverage relative to left and right edges, add, then subtract 1 to
620 // account for double counting. And similar for top/bottom.
621 half4 dists4 = clamp(half4(1, 1, -1, -1) *
622 half4(sk_FragCoord.xyxy - rectUniform), 0, 1);
623 half2 dists2 = dists4.xy + dists4.zw - 1;
624 coverage = dists2.x * dists2.y;
627 if (edgeType == kInverseFillBW || edgeType == kInverseFillAA) {
628 coverage = 1.0 - coverage;
631 return inColor * coverage;
635 SkASSERT(rect.isSorted());
636 // The AA math in the shader evaluates to 0 at the uploaded coordinates, so outset by 0.5
637 // to interpolate from 0 at a half pixel inset and 1 at a half pixel outset of rect.
638 SkRect rectUniform = GrClipEdgeTypeIsAA(edgeType) ? rect.makeOutset(.5f, .5f) : rect;
640 return GrSkSLFP::Make(effect, "Rect", std::move(inputFP),
641 GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
642 "edgeType", GrSkSLFP::Specialize(static_cast<int>(edgeType)),
643 "rectUniform", rectUniform);
646 GrFPResult GrFragmentProcessor::Circle(std::unique_ptr<GrFragmentProcessor> inputFP,
647 GrClipEdgeType edgeType,
650 // A radius below half causes the implicit insetting done by this processor to become
651 // inverted. We could handle this case by making the processor code more complicated.
652 if (radius < .5f && GrClipEdgeTypeIsInverseFill(edgeType)) {
653 return GrFPFailure(std::move(inputFP));
656 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader, CLIP_EDGE_SKSL R"(
657 uniform int edgeType; // GrClipEdgeType, specialized
658 // The circle uniform is (center.x, center.y, radius + 0.5, 1 / (radius + 0.5)) for regular
659 // fills and (..., radius - 0.5, 1 / (radius - 0.5)) for inverse fills.
660 uniform float4 circle;
662 half4 main(float2 xy, half4 inColor) {
663 // TODO: Right now the distance to circle calculation is performed in a space normalized
664 // to the radius and then denormalized. This is to mitigate overflow on devices that
665 // don't have full float.
667 if (edgeType == kInverseFillBW || edgeType == kInverseFillAA) {
668 d = half((length((circle.xy - sk_FragCoord.xy) * circle.w) - 1.0) * circle.z);
670 d = half((1.0 - length((circle.xy - sk_FragCoord.xy) * circle.w)) * circle.z);
672 if (edgeType == kFillAA || edgeType == kInverseFillAA) {
673 return inColor * saturate(d);
675 return d > 0.5 ? inColor : half4(0);
680 SkScalar effectiveRadius = radius;
681 if (GrClipEdgeTypeIsInverseFill(edgeType)) {
682 effectiveRadius -= 0.5f;
683 // When the radius is 0.5 effectiveRadius is 0 which causes an inf * 0 in the shader.
684 effectiveRadius = std::max(0.001f, effectiveRadius);
686 effectiveRadius += 0.5f;
688 SkV4 circle = {center.fX, center.fY, effectiveRadius, SkScalarInvert(effectiveRadius)};
690 return GrFPSuccess(GrSkSLFP::Make(effect, "Circle", std::move(inputFP),
691 GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
692 "edgeType", GrSkSLFP::Specialize(static_cast<int>(edgeType)),
696 GrFPResult GrFragmentProcessor::Ellipse(std::unique_ptr<GrFragmentProcessor> inputFP,
697 GrClipEdgeType edgeType,
700 const GrShaderCaps& caps) {
701 const bool medPrecision = !caps.floatIs32Bits();
703 // Small radii produce bad results on devices without full float.
704 if (medPrecision && (radii.fX < 0.5f || radii.fY < 0.5f)) {
705 return GrFPFailure(std::move(inputFP));
707 // Very narrow ellipses produce bad results on devices without full float
708 if (medPrecision && (radii.fX > 255*radii.fY || radii.fY > 255*radii.fX)) {
709 return GrFPFailure(std::move(inputFP));
711 // Very large ellipses produce bad results on devices without full float
712 if (medPrecision && (radii.fX > 16384 || radii.fY > 16384)) {
713 return GrFPFailure(std::move(inputFP));
716 static auto effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader, CLIP_EDGE_SKSL R"(
717 uniform int edgeType; // GrClipEdgeType, specialized
718 uniform int medPrecision; // !sk_Caps.floatIs32Bits, specialized
720 uniform float4 ellipse;
721 uniform float2 scale; // only for medPrecision
723 half4 main(float2 xy, half4 inColor) {
724 // d is the offset to the ellipse center
725 float2 d = sk_FragCoord.xy - ellipse.xy;
726 // If we're on a device with a "real" mediump then we'll do the distance computation in
727 // a space that is normalized by the larger radius or 128, whichever is smaller. The
728 // scale uniform will be scale, 1/scale. The inverse squared radii uniform values are
729 // already in this normalized space. The center is not.
730 if (bool(medPrecision)) {
733 float2 Z = d * ellipse.zw;
734 // implicit is the evaluation of (x/rx)^2 + (y/ry)^2 - 1.
735 float implicit = dot(Z, d) - 1;
736 // grad_dot is the squared length of the gradient of the implicit.
737 float grad_dot = 4 * dot(Z, Z);
738 // Avoid calling inversesqrt on zero.
739 if (bool(medPrecision)) {
740 grad_dot = max(grad_dot, 6.1036e-5);
742 grad_dot = max(grad_dot, 1.1755e-38);
744 float approx_dist = implicit * inversesqrt(grad_dot);
745 if (bool(medPrecision)) {
746 approx_dist *= scale.x;
750 if (edgeType == kFillBW) {
751 alpha = approx_dist > 0.0 ? 0.0 : 1.0;
752 } else if (edgeType == kFillAA) {
753 alpha = saturate(0.5 - half(approx_dist));
754 } else if (edgeType == kInverseFillBW) {
755 alpha = approx_dist > 0.0 ? 1.0 : 0.0;
756 } else { // edgeType == kInverseFillAA
757 alpha = saturate(0.5 + half(approx_dist));
759 return inColor * alpha;
766 // If we're using a scale factor to work around precision issues, choose the larger radius as
767 // the scale factor. The inv radii need to be pre-adjusted by the scale factor.
769 if (radii.fX > radii.fY) {
771 invRYSqd = (radii.fX * radii.fX) / (radii.fY * radii.fY);
772 scale = {radii.fX, 1.f / radii.fX};
774 invRXSqd = (radii.fY * radii.fY) / (radii.fX * radii.fX);
776 scale = {radii.fY, 1.f / radii.fY};
779 invRXSqd = 1.f / (radii.fX * radii.fX);
780 invRYSqd = 1.f / (radii.fY * radii.fY);
782 SkV4 ellipse = {center.fX, center.fY, invRXSqd, invRYSqd};
784 return GrFPSuccess(GrSkSLFP::Make(effect, "Ellipse", std::move(inputFP),
785 GrSkSLFP::OptFlags::kCompatibleWithCoverageAsAlpha,
786 "edgeType", GrSkSLFP::Specialize(static_cast<int>(edgeType)),
787 "medPrecision", GrSkSLFP::Specialize<int>(medPrecision),
792 //////////////////////////////////////////////////////////////////////////////
794 std::unique_ptr<GrFragmentProcessor> GrFragmentProcessor::HighPrecision(
795 std::unique_ptr<GrFragmentProcessor> fp) {
796 class HighPrecisionFragmentProcessor : public GrFragmentProcessor {
798 static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> fp) {
799 return std::unique_ptr<GrFragmentProcessor>(
800 new HighPrecisionFragmentProcessor(std::move(fp)));
803 const char* name() const override { return "HighPrecision"; }
805 std::unique_ptr<GrFragmentProcessor> clone() const override {
806 return Make(this->childProcessor(0)->clone());
810 HighPrecisionFragmentProcessor(std::unique_ptr<GrFragmentProcessor> fp)
811 : INHERITED(kHighPrecisionFragmentProcessor_ClassID,
812 ProcessorOptimizationFlags(fp.get())) {
813 this->registerChild(std::move(fp));
816 std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
817 class Impl : public ProgramImpl {
819 void emitCode(EmitArgs& args) override {
820 SkString childColor = this->invokeChild(0, args);
822 args.fFragBuilder->forceHighPrecision();
823 args.fFragBuilder->codeAppendf("return %s;", childColor.c_str());
826 return std::make_unique<Impl>();
829 void onAddToKey(const GrShaderCaps&, skgpu::KeyBuilder*) const override {}
830 bool onIsEqual(const GrFragmentProcessor& other) const override { return true; }
832 SkPMColor4f constantOutputForConstantInput(const SkPMColor4f& input) const override {
833 return ConstantOutputForConstantInput(this->childProcessor(0), input);
836 using INHERITED = GrFragmentProcessor;
839 return HighPrecisionFragmentProcessor::Make(std::move(fp));
842 //////////////////////////////////////////////////////////////////////////////
844 using ProgramImpl = GrFragmentProcessor::ProgramImpl;
846 void ProgramImpl::setData(const GrGLSLProgramDataManager& pdman,
847 const GrFragmentProcessor& processor) {
848 this->onSetData(pdman, processor);
851 SkString ProgramImpl::invokeChild(int childIndex,
852 const char* inputColor,
853 const char* destColor,
855 std::string_view skslCoords) {
856 SkASSERT(childIndex >= 0);
859 inputColor = args.fInputColor;
862 const GrFragmentProcessor* childProc = args.fFp.childProcessor(childIndex);
864 // If no child processor is provided, return the input color as-is.
865 return SkString(inputColor);
868 auto invocation = SkStringPrintf("%s(%s", this->childProcessor(childIndex)->functionName(),
871 if (childProc->isBlendFunction()) {
873 destColor = args.fFp.isBlendFunction() ? args.fDestColor : "half4(1)";
875 invocation.appendf(", %s", destColor);
878 // Assert that the child has no sample matrix. A uniform matrix sample call would go through
879 // invokeChildWithMatrix, not here.
880 SkASSERT(!childProc->sampleUsage().isUniformMatrix());
882 if (args.fFragBuilder->getProgramBuilder()->fragmentProcessorHasCoordsParam(childProc)) {
883 SkASSERT(!childProc->sampleUsage().isFragCoord() || skslCoords == "sk_FragCoord.xy");
884 // The child's function takes a half4 color and a float2 coordinate
885 if (!skslCoords.empty()) {
886 invocation.appendf(", %.*s", (int)skslCoords.size(), skslCoords.data());
888 invocation.appendf(", %s", args.fSampleCoord);
892 invocation.append(")");
896 SkString ProgramImpl::invokeChildWithMatrix(int childIndex,
897 const char* inputColor,
898 const char* destColor,
900 SkASSERT(childIndex >= 0);
903 inputColor = args.fInputColor;
906 const GrFragmentProcessor* childProc = args.fFp.childProcessor(childIndex);
908 // If no child processor is provided, return the input color as-is.
909 return SkString(inputColor);
912 SkASSERT(childProc->sampleUsage().isUniformMatrix());
914 // Every uniform matrix has the same (initial) name. Resolve that into the mangled name:
915 GrShaderVar uniform = args.fUniformHandler->getUniformMapping(
916 args.fFp, SkString(SkSL::SampleUsage::MatrixUniformName()));
917 SkASSERT(uniform.getType() == SkSLType::kFloat3x3);
918 const SkString& matrixName(uniform.getName());
920 auto invocation = SkStringPrintf("%s(%s", this->childProcessor(childIndex)->functionName(),
923 if (childProc->isBlendFunction()) {
925 destColor = args.fFp.isBlendFunction() ? args.fDestColor : "half4(1)";
927 invocation.appendf(", %s", destColor);
930 // Produce a string containing the call to the helper function. We have a uniform variable
931 // containing our transform (matrixName). If the parent coords were produced by uniform
932 // transforms, then the entire expression (matrixName * coords) is lifted to a vertex shader
933 // and is stored in a varying. In that case, childProc will not be sampled explicitly, so its
934 // function signature will not take in coords.
936 // In all other cases, we need to insert sksl to compute matrix * parent coords and then invoke
938 if (args.fFragBuilder->getProgramBuilder()->fragmentProcessorHasCoordsParam(childProc)) {
939 // Only check perspective for this specific matrix transform, not the aggregate FP property.
940 // Any parent perspective will have already been applied when evaluated in the FS.
941 if (childProc->sampleUsage().hasPerspective()) {
942 invocation.appendf(", proj((%s) * %s.xy1)", matrixName.c_str(), args.fSampleCoord);
943 } else if (args.fShaderCaps->nonsquareMatrixSupport()) {
944 invocation.appendf(", float3x2(%s) * %s.xy1", matrixName.c_str(), args.fSampleCoord);
946 invocation.appendf(", ((%s) * %s.xy1).xy", matrixName.c_str(), args.fSampleCoord);
950 invocation.append(")");