blob: 89557e54f1023e5adb53df41a924900e0dcd2ea7 [file] [log] [blame]
Brian Salomonbc6b99d2017-01-11 10:32:34 -05001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "tests/Test.h"
Brian Salomonbc6b99d2017-01-11 10:32:34 -05009
Robert Phillips6d344c32020-07-06 10:56:46 -040010#include "include/gpu/GrDirectContext.h"
Greg Daniel6f5441a2020-01-28 17:02:49 -050011#include "src/gpu/GrBitmapTextureMaker.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050012#include "src/gpu/GrClip.h"
Adlai Hollera0693042020-10-14 11:23:11 -040013#include "src/gpu/GrDirectContextPriv.h"
Greg Daniel456f9b52020-03-05 19:14:18 +000014#include "src/gpu/GrGpuResource.h"
Brian Salomonf2ebdd92019-09-30 12:15:30 -040015#include "src/gpu/GrImageInfo.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050016#include "src/gpu/GrMemoryPool.h"
17#include "src/gpu/GrProxyProvider.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050018#include "src/gpu/GrResourceProvider.h"
Brian Salomoneebe7352020-12-09 16:37:04 -050019#include "src/gpu/GrSurfaceDrawContext.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050020#include "src/gpu/glsl/GrGLSLFragmentProcessor.h"
21#include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
22#include "src/gpu/ops/GrFillRectOp.h"
23#include "src/gpu/ops/GrMeshDrawOp.h"
24#include "tests/TestUtils.h"
Brian Salomoneebe7352020-12-09 16:37:04 -050025
Mike Klein0ec1c572018-12-04 11:52:51 -050026#include <atomic>
Hal Canary8a001442018-09-19 11:31:27 -040027#include <random>
28
Brian Salomonbc6b99d2017-01-11 10:32:34 -050029namespace {
Brian Salomon82ddc942017-07-14 12:00:13 -040030class TestOp : public GrMeshDrawOp {
Brian Salomonbc6b99d2017-01-11 10:32:34 -050031public:
32 DEFINE_OP_CLASS_ID
Herb Derbyc76d4092020-10-07 16:46:15 -040033 static GrOp::Owner Make(GrRecordingContext* rContext,
34 std::unique_ptr<GrFragmentProcessor> fp) {
35 return GrOp::Make<TestOp>(rContext, std::move(fp));
Brian Salomon82ddc942017-07-14 12:00:13 -040036 }
37
Robert Phillips5f567c72017-09-14 08:27:37 -040038 const char* name() const override { return "TestOp"; }
39
Chris Dalton1706cbf2019-05-21 19:35:29 -060040 void visitProxies(const VisitProxyFunc& func) const override {
Robert Phillips5f567c72017-09-14 08:27:37 -040041 fProcessors.visitProxies(func);
42 }
43
Brian Salomon82ddc942017-07-14 12:00:13 -040044 FixedFunctionFlags fixedFunctionFlags() const override { return FixedFunctionFlags::kNone; }
45
Chris Dalton6ce447a2019-06-23 18:07:38 -060046 GrProcessorSet::Analysis finalize(
47 const GrCaps& caps, const GrAppliedClip* clip, bool hasMixedSampledCoverage,
48 GrClampType clampType) override {
Brian Salomon82ddc942017-07-14 12:00:13 -040049 static constexpr GrProcessorAnalysisColor kUnknownColor;
Brian Osmancf860852018-10-31 14:04:39 -040050 SkPMColor4f overrideColor;
Chris Daltonb8fff0d2019-03-05 10:11:58 -070051 return fProcessors.finalize(
52 kUnknownColor, GrProcessorAnalysisCoverage::kNone, clip,
Chris Dalton6ce447a2019-06-23 18:07:38 -060053 &GrUserStencilSettings::kUnused, hasMixedSampledCoverage, caps, clampType,
54 &overrideColor);
Brian Salomon649a3412017-03-09 13:50:43 -050055 }
Brian Salomonbc6b99d2017-01-11 10:32:34 -050056
57private:
Herb Derbyc76d4092020-10-07 16:46:15 -040058 friend class ::GrOp; // for ctor
Robert Phillips7c525e62018-06-12 10:11:12 -040059
Brian Salomonaff329b2017-08-11 09:40:37 -040060 TestOp(std::unique_ptr<GrFragmentProcessor> fp)
61 : INHERITED(ClassID()), fProcessors(std::move(fp)) {
Greg Daniel5faf4742019-10-01 15:14:44 -040062 this->setBounds(SkRect::MakeWH(100, 100), HasAABloat::kNo, IsHairline::kNo);
Brian Salomon82ddc942017-07-14 12:00:13 -040063 }
Brian Salomonbc6b99d2017-01-11 10:32:34 -050064
Robert Phillips2669a7b2020-03-12 12:07:19 -040065 GrProgramInfo* programInfo() override { return nullptr; }
Robert Phillips4133dc42020-03-11 15:55:55 -040066 void onCreateProgramInfo(const GrCaps*,
67 SkArenaAlloc*,
Adlai Hollere2296f72020-11-19 13:41:26 -050068 const GrSurfaceProxyView& writeView,
Robert Phillips4133dc42020-03-11 15:55:55 -040069 GrAppliedClip&&,
Greg Danield358cbe2020-09-11 09:33:54 -040070 const GrXferProcessor::DstProxyView&,
Greg Daniel42dbca52020-11-20 10:22:43 -050071 GrXferBarrierFlags renderPassXferBarriers,
72 GrLoadOp colorLoadOp) override {}
Robert Phillips2669a7b2020-03-12 12:07:19 -040073 void onPrePrepareDraws(GrRecordingContext*,
Adlai Hollere2296f72020-11-19 13:41:26 -050074 const GrSurfaceProxyView& writeView,
Robert Phillips2669a7b2020-03-12 12:07:19 -040075 GrAppliedClip*,
Greg Danield358cbe2020-09-11 09:33:54 -040076 const GrXferProcessor::DstProxyView&,
Greg Daniel42dbca52020-11-20 10:22:43 -050077 GrXferBarrierFlags renderPassXferBarriers,
78 GrLoadOp colorLoadOp) override {}
Brian Salomon91326c32017-08-09 16:02:19 -040079 void onPrepareDraws(Target* target) override { return; }
Chris Dalton07cdcfc92019-02-26 11:13:22 -070080 void onExecute(GrOpFlushState*, const SkRect&) override { return; }
Brian Salomonbc6b99d2017-01-11 10:32:34 -050081
Brian Salomon82ddc942017-07-14 12:00:13 -040082 GrProcessorSet fProcessors;
83
John Stiles7571f9e2020-09-02 22:42:33 -040084 using INHERITED = GrMeshDrawOp;
Brian Salomonbc6b99d2017-01-11 10:32:34 -050085};
86
87/**
Robert Phillips3d4cac52019-06-11 08:08:08 -040088 * FP used to test ref counts on owned GrGpuResources. Can also be a parent FP to test counts
Brian Salomonbc6b99d2017-01-11 10:32:34 -050089 * of resources owned by child FPs.
90 */
91class TestFP : public GrFragmentProcessor {
92public:
Brian Salomonaff329b2017-08-11 09:40:37 -040093 static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> child) {
94 return std::unique_ptr<GrFragmentProcessor>(new TestFP(std::move(child)));
Brian Salomonbc6b99d2017-01-11 10:32:34 -050095 }
Brian Salomon92b9ccf2020-06-17 14:19:19 -040096 static std::unique_ptr<GrFragmentProcessor> Make(const SkTArray<GrSurfaceProxyView>& views) {
97 return std::unique_ptr<GrFragmentProcessor>(new TestFP(views));
Brian Salomonbc6b99d2017-01-11 10:32:34 -050098 }
99
100 const char* name() const override { return "test"; }
101
102 void onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const override {
Mike Klein0ec1c572018-12-04 11:52:51 -0500103 static std::atomic<int32_t> nextKey{0};
104 b->add32(nextKey++);
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500105 }
106
Brian Salomonaff329b2017-08-11 09:40:37 -0400107 std::unique_ptr<GrFragmentProcessor> clone() const override {
108 return std::unique_ptr<GrFragmentProcessor>(new TestFP(*this));
Brian Salomonb17e6392017-07-28 13:41:51 -0400109 }
110
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500111private:
Brian Salomon92b9ccf2020-06-17 14:19:19 -0400112 TestFP(const SkTArray<GrSurfaceProxyView>& views)
113 : INHERITED(kTestFP_ClassID, kNone_OptimizationFlags) {
John Stilesfe7aed62020-07-20 13:48:02 -0400114 for (const GrSurfaceProxyView& view : views) {
Michael Ludwig9aba6252020-06-22 14:46:36 -0400115 this->registerChild(GrTextureEffect::Make(view, kUnknown_SkAlphaType));
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500116 }
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500117 }
118
Brian Salomonaff329b2017-08-11 09:40:37 -0400119 TestFP(std::unique_ptr<GrFragmentProcessor> child)
Brian Salomon92b9ccf2020-06-17 14:19:19 -0400120 : INHERITED(kTestFP_ClassID, kNone_OptimizationFlags) {
Michael Ludwig9aba6252020-06-22 14:46:36 -0400121 this->registerChild(std::move(child));
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500122 }
123
Brian Salomon92b9ccf2020-06-17 14:19:19 -0400124 explicit TestFP(const TestFP& that) : INHERITED(kTestFP_ClassID, that.optimizationFlags()) {
125 this->cloneAndRegisterAllChildProcessors(that);
Brian Salomonb17e6392017-07-28 13:41:51 -0400126 }
127
John Stiles1cf2c8d2020-08-13 22:58:04 -0400128 GrGLSLFragmentProcessor* onCreateGLSLInstance() const override {
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500129 class TestGLSLFP : public GrGLSLFragmentProcessor {
130 public:
131 TestGLSLFP() {}
132 void emitCode(EmitArgs& args) override {
Brian Osman03f9e2a2020-12-08 11:17:26 -0500133 args.fFragBuilder->codeAppendf("%s = half4(1);", args.fOutputColor);
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500134 }
135
136 private:
137 };
138 return new TestGLSLFP();
139 }
140
141 bool onIsEqual(const GrFragmentProcessor&) const override { return false; }
142
John Stiles7571f9e2020-09-02 22:42:33 -0400143 using INHERITED = GrFragmentProcessor;
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500144};
John Stilesa6841be2020-08-06 14:11:56 -0400145} // namespace
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500146
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500147DEF_GPUTEST_FOR_ALL_CONTEXTS(ProcessorRefTest, reporter, ctxInfo) {
Robert Phillips6d344c32020-07-06 10:56:46 -0400148 auto context = ctxInfo.directContext();
Robert Phillips9da87e02019-02-04 13:26:26 -0500149 GrProxyProvider* proxyProvider = context->priv().proxyProvider();
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500150
Brian Salomona56a7462020-02-07 14:17:25 -0500151 static constexpr SkISize kDims = {10, 10};
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500152
Greg Daniel4065d452018-11-16 15:43:41 -0500153 const GrBackendFormat format =
Robert Phillips0a15cc62019-07-30 12:49:10 -0400154 context->priv().caps()->getDefaultBackendFormat(GrColorType::kRGBA_8888,
155 GrRenderable::kNo);
Greg Daniel47c20e82020-01-21 14:29:57 -0500156 GrSwizzle swizzle = context->priv().caps()->getReadSwizzle(format, GrColorType::kRGBA_8888);
Greg Daniel4065d452018-11-16 15:43:41 -0500157
Brian Salomonb17e6392017-07-28 13:41:51 -0400158 for (bool makeClone : {false, true}) {
159 for (int parentCnt = 0; parentCnt < 2; parentCnt++) {
Brian Salomoneebe7352020-12-09 16:37:04 -0500160 auto renderTargetContext = GrSurfaceDrawContext::Make(
Greg Daniele20fcad2020-01-08 11:52:34 -0500161 context, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kApprox, {1, 1});
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500162 {
Robert Phillips3d4cac52019-06-11 08:08:08 -0400163 sk_sp<GrTextureProxy> proxy = proxyProvider->createProxy(
Brian Salomon7e67dca2020-07-21 09:27:25 -0400164 format, kDims, GrRenderable::kNo, 1, GrMipmapped::kNo, SkBackingFit::kExact,
Brian Salomondf1bd6d2020-03-26 20:37:01 -0400165 SkBudgeted::kYes, GrProtected::kNo);
Robert Phillips3d4cac52019-06-11 08:08:08 -0400166
Brian Salomonb17e6392017-07-28 13:41:51 -0400167 {
Greg Daniel026a60c2020-02-12 10:53:51 -0500168 SkTArray<GrSurfaceProxyView> views;
Greg Daniel026a60c2020-02-12 10:53:51 -0500169 views.push_back({proxy, kTopLeft_GrSurfaceOrigin, swizzle});
Brian Salomon92b9ccf2020-06-17 14:19:19 -0400170 auto fp = TestFP::Make(std::move(views));
Brian Salomonb17e6392017-07-28 13:41:51 -0400171 for (int i = 0; i < parentCnt; ++i) {
172 fp = TestFP::Make(std::move(fp));
173 }
Brian Salomonaff329b2017-08-11 09:40:37 -0400174 std::unique_ptr<GrFragmentProcessor> clone;
Brian Salomonb17e6392017-07-28 13:41:51 -0400175 if (makeClone) {
176 clone = fp->clone();
177 }
Herb Derbyc76d4092020-10-07 16:46:15 -0400178 GrOp::Owner op = TestOp::Make(context, std::move(fp));
Brian Salomon70fe17e2020-11-30 14:33:58 -0500179 renderTargetContext->addDrawOp(std::move(op));
Brian Salomonb17e6392017-07-28 13:41:51 -0400180 if (clone) {
Robert Phillips7c525e62018-06-12 10:11:12 -0400181 op = TestOp::Make(context, std::move(clone));
Brian Salomon70fe17e2020-11-30 14:33:58 -0500182 renderTargetContext->addDrawOp(std::move(op));
Brian Salomonb17e6392017-07-28 13:41:51 -0400183 }
184 }
Brian Salomonb17e6392017-07-28 13:41:51 -0400185
Robert Phillips3d4cac52019-06-11 08:08:08 -0400186 // If the fp is cloned the number of refs should increase by one (for the clone)
187 int expectedProxyRefs = makeClone ? 3 : 2;
188
Brian Salomon28a8f282019-10-24 20:07:39 -0400189 CheckSingleThreadedProxyRefs(reporter, proxy.get(), expectedProxyRefs, -1);
Brian Salomonb17e6392017-07-28 13:41:51 -0400190
Greg Daniel0a2464f2020-05-14 15:45:44 -0400191 context->flushAndSubmit();
Brian Salomonb17e6392017-07-28 13:41:51 -0400192
Brian Salomon557e8122019-10-24 10:37:08 -0400193 // just one from the 'proxy' sk_sp
Brian Salomon28a8f282019-10-24 20:07:39 -0400194 CheckSingleThreadedProxyRefs(reporter, proxy.get(), 1, 1);
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500195 }
196 }
197 }
198}
Brian Salomon587e08f2017-01-27 10:59:27 -0500199
Mike Kleinc0bd9f92019-04-23 12:05:21 -0500200#include "tools/flags/CommandLineFlags.h"
Mike Klein84836b72019-03-21 11:31:36 -0500201static DEFINE_bool(randomProcessorTest, false,
202 "Use non-deterministic seed for random processor tests?");
Mike Klein5b3f3432019-03-21 11:42:21 -0500203static DEFINE_int(processorSeed, 0,
204 "Use specific seed for processor tests. Overridden by --randomProcessorTest.");
Brian Salomon0e05a822017-07-25 09:43:22 -0400205
206#if GR_TEST_UTILS
207
Michael Ludwig7034f152018-10-08 16:43:58 -0400208static GrColor input_texel_color(int i, int j, SkScalar delta) {
209 // Delta must be less than 0.5 to prevent over/underflow issues with the input color
210 SkASSERT(delta <= 0.5);
Brian Salomon587e08f2017-01-27 10:59:27 -0500211
Brian Osman50ea3c02019-02-04 10:01:53 -0500212 SkColor color = SkColorSetARGB((uint8_t)(i & 0xFF),
213 (uint8_t)(j & 0xFF),
214 (uint8_t)((i + j) & 0xFF),
215 (uint8_t)((2 * j - i) & 0xFF));
Brian Osmancb3d0872018-10-16 15:19:28 -0400216 SkColor4f color4f = SkColor4f::FromColor(color);
Brian Salomonbc73eb42019-12-18 14:57:45 -0500217 // We only apply delta to the r,g, and b channels. This is because we're using this
218 // to test the canTweakAlphaForCoverage() optimization. A processor is allowed
219 // to use the input color's alpha in its calculation and report this optimization.
220 for (int i = 0; i < 3; i++) {
Brian Osmancb3d0872018-10-16 15:19:28 -0400221 if (color4f[i] > 0.5) {
222 color4f[i] -= delta;
Michael Ludwig7034f152018-10-08 16:43:58 -0400223 } else {
Brian Osmancb3d0872018-10-16 15:19:28 -0400224 color4f[i] += delta;
Michael Ludwig7034f152018-10-08 16:43:58 -0400225 }
226 }
Brian Osmancb3d0872018-10-16 15:19:28 -0400227 return color4f.premul().toBytes_RGBA();
Brian Salomon0e05a822017-07-25 09:43:22 -0400228}
Brian Salomon587e08f2017-01-27 10:59:27 -0500229
Robert Phillips58adb342020-07-23 09:41:57 -0400230void test_draw_op(GrRecordingContext* rContext,
Brian Salomoneebe7352020-12-09 16:37:04 -0500231 GrSurfaceDrawContext* rtc,
John Stiles0dee9b02020-07-20 11:45:58 -0400232 std::unique_ptr<GrFragmentProcessor> fp) {
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500233 GrPaint paint;
John Stiles5933d7d2020-07-21 12:28:35 -0400234 paint.setColorFragmentProcessor(std::move(fp));
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500235 paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
Brian Salomonac70f842017-05-08 10:43:33 -0400236
Robert Phillips58adb342020-07-23 09:41:57 -0400237 auto op = GrFillRectOp::MakeNonAARect(rContext, std::move(paint), SkMatrix::I(),
Michael Ludwigaa1b6b32019-05-29 14:43:13 -0400238 SkRect::MakeWH(rtc->width(), rtc->height()));
Brian Salomon70fe17e2020-11-30 14:33:58 -0500239 rtc->addDrawOp(std::move(op));
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500240}
241
John Stiles0dee9b02020-07-20 11:45:58 -0400242// The output buffer must be the same size as the render-target context.
Adlai Hollerc95b5892020-08-11 12:02:22 -0400243void render_fp(GrDirectContext* dContext,
Brian Salomoneebe7352020-12-09 16:37:04 -0500244 GrSurfaceDrawContext* rtc,
Brian Salomon3f4de782020-06-18 14:16:00 -0400245 std::unique_ptr<GrFragmentProcessor> fp,
John Stiles0dee9b02020-07-20 11:45:58 -0400246 GrColor* outBuffer) {
Adlai Hollerc95b5892020-08-11 12:02:22 -0400247 test_draw_op(dContext, rtc, std::move(fp));
John Stiles0dee9b02020-07-20 11:45:58 -0400248 std::fill_n(outBuffer, rtc->width() * rtc->height(), 0);
Adlai Hollerc95b5892020-08-11 12:02:22 -0400249 rtc->readPixels(dContext, SkImageInfo::Make(rtc->width(), rtc->height(), kRGBA_8888_SkColorType,
Brian Salomon9f2b86c2019-10-22 10:37:46 -0400250 kPremul_SkAlphaType),
John Stiles0dee9b02020-07-20 11:45:58 -0400251 outBuffer, /*rowBytes=*/0, /*srcPt=*/{0, 0});
Michael Ludwig7034f152018-10-08 16:43:58 -0400252}
253
John Stilesaf110302020-07-20 09:45:51 -0400254// This class is responsible for reproducibly generating a random fragment processor.
255// An identical randomly-designed FP can be generated as many times as needed.
256class TestFPGenerator {
257 public:
258 TestFPGenerator() = delete;
259 TestFPGenerator(GrDirectContext* context, GrResourceProvider* resourceProvider)
260 : fContext(context)
261 , fResourceProvider(resourceProvider)
262 , fInitialSeed(synthesizeInitialSeed())
263 , fRandomSeed(fInitialSeed) {}
Brian Osmanc35a2d42017-03-17 10:58:53 -0400264
John Stilesaf110302020-07-20 09:45:51 -0400265 uint32_t initialSeed() { return fInitialSeed; }
266
267 bool init() {
268 // Initializes the two test texture proxies that are available to the FP test factories.
269 SkRandom random{fRandomSeed};
270 static constexpr int kTestTextureSize = 256;
271
272 {
273 // Put premul data into the RGBA texture that the test FPs can optionally use.
274 GrColor* rgbaData = new GrColor[kTestTextureSize * kTestTextureSize];
275 for (int y = 0; y < kTestTextureSize; ++y) {
276 for (int x = 0; x < kTestTextureSize; ++x) {
277 rgbaData[kTestTextureSize * y + x] = input_texel_color(
278 random.nextULessThan(256), random.nextULessThan(256), 0.0f);
279 }
280 }
281
282 SkImageInfo ii = SkImageInfo::Make(kTestTextureSize, kTestTextureSize,
283 kRGBA_8888_SkColorType, kPremul_SkAlphaType);
284 SkBitmap bitmap;
285 bitmap.installPixels(
286 ii, rgbaData, ii.minRowBytes(),
287 [](void* addr, void* context) { delete[](GrColor*) addr; }, nullptr);
288 bitmap.setImmutable();
289 GrBitmapTextureMaker maker(fContext, bitmap,
290 GrImageTexGenPolicy::kNew_Uncached_Budgeted);
Brian Salomon7e67dca2020-07-21 09:27:25 -0400291 GrSurfaceProxyView view = maker.view(GrMipmapped::kNo);
John Stilesaf110302020-07-20 09:45:51 -0400292 if (!view.proxy() || !view.proxy()->instantiate(fResourceProvider)) {
293 SkDebugf("Unable to instantiate RGBA8888 test texture.");
294 return false;
295 }
296 fTestViews[0] = GrProcessorTestData::ViewInfo{view, GrColorType::kRGBA_8888,
297 kPremul_SkAlphaType};
298 }
299
300 {
301 // Put random values into the alpha texture that the test FPs can optionally use.
302 uint8_t* alphaData = new uint8_t[kTestTextureSize * kTestTextureSize];
303 for (int y = 0; y < kTestTextureSize; ++y) {
304 for (int x = 0; x < kTestTextureSize; ++x) {
305 alphaData[kTestTextureSize * y + x] = random.nextULessThan(256);
306 }
307 }
308
309 SkImageInfo ii = SkImageInfo::Make(kTestTextureSize, kTestTextureSize,
310 kAlpha_8_SkColorType, kPremul_SkAlphaType);
311 SkBitmap bitmap;
312 bitmap.installPixels(
313 ii, alphaData, ii.minRowBytes(),
314 [](void* addr, void* context) { delete[](uint8_t*) addr; }, nullptr);
315 bitmap.setImmutable();
316 GrBitmapTextureMaker maker(fContext, bitmap,
317 GrImageTexGenPolicy::kNew_Uncached_Budgeted);
Brian Salomon7e67dca2020-07-21 09:27:25 -0400318 GrSurfaceProxyView view = maker.view(GrMipmapped::kNo);
John Stilesaf110302020-07-20 09:45:51 -0400319 if (!view.proxy() || !view.proxy()->instantiate(fResourceProvider)) {
320 SkDebugf("Unable to instantiate A8 test texture.");
321 return false;
322 }
323 fTestViews[1] = GrProcessorTestData::ViewInfo{view, GrColorType::kAlpha_8,
324 kPremul_SkAlphaType};
325 }
326
327 return true;
328 }
329
330 void reroll() {
331 // Feed our current random seed into SkRandom to generate a new seed.
332 SkRandom random{fRandomSeed};
333 fRandomSeed = random.nextU();
334 }
335
John Stiles87d0a2f2020-08-10 13:12:41 -0400336 std::unique_ptr<GrFragmentProcessor> make(int type, int randomTreeDepth,
John Stiles0dee9b02020-07-20 11:45:58 -0400337 std::unique_ptr<GrFragmentProcessor> inputFP) {
John Stilesaf110302020-07-20 09:45:51 -0400338 // This will generate the exact same randomized FP (of each requested type) each time
339 // it's called. Call `reroll` to get a different FP.
340 SkRandom random{fRandomSeed};
John Stiles87d0a2f2020-08-10 13:12:41 -0400341 GrProcessorTestData testData{&random, fContext, randomTreeDepth,
342 SK_ARRAY_COUNT(fTestViews), fTestViews,
John Stiles0dee9b02020-07-20 11:45:58 -0400343 std::move(inputFP)};
John Stilesaf110302020-07-20 09:45:51 -0400344 return GrFragmentProcessorTestFactory::MakeIdx(type, &testData);
345 }
346
John Stiles87d0a2f2020-08-10 13:12:41 -0400347 std::unique_ptr<GrFragmentProcessor> make(int type, int randomTreeDepth,
348 GrSurfaceProxyView view,
John Stiles0dee9b02020-07-20 11:45:58 -0400349 SkAlphaType alpha = kPremul_SkAlphaType) {
John Stiles87d0a2f2020-08-10 13:12:41 -0400350 return make(type, randomTreeDepth, GrTextureEffect::Make(view, alpha));
John Stiles0dee9b02020-07-20 11:45:58 -0400351 }
352
John Stilesaf110302020-07-20 09:45:51 -0400353 private:
354 static uint32_t synthesizeInitialSeed() {
355 if (FLAGS_randomProcessorTest) {
356 std::random_device rd;
357 return rd();
358 } else {
359 return FLAGS_processorSeed;
Robert Phillips0bd24dc2018-01-16 08:06:32 -0500360 }
Brian Salomon0e05a822017-07-25 09:43:22 -0400361 }
Brian Salomon0e05a822017-07-25 09:43:22 -0400362
John Stilesaf110302020-07-20 09:45:51 -0400363 GrDirectContext* fContext; // owned by caller
364 GrResourceProvider* fResourceProvider; // owned by caller
365 const uint32_t fInitialSeed;
366 uint32_t fRandomSeed;
367 GrProcessorTestData::ViewInfo fTestViews[2];
368};
Brian Salomon0e05a822017-07-25 09:43:22 -0400369
John Stiles4ed69472020-08-11 16:04:31 -0400370// Creates an array of color values from input_texel_color(), to be used as an input texture.
371std::vector<GrColor> make_input_pixels(int width, int height, SkScalar delta) {
372 std::vector<GrColor> pixel(width * height);
Brian Salomon0e05a822017-07-25 09:43:22 -0400373 for (int y = 0; y < width; ++y) {
374 for (int x = 0; x < height; ++x) {
John Stiles4ed69472020-08-11 16:04:31 -0400375 pixel[width * y + x] = input_texel_color(x, y, delta);
Brian Salomon0e05a822017-07-25 09:43:22 -0400376 }
377 }
Robert Phillips0bd24dc2018-01-16 08:06:32 -0500378
John Stiles4ed69472020-08-11 16:04:31 -0400379 return pixel;
380}
381
382// Creates a texture of premul colors used as the output of the fragment processor that precedes
383// the fragment processor under test. An array of W*H colors are passed in as the texture data.
384GrSurfaceProxyView make_input_texture(GrRecordingContext* context,
385 int width, int height, GrColor* pixel) {
Brian Osman2700abc2018-09-12 10:19:41 -0400386 SkImageInfo ii = SkImageInfo::Make(width, height, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
Greg Daniel6f5441a2020-01-28 17:02:49 -0500387 SkBitmap bitmap;
John Stiles4ed69472020-08-11 16:04:31 -0400388 bitmap.installPixels(ii, pixel, ii.minRowBytes());
Greg Daniel6f5441a2020-01-28 17:02:49 -0500389 bitmap.setImmutable();
Brian Salomonbc074a62020-03-18 10:06:13 -0400390 GrBitmapTextureMaker maker(context, bitmap, GrImageTexGenPolicy::kNew_Uncached_Budgeted);
Brian Salomon7e67dca2020-07-21 09:27:25 -0400391 return maker.view(GrMipmapped::kNo);
Brian Salomon0e05a822017-07-25 09:43:22 -0400392}
Robert Phillips0bd24dc2018-01-16 08:06:32 -0500393
John Stilesaf110302020-07-20 09:45:51 -0400394// We tag logged data as unpremul to avoid conversion when encoding as PNG. The input texture
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400395// actually contains unpremul data. Also, even though we made the result data by rendering into
Brian Salomoneebe7352020-12-09 16:37:04 -0500396// a "unpremul" GrSurfaceDrawContext, our input texture is unpremul and outside of the random
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400397// effect configuration, we didn't do anything to ensure the output is actually premul. We just
Brian Salomoneebe7352020-12-09 16:37:04 -0500398// don't currently allow kUnpremul GrSurfaceDrawContexts.
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400399static constexpr auto kLogAlphaType = kUnpremul_SkAlphaType;
Michael Ludwige8e10752018-10-01 12:42:53 -0400400
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400401bool log_pixels(GrColor* pixels, int widthHeight, SkString* dst) {
John Stilesaf110302020-07-20 09:45:51 -0400402 SkImageInfo info =
403 SkImageInfo::Make(widthHeight, widthHeight, kRGBA_8888_SkColorType, kLogAlphaType);
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400404 SkBitmap bmp;
405 bmp.installPixels(info, pixels, widthHeight * sizeof(GrColor));
Brian Salomon28a8f282019-10-24 20:07:39 -0400406 return BipmapToBase64DataURI(bmp, dst);
Michael Ludwige8e10752018-10-01 12:42:53 -0400407}
408
Adlai Hollerc95b5892020-08-11 12:02:22 -0400409bool log_texture_view(GrDirectContext* dContext, GrSurfaceProxyView src, SkString* dst) {
Greg Daniel124486b2020-02-11 11:54:55 -0500410 SkImageInfo ii = SkImageInfo::Make(src.proxy()->dimensions(), kRGBA_8888_SkColorType,
411 kLogAlphaType);
Greg Daniel3912a4b2020-01-14 09:56:04 -0500412
Brian Salomon14f99fc2020-12-07 12:19:47 -0500413 auto sContext = GrSurfaceContext::Make(dContext, std::move(src), ii.colorInfo());
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400414 SkBitmap bm;
415 SkAssertResult(bm.tryAllocPixels(ii));
Adlai Hollerc95b5892020-08-11 12:02:22 -0400416 SkAssertResult(sContext->readPixels(dContext, ii, bm.getPixels(), bm.rowBytes(), {0, 0}));
Brian Salomon28a8f282019-10-24 20:07:39 -0400417 return BipmapToBase64DataURI(bm, dst);
Michael Ludwige8e10752018-10-01 12:42:53 -0400418}
419
Michael Ludwig7034f152018-10-08 16:43:58 -0400420bool fuzzy_color_equals(const SkPMColor4f& c1, const SkPMColor4f& c2) {
421 // With the loss of precision of rendering into 32-bit color, then estimating the FP's output
Brian Salomon682ba432019-12-17 20:20:23 +0000422 // from that, it is not uncommon for a valid output to differ from estimate by up to 0.01
Michael Ludwig7034f152018-10-08 16:43:58 -0400423 // (really 1/128 ~ .0078, but frequently floating point issues make that tolerance a little
424 // too unforgiving).
Brian Salomon682ba432019-12-17 20:20:23 +0000425 static constexpr SkScalar kTolerance = 0.01f;
Michael Ludwig7034f152018-10-08 16:43:58 -0400426 for (int i = 0; i < 4; i++) {
427 if (!SkScalarNearlyEqual(c1[i], c2[i], kTolerance)) {
428 return false;
429 }
430 }
431 return true;
432}
433
Brian Salomonbc73eb42019-12-18 14:57:45 -0500434// Given three input colors (color preceding the FP being tested) provided to the FP at the same
435// local coord and the three corresponding FP outputs, this ensures that either:
436// out[0] = fp * in[0].a, out[1] = fp * in[1].a, and out[2] = fp * in[2].a
437// where fp is the pre-modulated color that should not be changing across frames (FP's state doesn't
438// change), OR:
439// out[0] = fp * in[0], out[1] = fp * in[1], and out[2] = fp * in[2]
440// (per-channel modulation instead of modulation by just the alpha channel)
441// It does this by estimating the pre-modulated fp color from one of the input/output pairs and
442// confirms the conditions hold for the other two pairs.
443// It is required that the three input colors have the same alpha as fp is allowed to be a function
444// of the input alpha (but not r, g, or b).
445bool legal_modulation(const GrColor in[3], const GrColor out[3]) {
Michael Ludwig7034f152018-10-08 16:43:58 -0400446 // Convert to floating point, which is the number space the FP operates in (more or less)
Brian Salomonbc73eb42019-12-18 14:57:45 -0500447 SkPMColor4f inf[3], outf[3];
448 for (int i = 0; i < 3; ++i) {
449 inf[i] = SkPMColor4f::FromBytes_RGBA(in[i]);
450 outf[i] = SkPMColor4f::FromBytes_RGBA(out[i]);
451 }
452 // This test is only valid if all the input alphas are the same.
453 SkASSERT(inf[0].fA == inf[1].fA && inf[1].fA == inf[2].fA);
Michael Ludwig7034f152018-10-08 16:43:58 -0400454
455 // Reconstruct the output of the FP before the shader modulated its color with the input value.
456 // When the original input is very small, it may cause the final output color to round
457 // to 0, in which case we estimate the pre-modulated color using one of the stepped frames that
458 // will then have a guaranteed larger channel value (since the offset will be added to it).
Brian Salomon0a7ca7a2019-12-27 12:18:19 -0500459 SkPMColor4f fpPreColorModulation = {0,0,0,0};
460 SkPMColor4f fpPreAlphaModulation = {0,0,0,0};
Michael Ludwig7034f152018-10-08 16:43:58 -0400461 for (int i = 0; i < 4; i++) {
Brian Salomonbc73eb42019-12-18 14:57:45 -0500462 // Use the most stepped up frame
463 int maxInIdx = inf[0][i] > inf[1][i] ? 0 : 1;
464 maxInIdx = inf[maxInIdx][i] > inf[2][i] ? maxInIdx : 2;
John Stilesfe7aed62020-07-20 13:48:02 -0400465 const SkPMColor4f& in = inf[maxInIdx];
466 const SkPMColor4f& out = outf[maxInIdx];
Brian Salomon0a7ca7a2019-12-27 12:18:19 -0500467 if (in[i] > 0) {
468 fpPreColorModulation[i] = out[i] / in[i];
469 }
470 if (in[3] > 0) {
471 fpPreAlphaModulation[i] = out[i] / in[3];
472 }
Michael Ludwig7034f152018-10-08 16:43:58 -0400473 }
474
475 // With reconstructed pre-modulated FP output, derive the expected value of fp * input for each
476 // of the transformed input colors.
Brian Salomonbc73eb42019-12-18 14:57:45 -0500477 SkPMColor4f expectedForAlphaModulation[3];
478 SkPMColor4f expectedForColorModulation[3];
479 for (int i = 0; i < 3; ++i) {
480 expectedForAlphaModulation[i] = fpPreAlphaModulation * inf[i].fA;
481 expectedForColorModulation[i] = fpPreColorModulation * inf[i];
482 // If the input alpha is 0 then the other channels should also be zero
483 // since the color is assumed to be premul. Modulating zeros by anything
484 // should produce zeros.
485 if (inf[i].fA == 0) {
486 SkASSERT(inf[i].fR == 0 && inf[i].fG == 0 && inf[i].fB == 0);
487 expectedForColorModulation[i] = expectedForAlphaModulation[i] = {0, 0, 0, 0};
488 }
489 }
Michael Ludwig7034f152018-10-08 16:43:58 -0400490
Brian Salomonbc73eb42019-12-18 14:57:45 -0500491 bool isLegalColorModulation = fuzzy_color_equals(outf[0], expectedForColorModulation[0]) &&
492 fuzzy_color_equals(outf[1], expectedForColorModulation[1]) &&
493 fuzzy_color_equals(outf[2], expectedForColorModulation[2]);
494
495 bool isLegalAlphaModulation = fuzzy_color_equals(outf[0], expectedForAlphaModulation[0]) &&
496 fuzzy_color_equals(outf[1], expectedForAlphaModulation[1]) &&
497 fuzzy_color_equals(outf[2], expectedForAlphaModulation[2]);
498
499 // This can be enabled to print the values that caused this check to fail.
500 if (0 && !isLegalColorModulation && !isLegalAlphaModulation) {
501 SkDebugf("Color modulation test\n\timplied mod color: (%.03f, %.03f, %.03f, %.03f)\n",
502 fpPreColorModulation[0],
503 fpPreColorModulation[1],
504 fpPreColorModulation[2],
505 fpPreColorModulation[3]);
506 for (int i = 0; i < 3; ++i) {
507 SkDebugf("\t(%.03f, %.03f, %.03f, %.03f) -> "
508 "(%.03f, %.03f, %.03f, %.03f) | "
509 "(%.03f, %.03f, %.03f, %.03f), ok: %d\n",
510 inf[i].fR, inf[i].fG, inf[i].fB, inf[i].fA,
511 outf[i].fR, outf[i].fG, outf[i].fB, outf[i].fA,
512 expectedForColorModulation[i].fR, expectedForColorModulation[i].fG,
513 expectedForColorModulation[i].fB, expectedForColorModulation[i].fA,
514 fuzzy_color_equals(outf[i], expectedForColorModulation[i]));
515 }
516 SkDebugf("Alpha modulation test\n\timplied mod color: (%.03f, %.03f, %.03f, %.03f)\n",
517 fpPreAlphaModulation[0],
518 fpPreAlphaModulation[1],
519 fpPreAlphaModulation[2],
520 fpPreAlphaModulation[3]);
521 for (int i = 0; i < 3; ++i) {
522 SkDebugf("\t(%.03f, %.03f, %.03f, %.03f) -> "
523 "(%.03f, %.03f, %.03f, %.03f) | "
524 "(%.03f, %.03f, %.03f, %.03f), ok: %d\n",
525 inf[i].fR, inf[i].fG, inf[i].fB, inf[i].fA,
526 outf[i].fR, outf[i].fG, outf[i].fB, outf[i].fA,
527 expectedForAlphaModulation[i].fR, expectedForAlphaModulation[i].fG,
528 expectedForAlphaModulation[i].fB, expectedForAlphaModulation[i].fA,
529 fuzzy_color_equals(outf[i], expectedForAlphaModulation[i]));
530 }
531 }
532 return isLegalColorModulation || isLegalAlphaModulation;
Michael Ludwig7034f152018-10-08 16:43:58 -0400533}
534
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500535DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ProcessorOptimizationValidationTest, reporter, ctxInfo) {
John Stilesaf110302020-07-20 09:45:51 -0400536 GrDirectContext* context = ctxInfo.directContext();
537 GrResourceProvider* resourceProvider = context->priv().resourceProvider();
Brian Salomon1c053642017-07-24 10:16:19 -0400538 using FPFactory = GrFragmentProcessorTestFactory;
Brian Osmanc35a2d42017-03-17 10:58:53 -0400539
John Stilesaf110302020-07-20 09:45:51 -0400540 TestFPGenerator fpGenerator{context, resourceProvider};
541 if (!fpGenerator.init()) {
542 ERRORF(reporter, "Could not initialize TestFPGenerator");
543 return;
Brian Osmanc35a2d42017-03-17 10:58:53 -0400544 }
Brian Osmanc35a2d42017-03-17 10:58:53 -0400545
Brian Salomon0e05a822017-07-25 09:43:22 -0400546 // Make the destination context for the test.
547 static constexpr int kRenderSize = 256;
Brian Salomoneebe7352020-12-09 16:37:04 -0500548 auto rtc = GrSurfaceDrawContext::Make(
Greg Daniele20fcad2020-01-08 11:52:34 -0500549 context, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kExact,
550 {kRenderSize, kRenderSize});
Brian Salomond1a8bdf2017-02-10 12:39:26 -0500551
Michael Ludwig7034f152018-10-08 16:43:58 -0400552 // Coverage optimization uses three frames with a linearly transformed input texture. The first
553 // frame has no offset, second frames add .2 and .4, which should then be present as a fixed
554 // difference between the frame outputs if the FP is properly following the modulation
555 // requirements of the coverage optimization.
556 static constexpr SkScalar kInputDelta = 0.2f;
John Stiles4ed69472020-08-11 16:04:31 -0400557 std::vector<GrColor> inputPixels1 = make_input_pixels(kRenderSize, kRenderSize, 0.0f);
558 std::vector<GrColor> inputPixels2 =
559 make_input_pixels(kRenderSize, kRenderSize, 1 * kInputDelta);
560 std::vector<GrColor> inputPixels3 =
561 make_input_pixels(kRenderSize, kRenderSize, 2 * kInputDelta);
562 GrSurfaceProxyView inputTexture1 =
563 make_input_texture(context, kRenderSize, kRenderSize, inputPixels1.data());
564 GrSurfaceProxyView inputTexture2 =
565 make_input_texture(context, kRenderSize, kRenderSize, inputPixels2.data());
566 GrSurfaceProxyView inputTexture3 =
567 make_input_texture(context, kRenderSize, kRenderSize, inputPixels3.data());
Robert Phillips30f9bc62017-02-22 15:28:38 -0500568
Michael Ludwige8e10752018-10-01 12:42:53 -0400569 // Encoded images are very verbose and this tests many potential images, so only export the
570 // first failure (subsequent failures have a reasonable chance of being related).
571 bool loggedFirstFailure = false;
Michael Ludwig314d3772018-10-03 16:04:38 -0400572 bool loggedFirstWarning = false;
Michael Ludwig7034f152018-10-08 16:43:58 -0400573
John Stilesaf110302020-07-20 09:45:51 -0400574 // Storage for the three frames required for coverage compatibility optimization testing.
575 // Each frame uses the correspondingly numbered inputTextureX.
576 std::vector<GrColor> readData1(kRenderSize * kRenderSize);
577 std::vector<GrColor> readData2(kRenderSize * kRenderSize);
578 std::vector<GrColor> readData3(kRenderSize * kRenderSize);
Michael Ludwig7034f152018-10-08 16:43:58 -0400579
Brian Salomon0e05a822017-07-25 09:43:22 -0400580 // Because processor factories configure themselves in random ways, this is not exhaustive.
Brian Salomon587e08f2017-01-27 10:59:27 -0500581 for (int i = 0; i < FPFactory::Count(); ++i) {
John Stilesfe7aed62020-07-20 13:48:02 -0400582 int optimizedForOpaqueInput = 0;
583 int optimizedForCoverageAsAlpha = 0;
584 int optimizedForConstantOutputForInput = 0;
John Stilesaf110302020-07-20 09:45:51 -0400585
John Stilesfe7aed62020-07-20 13:48:02 -0400586#ifdef __MSVC_RUNTIME_CHECKS
Brian Osman50ea3c02019-02-04 10:01:53 -0500587 // This test is infuriatingly slow with MSVC runtime checks enabled
John Stilesfe7aed62020-07-20 13:48:02 -0400588 static constexpr int kMinimumTrials = 1;
589 static constexpr int kMaximumTrials = 1;
590 static constexpr int kExpectedSuccesses = 1;
591#else
592 // We start by testing each fragment-processor 100 times, watching the optimization bits
593 // that appear. If we see an optimization bit appear in those first 100 trials, we keep
594 // running tests until we see at least five successful trials that have this optimization
595 // bit enabled. If we never see a particular optimization bit after 100 trials, we assume
596 // that this FP doesn't support that optimization at all.
597 static constexpr int kMinimumTrials = 100;
598 static constexpr int kMaximumTrials = 2000;
599 static constexpr int kExpectedSuccesses = 5;
Brian Osman50ea3c02019-02-04 10:01:53 -0500600#endif
Robert Phillipsa91e0b72017-05-01 13:12:20 -0400601
John Stilesfe7aed62020-07-20 13:48:02 -0400602 for (int trial = 0;; ++trial) {
John Stilesaf110302020-07-20 09:45:51 -0400603 // Create a randomly-configured FP.
604 fpGenerator.reroll();
John Stiles87d0a2f2020-08-10 13:12:41 -0400605 std::unique_ptr<GrFragmentProcessor> fp =
John Stiles9fbe9e92020-08-10 16:35:01 -0400606 fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture1);
John Stilesaf110302020-07-20 09:45:51 -0400607
John Stilesfe7aed62020-07-20 13:48:02 -0400608 // If we have iterated enough times and seen a sufficient number of successes on each
609 // optimization bit that can be returned, stop running trials.
610 if (trial >= kMinimumTrials) {
611 bool moreTrialsNeeded = (optimizedForOpaqueInput > 0 &&
612 optimizedForOpaqueInput < kExpectedSuccesses) ||
613 (optimizedForCoverageAsAlpha > 0 &&
614 optimizedForCoverageAsAlpha < kExpectedSuccesses) ||
615 (optimizedForConstantOutputForInput > 0 &&
616 optimizedForConstantOutputForInput < kExpectedSuccesses);
617 if (!moreTrialsNeeded) break;
618
619 if (trial >= kMaximumTrials) {
620 SkDebugf("Abandoning ProcessorOptimizationValidationTest after %d trials. "
John Stilesba1879d2020-08-11 13:58:32 -0400621 "Seed: 0x%08x, processor:\n%s",
622 kMaximumTrials, fpGenerator.initialSeed(), fp->dumpTreeInfo().c_str());
John Stilesfe7aed62020-07-20 13:48:02 -0400623 break;
624 }
625 }
626
627 // Skip further testing if this trial has no optimization bits enabled.
Brian Salomon587e08f2017-01-27 10:59:27 -0500628 if (!fp->hasConstantOutputForConstantInput() && !fp->preservesOpaqueInput() &&
Brian Salomonf3b995b2017-02-15 10:22:23 -0500629 !fp->compatibleWithCoverageAsAlpha()) {
Brian Salomon587e08f2017-01-27 10:59:27 -0500630 continue;
631 }
Brian Salomonaff329b2017-08-11 09:40:37 -0400632
John Stilesaf110302020-07-20 09:45:51 -0400633 // We can make identical copies of the test FP in order to test coverage-as-alpha.
Michael Ludwig7034f152018-10-08 16:43:58 -0400634 if (fp->compatibleWithCoverageAsAlpha()) {
John Stiles0dee9b02020-07-20 11:45:58 -0400635 // Create and render two identical versions of this FP, but using different input
636 // textures, to check coverage optimization. We don't need to do this step for
637 // constant-output or preserving-opacity tests.
John Stiles87d0a2f2020-08-10 13:12:41 -0400638 render_fp(context, rtc.get(),
John Stiles9fbe9e92020-08-10 16:35:01 -0400639 fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture2),
John Stiles87d0a2f2020-08-10 13:12:41 -0400640 readData2.data());
641 render_fp(context, rtc.get(),
John Stiles9fbe9e92020-08-10 16:35:01 -0400642 fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture3),
John Stiles87d0a2f2020-08-10 13:12:41 -0400643 readData3.data());
John Stilesfe7aed62020-07-20 13:48:02 -0400644 ++optimizedForCoverageAsAlpha;
645 }
646
647 if (fp->hasConstantOutputForConstantInput()) {
648 ++optimizedForConstantOutputForInput;
649 }
650
651 if (fp->preservesOpaqueInput()) {
652 ++optimizedForOpaqueInput;
Michael Ludwig7034f152018-10-08 16:43:58 -0400653 }
Brian Salomon3f4de782020-06-18 14:16:00 -0400654
John Stiles0dee9b02020-07-20 11:45:58 -0400655 // Draw base frame last so that rtc holds the original FP behavior if we need to dump
656 // the image to the log.
John Stiles9fbe9e92020-08-10 16:35:01 -0400657 render_fp(context, rtc.get(), fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture1),
John Stiles87d0a2f2020-08-10 13:12:41 -0400658 readData1.data());
Brian Salomonaff329b2017-08-11 09:40:37 -0400659
Michael Ludwig314d3772018-10-03 16:04:38 -0400660 // This test has a history of being flaky on a number of devices. If an FP is logically
661 // violating the optimizations, it's reasonable to expect it to violate requirements on
662 // a large number of pixels in the image. Sporadic pixel violations are more indicative
663 // of device errors and represents a separate problem.
Michael Ludwig72ab3462018-12-10 12:43:36 -0500664#if defined(SK_BUILD_FOR_SKQP)
Michael Ludwig314d3772018-10-03 16:04:38 -0400665 static constexpr int kMaxAcceptableFailedPixels = 0; // Strict when running as SKQP
666#else
667 static constexpr int kMaxAcceptableFailedPixels = 2 * kRenderSize; // ~0.7% of the image
668#endif
669
Michael Ludwig314d3772018-10-03 16:04:38 -0400670 // Collect first optimization failure message, to be output later as a warning or an
671 // error depending on whether the rendering "passed" or failed.
John Stilesaf110302020-07-20 09:45:51 -0400672 int failedPixelCount = 0;
Michael Ludwig314d3772018-10-03 16:04:38 -0400673 SkString coverageMessage;
674 SkString opaqueMessage;
675 SkString constMessage;
676 for (int y = 0; y < kRenderSize; ++y) {
677 for (int x = 0; x < kRenderSize; ++x) {
678 bool passing = true;
John Stiles4ed69472020-08-11 16:04:31 -0400679 GrColor input = inputPixels1[y * kRenderSize + x];
John Stilesaf110302020-07-20 09:45:51 -0400680 GrColor output = readData1[y * kRenderSize + x];
Michael Ludwig7034f152018-10-08 16:43:58 -0400681
682 if (fp->compatibleWithCoverageAsAlpha()) {
Brian Salomonbc73eb42019-12-18 14:57:45 -0500683 GrColor ins[3];
684 ins[0] = input;
John Stiles4ed69472020-08-11 16:04:31 -0400685 ins[1] = inputPixels2[y * kRenderSize + x];
686 ins[2] = inputPixels3[y * kRenderSize + x];
Michael Ludwig7034f152018-10-08 16:43:58 -0400687
Brian Salomonbc73eb42019-12-18 14:57:45 -0500688 GrColor outs[3];
689 outs[0] = output;
John Stilesaf110302020-07-20 09:45:51 -0400690 outs[1] = readData2[y * kRenderSize + x];
691 outs[2] = readData3[y * kRenderSize + x];
Michael Ludwig7034f152018-10-08 16:43:58 -0400692
Brian Salomonbc73eb42019-12-18 14:57:45 -0500693 if (!legal_modulation(ins, outs)) {
Brian Salomon587e08f2017-01-27 10:59:27 -0500694 passing = false;
Michael Ludwig314d3772018-10-03 16:04:38 -0400695 if (coverageMessage.isEmpty()) {
Brian Salomonbc73eb42019-12-18 14:57:45 -0500696 coverageMessage.printf(
John Stilesba1879d2020-08-11 13:58:32 -0400697 "\"Modulating\" processor did not match alpha-modulation "
698 "nor color-modulation rules.\n"
Michael Ludwig7034f152018-10-08 16:43:58 -0400699 "Input: 0x%08x, Output: 0x%08x, pixel (%d, %d).",
John Stilesba1879d2020-08-11 13:58:32 -0400700 input, output, x, y);
Michael Ludwig314d3772018-10-03 16:04:38 -0400701 }
Brian Salomon587e08f2017-01-27 10:59:27 -0500702 }
703 }
Michael Ludwig7034f152018-10-08 16:43:58 -0400704
Brian Osmancb3d0872018-10-16 15:19:28 -0400705 SkPMColor4f input4f = SkPMColor4f::FromBytes_RGBA(input);
706 SkPMColor4f output4f = SkPMColor4f::FromBytes_RGBA(output);
Brian Osman1d5b5982018-10-01 13:41:39 -0400707 SkPMColor4f expected4f;
Michael Ludwig7034f152018-10-08 16:43:58 -0400708 if (fp->hasConstantOutputForConstantInput(input4f, &expected4f)) {
Brian Osmancb3d0872018-10-16 15:19:28 -0400709 float rDiff = fabsf(output4f.fR - expected4f.fR);
710 float gDiff = fabsf(output4f.fG - expected4f.fG);
711 float bDiff = fabsf(output4f.fB - expected4f.fB);
712 float aDiff = fabsf(output4f.fA - expected4f.fA);
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500713 static constexpr float kTol = 4 / 255.f;
Brian Salomon587e08f2017-01-27 10:59:27 -0500714 if (rDiff > kTol || gDiff > kTol || bDiff > kTol || aDiff > kTol) {
Michael Ludwig314d3772018-10-03 16:04:38 -0400715 if (constMessage.isEmpty()) {
716 passing = false;
717
John Stilesba1879d2020-08-11 13:58:32 -0400718 constMessage.printf(
719 "Processor claimed output for const input doesn't match "
720 "actual output.\n"
721 "Error: %f, Tolerance: %f, input: (%f, %f, %f, %f), "
722 "actual: (%f, %f, %f, %f), expected(%f, %f, %f, %f).",
723 std::max(rDiff, std::max(gDiff, std::max(bDiff, aDiff))),
724 kTol, input4f.fR, input4f.fG, input4f.fB, input4f.fA,
Brian Osmancb3d0872018-10-16 15:19:28 -0400725 output4f.fR, output4f.fG, output4f.fB, output4f.fA,
726 expected4f.fR, expected4f.fG, expected4f.fB, expected4f.fA);
Michael Ludwig314d3772018-10-03 16:04:38 -0400727 }
Brian Salomon587e08f2017-01-27 10:59:27 -0500728 }
729 }
Brian Osman00b29392018-11-05 15:42:43 -0500730 if (input4f.isOpaque() && fp->preservesOpaqueInput() && !output4f.isOpaque()) {
Brian Salomon587e08f2017-01-27 10:59:27 -0500731 passing = false;
Michael Ludwig314d3772018-10-03 16:04:38 -0400732
733 if (opaqueMessage.isEmpty()) {
John Stilesba1879d2020-08-11 13:58:32 -0400734 opaqueMessage.printf(
735 "Processor claimed opaqueness is preserved but "
Michael Ludwig314d3772018-10-03 16:04:38 -0400736 "it is not. Input: 0x%08x, Output: 0x%08x.",
John Stilesba1879d2020-08-11 13:58:32 -0400737 input, output);
Michael Ludwige8e10752018-10-01 12:42:53 -0400738 }
Brian Osmanbd1f76f2017-03-15 11:33:12 -0400739 }
Michael Ludwig314d3772018-10-03 16:04:38 -0400740
741 if (!passing) {
742 // Regardless of how many optimizations the pixel violates, count it as a
743 // single bad pixel.
744 failedPixelCount++;
745 }
746 }
747 }
748
749 // Finished analyzing the entire image, see if the number of pixel failures meets the
750 // threshold for an FP violating the optimization requirements.
751 if (failedPixelCount > kMaxAcceptableFailedPixels) {
John Stilesba1879d2020-08-11 13:58:32 -0400752 ERRORF(reporter,
753 "Processor violated %d of %d pixels, seed: 0x%08x.\n"
754 "Processor:\n%s\nFirst failing pixel details are below:",
John Stilesaf110302020-07-20 09:45:51 -0400755 failedPixelCount, kRenderSize * kRenderSize, fpGenerator.initialSeed(),
John Stilesba1879d2020-08-11 13:58:32 -0400756 fp->dumpTreeInfo().c_str());
Michael Ludwig314d3772018-10-03 16:04:38 -0400757
758 // Print first failing pixel's details.
759 if (!coverageMessage.isEmpty()) {
760 ERRORF(reporter, coverageMessage.c_str());
761 }
762 if (!constMessage.isEmpty()) {
763 ERRORF(reporter, constMessage.c_str());
764 }
765 if (!opaqueMessage.isEmpty()) {
766 ERRORF(reporter, opaqueMessage.c_str());
767 }
768
769 if (!loggedFirstFailure) {
770 // Print with ERRORF to make sure the encoded image is output
771 SkString input;
Greg Daniel124486b2020-02-11 11:54:55 -0500772 log_texture_view(context, inputTexture1, &input);
Michael Ludwig314d3772018-10-03 16:04:38 -0400773 SkString output;
John Stilesaf110302020-07-20 09:45:51 -0400774 log_pixels(readData1.data(), kRenderSize, &output);
Michael Ludwig314d3772018-10-03 16:04:38 -0400775 ERRORF(reporter, "Input image: %s\n\n"
776 "===========================================================\n\n"
777 "Output image: %s\n", input.c_str(), output.c_str());
778 loggedFirstFailure = true;
779 }
John Stilesaf110302020-07-20 09:45:51 -0400780 } else if (failedPixelCount > 0) {
Michael Ludwig314d3772018-10-03 16:04:38 -0400781 // Don't trigger an error, but don't just hide the failures either.
782 INFOF(reporter, "Processor violated %d of %d pixels (below error threshold), seed: "
783 "0x%08x, processor: %s", failedPixelCount, kRenderSize * kRenderSize,
John Stilesaf110302020-07-20 09:45:51 -0400784 fpGenerator.initialSeed(), fp->dumpInfo().c_str());
Michael Ludwig314d3772018-10-03 16:04:38 -0400785 if (!coverageMessage.isEmpty()) {
786 INFOF(reporter, coverageMessage.c_str());
787 }
788 if (!constMessage.isEmpty()) {
789 INFOF(reporter, constMessage.c_str());
790 }
791 if (!opaqueMessage.isEmpty()) {
792 INFOF(reporter, opaqueMessage.c_str());
793 }
794 if (!loggedFirstWarning) {
795 SkString input;
Greg Daniel124486b2020-02-11 11:54:55 -0500796 log_texture_view(context, inputTexture1, &input);
Michael Ludwig314d3772018-10-03 16:04:38 -0400797 SkString output;
John Stilesaf110302020-07-20 09:45:51 -0400798 log_pixels(readData1.data(), kRenderSize, &output);
Michael Ludwig314d3772018-10-03 16:04:38 -0400799 INFOF(reporter, "Input image: %s\n\n"
800 "===========================================================\n\n"
801 "Output image: %s\n", input.c_str(), output.c_str());
802 loggedFirstWarning = true;
Brian Salomon587e08f2017-01-27 10:59:27 -0500803 }
804 }
805 }
806 }
807}
Robert Phillips18166ee2017-06-01 12:55:44 -0400808
John Stilesea8be212020-08-10 11:38:41 -0400809static void assert_processor_equality(skiatest::Reporter* reporter,
810 const GrFragmentProcessor& fp,
811 const GrFragmentProcessor& clone) {
812 REPORTER_ASSERT(reporter, !strcmp(fp.name(), clone.name()),
John Stilesba1879d2020-08-11 13:58:32 -0400813 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400814 REPORTER_ASSERT(reporter, fp.compatibleWithCoverageAsAlpha() ==
815 clone.compatibleWithCoverageAsAlpha(),
John Stilesba1879d2020-08-11 13:58:32 -0400816 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400817 REPORTER_ASSERT(reporter, fp.isEqual(clone),
John Stilesba1879d2020-08-11 13:58:32 -0400818 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400819 REPORTER_ASSERT(reporter, fp.preservesOpaqueInput() == clone.preservesOpaqueInput(),
John Stilesba1879d2020-08-11 13:58:32 -0400820 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400821 REPORTER_ASSERT(reporter, fp.hasConstantOutputForConstantInput() ==
822 clone.hasConstantOutputForConstantInput(),
John Stilesba1879d2020-08-11 13:58:32 -0400823 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400824 REPORTER_ASSERT(reporter, fp.numChildProcessors() == clone.numChildProcessors(),
John Stilesba1879d2020-08-11 13:58:32 -0400825 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400826 REPORTER_ASSERT(reporter, fp.usesVaryingCoords() == clone.usesVaryingCoords(),
John Stilesba1879d2020-08-11 13:58:32 -0400827 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400828 REPORTER_ASSERT(reporter, fp.referencesSampleCoords() == clone.referencesSampleCoords(),
John Stilesba1879d2020-08-11 13:58:32 -0400829 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400830}
831
832static bool verify_identical_render(skiatest::Reporter* reporter, int renderSize,
833 const char* processorType,
834 const GrColor readData1[], const GrColor readData2[]) {
835 // The ProcessorClone test has a history of being flaky on a number of devices. If an FP clone
836 // is logically wrong, it's reasonable to expect it produce a large number of pixel differences
837 // in the image. Sporadic pixel violations are more indicative device errors and represents a
838 // separate problem.
839#if defined(SK_BUILD_FOR_SKQP)
840 const int maxAcceptableFailedPixels = 0; // Strict when running as SKQP
841#else
842 const int maxAcceptableFailedPixels = 2 * renderSize; // ~0.002% of the pixels (size 1024*1024)
843#endif
844
845 int failedPixelCount = 0;
846 int firstWrongX = 0;
847 int firstWrongY = 0;
848 int idx = 0;
849 for (int y = 0; y < renderSize; ++y) {
850 for (int x = 0; x < renderSize; ++x, ++idx) {
851 if (readData1[idx] != readData2[idx]) {
852 if (!failedPixelCount) {
853 firstWrongX = x;
854 firstWrongY = y;
855 }
856 ++failedPixelCount;
857 }
858 if (failedPixelCount > maxAcceptableFailedPixels) {
859 idx = firstWrongY * renderSize + firstWrongX;
860 ERRORF(reporter,
861 "%s produced different output at (%d, %d). "
862 "Input color: 0x%08x, Original Output Color: 0x%08x, "
863 "Clone Output Color: 0x%08x.",
864 processorType, firstWrongX, firstWrongY, input_texel_color(x, y, 0.0f),
865 readData1[idx], readData2[idx]);
866
867 return false;
868 }
869 }
870 }
871
872 return true;
873}
874
875static void log_clone_failure(skiatest::Reporter* reporter, int renderSize,
876 GrDirectContext* context, const GrSurfaceProxyView& inputTexture,
877 GrColor pixelsFP[], GrColor pixelsClone[], GrColor pixelsRegen[]) {
878 // Write the images out as data URLs for inspection.
879 SkString inputURL, origURL, cloneURL, regenURL;
880 if (log_texture_view(context, inputTexture, &inputURL) &&
881 log_pixels(pixelsFP, renderSize, &origURL) &&
882 log_pixels(pixelsClone, renderSize, &cloneURL) &&
883 log_pixels(pixelsRegen, renderSize, &regenURL)) {
884 ERRORF(reporter,
885 "\nInput image:\n%s\n\n"
886 "==========================================================="
887 "\n\n"
888 "Orig output image:\n%s\n"
889 "==========================================================="
890 "\n\n"
891 "Clone output image:\n%s\n"
892 "==========================================================="
893 "\n\n"
894 "Regen output image:\n%s\n",
895 inputURL.c_str(), origURL.c_str(), cloneURL.c_str(), regenURL.c_str());
896 }
897}
898
Brian Salomon3f4de782020-06-18 14:16:00 -0400899// Tests that a fragment processor returned by GrFragmentProcessor::clone() is equivalent to its
900// progenitor.
Brian Salomon0e05a822017-07-25 09:43:22 -0400901DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ProcessorCloneTest, reporter, ctxInfo) {
John Stilesaf110302020-07-20 09:45:51 -0400902 GrDirectContext* context = ctxInfo.directContext();
903 GrResourceProvider* resourceProvider = context->priv().resourceProvider();
Brian Salomon0e05a822017-07-25 09:43:22 -0400904
John Stilesaf110302020-07-20 09:45:51 -0400905 TestFPGenerator fpGenerator{context, resourceProvider};
906 if (!fpGenerator.init()) {
907 ERRORF(reporter, "Could not initialize TestFPGenerator");
908 return;
909 }
Brian Salomon0e05a822017-07-25 09:43:22 -0400910
911 // Make the destination context for the test.
912 static constexpr int kRenderSize = 1024;
Brian Salomoneebe7352020-12-09 16:37:04 -0500913 auto rtc = GrSurfaceDrawContext::Make(
Greg Daniele20fcad2020-01-08 11:52:34 -0500914 context, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kExact,
915 {kRenderSize, kRenderSize});
Brian Salomon0e05a822017-07-25 09:43:22 -0400916
John Stiles4ed69472020-08-11 16:04:31 -0400917 std::vector<GrColor> inputPixels = make_input_pixels(kRenderSize, kRenderSize, 0.0f);
918 GrSurfaceProxyView inputTexture =
919 make_input_texture(context, kRenderSize, kRenderSize, inputPixels.data());
John Stilesaf110302020-07-20 09:45:51 -0400920
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400921 // On failure we write out images, but just write the first failing set as the print is very
922 // large.
923 bool loggedFirstFailure = false;
924
John Stilesaf110302020-07-20 09:45:51 -0400925 // Storage for the original frame's readback and the readback of its clone.
John Stilesea8be212020-08-10 11:38:41 -0400926 std::vector<GrColor> readDataFP(kRenderSize * kRenderSize);
927 std::vector<GrColor> readDataClone(kRenderSize * kRenderSize);
928 std::vector<GrColor> readDataRegen(kRenderSize * kRenderSize);
Brian Salomon0e05a822017-07-25 09:43:22 -0400929
930 // Because processor factories configure themselves in random ways, this is not exhaustive.
931 for (int i = 0; i < GrFragmentProcessorTestFactory::Count(); ++i) {
932 static constexpr int kTimesToInvokeFactory = 10;
933 for (int j = 0; j < kTimesToInvokeFactory; ++j) {
John Stilesaf110302020-07-20 09:45:51 -0400934 fpGenerator.reroll();
John Stiles87d0a2f2020-08-10 13:12:41 -0400935 std::unique_ptr<GrFragmentProcessor> fp =
John Stiles9fbe9e92020-08-10 16:35:01 -0400936 fpGenerator.make(i, /*randomTreeDepth=*/1, /*inputFP=*/nullptr);
John Stiles87d0a2f2020-08-10 13:12:41 -0400937 std::unique_ptr<GrFragmentProcessor> regen =
John Stiles9fbe9e92020-08-10 16:35:01 -0400938 fpGenerator.make(i, /*randomTreeDepth=*/1, /*inputFP=*/nullptr);
John Stiles8c71f3e2020-06-15 15:07:19 -0400939 std::unique_ptr<GrFragmentProcessor> clone = fp->clone();
Brian Salomon0e05a822017-07-25 09:43:22 -0400940 if (!clone) {
John Stilesba1879d2020-08-11 13:58:32 -0400941 ERRORF(reporter, "Clone of processor %s failed.", fp->dumpTreeInfo().c_str());
Brian Salomon0e05a822017-07-25 09:43:22 -0400942 continue;
943 }
John Stilesea8be212020-08-10 11:38:41 -0400944 assert_processor_equality(reporter, *fp, *clone);
945
Brian Salomon0e05a822017-07-25 09:43:22 -0400946 // Draw with original and read back the results.
John Stilesea8be212020-08-10 11:38:41 -0400947 render_fp(context, rtc.get(), std::move(fp), readDataFP.data());
Brian Salomon0e05a822017-07-25 09:43:22 -0400948
949 // Draw with clone and read back the results.
John Stilesea8be212020-08-10 11:38:41 -0400950 render_fp(context, rtc.get(), std::move(clone), readDataClone.data());
Brian Salomon0e05a822017-07-25 09:43:22 -0400951
952 // Check that the results are the same.
John Stilesea8be212020-08-10 11:38:41 -0400953 if (!verify_identical_render(reporter, kRenderSize, "Processor clone",
954 readDataFP.data(), readDataClone.data())) {
955 // Dump a description from the regenerated processor (since the original FP has
956 // already been consumed).
John Stilesba1879d2020-08-11 13:58:32 -0400957 ERRORF(reporter, "FP hierarchy:\n%s", regen->dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400958
959 // Render and readback output from the regenerated FP. If this also mismatches, the
960 // FP itself doesn't generate consistent output. This could happen if:
961 // - the FP's TestCreate() does not always generate the same FP from a given seed
962 // - the FP's Make() does not always generate the same FP when given the same inputs
963 // - the FP itself generates inconsistent pixels (shader UB?)
964 // - the driver has a bug
965 render_fp(context, rtc.get(), std::move(regen), readDataRegen.data());
966
967 if (!verify_identical_render(reporter, kRenderSize, "Regenerated processor",
968 readDataFP.data(), readDataRegen.data())) {
969 ERRORF(reporter, "Output from regen did not match original!\n");
970 } else {
971 ERRORF(reporter, "Regenerated processor output matches original results.\n");
972 }
973
974 // If this is the first time we've encountered a cloning failure, log the generated
975 // images to the reporter as data URLs.
976 if (!loggedFirstFailure) {
977 log_clone_failure(reporter, kRenderSize, context, inputTexture,
978 readDataFP.data(), readDataClone.data(),
979 readDataRegen.data());
980 loggedFirstFailure = true;
Brian Salomon0e05a822017-07-25 09:43:22 -0400981 }
982 }
983 }
984 }
985}
986
Hal Canary6f6961e2017-01-31 13:50:44 -0500987#endif // GR_TEST_UTILS