xref: /aosp_15_r20/external/skia/tests/SkRuntimeEffectTest.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2019 Google LLC
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "include/core/SkAlphaType.h"
9 #include "include/core/SkBlendMode.h"
10 #include "include/core/SkBlender.h"
11 #include "include/core/SkCanvas.h"
12 #include "include/core/SkCapabilities.h"
13 #include "include/core/SkColor.h"
14 #include "include/core/SkColorFilter.h"
15 #include "include/core/SkColorType.h"
16 #include "include/core/SkData.h"
17 #include "include/core/SkImageInfo.h"
18 #include "include/core/SkPaint.h"
19 #include "include/core/SkPixmap.h"
20 #include "include/core/SkRefCnt.h"
21 #include "include/core/SkScalar.h"
22 #include "include/core/SkShader.h"
23 #include "include/core/SkSize.h"
24 #include "include/core/SkSpan.h"
25 #include "include/core/SkStream.h"
26 #include "include/core/SkString.h"
27 #include "include/core/SkSurface.h"
28 #include "include/core/SkTypes.h"
29 #include "include/effects/SkBlenders.h"
30 #include "include/effects/SkGradientShader.h"
31 #include "include/effects/SkRuntimeEffect.h"
32 #include "include/gpu/GpuTypes.h"
33 #include "include/gpu/ganesh/GrDirectContext.h"
34 #include "include/gpu/ganesh/SkSurfaceGanesh.h"
35 #include "include/private/SkColorData.h"
36 #include "include/private/SkSLSampleUsage.h"
37 #include "include/private/base/SkTArray.h"
38 #include "include/sksl/SkSLDebugTrace.h"
39 #include "include/sksl/SkSLVersion.h"
40 #include "src/base/SkStringView.h"
41 #include "src/base/SkTLazy.h"
42 #include "src/core/SkColorSpacePriv.h"
43 #include "src/core/SkRuntimeEffectPriv.h"
44 #include "src/gpu/KeyBuilder.h"
45 #include "src/gpu/SkBackingFit.h"
46 #include "src/gpu/ganesh/GrCaps.h"
47 #include "src/gpu/ganesh/GrColor.h"
48 #include "src/gpu/ganesh/GrDirectContextPriv.h"
49 #include "src/gpu/ganesh/GrFragmentProcessor.h"
50 #include "src/gpu/ganesh/GrImageInfo.h"
51 #include "src/gpu/ganesh/GrPixmap.h"
52 #include "src/gpu/ganesh/SurfaceFillContext.h"
53 #include "src/gpu/ganesh/effects/GrSkSLFP.h"
54 #include "src/sksl/SkSLString.h"
55 #include "tests/CtsEnforcement.h"
56 #include "tests/Test.h"
57 
58 #include <array>
59 #include <cstdint>
60 #include <functional>
61 #include <initializer_list>
62 #include <memory>
63 #include <string>
64 #include <thread>
65 #include <utility>
66 
67 using namespace skia_private;
68 
69 class GrRecordingContext;
70 struct GrContextOptions;
71 struct SkIPoint;
72 
73 #if defined(SK_GRAPHITE)
74 #include "include/gpu/graphite/Context.h"
75 #include "include/gpu/graphite/Recorder.h"
76 #include "include/gpu/graphite/Recording.h"
77 #include "include/gpu/graphite/Surface.h"
78 #include "src/gpu/graphite/Surface_Graphite.h"
79 
80 struct GraphiteInfo {
81     skgpu::graphite::Context* context = nullptr;
82     skgpu::graphite::Recorder* recorder = nullptr;
83 };
84 #else
85 struct GraphiteInfo {
86     void* context = nullptr;
87     void* recorder = nullptr;
88 };
89 #endif
90 
test_invalid_effect(skiatest::Reporter * r,const char * src,const char * expected)91 void test_invalid_effect(skiatest::Reporter* r, const char* src, const char* expected) {
92     auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(src));
93     REPORTER_ASSERT(r, !effect);
94     REPORTER_ASSERT(r, errorText.contains(expected),
95                     "Expected error message to contain \"%s\". Actual message: \"%s\"",
96                     expected, errorText.c_str());
97 }
98 
99 #define EMPTY_MAIN "half4 main(float2 p) { return half4(0); }"
100 
DEF_TEST(SkRuntimeEffectInvalid_NoInVariables,r)101 DEF_TEST(SkRuntimeEffectInvalid_NoInVariables, r) {
102     // 'in' variables aren't allowed at all:
103     test_invalid_effect(r, "in bool b;"    EMPTY_MAIN, "'in'");
104     test_invalid_effect(r, "in float f;"   EMPTY_MAIN, "'in'");
105     test_invalid_effect(r, "in float2 v;"  EMPTY_MAIN, "'in'");
106     test_invalid_effect(r, "in half3x3 m;" EMPTY_MAIN, "'in'");
107 }
108 
DEF_TEST(SkRuntimeEffectInvalid_UndefinedFunction,r)109 DEF_TEST(SkRuntimeEffectInvalid_UndefinedFunction, r) {
110     test_invalid_effect(r, "half4 missing(); half4 main(float2 p) { return missing(); }",
111                            "function 'half4 missing()' is not defined");
112 }
113 
DEF_TEST(SkRuntimeEffectInvalid_UndefinedMain,r)114 DEF_TEST(SkRuntimeEffectInvalid_UndefinedMain, r) {
115     // Shouldn't be possible to create an SkRuntimeEffect without "main"
116     test_invalid_effect(r, "", "main");
117 }
118 
DEF_TEST(SkRuntimeEffectInvalid_SkCapsDisallowed,r)119 DEF_TEST(SkRuntimeEffectInvalid_SkCapsDisallowed, r) {
120     // sk_Caps is an internal system. It should not be visible to runtime effects
121     test_invalid_effect(
122             r,
123             "half4 main(float2 p) { return sk_Caps.floatIs32Bits ? half4(1) : half4(0); }",
124             "name 'sk_Caps' is reserved");
125 }
126 
DEF_TEST(SkRuntimeEffect_DeadCodeEliminationStackOverflow,r)127 DEF_TEST(SkRuntimeEffect_DeadCodeEliminationStackOverflow, r) {
128     // Verify that a deeply-nested loop does not cause stack overflow during dead-code elimination.
129     auto [effect, errorText] = SkRuntimeEffect::MakeForColorFilter(SkString(R"(
130         half4 main(half4 color) {
131             half value = color.r;
132 
133             for (int a=0; a<10; ++a) { // 10
134             for (int b=0; b<10; ++b) { // 100
135             for (int c=0; c<10; ++c) { // 1000
136             for (int d=0; d<10; ++d) { // 10000
137                 ++value;
138             }}}}
139 
140             return value.xxxx;
141         }
142     )"));
143     REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
144 }
145 
DEF_TEST(SkRuntimeEffectCanDisableES2Restrictions,r)146 DEF_TEST(SkRuntimeEffectCanDisableES2Restrictions, r) {
147     auto test_valid_es3 = [](skiatest::Reporter* r, const char* sksl) {
148         SkRuntimeEffect::Options opt = SkRuntimeEffectPriv::ES3Options();
149         auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(sksl), opt);
150         REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
151     };
152 
153     test_invalid_effect(r, "float f[2] = float[2](0, 1);" EMPTY_MAIN, "construction of array type");
154     test_valid_es3     (r, "float f[2] = float[2](0, 1);" EMPTY_MAIN);
155 }
156 
DEF_TEST(SkRuntimeEffectCanEnableVersion300,r)157 DEF_TEST(SkRuntimeEffectCanEnableVersion300, r) {
158     auto test_valid = [](skiatest::Reporter* r, const char* sksl) {
159         auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(sksl));
160         REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
161     };
162 
163     test_invalid_effect(r, "#version 100\nfloat f[2] = float[2](0, 1);" EMPTY_MAIN,
164                            "construction of array type");
165     test_valid         (r, "#version 300\nfloat f[2] = float[2](0, 1);" EMPTY_MAIN);
166 }
167 
DEF_TEST(SkRuntimeEffectUniformFlags,r)168 DEF_TEST(SkRuntimeEffectUniformFlags, r) {
169     auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(R"(
170         uniform int simple;                      // should have no flags
171         uniform float arrayOfOne[1];             // should have kArray_Flag
172         uniform float arrayOfMultiple[2];        // should have kArray_Flag
173         layout(color) uniform float4 color;      // should have kColor_Flag
174         uniform half3 halfPrecisionFloat;        // should have kHalfPrecision_Flag
175         layout(color) uniform half4 allFlags[2]; // should have Array | Color | HalfPrecision
176     )"  EMPTY_MAIN));
177     REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
178 
179     SkSpan<const SkRuntimeEffect::Uniform> uniforms = effect->uniforms();
180     REPORTER_ASSERT(r, uniforms.size() == 6);
181 
182     REPORTER_ASSERT(r, uniforms[0].flags == 0);
183     REPORTER_ASSERT(r, uniforms[1].flags == SkRuntimeEffect::Uniform::kArray_Flag);
184     REPORTER_ASSERT(r, uniforms[2].flags == SkRuntimeEffect::Uniform::kArray_Flag);
185     REPORTER_ASSERT(r, uniforms[3].flags == SkRuntimeEffect::Uniform::kColor_Flag);
186     REPORTER_ASSERT(r, uniforms[4].flags == SkRuntimeEffect::Uniform::kHalfPrecision_Flag);
187     REPORTER_ASSERT(r, uniforms[5].flags == (SkRuntimeEffect::Uniform::kArray_Flag |
188                                              SkRuntimeEffect::Uniform::kColor_Flag |
189                                              SkRuntimeEffect::Uniform::kHalfPrecision_Flag));
190 }
191 
DEF_TEST(SkRuntimeEffectValidation,r)192 DEF_TEST(SkRuntimeEffectValidation, r) {
193     auto es2Effect = SkRuntimeEffect::MakeForShader(SkString("#version 100\n" EMPTY_MAIN)).effect;
194     auto es3Effect = SkRuntimeEffect::MakeForShader(SkString("#version 300\n" EMPTY_MAIN)).effect;
195     REPORTER_ASSERT(r, es2Effect && es3Effect);
196 
197     auto es2Caps = SkCapabilities::RasterBackend();
198     REPORTER_ASSERT(r, es2Caps->skslVersion() == SkSL::Version::k100);
199 
200     REPORTER_ASSERT(r, SkRuntimeEffectPriv::CanDraw(es2Caps.get(), es2Effect.get()));
201     REPORTER_ASSERT(r, !SkRuntimeEffectPriv::CanDraw(es2Caps.get(), es3Effect.get()));
202 }
203 
DEF_TEST(SkRuntimeEffectForColorFilter,r)204 DEF_TEST(SkRuntimeEffectForColorFilter, r) {
205     // Tests that the color filter factory rejects or accepts certain SkSL constructs
206     auto test_valid = [r](const char* sksl) {
207         auto [effect, errorText] = SkRuntimeEffect::MakeForColorFilter(SkString(sksl));
208         REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
209     };
210 
211     auto test_invalid = [r](const char* sksl, const char* expected) {
212         auto [effect, errorText] = SkRuntimeEffect::MakeForColorFilter(SkString(sksl));
213         REPORTER_ASSERT(r, !effect);
214         REPORTER_ASSERT(r,
215                         errorText.contains(expected),
216                         "Expected error message to contain \"%s\". Actual message: \"%s\"",
217                         expected,
218                         errorText.c_str());
219     };
220 
221     // Color filters must use the 'half4 main(half4)' signature. Either color can be float4/vec4
222     test_valid("half4  main(half4  c) { return c; }");
223     test_valid("float4 main(half4  c) { return c; }");
224     test_valid("half4  main(float4 c) { return c; }");
225     test_valid("float4 main(float4 c) { return c; }");
226     test_valid("vec4   main(half4  c) { return c; }");
227     test_valid("half4  main(vec4   c) { return c; }");
228     test_valid("vec4   main(vec4   c) { return c; }");
229 
230     // Invalid return types
231     test_invalid("void  main(half4 c) {}",                "'main' must return");
232     test_invalid("half3 main(half4 c) { return c.rgb; }", "'main' must return");
233 
234     // Invalid argument types (some are valid as shaders, but not color filters)
235     test_invalid("half4 main() { return half4(1); }",           "'main' parameter");
236     test_invalid("half4 main(float2 p) { return half4(1); }",   "'main' parameter");
237     test_invalid("half4 main(float2 p, half4 c) { return c; }", "'main' parameter");
238 
239     // sk_FragCoord should not be available
240     test_invalid("half4 main(half4 c) { return sk_FragCoord.xy01; }", "unknown identifier");
241 
242     // Sampling a child shader requires that we pass explicit coords
243     test_valid("uniform shader child;"
244                "half4 main(half4 c) { return child.eval(c.rg); }");
245 
246     // Sampling a colorFilter requires a color
247     test_valid("uniform colorFilter child;"
248                "half4 main(half4 c) { return child.eval(c); }");
249 
250     // Sampling a blender requires two colors
251     test_valid("uniform blender child;"
252                "half4 main(half4 c) { return child.eval(c, c); }");
253 }
254 
DEF_TEST(SkRuntimeEffectForBlender,r)255 DEF_TEST(SkRuntimeEffectForBlender, r) {
256     // Tests that the blender factory rejects or accepts certain SkSL constructs
257     auto test_valid = [r](const char* sksl) {
258         auto [effect, errorText] = SkRuntimeEffect::MakeForBlender(SkString(sksl));
259         REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
260     };
261 
262     auto test_invalid = [r](const char* sksl, const char* expected) {
263         auto [effect, errorText] = SkRuntimeEffect::MakeForBlender(SkString(sksl));
264         REPORTER_ASSERT(r, !effect);
265         REPORTER_ASSERT(r,
266                         errorText.contains(expected),
267                         "Expected error message to contain \"%s\". Actual message: \"%s\"",
268                         expected,
269                         errorText.c_str());
270     };
271 
272     // Blenders must use the 'half4 main(half4, half4)' signature. Any mixture of float4/vec4/half4
273     // is allowed.
274     test_valid("half4  main(half4  s, half4  d) { return s; }");
275     test_valid("float4 main(float4 s, float4 d) { return d; }");
276     test_valid("float4 main(half4  s, float4 d) { return s; }");
277     test_valid("half4  main(float4 s, half4  d) { return d; }");
278     test_valid("vec4   main(half4  s, half4  d) { return s; }");
279     test_valid("half4  main(vec4   s, vec4   d) { return d; }");
280     test_valid("vec4   main(vec4   s, vec4   d) { return s; }");
281 
282     // Invalid return types
283     test_invalid("void  main(half4 s, half4 d) {}",                "'main' must return");
284     test_invalid("half3 main(half4 s, half4 d) { return s.rgb; }", "'main' must return");
285 
286     // Invalid argument types (some are valid as shaders/color filters)
287     test_invalid("half4 main() { return half4(1); }",                    "'main' parameter");
288     test_invalid("half4 main(half4 c) { return c; }",                    "'main' parameter");
289     test_invalid("half4 main(float2 p) { return half4(1); }",            "'main' parameter");
290     test_invalid("half4 main(float2 p, half4 c) { return c; }",          "'main' parameter");
291     test_invalid("half4 main(float2 p, half4 a, half4 b) { return a; }", "'main' parameter");
292     test_invalid("half4 main(half4 a, half4 b, half4 c) { return a; }",  "'main' parameter");
293 
294     // sk_FragCoord should not be available
295     test_invalid("half4 main(half4 s, half4 d) { return sk_FragCoord.xy01; }",
296                  "unknown identifier");
297 
298     // Sampling a child shader requires that we pass explicit coords
299     test_valid("uniform shader child;"
300                "half4 main(half4 s, half4 d) { return child.eval(s.rg); }");
301 
302     // Sampling a colorFilter requires a color
303     test_valid("uniform colorFilter child;"
304                "half4 main(half4 s, half4 d) { return child.eval(d); }");
305 
306     // Sampling a blender requires two colors
307     test_valid("uniform blender child;"
308                "half4 main(half4 s, half4 d) { return child.eval(s, d); }");
309 }
310 
DEF_TEST(SkRuntimeEffectForShader,r)311 DEF_TEST(SkRuntimeEffectForShader, r) {
312     // Tests that the shader factory rejects or accepts certain SkSL constructs
313     auto test_valid = [r](const char* sksl, SkRuntimeEffect::Options options = {}) {
314         auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(sksl), options);
315         REPORTER_ASSERT(r, effect, "%s", errorText.c_str());
316     };
317 
318     auto test_invalid = [r](const char* sksl,
319                             const char* expected,
320                             SkRuntimeEffect::Options options = {}) {
321         auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(sksl));
322         REPORTER_ASSERT(r, !effect);
323         REPORTER_ASSERT(r,
324                         errorText.contains(expected),
325                         "Expected error message to contain \"%s\". Actual message: \"%s\"",
326                         expected,
327                         errorText.c_str());
328     };
329 
330     // Shaders must use the 'half4 main(float2)' signature
331     // Either color can be half4/float4/vec4, but the coords must be float2/vec2
332     test_valid("half4  main(float2 p) { return p.xyxy; }");
333     test_valid("float4 main(float2 p) { return p.xyxy; }");
334     test_valid("vec4   main(float2 p) { return p.xyxy; }");
335     test_valid("half4  main(vec2   p) { return p.xyxy; }");
336     test_valid("vec4   main(vec2   p) { return p.xyxy; }");
337 
338     // The 'half4 main(float2, half4|float4)' signature is disallowed on both public and private
339     // runtime effects.
340     SkRuntimeEffect::Options options;
341     SkRuntimeEffectPriv::AllowPrivateAccess(&options);
342     test_invalid("half4  main(float2 p, half4  c) { return c; }", "'main' parameter");
343     test_invalid("half4  main(float2 p, half4  c) { return c; }", "'main' parameter", options);
344 
345     test_invalid("half4  main(float2 p, float4 c) { return c; }", "'main' parameter");
346     test_invalid("half4  main(float2 p, float4 c) { return c; }", "'main' parameter", options);
347 
348     test_invalid("half4  main(float2 p, vec4   c) { return c; }", "'main' parameter");
349     test_invalid("half4  main(float2 p, vec4   c) { return c; }", "'main' parameter", options);
350 
351     test_invalid("float4 main(float2 p, half4  c) { return c; }", "'main' parameter");
352     test_invalid("float4 main(float2 p, half4  c) { return c; }", "'main' parameter", options);
353 
354     test_invalid("vec4   main(float2 p, half4  c) { return c; }", "'main' parameter");
355     test_invalid("vec4   main(float2 p, half4  c) { return c; }", "'main' parameter", options);
356 
357     test_invalid("vec4   main(vec2   p, vec4   c) { return c; }", "'main' parameter");
358     test_invalid("vec4   main(vec2   p, vec4   c) { return c; }", "'main' parameter", options);
359 
360     // Invalid return types
361     test_invalid("void  main(float2 p) {}",                "'main' must return");
362     test_invalid("half3 main(float2 p) { return p.xy1; }", "'main' must return");
363 
364     // Invalid argument types (some are valid as color filters, but not shaders)
365     test_invalid("half4 main() { return half4(1); }", "'main' parameter");
366     test_invalid("half4 main(half4 c) { return c; }", "'main' parameter");
367 
368     // sk_FragCoord should be available, but only if we've enabled it via Options
369     test_invalid("half4 main(float2 p) { return sk_FragCoord.xy01; }",
370                  "unknown identifier 'sk_FragCoord'");
371 
372     test_valid("half4 main(float2 p) { return sk_FragCoord.xy01; }", options);
373 
374     // Sampling a child shader requires that we pass explicit coords
375     test_valid("uniform shader child;"
376                "half4 main(float2 p) { return child.eval(p); }");
377 
378     // Sampling a colorFilter requires a color
379     test_valid("uniform colorFilter child;"
380                "half4 main(float2 p) { return child.eval(half4(1)); }");
381 
382     // Sampling a blender requires two colors
383     test_valid("uniform blender child;"
384                "half4 main(float2 p) { return child.eval(half4(0.5), half4(0.6)); }");
385 }
386 
387 using PreTestFn = std::function<void(SkCanvas*, SkPaint*)>;
388 
paint_canvas(SkCanvas * canvas,SkPaint * paint,const PreTestFn & preTestCallback)389 void paint_canvas(SkCanvas* canvas, SkPaint* paint, const PreTestFn& preTestCallback) {
390     canvas->save();
391     if (preTestCallback) {
392         preTestCallback(canvas, paint);
393     }
394     canvas->drawPaint(*paint);
395     canvas->restore();
396 }
397 
read_pixels(SkSurface * surface,GrColor * pixels)398 static bool read_pixels(SkSurface* surface,
399                         GrColor* pixels) {
400     SkImageInfo info = surface->imageInfo();
401     SkPixmap dest{info, pixels, info.minRowBytes()};
402     return surface->readPixels(dest, /*srcX=*/0, /*srcY=*/0);
403 }
404 
verify_2x2_surface_results(skiatest::Reporter * r,const SkRuntimeEffect * effect,SkSurface * surface,std::array<GrColor,4> expected)405 static void verify_2x2_surface_results(skiatest::Reporter* r,
406                                        const SkRuntimeEffect* effect,
407                                        SkSurface* surface,
408                                        std::array<GrColor, 4> expected) {
409     std::array<GrColor, 4> actual;
410     SkImageInfo info = surface->imageInfo();
411     if (!read_pixels(surface, actual.data())) {
412         REPORT_FAILURE(r, "readPixels", SkString("readPixels failed"));
413         return;
414     }
415 
416     if (actual != expected) {
417         REPORT_FAILURE(r, "Runtime effect didn't match expectations",
418                        SkStringPrintf("\n"
419                                       "Expected: [ %08x %08x %08x %08x ]\n"
420                                       "Got     : [ %08x %08x %08x %08x ]\n"
421                                       "SkSL:\n%s\n",
422                                       expected[0], expected[1], expected[2], expected[3],
423                                       actual[0],   actual[1],   actual[2],   actual[3],
424                                       effect->source().c_str()));
425     }
426 }
427 
make_surface(GrRecordingContext * grContext,const GraphiteInfo * graphite,SkISize size)428 static sk_sp<SkSurface> make_surface(GrRecordingContext* grContext,
429                                      const GraphiteInfo* graphite,
430                                      SkISize size) {
431     const SkImageInfo info = SkImageInfo::Make(size, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
432     sk_sp<SkSurface> surface;
433     if (graphite) {
434 #if defined(SK_GRAPHITE)
435         surface = SkSurfaces::RenderTarget(graphite->recorder, info);
436 #endif
437     } else if (grContext) {
438         surface = SkSurfaces::RenderTarget(grContext, skgpu::Budgeted::kNo, info);
439     } else {
440         surface = SkSurfaces::Raster(info);
441     }
442     SkASSERT(surface);
443     return surface;
444 }
445 
446 class TestEffect {
447 public:
TestEffect(skiatest::Reporter * r,GrRecordingContext * grContext,const GraphiteInfo * graphite,SkISize size={2, 2})448     TestEffect(skiatest::Reporter* r,
449                GrRecordingContext* grContext,
450                const GraphiteInfo* graphite,
451                SkISize size = {2, 2})
452             : fReporter(r), fGrContext(grContext), fGraphite(graphite), fSize(size) {
453         fSurface = make_surface(fGrContext, fGraphite, fSize);
454     }
455 
build(const char * src)456     void build(const char* src) {
457         SkRuntimeEffect::Options options;
458         SkRuntimeEffectPriv::AllowPrivateAccess(&options);
459         auto [effect, errorText] = SkRuntimeEffect::MakeForShader(SkString(src), options);
460         if (!effect) {
461             ERRORF(fReporter, "Effect didn't compile: %s", errorText.c_str());
462             return;
463         }
464         fBuilder.init(std::move(effect));
465     }
466 
uniform(const char * name)467     SkRuntimeShaderBuilder::BuilderUniform uniform(const char* name) {
468         return fBuilder->uniform(name);
469     }
470 
child(const char * name)471     SkRuntimeShaderBuilder::BuilderChild child(const char* name) {
472         return fBuilder->child(name);
473     }
474 
test(std::array<GrColor,4> expected,PreTestFn preTestCallback=nullptr)475     void test(std::array<GrColor, 4> expected, PreTestFn preTestCallback = nullptr) {
476         auto shader = fBuilder->makeShader();
477         if (!shader) {
478             ERRORF(fReporter, "Effect didn't produce a shader");
479             return;
480         }
481 
482         SkCanvas* canvas = fSurface->getCanvas();
483 
484         // We shouldn't need to clear the canvas, because we are about to paint over the whole thing
485         // with a `source` blend mode. However, there are a few devices where the background can
486         // leak through when we paint with MSAA on. (This seems to be a driver/hardware bug.)
487         // Graphite, at present, uses MSAA to do `drawPaint`. To avoid flakiness in this test on
488         // those devices, we explicitly clear the canvas here. (skia:13761)
489         canvas->clear(SK_ColorBLACK);
490 
491         SkPaint paint;
492         paint.setShader(std::move(shader));
493         paint.setBlendMode(SkBlendMode::kSrc);
494 
495         paint_canvas(canvas, &paint, preTestCallback);
496 
497         verify_2x2_surface_results(fReporter, fBuilder->effect(), fSurface.get(), expected);
498     }
499 
trace(const SkIPoint & traceCoord)500     std::string trace(const SkIPoint& traceCoord) {
501         sk_sp<SkShader> shader = fBuilder->makeShader();
502         if (!shader) {
503             ERRORF(fReporter, "Effect didn't produce a shader");
504             return {};
505         }
506 
507         auto [debugShader, debugTrace] = SkRuntimeEffect::MakeTraced(std::move(shader), traceCoord);
508 
509         SkCanvas* canvas = fSurface->getCanvas();
510         SkPaint paint;
511         paint.setShader(std::move(debugShader));
512         paint.setBlendMode(SkBlendMode::kSrc);
513 
514         paint_canvas(canvas, &paint, /*preTestCallback=*/nullptr);
515 
516         SkDynamicMemoryWStream wstream;
517         debugTrace->dump(&wstream);
518         sk_sp<SkData> streamData = wstream.detachAsData();
519         return std::string(static_cast<const char*>(streamData->data()), streamData->size());
520     }
521 
test(GrColor expected,PreTestFn preTestCallback=nullptr)522     void test(GrColor expected, PreTestFn preTestCallback = nullptr) {
523         this->test({expected, expected, expected, expected}, preTestCallback);
524     }
525 
526 private:
527     skiatest::Reporter*             fReporter;
528     sk_sp<SkSurface>                fSurface;
529     GrRecordingContext*             fGrContext;
530     const GraphiteInfo*             fGraphite;
531     SkISize                         fSize;
532     SkTLazy<SkRuntimeShaderBuilder> fBuilder;
533 };
534 
535 class TestBlend {
536 public:
TestBlend(skiatest::Reporter * r,GrRecordingContext * grContext,const GraphiteInfo * graphite)537     TestBlend(skiatest::Reporter* r, GrRecordingContext* grContext, const GraphiteInfo* graphite)
538             : fReporter(r), fGrContext(grContext), fGraphite(graphite) {
539         fSurface = make_surface(fGrContext, fGraphite, /*size=*/{2, 2});
540     }
541 
build(const char * src,bool allowPrivateAccess=false)542     void build(const char* src, bool allowPrivateAccess = false) {
543         SkRuntimeEffect::Options options;
544         if (allowPrivateAccess) {
545             SkRuntimeEffectPriv::AllowPrivateAccess(&options);
546         }
547         auto [effect, errorText] = SkRuntimeEffect::MakeForBlender(SkString(src), options);
548         if (!effect) {
549             ERRORF(fReporter, "Effect didn't compile: %s", errorText.c_str());
550             return;
551         }
552         fBuilder.init(std::move(effect));
553     }
554 
surface()555     SkSurface* surface() {
556         return fSurface.get();
557     }
558 
uniform(const char * name)559     SkRuntimeBlendBuilder::BuilderUniform uniform(const char* name) {
560         return fBuilder->uniform(name);
561     }
562 
child(const char * name)563     SkRuntimeBlendBuilder::BuilderChild child(const char* name) {
564         return fBuilder->child(name);
565     }
566 
test(std::array<GrColor,4> expected,PreTestFn preTestCallback=nullptr)567     void test(std::array<GrColor, 4> expected, PreTestFn preTestCallback = nullptr) {
568         auto blender = fBuilder->makeBlender();
569         if (!blender) {
570             ERRORF(fReporter, "Effect didn't produce a blender");
571             return;
572         }
573 
574         SkCanvas* canvas = fSurface->getCanvas();
575         SkPaint paint;
576         paint.setBlender(std::move(blender));
577         paint.setColor(SK_ColorGRAY);
578 
579         paint_canvas(canvas, &paint, preTestCallback);
580 
581         verify_2x2_surface_results(fReporter, fBuilder->effect(), fSurface.get(), expected);
582     }
583 
test(GrColor expected,PreTestFn preTestCallback=nullptr)584     void test(GrColor expected, PreTestFn preTestCallback = nullptr) {
585         this->test({expected, expected, expected, expected}, preTestCallback);
586     }
587 
588 private:
589     skiatest::Reporter*            fReporter;
590     sk_sp<SkSurface>               fSurface;
591     GrRecordingContext*            fGrContext;
592     const GraphiteInfo*            fGraphite;
593     SkTLazy<SkRuntimeBlendBuilder> fBuilder;
594 };
595 
596 // Produces a shader which will paint these opaque colors in a 2x2 rectangle:
597 // [  Red, Green ]
598 // [ Blue, White ]
make_RGBW_shader()599 static sk_sp<SkShader> make_RGBW_shader() {
600     static constexpr SkColor colors[] = {SK_ColorWHITE, SK_ColorWHITE,
601                                          SK_ColorBLUE, SK_ColorBLUE,
602                                          SK_ColorRED, SK_ColorRED,
603                                          SK_ColorGREEN, SK_ColorGREEN};
604     static constexpr SkScalar   pos[] = { 0, .25f, .25f, .50f, .50f, .75, .75, 1 };
605     static_assert(std::size(colors) == std::size(pos), "size mismatch");
606     return SkGradientShader::MakeSweep(1, 1, colors, pos, std::size(colors));
607 }
608 
test_RuntimeEffect_Shaders(skiatest::Reporter * r,GrRecordingContext * grContext,const GraphiteInfo * graphite)609 static void test_RuntimeEffect_Shaders(skiatest::Reporter* r,
610                                        GrRecordingContext* grContext,
611                                        const GraphiteInfo* graphite) {
612     TestEffect effect(r, grContext, graphite);
613     using float4 = std::array<float, 4>;
614     using int4 = std::array<int, 4>;
615 
616     // Local coords
617     effect.build("half4 main(float2 p) { return half4(half2(p - 0.5), 0, 1); }");
618     effect.test({0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF});
619 
620     // Use of a simple uniform. (Draw twice with two values to ensure it's updated).
621     effect.build("uniform float4 gColor; half4 main(float2 p) { return half4(gColor); }");
622     effect.uniform("gColor") = float4{ 0.0f, 0.25f, 0.75f, 1.0f };
623     effect.test(0xFFBF4000);
624     effect.uniform("gColor") = float4{ 1.0f, 0.0f, 0.0f, 0.498f };
625     effect.test(0x7F0000FF);  // Tests that we don't clamp to valid premul
626 
627     // Same, with integer uniforms
628     effect.build("uniform int4 gColor; half4 main(float2 p) { return half4(gColor) / 255.0; }");
629     effect.uniform("gColor") = int4{ 0x00, 0x40, 0xBF, 0xFF };
630     effect.test(0xFFBF4000);
631     effect.uniform("gColor") = int4{ 0xFF, 0x00, 0x00, 0x7F };
632     effect.test(0x7F0000FF);  // Tests that we don't clamp to valid premul
633 
634     // Test sk_FragCoord (device coords). Rotate the canvas to be sure we're seeing device coords.
635     // Since the surface is 2x2, we should see (0,0), (1,0), (0,1), (1,1). Multiply by 0.498 to
636     // make sure we're not saturating unexpectedly.
637     effect.build(
638             "half4 main(float2 p) { return half4(0.498 * (half2(sk_FragCoord.xy) - 0.5), 0, 1); }");
639     effect.test({0xFF000000, 0xFF00007F, 0xFF007F00, 0xFF007F7F},
640                 [](SkCanvas* canvas, SkPaint*) { canvas->rotate(45.0f); });
641 
642     // Runtime effects should use relaxed precision rules by default
643     effect.build("half4 main(float2 p) { return float4(p - 0.5, 0, 1); }");
644     effect.test({0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF});
645 
646     // ... and support *returning* float4 (aka vec4), not just half4
647     effect.build("float4 main(float2 p) { return float4(p - 0.5, 0, 1); }");
648     effect.test({0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF});
649     effect.build("vec4 main(float2 p) { return float4(p - 0.5, 0, 1); }");
650     effect.test({0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF});
651 
652     // Mutating coords should work. (skbug.com/10918)
653     effect.build("vec4 main(vec2 p) { p -= 0.5; return vec4(p, 0, 1); }");
654     effect.test({0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF});
655     effect.build("void moveCoords(inout vec2 p) { p -= 0.5; }"
656                  "vec4 main(vec2 p) { moveCoords(p); return vec4(p, 0, 1); }");
657     effect.test({0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF});
658 
659     //
660     // Sampling children
661     //
662 
663     // Sampling a null shader should return transparent black
664     if (!graphite) {
665         // TODO: Graphite does not yet pass this test.
666         effect.build("uniform shader child;"
667                      "half4 main(float2 p) { return child.eval(p); }");
668         effect.child("child") = nullptr;
669         effect.test(0x00000000,
670                     [](SkCanvas*, SkPaint* paint) { paint->setColor4f({1.0f, 1.0f, 0.0f, 1.0f}); });
671     }
672 
673     // Sampling a null color-filter should return the passed-in color
674     effect.build("uniform colorFilter child;"
675                  "half4 main(float2 p) { return child.eval(half4(1, 1, 0, 1)); }");
676     effect.child("child") = nullptr;
677     effect.test(0xFF00FFFF);
678 
679     // Sampling a null blender should return blend_src_over(src, dest).
680     effect.build("uniform blender child;"
681                  "half4 main(float2 p) {"
682                  "    float4 src = float4(p - 0.5, 0, 1) * 0.498;"
683                  "    return child.eval(src, half4(0, 0, 0, 1));"
684                  "}");
685     effect.child("child") = nullptr;
686     effect.test({0xFF000000, 0xFF00007F, 0xFF007F00, 0xFF007F7F});
687 
688     // Sampling a simple child at our coordinates
689     sk_sp<SkShader> rgbwShader = make_RGBW_shader();
690 
691     effect.build("uniform shader child;"
692                  "half4 main(float2 p) { return child.eval(p); }");
693     effect.child("child") = rgbwShader;
694     effect.test({0xFF0000FF, 0xFF00FF00, 0xFFFF0000, 0xFFFFFFFF});
695 
696     // Sampling with explicit coordinates (reflecting about the diagonal)
697     effect.build("uniform shader child;"
698                  "half4 main(float2 p) { return child.eval(p.yx); }");
699     effect.child("child") = rgbwShader;
700     effect.test({0xFF0000FF, 0xFFFF0000, 0xFF00FF00, 0xFFFFFFFF});
701 
702     // Bind an image shader, but don't use it - ensure that we don't assert or generate bad shaders.
703     // (skbug.com/12429)
704     effect.build("uniform shader child;"
705                  "half4 main(float2 p) { return half4(0, 1, 0, 1); }");
706     effect.child("child") = rgbwShader;
707     effect.test(0xFF00FF00);
708 
709     //
710     // Helper functions
711     //
712 
713     // Test case for inlining in the pipeline-stage and fragment-shader passes (skbug.com/10526):
714     effect.build("float2 helper(float2 x) { return x + 1; }"
715                  "half4 main(float2 p) { float2 v = helper(p); return half4(half2(v), 0, 1); }");
716     effect.test(0xFF00FFFF);
717 
718     // Passing a shader to a helper function
719     effect.build("uniform shader child; float2 position;"
720                  "noinline half4 my_eval(shader s) { return s.eval(position); }"
721                  "half4 main(float2 p) { position = p; return my_eval(child); }");
722     effect.child("child") = rgbwShader;
723     effect.test({0xFF0000FF, 0xFF00FF00, 0xFFFF0000, 0xFFFFFFFF});
724 }
725 
DEF_TEST(SkRuntimeEffectSimple,r)726 DEF_TEST(SkRuntimeEffectSimple, r) {
727     test_RuntimeEffect_Shaders(r, /*grContext=*/nullptr, /*graphite=*/nullptr);
728 }
729 
730 #if defined(SK_GRAPHITE)
DEF_GRAPHITE_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffectSimple_Graphite,r,context,CtsEnforcement::kApiLevel_V)731 DEF_GRAPHITE_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffectSimple_Graphite, r, context,
732                                          CtsEnforcement::kApiLevel_V) {
733     std::unique_ptr<skgpu::graphite::Recorder> recorder = context->makeRecorder();
734     GraphiteInfo graphite = {context, recorder.get()};
735     test_RuntimeEffect_Shaders(r, /*grContext=*/nullptr, &graphite);
736 }
737 #endif
738 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffectSimple_GPU,r,ctxInfo,CtsEnforcement::kApiLevel_T)739 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffectSimple_GPU,
740                                        r,
741                                        ctxInfo,
742                                        CtsEnforcement::kApiLevel_T) {
743     test_RuntimeEffect_Shaders(r, ctxInfo.directContext(), /*graphite=*/nullptr);
744 }
745 
verify_draw_obeys_capabilities(skiatest::Reporter * r,const SkRuntimeEffect * effect,SkSurface * surface,const SkPaint & paint)746 static void verify_draw_obeys_capabilities(skiatest::Reporter* r,
747                                            const SkRuntimeEffect* effect,
748                                            SkSurface* surface,
749                                            const SkPaint& paint) {
750     // We expect the draw to do something if-and-only-if expectSuccess is true:
751     const bool expectSuccess = surface->capabilities()->skslVersion() >= SkSL::Version::k300;
752 
753     constexpr GrColor kGreen = 0xFF00FF00;
754     constexpr GrColor kRed   = 0xFF0000FF;
755     const GrColor kExpected = expectSuccess ? kGreen : kRed;
756 
757     surface->getCanvas()->clear(SK_ColorRED);
758     surface->getCanvas()->drawPaint(paint);
759     verify_2x2_surface_results(r, effect, surface, {kExpected, kExpected, kExpected, kExpected});
760 }
761 
test_RuntimeEffectObeysCapabilities(skiatest::Reporter * r,SkSurface * surface)762 static void test_RuntimeEffectObeysCapabilities(skiatest::Reporter* r, SkSurface* surface) {
763     // This test creates shaders and blenders that target `#version 300`. If a user validates an
764     // effect like this against a particular device, and later draws that effect to a device with
765     // insufficient capabilities -- we want to fail gracefully (drop the draw entirely).
766     // If the capabilities indicate that the effect is supported, we expect it to work.
767     //
768     // We test two different scenarios here:
769     // 1) An effect flagged as #version 300, but actually compatible with #version 100.
770     // 2) An effect flagged as #version 300, and using features not available in ES2.
771     //
772     // We expect both cases to fail cleanly on ES2-only devices -- nothing should be drawn, and
773     // there should be no asserts or driver shader-compilation errors.
774     //
775     // In all tests, we first clear the canvas to RED, then draw an effect that (if it renders)
776     // will fill the canvas with GREEN. We check that the final colors match our expectations,
777     // based on the device capabilities.
778 
779     // Effect that would actually work on CPU/ES2, but should still fail on those devices:
780     {
781         auto effect = SkRuntimeEffect::MakeForShader(SkString(R"(
782             #version 300
783             half4 main(float2 xy) { return half4(0, 1, 0, 1); }
784         )")).effect;
785         REPORTER_ASSERT(r, effect);
786         SkPaint paint;
787         paint.setShader(effect->makeShader(/*uniforms=*/nullptr, /*children=*/{}));
788         REPORTER_ASSERT(r, paint.getShader());
789         verify_draw_obeys_capabilities(r, effect.get(), surface, paint);
790     }
791 
792     // Effect that won't work on CPU/ES2 at all, and should fail gracefully on those devices.
793     // We choose to use bit-pun intrinsics because SkSL doesn't automatically inject an extension
794     // to enable them (like it does for derivatives). We pass a non-literal value so that SkSL's
795     // constant folding doesn't elide them entirely before the driver sees the shader.
796     {
797         auto effect = SkRuntimeEffect::MakeForShader(SkString(R"(
798             #version 300
799             half4 main(float2 xy) {
800                 half4 result = half4(0, 1, 0, 1);
801                 result.g = intBitsToFloat(floatBitsToInt(result.g));
802                 return result;
803             }
804         )")).effect;
805         REPORTER_ASSERT(r, effect);
806         SkPaint paint;
807         paint.setShader(effect->makeShader(/*uniforms=*/nullptr, /*children=*/{}));
808         REPORTER_ASSERT(r, paint.getShader());
809         verify_draw_obeys_capabilities(r, effect.get(), surface, paint);
810     }
811 
812     //
813     // As above, but with a blender
814     //
815 
816     {
817         auto effect = SkRuntimeEffect::MakeForBlender(SkString(R"(
818             #version 300
819             half4 main(half4 src, half4 dst) { return half4(0, 1, 0, 1); }
820         )")).effect;
821         REPORTER_ASSERT(r, effect);
822         SkPaint paint;
823         paint.setBlender(effect->makeBlender(/*uniforms=*/nullptr, /*children=*/{}));
824         REPORTER_ASSERT(r, paint.getBlender());
825         verify_draw_obeys_capabilities(r, effect.get(), surface, paint);
826     }
827 
828     {
829         auto effect = SkRuntimeEffect::MakeForBlender(SkString(R"(
830             #version 300
831             half4 main(half4 src, half4 dst) {
832                 half4 result = half4(0, 1, 0, 1);
833                 result.g = intBitsToFloat(floatBitsToInt(result.g));
834                 return result;
835             }
836         )")).effect;
837         REPORTER_ASSERT(r, effect);
838         SkPaint paint;
839         paint.setBlender(effect->makeBlender(/*uniforms=*/nullptr, /*children=*/{}));
840         REPORTER_ASSERT(r, paint.getBlender());
841         verify_draw_obeys_capabilities(r, effect.get(), surface, paint);
842     }
843 }
844 
DEF_TEST(SkRuntimeEffectObeysCapabilities_CPU,r)845 DEF_TEST(SkRuntimeEffectObeysCapabilities_CPU, r) {
846     SkImageInfo info = SkImageInfo::Make(2, 2, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
847     sk_sp<SkSurface> surface = SkSurfaces::Raster(info);
848     REPORTER_ASSERT(r, surface);
849     test_RuntimeEffectObeysCapabilities(r, surface.get());
850 }
851 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffectObeysCapabilities_GPU,r,ctxInfo,CtsEnforcement::kApiLevel_U)852 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffectObeysCapabilities_GPU,
853                                        r,
854                                        ctxInfo,
855                                        CtsEnforcement::kApiLevel_U) {
856     SkImageInfo info = SkImageInfo::Make(2, 2, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
857     sk_sp<SkSurface> surface =
858             SkSurfaces::RenderTarget(ctxInfo.directContext(), skgpu::Budgeted::kNo, info);
859     REPORTER_ASSERT(r, surface);
860     test_RuntimeEffectObeysCapabilities(r, surface.get());
861 }
862 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeColorFilterReturningInvalidAlpha_GPU,r,ctxInfo,CtsEnforcement::kNever)863 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeColorFilterReturningInvalidAlpha_GPU,
864                                        r,
865                                        ctxInfo,
866                                        CtsEnforcement::kNever) {
867     SkImageInfo info = SkImageInfo::Make(2, 2, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
868     sk_sp<SkSurface> surface =
869             SkSurfaces::RenderTarget(ctxInfo.directContext(), skgpu::Budgeted::kNo, info);
870     REPORTER_ASSERT(r, surface);
871 
872     auto effect = SkRuntimeEffect::MakeForColorFilter(SkString(R"(
873         half4 main(half4 color) { return half4(2); }
874     )")).effect;
875     REPORTER_ASSERT(r, effect);
876     SkPaint paint;
877     paint.setColorFilter(effect->makeColorFilter(/*uniforms=*/nullptr));
878     REPORTER_ASSERT(r, paint.getColorFilter());
879     surface->getCanvas()->drawPaint(paint);
880 }
881 
DEF_TEST(SkRuntimeColorFilterLimitedToES2,r)882 DEF_TEST(SkRuntimeColorFilterLimitedToES2, r) {
883     // Verify that SkSL requesting #version 300 can't be used to create a color-filter effect.
884     // This restriction could be removed if we can find a way to implement filterColor4f for these
885     // color filters.
886     {
887         auto effect = SkRuntimeEffect::MakeForColorFilter(SkString(R"(
888             #version 300
889             half4 main(half4 inColor) { return half4(1, 0, 0, 1); }
890         )")).effect;
891         REPORTER_ASSERT(r, !effect);
892     }
893 
894     {
895         auto effect = SkRuntimeEffect::MakeForColorFilter(SkString(R"(
896             #version 300
897             uniform int loops;
898             half4 main(half4 inColor) {
899                 half4 result = half4(1, 0, 0, 1);
900                 for (int i = 0; i < loops; i++) {
901                     result = result.argb;
902                 }
903                 return result;
904             }
905         )")).effect;
906         REPORTER_ASSERT(r, !effect);
907     }
908 }
909 
DEF_TEST(SkRuntimeEffectTraceShader,r)910 DEF_TEST(SkRuntimeEffectTraceShader, r) {
911     for (int imageSize : {2, 80}) {
912         TestEffect effect(r, /*grContext=*/nullptr, /*graphite=*/nullptr,
913                           SkISize{imageSize, imageSize});
914         effect.build(R"(
915             half4 main(float2 p) {
916                 float2 val = p - 0.5;
917                 return val.0y01;
918             }
919         )");
920         int center = imageSize / 2;
921         std::string dump = effect.trace({center, 1});
922         static constexpr char kSkRPSlotDump[] =
923 R"($0 = p (float2 : slot 1/2, L0)
924 $1 = p (float2 : slot 2/2, L0)
925 $2 = [main].result (float4 : slot 1/4, L0)
926 $3 = [main].result (float4 : slot 2/4, L0)
927 $4 = [main].result (float4 : slot 3/4, L0)
928 $5 = [main].result (float4 : slot 4/4, L0)
929 $6 = val (float2 : slot 1/2, L0)
930 $7 = val (float2 : slot 2/2, L0)
931 F0 = half4 main(float2 p)
932 )";
933         auto expectedTrace = SkSL::String::printf(R"(
934 enter half4 main(float2 p)
935   p.x = %d.5
936   p.y = 1.5
937   scope +1
938    line 3
939    val.x = %d
940    val.y = 1
941    line 4
942    [main].result.x = 0
943    [main].result.y = 1
944    [main].result.z = 0
945    [main].result.w = 1
946   scope -1
947 exit half4 main(float2 p)
948 )", center, center);
949         REPORTER_ASSERT(
950                 r,
951                 skstd::starts_with(dump, kSkRPSlotDump) && skstd::ends_with(dump, expectedTrace),
952                 "Trace does not match expectation for %dx%d:\n%.*s\n",
953                 imageSize, imageSize, (int)dump.size(), dump.data());
954     }
955 }
956 
DEF_TEST(SkRuntimeEffectTracesAreUnoptimized,r)957 DEF_TEST(SkRuntimeEffectTracesAreUnoptimized, r) {
958     TestEffect effect(r, /*grContext=*/nullptr, /*graphite=*/nullptr);
959 
960     effect.build(R"(
961         int globalUnreferencedVar = 7;
962         half inlinableFunction() {
963             return 1;
964         }
965         half4 main(float2 p) {
966             if (true) {
967                 int localUnreferencedVar = 7;
968             }
969             return inlinableFunction().xxxx;
970         }
971     )");
972     std::string dump = effect.trace({1, 1});
973     static constexpr char kSkRPSlotDump[] =
974 R"($0 = p (float2 : slot 1/2, L0)
975 $1 = p (float2 : slot 2/2, L0)
976 $2 = globalUnreferencedVar (int, L0)
977 $3 = [main].result (float4 : slot 1/4, L0)
978 $4 = [main].result (float4 : slot 2/4, L0)
979 $5 = [main].result (float4 : slot 3/4, L0)
980 $6 = [main].result (float4 : slot 4/4, L0)
981 $7 = localUnreferencedVar (int, L0)
982 $8 = [inlinableFunction].result (float, L0)
983 F0 = half4 main(float2 p)
984 F1 = half inlinableFunction()
985 )";
986     static constexpr char kExpectedTrace[] = R"(
987 globalUnreferencedVar = 7
988 enter half4 main(float2 p)
989   p.x = 1.5
990   p.y = 1.5
991   scope +1
992    line 7
993    scope +1
994     line 8
995     localUnreferencedVar = 7
996    scope -1
997    line 10
998    enter half inlinableFunction()
999      scope +1
1000       line 4
1001       [inlinableFunction].result = 1
1002      scope -1
1003    exit half inlinableFunction()
1004    [main].result.x = 1
1005    [main].result.y = 1
1006    [main].result.z = 1
1007    [main].result.w = 1
1008   scope -1
1009 exit half4 main(float2 p)
1010 )";
1011     REPORTER_ASSERT(
1012             r,
1013             skstd::starts_with(dump, kSkRPSlotDump) && skstd::ends_with(dump, kExpectedTrace),
1014             "Trace output does not match expectation:\n%.*s\n", (int)dump.size(), dump.data());
1015 }
1016 
DEF_TEST(SkRuntimeEffectTraceCodeThatCannotBeUnoptimized,r)1017 DEF_TEST(SkRuntimeEffectTraceCodeThatCannotBeUnoptimized, r) {
1018     TestEffect effect(r, /*grContext=*/nullptr, /*graphite=*/nullptr);
1019 
1020     effect.build(R"(
1021         half4 main(float2 p) {
1022             int variableThatGetsOptimizedAway = 7;
1023             if (true) {
1024                 return half4(1);
1025             }
1026             // This (unreachable) path doesn't return a value.
1027             // Without optimization, SkSL thinks this code doesn't return a value on every path.
1028         }
1029     )");
1030     std::string dump = effect.trace({1, 1});
1031     static constexpr char kSkRPSlotDump[] =
1032 R"($0 = p (float2 : slot 1/2, L0)
1033 $1 = p (float2 : slot 2/2, L0)
1034 $2 = [main].result (float4 : slot 1/4, L0)
1035 $3 = [main].result (float4 : slot 2/4, L0)
1036 $4 = [main].result (float4 : slot 3/4, L0)
1037 $5 = [main].result (float4 : slot 4/4, L0)
1038 F0 = half4 main(float2 p)
1039 )";
1040     static constexpr char kExpectedTrace[] = R"(
1041 enter half4 main(float2 p)
1042   p.x = 1.5
1043   p.y = 1.5
1044   scope +1
1045    scope +1
1046     line 5
1047     [main].result.x = 1
1048     [main].result.y = 1
1049     [main].result.z = 1
1050     [main].result.w = 1
1051    scope -1
1052   scope -1
1053 exit half4 main(float2 p)
1054 )";
1055     REPORTER_ASSERT(
1056             r,
1057             skstd::starts_with(dump, kSkRPSlotDump) && skstd::ends_with(dump, kExpectedTrace),
1058             "Trace output does not match expectation:\n%.*s\n", (int)dump.size(), dump.data());
1059 }
1060 
test_RuntimeEffect_Blenders(skiatest::Reporter * r,GrRecordingContext * grContext,const GraphiteInfo * graphite)1061 static void test_RuntimeEffect_Blenders(skiatest::Reporter* r,
1062                                         GrRecordingContext* grContext,
1063                                         const GraphiteInfo* graphite) {
1064     TestBlend effect(r, grContext, graphite);
1065 
1066     using float2 = std::array<float, 2>;
1067     using float4 = std::array<float, 4>;
1068     using int4 = std::array<int, 4>;
1069 
1070     SkPaint rgbwPaint;
1071     rgbwPaint.setShader(make_RGBW_shader());
1072     rgbwPaint.setBlendMode(SkBlendMode::kSrc);
1073 
1074     // Use of a simple uniform. (Draw twice with two values to ensure it's updated).
1075     effect.build("uniform float4 gColor; half4 main(half4 s, half4 d) { return half4(gColor); }");
1076     effect.uniform("gColor") = float4{ 0.0f, 0.25f, 0.75f, 1.0f };
1077     effect.test(0xFFBF4000);
1078     effect.uniform("gColor") = float4{ 1.0f, 0.0f, 0.0f, 0.498f };
1079     effect.test(0x7F0000FF);  // We don't clamp here either
1080 
1081     // Same, with integer uniforms
1082     effect.build("uniform int4 gColor;"
1083                  "half4 main(half4 s, half4 d) { return half4(gColor) / 255.0; }");
1084     effect.uniform("gColor") = int4{ 0x00, 0x40, 0xBF, 0xFF };
1085     effect.test(0xFFBF4000);
1086     effect.uniform("gColor") = int4{ 0xFF, 0x00, 0x00, 0x7F };
1087     effect.test(0x7F0000FF);  // We don't clamp here either
1088 
1089     // Verify that mutating the source and destination colors is allowed
1090     effect.build("half4 main(half4 s, half4 d) { s += d; d += s; return half4(1); }");
1091     effect.test(0xFFFFFFFF);
1092 
1093     // Verify that we can write out the source color (ignoring the dest color)
1094     // This is equivalent to the kSrc blend mode.
1095     effect.build("half4 main(half4 s, half4 d) { return s; }");
1096     effect.test(0xFF888888);
1097 
1098     // Fill the destination with a variety of colors (using the RGBW shader)
1099     effect.surface()->getCanvas()->drawPaint(rgbwPaint);
1100 
1101     // Verify that we can read back the dest color exactly as-is (ignoring the source color)
1102     // This is equivalent to the kDst blend mode.
1103     effect.build("half4 main(half4 s, half4 d) { return d; }");
1104     effect.test({0xFF0000FF, 0xFF00FF00, 0xFFFF0000, 0xFFFFFFFF});
1105 
1106     // Verify that we can invert the destination color (including the alpha channel).
1107     // The expected outputs are the exact inverse of the previous test.
1108     effect.build("half4 main(half4 s, half4 d) { return half4(1) - d; }");
1109     effect.test({0x00FFFF00, 0x00FF00FF, 0x0000FFFF, 0x00000000});
1110 
1111     // Verify that color values are clamped to 0 and 1.
1112     effect.build("half4 main(half4 s, half4 d) { return half4(-1); }");
1113     effect.test(0x00000000);
1114     effect.build("half4 main(half4 s, half4 d) { return half4(2); }");
1115     effect.test(0xFFFFFFFF);
1116 
1117     //
1118     // Sampling children
1119     //
1120 
1121     // Sampling a null shader should return transparent black.
1122     effect.build("uniform shader child;"
1123                  "half4 main(half4 s, half4 d) { return child.eval(s.rg); }");
1124     effect.child("child") = nullptr;
1125     effect.test(0x00000000,
1126                 [](SkCanvas*, SkPaint* paint) { paint->setColor4f({1.0f, 1.0f, 0.0f, 1.0f}); });
1127 
1128     effect.build("uniform colorFilter child;"
1129                  "half4 main(half4 s, half4 d) { return child.eval(s); }");
1130     effect.child("child") = nullptr;
1131     effect.test(0xFF00FFFF,
1132                 [](SkCanvas*, SkPaint* paint) { paint->setColor4f({1.0f, 1.0f, 0.0f, 1.0f}); });
1133 
1134     // Sampling a null blender should do a src-over blend. Draw 50% black over RGBW to verify this.
1135     effect.surface()->getCanvas()->drawPaint(rgbwPaint);
1136     effect.build("uniform blender child;"
1137                  "half4 main(half4 s, half4 d) { return child.eval(s, d); }");
1138     effect.child("child") = nullptr;
1139     effect.test({0xFF000080, 0xFF008000, 0xFF800000, 0xFF808080},
1140                 [](SkCanvas*, SkPaint* paint) { paint->setColor4f({0.0f, 0.0f, 0.0f, 0.497f}); });
1141 
1142     // Sampling a shader at various coordinates
1143     effect.build("uniform shader child;"
1144                  "uniform half2 pos;"
1145                  "half4 main(half4 s, half4 d) { return child.eval(pos); }");
1146     effect.child("child") = make_RGBW_shader();
1147     effect.uniform("pos") = float2{0.5, 0.5};
1148     effect.test(0xFF0000FF);
1149 
1150     effect.uniform("pos") = float2{1.5, 0.5};
1151     effect.test(0xFF00FF00);
1152 
1153     effect.uniform("pos") = float2{0.5, 1.5};
1154     effect.test(0xFFFF0000);
1155 
1156     effect.uniform("pos") = float2{1.5, 1.5};
1157     effect.test(0xFFFFFFFF);
1158 
1159     // Sampling a shader as above, but via a helper function
1160     effect.build("uniform shader child;"
1161                  "uniform half2 pos;"
1162                  "half4 eval_at_pos(shader x) { return x.eval(pos); }"
1163                  "half4 main(half4 s, half4 d) { return eval_at_pos(child); }",
1164                  /*allowPrivateAccess=*/true);
1165     effect.child("child") = make_RGBW_shader();
1166     effect.uniform("pos") = float2{0.5, 0.5};
1167     effect.test(0xFF0000FF);
1168 
1169     effect.uniform("pos") = float2{1.5, 0.5};
1170     effect.test(0xFF00FF00);
1171 
1172     effect.uniform("pos") = float2{0.5, 1.5};
1173     effect.test(0xFFFF0000);
1174 
1175     effect.uniform("pos") = float2{1.5, 1.5};
1176     effect.test(0xFFFFFFFF);
1177 
1178     // Sampling a color filter
1179     effect.build("uniform colorFilter child;"
1180                  "half4 main(half4 s, half4 d) { return child.eval(half4(1)); }");
1181     effect.child("child") = SkColorFilters::Blend(0xFF012345, SkBlendMode::kSrc);
1182     effect.test(0xFF452301);
1183 
1184     // Sampling a built-in blender
1185     effect.surface()->getCanvas()->drawPaint(rgbwPaint);
1186     effect.build("uniform blender child;"
1187                  "half4 main(half4 s, half4 d) { return child.eval(s, d); }");
1188     effect.child("child") = SkBlender::Mode(SkBlendMode::kPlus);
1189     effect.test({0xFF4523FF, 0xFF45FF01, 0xFFFF2301, 0xFFFFFFFF},
1190                 [](SkCanvas*, SkPaint* paint) { paint->setColor(0xFF012345); });
1191 
1192     // Sampling a runtime-effect blender
1193     effect.surface()->getCanvas()->drawPaint(rgbwPaint);
1194     effect.build("uniform blender child;"
1195                  "half4 main(half4 s, half4 d) { return child.eval(s, d); }");
1196     effect.child("child") = SkBlenders::Arithmetic(0, 1, 1, 0, /*enforcePremul=*/false);
1197     effect.test({0xFF4523FF, 0xFF45FF01, 0xFFFF2301, 0xFFFFFFFF},
1198                 [](SkCanvas*, SkPaint* paint) { paint->setColor(0xFF012345); });
1199 }
1200 
DEF_TEST(SkRuntimeEffect_Blender_CPU,r)1201 DEF_TEST(SkRuntimeEffect_Blender_CPU, r) {
1202     test_RuntimeEffect_Blenders(r, /*grContext=*/nullptr, /*graphite=*/nullptr);
1203 }
1204 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffect_Blender_GPU,r,ctxInfo,CtsEnforcement::kApiLevel_T)1205 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffect_Blender_GPU,
1206                                        r,
1207                                        ctxInfo,
1208                                        CtsEnforcement::kApiLevel_T) {
1209     test_RuntimeEffect_Blenders(r, ctxInfo.directContext(), /*graphite=*/nullptr);
1210 }
1211 
DEF_TEST(SkRuntimeShaderBuilderReuse,r)1212 DEF_TEST(SkRuntimeShaderBuilderReuse, r) {
1213     const char* kSource = R"(
1214         uniform half x;
1215         half4 main(float2 p) { return half4(x); }
1216     )";
1217 
1218     sk_sp<SkRuntimeEffect> effect = SkRuntimeEffect::MakeForShader(SkString(kSource)).effect;
1219     REPORTER_ASSERT(r, effect);
1220 
1221     // Test passes if this sequence doesn't assert.  skbug.com/10667
1222     SkRuntimeShaderBuilder b(std::move(effect));
1223     b.uniform("x") = 0.0f;
1224     auto shader_0 = b.makeShader();
1225 
1226     b.uniform("x") = 1.0f;
1227     auto shader_1 = b.makeShader();
1228 }
1229 
DEF_TEST(SkRuntimeBlendBuilderReuse,r)1230 DEF_TEST(SkRuntimeBlendBuilderReuse, r) {
1231     const char* kSource = R"(
1232         uniform half x;
1233         half4 main(half4 s, half4 d) { return half4(x); }
1234     )";
1235 
1236     sk_sp<SkRuntimeEffect> effect = SkRuntimeEffect::MakeForBlender(SkString(kSource)).effect;
1237     REPORTER_ASSERT(r, effect);
1238 
1239     // We should be able to construct multiple SkBlenders in a row without asserting.
1240     SkRuntimeBlendBuilder b(std::move(effect));
1241     for (float x = 0.0f; x <= 2.0f; x += 2.0f) {
1242         b.uniform("x") = x;
1243         sk_sp<SkBlender> blender = b.makeBlender();
1244     }
1245 }
1246 
DEF_TEST(SkRuntimeShaderBuilderSetUniforms,r)1247 DEF_TEST(SkRuntimeShaderBuilderSetUniforms, r) {
1248     const char* kSource = R"(
1249         uniform half x;
1250         uniform vec2 offset;
1251         half4 main(float2 p) { return half4(x); }
1252     )";
1253 
1254     sk_sp<SkRuntimeEffect> effect = SkRuntimeEffect::MakeForShader(SkString(kSource)).effect;
1255     REPORTER_ASSERT(r, effect);
1256 
1257     SkRuntimeShaderBuilder b(std::move(effect));
1258 
1259     // Test passes if this sequence doesn't assert.
1260     float x = 1.0f;
1261     REPORTER_ASSERT(r, b.uniform("x").set(&x, 1));
1262 
1263     // add extra value to ensure that set doesn't try to use sizeof(array)
1264     float origin[] = { 2.0f, 3.0f, 4.0f };
1265     REPORTER_ASSERT(r, b.uniform("offset").set<float>(origin, 2));
1266 
1267 #ifndef SK_DEBUG
1268     REPORTER_ASSERT(r, !b.uniform("offset").set<float>(origin, 1));
1269     REPORTER_ASSERT(r, !b.uniform("offset").set<float>(origin, 3));
1270 #endif
1271 
1272     auto shader = b.makeShader();
1273 }
1274 
DEF_TEST(SkRuntimeEffectThreaded,r)1275 DEF_TEST(SkRuntimeEffectThreaded, r) {
1276     // This tests that we can safely use SkRuntimeEffect::MakeForShader from more than one thread,
1277     // and also that programs don't refer to shared structures owned by the compiler.
1278     // skbug.com/10589
1279     static constexpr char kSource[] = "half4 main(float2 p) { return sk_FragCoord.xyxy; }";
1280 
1281     std::thread threads[16];
1282     for (auto& thread : threads) {
1283         thread = std::thread([r]() {
1284             SkRuntimeEffect::Options options;
1285             SkRuntimeEffectPriv::AllowPrivateAccess(&options);
1286             auto [effect, error] = SkRuntimeEffect::MakeForShader(SkString(kSource), options);
1287             REPORTER_ASSERT(r, effect);
1288         });
1289     }
1290 
1291     for (auto& thread : threads) {
1292         thread.join();
1293     }
1294 }
1295 
DEF_TEST(SkRuntimeEffectAllowsPrivateAccess,r)1296 DEF_TEST(SkRuntimeEffectAllowsPrivateAccess, r) {
1297     SkRuntimeEffect::Options defaultOptions;
1298     SkRuntimeEffect::Options optionsWithAccess;
1299     SkRuntimeEffectPriv::AllowPrivateAccess(&optionsWithAccess);
1300 
1301     // Confirm that shaders can only access $private_functions when private access is allowed.
1302     {
1303         static constexpr char kShader[] =
1304                 "half4 main(float2 p) { return $hsl_to_rgb(p.xxx, p.y); }";
1305         SkRuntimeEffect::Result normal =
1306                 SkRuntimeEffect::MakeForShader(SkString(kShader), defaultOptions);
1307         REPORTER_ASSERT(r, !normal.effect);
1308         SkRuntimeEffect::Result privileged =
1309                 SkRuntimeEffect::MakeForShader(SkString(kShader), optionsWithAccess);
1310         REPORTER_ASSERT(r, privileged.effect, "%s", privileged.errorText.c_str());
1311     }
1312 
1313     // Confirm that color filters can only access $private_functions when private access is allowed.
1314     {
1315         static constexpr char kColorFilter[] =
1316                 "half4 main(half4 c)  { return $hsl_to_rgb(c.rgb, c.a); }";
1317         SkRuntimeEffect::Result normal =
1318                 SkRuntimeEffect::MakeForColorFilter(SkString(kColorFilter), defaultOptions);
1319         REPORTER_ASSERT(r, !normal.effect);
1320         SkRuntimeEffect::Result privileged =
1321                 SkRuntimeEffect::MakeForColorFilter(SkString(kColorFilter), optionsWithAccess);
1322         REPORTER_ASSERT(r, privileged.effect, "%s", privileged.errorText.c_str());
1323     }
1324 
1325     // Confirm that blenders can only access $private_functions when private access is allowed.
1326     {
1327         static constexpr char kBlender[] =
1328                 "half4 main(half4 s, half4 d) { return $hsl_to_rgb(s.rgb, d.a); }";
1329         SkRuntimeEffect::Result normal =
1330                 SkRuntimeEffect::MakeForBlender(SkString(kBlender), defaultOptions);
1331         REPORTER_ASSERT(r, !normal.effect);
1332         SkRuntimeEffect::Result privileged =
1333                 SkRuntimeEffect::MakeForBlender(SkString(kBlender), optionsWithAccess);
1334         REPORTER_ASSERT(r, privileged.effect, "%s", privileged.errorText.c_str());
1335     }
1336 }
1337 
DEF_TEST(SkRuntimeColorFilterSingleColor,r)1338 DEF_TEST(SkRuntimeColorFilterSingleColor, r) {
1339     // Test runtime colorfilters support filterColor4f().
1340     auto [effect, err] =
1341             SkRuntimeEffect::MakeForColorFilter(SkString{"half4 main(half4 c) { return c*c; }"});
1342     REPORTER_ASSERT(r, effect);
1343     REPORTER_ASSERT(r, err.isEmpty());
1344 
1345     sk_sp<SkColorFilter> cf = effect->makeColorFilter(SkData::MakeEmpty());
1346     REPORTER_ASSERT(r, cf);
1347 
1348     SkColor4f c = cf->filterColor4f({0.25, 0.5, 0.75, 1.0},
1349                                     sk_srgb_singleton(), sk_srgb_singleton());
1350     REPORTER_ASSERT(r, c.fR == 0.0625f);
1351     REPORTER_ASSERT(r, c.fG == 0.25f);
1352     REPORTER_ASSERT(r, c.fB == 0.5625f);
1353     REPORTER_ASSERT(r, c.fA == 1.0f);
1354 }
1355 
test_RuntimeEffectStructNameReuse(skiatest::Reporter * r,GrRecordingContext * rContext)1356 static void test_RuntimeEffectStructNameReuse(skiatest::Reporter* r, GrRecordingContext* rContext) {
1357     // Test that two different runtime effects can reuse struct names in a single paint operation
1358     auto [childEffect, err] = SkRuntimeEffect::MakeForShader(SkString(
1359         "uniform shader paint;"
1360         "struct S { half4 rgba; };"
1361         "void process(inout S s) { s.rgba.rgb *= 0.5; }"
1362         "half4 main(float2 p) { S s; s.rgba = paint.eval(p); process(s); return s.rgba; }"
1363     ));
1364     REPORTER_ASSERT(r, childEffect, "%s\n", err.c_str());
1365     sk_sp<SkShader> sourceColor = SkShaders::Color({0.99608f, 0.50196f, 0.0f, 1.0f}, nullptr);
1366     const GrColor kExpected = 0xFF00407F;
1367     sk_sp<SkShader> child = childEffect->makeShader(/*uniforms=*/nullptr,
1368                                                     &sourceColor,
1369                                                     /*childCount=*/1);
1370 
1371     TestEffect effect(r, /*grContext=*/nullptr, /*graphite=*/nullptr);
1372     effect.build(
1373             "uniform shader child;"
1374             "struct S { float2 coord; };"
1375             "void process(inout S s) { s.coord = s.coord.yx; }"
1376             "half4 main(float2 p) { S s; s.coord = p; process(s); return child.eval(s.coord); "
1377             "}");
1378     effect.child("child") = child;
1379     effect.test(kExpected, [](SkCanvas*, SkPaint* paint) {});
1380 }
1381 
DEF_TEST(SkRuntimeStructNameReuse,r)1382 DEF_TEST(SkRuntimeStructNameReuse, r) {
1383     test_RuntimeEffectStructNameReuse(r, nullptr);
1384 }
1385 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeStructNameReuse_GPU,r,ctxInfo,CtsEnforcement::kApiLevel_T)1386 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SkRuntimeStructNameReuse_GPU,
1387                                        r,
1388                                        ctxInfo,
1389                                        CtsEnforcement::kApiLevel_T) {
1390     test_RuntimeEffectStructNameReuse(r, ctxInfo.directContext());
1391 }
1392 
DEF_TEST(SkRuntimeColorFilterFlags,r)1393 DEF_TEST(SkRuntimeColorFilterFlags, r) {
1394     auto expectAlphaUnchanged = [&](const char* shader) {
1395         auto [effect, err] = SkRuntimeEffect::MakeForColorFilter(SkString{shader});
1396         REPORTER_ASSERT(r, effect && err.isEmpty(), "%s", shader);
1397         sk_sp<SkColorFilter> filter = effect->makeColorFilter(SkData::MakeEmpty());
1398         REPORTER_ASSERT(r, filter && filter->isAlphaUnchanged(), "%s", shader);
1399     };
1400 
1401     auto expectAlphaChanged = [&](const char* shader) {
1402         auto [effect, err] = SkRuntimeEffect::MakeForColorFilter(SkString{shader});
1403         REPORTER_ASSERT(r, effect && err.isEmpty(), "%s", shader);
1404         sk_sp<SkColorFilter> filter = effect->makeColorFilter(SkData::MakeEmpty());
1405         REPORTER_ASSERT(r, filter && !filter->isAlphaUnchanged(), "%s", shader);
1406     };
1407 
1408     // We expect these patterns to be detected as alpha-unchanged.
1409     expectAlphaUnchanged("half4 main(half4 color) { return color; }");
1410     expectAlphaUnchanged("half4 main(half4 color) { return color.aaaa; }");
1411     expectAlphaUnchanged("half4 main(half4 color) { return color.bgra; }");
1412     expectAlphaUnchanged("half4 main(half4 color) { return color.rraa; }");
1413     expectAlphaUnchanged("half4 main(half4 color) { return color.010a; }");
1414     expectAlphaUnchanged("half4 main(half4 color) { return half4(0, 0, 0, color.a); }");
1415     expectAlphaUnchanged("half4 main(half4 color) { return half4(half2(1), color.ba); }");
1416     expectAlphaUnchanged("half4 main(half4 color) { return half4(half2(1), half2(color.a)); }");
1417     expectAlphaUnchanged("half4 main(half4 color) { return half4(color.a); }");
1418     expectAlphaUnchanged("half4 main(half4 color) { return half4(float4(color.baba)); }");
1419     expectAlphaUnchanged("half4 main(half4 color) { return color.r != color.g ? color :"
1420                                                                               " color.000a; }");
1421     expectAlphaUnchanged("half4 main(half4 color) { return color.a == color.r ? color.rrra : "
1422                                                           "color.g == color.b ? color.ggga : "
1423                                                                             "   color.bbba; }");
1424     // Modifying the input color invalidates the check.
1425     expectAlphaChanged("half4 main(half4 color) { color.a = 0; return color; }");
1426 
1427     // These swizzles don't end in alpha.
1428     expectAlphaChanged("half4 main(half4 color) { return color.argb; }");
1429     expectAlphaChanged("half4 main(half4 color) { return color.rrrr; }");
1430 
1431     // This compound constructor doesn't end in alpha.
1432     expectAlphaChanged("half4 main(half4 color) { return half4(1, 1, 1, color.r); }");
1433 
1434     // This splat constructor doesn't use alpha.
1435     expectAlphaChanged("half4 main(half4 color) { return half4(color.r); }");
1436 
1437     // These ternaries don't return alpha on both sides
1438     expectAlphaChanged("half4 main(half4 color) { return color.a > 0 ? half4(0) : color; }");
1439     expectAlphaChanged("half4 main(half4 color) { return color.g < 1 ? color.bgra : color.abgr; }");
1440     expectAlphaChanged("half4 main(half4 color) { return color.b > 0.5 ? half4(0) : half4(1); }");
1441 
1442     // Performing arithmetic on the input causes it to report as "alpha changed" even if the
1443     // arithmetic is a no-op; we aren't smart enough to see through it.
1444     expectAlphaChanged("half4 main(half4 color) { return color + half4(1,1,1,0); }");
1445     expectAlphaChanged("half4 main(half4 color) { return color + half4(0,0,0,4); }");
1446 
1447     // All exit paths are checked.
1448     expectAlphaChanged("half4 main(half4 color) { "
1449                        "    if (color.r > 0.5) { return color; }"
1450                        "    return half4(0);"
1451                        "}");
1452     expectAlphaChanged("half4 main(half4 color) { "
1453                        "    if (color.r > 0.5) { return half4(0); }"
1454                        "    return color;"
1455                        "}");
1456 }
1457 
DEF_TEST(SkRuntimeShaderSampleCoords,r)1458 DEF_TEST(SkRuntimeShaderSampleCoords, r) {
1459     // This test verifies that we detect calls to sample where the coords are the same as those
1460     // passed to main. In those cases, it's safe to turn the "explicit" sampling into "passthrough"
1461     // sampling. This optimization is implemented very conservatively.
1462     //
1463     // It also checks that we correctly set the "referencesSampleCoords" bit on the runtime effect
1464     // FP, depending on how the coords parameter to main is used.
1465 
1466     auto test = [&](const char* src, bool expectExplicit, bool expectReferencesSampleCoords) {
1467         auto [effect, err] =
1468                 SkRuntimeEffect::MakeForShader(SkStringPrintf("uniform shader child; %s", src));
1469         REPORTER_ASSERT(r, effect);
1470 
1471         auto child = GrFragmentProcessor::MakeColor({ 1, 1, 1, 1 });
1472         auto fp = GrSkSLFP::Make(effect.get(), "test_fp", /*inputFP=*/nullptr,
1473                                  GrSkSLFP::OptFlags::kNone, "child", std::move(child));
1474         REPORTER_ASSERT(r, fp);
1475 
1476         REPORTER_ASSERT(r, fp->childProcessor(0)->sampleUsage().isExplicit() == expectExplicit);
1477         REPORTER_ASSERT(r, fp->usesSampleCoords() == expectReferencesSampleCoords);
1478     };
1479 
1480     // Cases where our optimization is valid, and works:
1481 
1482     // Direct use of passed-in coords. Here, the only use of sample coords is for a sample call
1483     // converted to passthrough, so referenceSampleCoords is *false*, despite appearing in main.
1484     test("half4 main(float2 xy) { return child.eval(xy); }", false, false);
1485     // Sample with passed-in coords, read (but don't write) sample coords elsewhere
1486     test("half4 main(float2 xy) { return child.eval(xy) + sin(xy.x); }", false, true);
1487 
1488     // Cases where our optimization is not valid, and does not happen:
1489 
1490     // Sampling with values completely unrelated to passed-in coords
1491     test("half4 main(float2 xy) { return child.eval(float2(0, 0)); }", true, false);
1492     // Use of expression involving passed in coords
1493     test("half4 main(float2 xy) { return child.eval(xy * 0.5); }", true, true);
1494     // Use of coords after modification
1495     test("half4 main(float2 xy) { xy *= 2; return child.eval(xy); }", true, true);
1496     // Use of coords after modification via out-param call
1497     test("void adjust(inout float2 xy) { xy *= 2; }"
1498          "half4 main(float2 xy) { adjust(xy); return child.eval(xy); }", true, true);
1499 
1500     // There should (must) not be any false-positive cases. There are false-negatives.
1501     // In all of these cases, our optimization would be valid, but does not happen:
1502 
1503     // Direct use of passed-in coords, modified after use
1504     test("half4 main(float2 xy) { half4 c = child.eval(xy); xy *= 2; return c; }", true, true);
1505     // Passed-in coords copied to a temp variable
1506     test("half4 main(float2 xy) { float2 p = xy; return child.eval(p); }", true, true);
1507     // Use of coords passed to helper function
1508     test("half4 helper(float2 xy) { return child.eval(xy); }"
1509          "half4 main(float2 xy) { return helper(xy); }", true, true);
1510 }
1511 
DEF_TEST(SkRuntimeShaderIsOpaque,r)1512 DEF_TEST(SkRuntimeShaderIsOpaque, r) {
1513     // This test verifies that we detect certain simple patterns in runtime shaders, and can deduce
1514     // (via code in SkSL::Analysis::ReturnsOpaqueColor) that the resulting shader is always opaque.
1515     // That logic is conservative, and the tests below reflect this.
1516 
1517     auto test = [&](const char* body, bool expectOpaque) {
1518         auto [effect, err] = SkRuntimeEffect::MakeForShader(SkStringPrintf(R"(
1519             uniform shader cOnes;
1520             uniform shader cZeros;
1521             uniform float4 uOnes;
1522             uniform float4 uZeros;
1523             half4 main(float2 xy) {
1524                 %s
1525             })", body));
1526         REPORTER_ASSERT(r, effect);
1527 
1528         auto cOnes = SkShaders::Color(SK_ColorWHITE);
1529         auto cZeros = SkShaders::Color(SK_ColorTRANSPARENT);
1530         SkASSERT(cOnes->isOpaque());
1531         SkASSERT(!cZeros->isOpaque());
1532 
1533         SkRuntimeShaderBuilder builder(effect);
1534         builder.child("cOnes") = std::move(cOnes);
1535         builder.child("cZeros") = std::move(cZeros);
1536         builder.uniform("uOnes") = SkColors::kWhite;
1537         builder.uniform("uZeros") = SkColors::kTransparent;
1538 
1539         auto shader = builder.makeShader();
1540         REPORTER_ASSERT(r, shader->isOpaque() == expectOpaque);
1541     };
1542 
1543     // Cases where our optimization is valid, and works:
1544 
1545     // Returning opaque literals
1546     test("return half4(1);",          true);
1547     test("return half4(0, 1, 0, 1);", true);
1548     test("return half4(0, 0, 0, 1);", true);
1549 
1550     // Simple expressions involving uniforms
1551     test("return uZeros.rgb1;",          true);
1552     test("return uZeros.bgra.rgb1;",     true);
1553     test("return half4(uZeros.rgb, 1);", true);
1554 
1555     // Simple expressions involving child.eval
1556     test("return cZeros.eval(xy).rgb1;",          true);
1557     test("return cZeros.eval(xy).bgra.rgb1;",     true);
1558     test("return half4(cZeros.eval(xy).rgb, 1);", true);
1559 
1560     // Multiple returns
1561     test("if (xy.x < 100) { return uZeros.rgb1; } else { return cZeros.eval(xy).rgb1; }", true);
1562 
1563     // More expression cases:
1564     test("return (cZeros.eval(xy) * uZeros).rgb1;", true);
1565     test("return half4(1, 1, 1, 0.5 + 0.5);",       true);
1566 
1567     // Constant variable propagation
1568     test("const half4 kWhite = half4(1); return kWhite;", true);
1569 
1570     // Cases where our optimization is not valid, and does not happen:
1571 
1572     // Returning non-opaque literals
1573     test("return half4(0);",          false);
1574     test("return half4(1, 1, 1, 0);", false);
1575 
1576     // Returning non-opaque uniforms or children
1577     test("return uZeros;",          false);
1578     test("return cZeros.eval(xy);", false);
1579 
1580     // Multiple returns
1581     test("if (xy.x < 100) { return uZeros; } else { return cZeros.eval(xy).rgb1; }", false);
1582     test("if (xy.x < 100) { return uZeros.rgb1; } else { return cZeros.eval(xy); }", false);
1583 
1584     // There should (must) not be any false-positive cases. There are false-negatives.
1585     // In these cases, our optimization would be valid, but does not happen:
1586 
1587     // More complex expressions that can't be simplified
1588     test("return xy.x < 100 ? uZeros.rgb1 : cZeros.eval(xy).rgb1;", false);
1589 
1590     // Finally, there are cases that are conditional on the uniforms and children. These *could*
1591     // determine dynamically if the uniform and/or child being referenced is opaque, and use that
1592     // information. Today, we don't do this, so we pessimistically assume they're transparent:
1593     test("return uOnes;",          false);
1594     test("return cOnes.eval(xy);", false);
1595 }
1596 
DEF_GANESH_TEST_FOR_ALL_CONTEXTS(GrSkSLFP_Specialized,r,ctxInfo,CtsEnforcement::kApiLevel_T)1597 DEF_GANESH_TEST_FOR_ALL_CONTEXTS(GrSkSLFP_Specialized, r, ctxInfo, CtsEnforcement::kApiLevel_T) {
1598     struct FpAndKey {
1599         std::unique_ptr<GrFragmentProcessor> fp;
1600         TArray<uint32_t, true>             key;
1601     };
1602 
1603     // Constant color, but with an 'specialize' option that decides if the color is inserted in the
1604     // SkSL as a literal, or left as a uniform
1605     auto make_color_fp = [&](SkPMColor4f color, bool specialize) {
1606         static const SkRuntimeEffect* effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader,
1607             "uniform half4 color;"
1608             "half4 main(float2 xy) { return color; }"
1609         );
1610         FpAndKey result;
1611         result.fp = GrSkSLFP::Make(effect, "color_fp", /*inputFP=*/nullptr,
1612                                    GrSkSLFP::OptFlags::kNone,
1613                                    "color", GrSkSLFP::SpecializeIf(specialize, color));
1614         skgpu::KeyBuilder builder(&result.key);
1615         result.fp->addToKey(*ctxInfo.directContext()->priv().caps()->shaderCaps(), &builder);
1616         builder.flush();
1617         return result;
1618     };
1619 
1620     FpAndKey uRed   = make_color_fp({1, 0, 0, 1}, false),
1621              uGreen = make_color_fp({0, 1, 0, 1}, false),
1622              sRed   = make_color_fp({1, 0, 0, 1}, true),
1623              sGreen = make_color_fp({0, 1, 0, 1}, true);
1624 
1625     // uRed and uGreen should have the same key - they just have different uniforms
1626     SkASSERT(uRed.key == uGreen.key);
1627     // sRed and sGreen should have keys that are different from the uniform case, and each other
1628     SkASSERT(sRed.key != uRed.key);
1629     SkASSERT(sGreen.key != uRed.key);
1630     SkASSERT(sRed.key != sGreen.key);
1631 }
1632 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(GrSkSLFP_UniformArray,r,ctxInfo,CtsEnforcement::kApiLevel_T)1633 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(GrSkSLFP_UniformArray,
1634                                        r,
1635                                        ctxInfo,
1636                                        CtsEnforcement::kApiLevel_T) {
1637     // Make a fill-context to draw into.
1638     GrDirectContext* directContext = ctxInfo.directContext();
1639     SkImageInfo info = SkImageInfo::Make(1, 1, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
1640     std::unique_ptr<skgpu::ganesh::SurfaceFillContext> testCtx =
1641             directContext->priv().makeSFC(info, /*label=*/{}, SkBackingFit::kExact);
1642 
1643     // Make an effect that takes a uniform array as input.
1644     static constexpr std::array<float, 4> kRed  {1.0f, 0.0f, 0.0f, 1.0f};
1645     static constexpr std::array<float, 4> kGreen{0.0f, 1.0f, 0.0f, 1.0f};
1646     static constexpr std::array<float, 4> kBlue {0.0f, 0.0f, 1.0f, 1.0f};
1647     static constexpr std::array<float, 4> kGray {0.499f, 0.499f, 0.499f, 1.0f};
1648 
1649     for (const auto& colorArray : {kRed, kGreen, kBlue, kGray}) {
1650         // Compile our runtime effect.
1651         static const SkRuntimeEffect* effect = SkMakeRuntimeEffect(SkRuntimeEffect::MakeForShader,
1652             "uniform half color[4];"
1653             "half4 main(float2 xy) { return half4(color[0], color[1], color[2], color[3]); }"
1654         );
1655         // Render our shader into the fill-context with our various input colors.
1656         testCtx->fillWithFP(GrSkSLFP::Make(effect, "test_fp", /*inputFP=*/nullptr,
1657                                            GrSkSLFP::OptFlags::kNone,
1658                                            "color", SkSpan(colorArray)));
1659         // Read our color back and ensure it matches.
1660         GrColor actual;
1661         GrPixmap pixmap(info, &actual, sizeof(GrColor));
1662         if (!testCtx->readPixels(directContext, pixmap, /*srcPt=*/{0, 0})) {
1663             REPORT_FAILURE(r, "readPixels", SkString("readPixels failed"));
1664             break;
1665         }
1666         if (actual != GrColorPackRGBA(255 * colorArray[0], 255 * colorArray[1],
1667                                       255 * colorArray[2], 255 * colorArray[3])) {
1668             REPORT_FAILURE(r, "Uniform array didn't match expectations",
1669                            SkStringPrintf("\n"
1670                                           "Expected: [ %g %g %g %g ]\n"
1671                                           "Got     : [ %08x ]\n",
1672                                           colorArray[0], colorArray[1],
1673                                           colorArray[2], colorArray[3],
1674                                           actual));
1675             break;
1676         }
1677     }
1678 }
1679