Expose the Input variable and Child name collections in SkRuntimeEffect

Add framework for unit tests that draw (CPU and GPU) with a runtime
shader, as well as couple example tests.

Change-Id: I43b3b39e86634ec55521a2689a4c55c21939dce5
Reviewed-on: https://skia-review.googlesource.com/c/skia/+/262809
Reviewed-by: Brian Salomon <bsalomon@google.com>
Commit-Queue: Brian Osman <brianosman@google.com>
diff --git a/include/effects/SkRuntimeEffect.h b/include/effects/SkRuntimeEffect.h
index fae4e3c..5a39edc 100644
--- a/include/effects/SkRuntimeEffect.h
+++ b/include/effects/SkRuntimeEffect.h
@@ -86,8 +86,25 @@
 
     const SkString& source() const { return fSkSL; }
     int index() const { return fIndex; }
+
+    template <typename T>
+    class ConstIterable {
+    public:
+        ConstIterable(const std::vector<T>& vec) : fVec(vec) {}
+
+        using const_iterator = typename std::vector<T>::const_iterator;
+
+        const_iterator begin() const { return fVec.begin(); }
+        const_iterator end() const { return fVec.end(); }
+        size_t count() const { return fVec.size(); }
+
+    private:
+        const std::vector<T>& fVec;
+    };
+
     size_t inputSize() const;
-    size_t childCount() const { return fChildren.size(); }
+    ConstIterable<Variable> inputs() const { return ConstIterable<Variable>(fInAndUniformVars); }
+    ConstIterable<SkString> children() const { return ConstIterable<SkString>(fChildren); }
 
 #if SK_SUPPORT_GPU
     // This re-compiles the program from scratch, using the supplied shader caps.
@@ -114,10 +131,6 @@
     std::unique_ptr<SkSL::Program> fBaseProgram;
     std::vector<Variable> fInAndUniformVars;
     std::vector<SkString> fChildren;
-
-    friend class GrGLSLSkSLFP;
-    friend class GrSkSLFP;
-    friend class SkSLSlide;
 };
 
 #endif
diff --git a/src/core/SkRuntimeEffect.cpp b/src/core/SkRuntimeEffect.cpp
index b177b7c..17b1ce9 100644
--- a/src/core/SkRuntimeEffect.cpp
+++ b/src/core/SkRuntimeEffect.cpp
@@ -279,7 +279,7 @@
 sk_sp<SkShader> SkRuntimeEffect::makeShader(sk_sp<SkData> inputs,
                                             sk_sp<SkShader> children[], size_t childCount,
                                             const SkMatrix* localMatrix, bool isOpaque) {
-    return inputs && inputs->size() >= this->inputSize() && childCount >= this->childCount()
+    return inputs && inputs->size() >= this->inputSize() && childCount >= fChildren.size()
         ? sk_sp<SkShader>(new SkRTShader(sk_ref_sp(this), std::move(inputs), localMatrix,
                                          children, childCount, isOpaque))
         : nullptr;
diff --git a/src/gpu/effects/GrSkSLFP.cpp b/src/gpu/effects/GrSkSLFP.cpp
index 6d12d17..a995b0b 100644
--- a/src/gpu/effects/GrSkSLFP.cpp
+++ b/src/gpu/effects/GrSkSLFP.cpp
@@ -85,7 +85,7 @@
 
     void emitCode(EmitArgs& args) override {
         const GrSkSLFP& fp = args.fFp.cast<GrSkSLFP>();
-        for (const auto& v : fp.fEffect->fInAndUniformVars) {
+        for (const auto& v : fp.fEffect->inputs()) {
             if (v.fQualifier == SkRuntimeEffect::Variable::Qualifier::kUniform) {
                 auto handle = args.fUniformHandler->addUniformArray(kFragment_GrShaderFlag,
                                                                     v.fGPUType,
@@ -123,7 +123,7 @@
         size_t uniIndex = 0;
         const GrSkSLFP& outer = _proc.cast<GrSkSLFP>();
         char* inputs = (char*) outer.fInputs.get();
-        for (const auto& v : outer.fEffect->fInAndUniformVars) {
+        for (const auto& v : outer.fEffect->inputs()) {
             if (v.fQualifier != SkRuntimeEffect::Variable::Qualifier::kUniform) {
                 continue;
             }
@@ -226,7 +226,7 @@
 void GrSkSLFP::onGetGLSLProcessorKey(const GrShaderCaps& caps, GrProcessorKeyBuilder* b) const {
     b->add32(fEffect->index());
     char* inputs = (char*) fInputs.get();
-    for (const auto& v : fEffect->fInAndUniformVars) {
+    for (const auto& v : fEffect->inputs()) {
         if (v.fQualifier != SkRuntimeEffect::Variable::Qualifier::kIn) {
             continue;
         }
diff --git a/tests/SkRuntimeEffectTest.cpp b/tests/SkRuntimeEffectTest.cpp
index 45ba89a..ed017af 100644
--- a/tests/SkRuntimeEffectTest.cpp
+++ b/tests/SkRuntimeEffectTest.cpp
@@ -5,13 +5,19 @@
  * found in the LICENSE file.
  */
 
+#include "include/core/SkCanvas.h"
+#include "include/core/SkPaint.h"
+#include "include/core/SkSurface.h"
 #include "include/effects/SkRuntimeEffect.h"
+#include "include/gpu/GrContext.h"
 #include "tests/Test.h"
 
+#include <algorithm>
+
 DEF_TEST(SkRuntimeEffectInvalidInputs, r) {
     auto test = [r](const char* hdr, const char* expected) {
         SkString src = SkStringPrintf("%s void main(float x, float y, inout half4 color) {}", hdr);
-        auto [effect, errorText] = SkRuntimeEffect::Make(src);
+        auto[effect, errorText] = SkRuntimeEffect::Make(src);
         REPORTER_ASSERT(r, !effect);
         REPORTER_ASSERT(r, errorText.contains(expected),
                         "Expected error message to contain \"%s\". Actual message: \"%s\"",
@@ -42,3 +48,114 @@
     test("in float2 Input;", "'in'");
     test("in half3x3 Input;", "'in'");
 }
+
+// Our packing rules and unit test code here relies on this:
+static_assert(sizeof(bool) == 1);
+
+class TestEffect {
+public:
+    TestEffect(skiatest::Reporter* r, const char* hdr, const char* body) {
+        SkString src = SkStringPrintf("%s void main(float x, float y, inout half4 color) { %s }",
+                                      hdr, body);
+        auto[effect, errorText] = SkRuntimeEffect::Make(src);
+        if (!effect) {
+            REPORT_FAILURE(r, "effect",
+                           SkStringPrintf("Effect didn't compile: %s", errorText.c_str()));
+            return;
+        }
+
+        fEffect = std::move(effect);
+        fInputs = SkData::MakeUninitialized(fEffect->inputSize());
+    }
+
+    struct InputVar {
+        template <typename T> InputVar& operator=(const T& val) {
+            SkASSERT(sizeof(T) == fVar.sizeInBytes());
+            memcpy(SkTAddOffset<void>(fOwner->fInputs->writable_data(), fVar.fOffset), &val,
+                   sizeof(T));
+            return *this;
+        }
+        TestEffect* fOwner;
+        const SkRuntimeEffect::Variable& fVar;
+    };
+
+    InputVar operator[](const char* name) {
+        auto input = std::find_if(fEffect->inputs().begin(), fEffect->inputs().end(),
+                                  [name](const auto& v) { return v.fName.equals(name); });
+        SkASSERT(input != fEffect->inputs().end());
+        return {this, *input};
+    }
+
+    void test(skiatest::Reporter* r, sk_sp<SkSurface> surface,
+              uint32_t TL, uint32_t TR, uint32_t BL, uint32_t BR) {
+        if (!fEffect) { return; }
+
+        auto shader = fEffect->makeShader(fInputs, nullptr, 0, nullptr, false);
+        if (!shader) {
+            REPORT_FAILURE(r, "shader", SkString("Effect didn't produce a shader"));
+            return;
+        }
+
+        SkPaint paint;
+        paint.setShader(std::move(shader));
+        paint.setBlendMode(SkBlendMode::kSrc);
+        surface->getCanvas()->drawPaint(paint);
+
+        uint32_t actual[4];
+        SkImageInfo info = surface->imageInfo();
+        if (!surface->readPixels(info, actual, info.minRowBytes(), 0, 0)) {
+            REPORT_FAILURE(r, "readPixels", SkString("readPixels failed"));
+            return;
+        }
+
+        uint32_t expected[4] = {TL, TR, BL, BR};
+        if (memcmp(actual, expected, sizeof(actual)) != 0) {
+            REPORT_FAILURE(r, "Runtime effect didn't match expectations",
+                           SkStringPrintf("\n"
+                                          "Expected: [ %08x %08x %08x %08x ]\n"
+                                          "Got     : [ %08x %08x %08x %08x ]\n"
+                                          "SkSL:\n%s\n",
+                                          TL, TR, BL, BR, actual[0], actual[1], actual[2],
+                                          actual[3], fEffect->source().c_str()));
+        }
+    }
+
+    void test(skiatest::Reporter* r, sk_sp<SkSurface> surface, uint32_t expected) {
+        this->test(r, surface, expected, expected, expected, expected);
+    }
+
+private:
+    sk_sp<SkRuntimeEffect> fEffect;
+    sk_sp<SkData> fInputs;
+};
+
+static void test_RuntimeEffect_Shaders(skiatest::Reporter* r, GrContext* context) {
+    SkImageInfo info = SkImageInfo::Make(2, 2, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
+    sk_sp<SkSurface> surface;
+    if (context) {
+        surface = SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info);
+    } else {
+        surface = SkSurface::MakeRaster(info);
+    }
+    REPORTER_ASSERT(r, surface);
+
+    TestEffect xy(r, "", "color = half4(half(x - 0.5), half(y - 0.5), 0, 1);");
+    xy.test(r, surface, 0xFF000000, 0xFF0000FF, 0xFF00FF00, 0xFF00FFFF);
+
+    // NOTE: For now, we always emit valid premul colors, until CPU and GPU agree on clamping
+    TestEffect uniformColor(r, "uniform float4 gColor;", "color = half4(gColor);");
+
+    uniformColor["gColor"] = std::array<float, 4>{ 0.0f, 0.25f, 0.75f, 1.0f };
+    uniformColor.test(r, surface, 0xFFBF4000);
+
+    uniformColor["gColor"] = std::array<float, 4>{ 0.75f, 0.25f, 0.0f, 1.0f };
+    uniformColor.test(r, surface, 0xFF0040BF);
+}
+
+DEF_TEST(SkRuntimeEffectSimple, r) {
+    test_RuntimeEffect_Shaders(r, nullptr);
+}
+
+DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SkRuntimeEffectSimple_GPU, r, ctxInfo) {
+    test_RuntimeEffect_Shaders(r, ctxInfo.grContext());
+}
diff --git a/tools/viewer/SkSLSlide.cpp b/tools/viewer/SkSLSlide.cpp
index 4fcca64..c2ca079 100644
--- a/tools/viewer/SkSLSlide.cpp
+++ b/tools/viewer/SkSLSlide.cpp
@@ -83,7 +83,7 @@
     if (effect->inputSize() > oldSize) {
         memset(fInputs.get() + oldSize, 0, effect->inputSize() - oldSize);
     }
-    fChildren.resize_back(effect->fChildren.size());
+    fChildren.resize_back(effect->children().count());
     for (auto& c : fChildren) {
         if (!c) {
             c = fShaders[0].second;
@@ -112,7 +112,7 @@
         return;
     }
 
-    for (const auto& v : fEffect->fInAndUniformVars) {
+    for (const auto& v : fEffect->inputs()) {
         switch (v.fType) {
             case SkRuntimeEffect::Variable::Type::kBool:
                 ImGui::Checkbox(v.fName.c_str(), (bool*)(fInputs.get() + v.fOffset));
@@ -154,7 +154,7 @@
         }
     }
 
-    for (const auto [i, name] : SkMakeEnumerate(fEffect->fChildren)) {
+    for (const auto [i, name] : SkMakeEnumerate(fEffect->children())) {
         auto curShader = std::find_if(fShaders.begin(), fShaders.end(),
                                       [tgt = fChildren[i]](auto p) { return p.second == tgt; });
         SkASSERT(curShader!= fShaders.end());