blob: c5d96c632744563ef480935190f4b78c047da4ae [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"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "src/gpu/GrClip.h"
Adlai Hollera0693042020-10-14 11:23:11 -040012#include "src/gpu/GrDirectContextPriv.h"
Brian Salomon48959462021-08-11 13:01:06 -040013#include "src/gpu/GrFragmentProcessor.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 Salomon27c42022021-04-28 12:39:21 -040019#include "src/gpu/SkGr.h"
Robert Phillips550de7f2021-07-06 16:28:52 -040020#include "src/gpu/effects/GrTextureEffect.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050021#include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050022#include "src/gpu/ops/GrMeshDrawOp.h"
Robert Phillips4dca8312021-07-28 15:13:20 -040023#include "src/gpu/v1/SurfaceDrawContext_v1.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050024#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
Robert Phillips294723d2021-06-17 09:23:58 -040040 void visitProxies(const GrVisitProxyFunc& 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 Dalton57ab06c2021-04-22 12:57:28 -060046 GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip,
47 GrClampType clampType) override {
Brian Salomon82ddc942017-07-14 12:00:13 -040048 static constexpr GrProcessorAnalysisColor kUnknownColor;
Brian Osmancf860852018-10-31 14:04:39 -040049 SkPMColor4f overrideColor;
Chris Daltonb8fff0d2019-03-05 10:11:58 -070050 return fProcessors.finalize(
51 kUnknownColor, GrProcessorAnalysisCoverage::kNone, clip,
Chris Dalton57ab06c2021-04-22 12:57:28 -060052 &GrUserStencilSettings::kUnused, caps, clampType, &overrideColor);
Brian Salomon649a3412017-03-09 13:50:43 -050053 }
Brian Salomonbc6b99d2017-01-11 10:32:34 -050054
55private:
Herb Derbyc76d4092020-10-07 16:46:15 -040056 friend class ::GrOp; // for ctor
Robert Phillips7c525e62018-06-12 10:11:12 -040057
Brian Salomonaff329b2017-08-11 09:40:37 -040058 TestOp(std::unique_ptr<GrFragmentProcessor> fp)
59 : INHERITED(ClassID()), fProcessors(std::move(fp)) {
Greg Daniel5faf4742019-10-01 15:14:44 -040060 this->setBounds(SkRect::MakeWH(100, 100), HasAABloat::kNo, IsHairline::kNo);
Brian Salomon82ddc942017-07-14 12:00:13 -040061 }
Brian Salomonbc6b99d2017-01-11 10:32:34 -050062
Robert Phillips2669a7b2020-03-12 12:07:19 -040063 GrProgramInfo* programInfo() override { return nullptr; }
Robert Phillips4133dc42020-03-11 15:55:55 -040064 void onCreateProgramInfo(const GrCaps*,
65 SkArenaAlloc*,
Adlai Hollere2296f72020-11-19 13:41:26 -050066 const GrSurfaceProxyView& writeView,
Chris Dalton6aaf00f2021-07-13 13:26:39 -060067 bool usesMSAASurface,
Robert Phillips4133dc42020-03-11 15:55:55 -040068 GrAppliedClip&&,
John Stiles52cb1d02021-06-02 11:58:05 -040069 const GrDstProxyView&,
Greg Daniel42dbca52020-11-20 10:22:43 -050070 GrXferBarrierFlags renderPassXferBarriers,
71 GrLoadOp colorLoadOp) override {}
Robert Phillips2669a7b2020-03-12 12:07:19 -040072 void onPrePrepareDraws(GrRecordingContext*,
Adlai Hollere2296f72020-11-19 13:41:26 -050073 const GrSurfaceProxyView& writeView,
Robert Phillips2669a7b2020-03-12 12:07:19 -040074 GrAppliedClip*,
John Stiles52cb1d02021-06-02 11:58:05 -040075 const GrDstProxyView&,
Greg Daniel42dbca52020-11-20 10:22:43 -050076 GrXferBarrierFlags renderPassXferBarriers,
77 GrLoadOp colorLoadOp) override {}
Robert Phillips71143952021-06-17 14:55:07 -040078 void onPrepareDraws(GrMeshDrawTarget*) override { return; }
Chris Dalton07cdcfc92019-02-26 11:13:22 -070079 void onExecute(GrOpFlushState*, const SkRect&) override { return; }
Brian Salomonbc6b99d2017-01-11 10:32:34 -050080
Brian Salomon82ddc942017-07-14 12:00:13 -040081 GrProcessorSet fProcessors;
82
John Stiles7571f9e2020-09-02 22:42:33 -040083 using INHERITED = GrMeshDrawOp;
Brian Salomonbc6b99d2017-01-11 10:32:34 -050084};
85
86/**
Robert Phillips3d4cac52019-06-11 08:08:08 -040087 * 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 -050088 * of resources owned by child FPs.
89 */
90class TestFP : public GrFragmentProcessor {
91public:
Brian Salomonaff329b2017-08-11 09:40:37 -040092 static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> child) {
93 return std::unique_ptr<GrFragmentProcessor>(new TestFP(std::move(child)));
Brian Salomonbc6b99d2017-01-11 10:32:34 -050094 }
Brian Salomon92b9ccf2020-06-17 14:19:19 -040095 static std::unique_ptr<GrFragmentProcessor> Make(const SkTArray<GrSurfaceProxyView>& views) {
96 return std::unique_ptr<GrFragmentProcessor>(new TestFP(views));
Brian Salomonbc6b99d2017-01-11 10:32:34 -050097 }
98
99 const char* name() const override { return "test"; }
100
Brian Salomon13b28732021-08-06 15:33:58 -0400101 void onAddToKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const override {
Mike Klein0ec1c572018-12-04 11:52:51 -0500102 static std::atomic<int32_t> nextKey{0};
103 b->add32(nextKey++);
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500104 }
105
Brian Salomonaff329b2017-08-11 09:40:37 -0400106 std::unique_ptr<GrFragmentProcessor> clone() const override {
107 return std::unique_ptr<GrFragmentProcessor>(new TestFP(*this));
Brian Salomonb17e6392017-07-28 13:41:51 -0400108 }
109
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500110private:
Brian Salomon92b9ccf2020-06-17 14:19:19 -0400111 TestFP(const SkTArray<GrSurfaceProxyView>& views)
112 : INHERITED(kTestFP_ClassID, kNone_OptimizationFlags) {
John Stilesfe7aed62020-07-20 13:48:02 -0400113 for (const GrSurfaceProxyView& view : views) {
Michael Ludwig9aba6252020-06-22 14:46:36 -0400114 this->registerChild(GrTextureEffect::Make(view, kUnknown_SkAlphaType));
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500115 }
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500116 }
117
Brian Salomonaff329b2017-08-11 09:40:37 -0400118 TestFP(std::unique_ptr<GrFragmentProcessor> child)
Brian Salomon92b9ccf2020-06-17 14:19:19 -0400119 : INHERITED(kTestFP_ClassID, kNone_OptimizationFlags) {
Michael Ludwig9aba6252020-06-22 14:46:36 -0400120 this->registerChild(std::move(child));
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500121 }
122
John Stiles307f8f52021-08-09 15:36:59 -0400123 explicit TestFP(const TestFP& that) : INHERITED(that) {}
Brian Salomonb17e6392017-07-28 13:41:51 -0400124
Brian Salomon3176e862021-08-09 11:23:04 -0400125 std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
Brian Salomonb25560a2021-08-10 13:56:13 -0400126 class Impl : public ProgramImpl {
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500127 public:
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500128 void emitCode(EmitArgs& args) override {
John Stilesd1eab8b2020-12-15 09:47:26 -0500129 args.fFragBuilder->codeAppendf("return half4(1);");
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500130 }
131
132 private:
133 };
Brian Salomonb25560a2021-08-10 13:56:13 -0400134 return std::make_unique<Impl>();
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500135 }
136
137 bool onIsEqual(const GrFragmentProcessor&) const override { return false; }
138
John Stiles7571f9e2020-09-02 22:42:33 -0400139 using INHERITED = GrFragmentProcessor;
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500140};
John Stilesa6841be2020-08-06 14:11:56 -0400141} // namespace
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500142
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500143DEF_GPUTEST_FOR_ALL_CONTEXTS(ProcessorRefTest, reporter, ctxInfo) {
Robert Phillips4dca8312021-07-28 15:13:20 -0400144 auto dContext = ctxInfo.directContext();
145 GrProxyProvider* proxyProvider = dContext->priv().proxyProvider();
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500146
Brian Salomona56a7462020-02-07 14:17:25 -0500147 static constexpr SkISize kDims = {10, 10};
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500148
Greg Daniel4065d452018-11-16 15:43:41 -0500149 const GrBackendFormat format =
Robert Phillips4dca8312021-07-28 15:13:20 -0400150 dContext->priv().caps()->getDefaultBackendFormat(GrColorType::kRGBA_8888,
151 GrRenderable::kNo);
152 GrSwizzle swizzle = dContext->priv().caps()->getReadSwizzle(format, GrColorType::kRGBA_8888);
Greg Daniel4065d452018-11-16 15:43:41 -0500153
Brian Salomonb17e6392017-07-28 13:41:51 -0400154 for (bool makeClone : {false, true}) {
155 for (int parentCnt = 0; parentCnt < 2; parentCnt++) {
Robert Phillips4dca8312021-07-28 15:13:20 -0400156 auto sdc = skgpu::v1::SurfaceDrawContext::Make(
157 dContext, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kApprox, {1, 1},
Chris Daltonf5b87f92021-04-19 17:27:09 -0600158 SkSurfaceProps());
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500159 {
Robert Phillips3d4cac52019-06-11 08:08:08 -0400160 sk_sp<GrTextureProxy> proxy = proxyProvider->createProxy(
Brian Salomon7e67dca2020-07-21 09:27:25 -0400161 format, kDims, GrRenderable::kNo, 1, GrMipmapped::kNo, SkBackingFit::kExact,
Brian Salomondf1bd6d2020-03-26 20:37:01 -0400162 SkBudgeted::kYes, GrProtected::kNo);
Robert Phillips3d4cac52019-06-11 08:08:08 -0400163
Brian Salomonb17e6392017-07-28 13:41:51 -0400164 {
Greg Daniel026a60c2020-02-12 10:53:51 -0500165 SkTArray<GrSurfaceProxyView> views;
Greg Daniel026a60c2020-02-12 10:53:51 -0500166 views.push_back({proxy, kTopLeft_GrSurfaceOrigin, swizzle});
Brian Salomon92b9ccf2020-06-17 14:19:19 -0400167 auto fp = TestFP::Make(std::move(views));
Brian Salomonb17e6392017-07-28 13:41:51 -0400168 for (int i = 0; i < parentCnt; ++i) {
169 fp = TestFP::Make(std::move(fp));
170 }
Brian Salomonaff329b2017-08-11 09:40:37 -0400171 std::unique_ptr<GrFragmentProcessor> clone;
Brian Salomonb17e6392017-07-28 13:41:51 -0400172 if (makeClone) {
173 clone = fp->clone();
174 }
Robert Phillips4dca8312021-07-28 15:13:20 -0400175 GrOp::Owner op = TestOp::Make(dContext, std::move(fp));
176 sdc->addDrawOp(std::move(op));
Brian Salomonb17e6392017-07-28 13:41:51 -0400177 if (clone) {
Robert Phillips4dca8312021-07-28 15:13:20 -0400178 op = TestOp::Make(dContext, std::move(clone));
179 sdc->addDrawOp(std::move(op));
Brian Salomonb17e6392017-07-28 13:41:51 -0400180 }
181 }
Brian Salomonb17e6392017-07-28 13:41:51 -0400182
Robert Phillips3d4cac52019-06-11 08:08:08 -0400183 // If the fp is cloned the number of refs should increase by one (for the clone)
184 int expectedProxyRefs = makeClone ? 3 : 2;
185
Brian Salomon28a8f282019-10-24 20:07:39 -0400186 CheckSingleThreadedProxyRefs(reporter, proxy.get(), expectedProxyRefs, -1);
Brian Salomonb17e6392017-07-28 13:41:51 -0400187
Robert Phillips4dca8312021-07-28 15:13:20 -0400188 dContext->flushAndSubmit();
Brian Salomonb17e6392017-07-28 13:41:51 -0400189
Brian Salomon557e8122019-10-24 10:37:08 -0400190 // just one from the 'proxy' sk_sp
Brian Salomon28a8f282019-10-24 20:07:39 -0400191 CheckSingleThreadedProxyRefs(reporter, proxy.get(), 1, 1);
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500192 }
193 }
194 }
195}
Brian Salomon587e08f2017-01-27 10:59:27 -0500196
Mike Kleinc0bd9f92019-04-23 12:05:21 -0500197#include "tools/flags/CommandLineFlags.h"
Mike Klein84836b72019-03-21 11:31:36 -0500198static DEFINE_bool(randomProcessorTest, false,
199 "Use non-deterministic seed for random processor tests?");
Mike Klein5b3f3432019-03-21 11:42:21 -0500200static DEFINE_int(processorSeed, 0,
201 "Use specific seed for processor tests. Overridden by --randomProcessorTest.");
Brian Salomon0e05a822017-07-25 09:43:22 -0400202
203#if GR_TEST_UTILS
204
John Stilesfa088a62021-08-12 23:01:41 -0400205static GrColor input_texel_color(int x, int y, SkScalar delta) {
Michael Ludwig7034f152018-10-08 16:43:58 -0400206 // Delta must be less than 0.5 to prevent over/underflow issues with the input color
207 SkASSERT(delta <= 0.5);
Brian Salomon587e08f2017-01-27 10:59:27 -0500208
John Stilesfa088a62021-08-12 23:01:41 -0400209 SkColor color = SkColorSetARGB((uint8_t)(x & 0xFF),
210 (uint8_t)(y & 0xFF),
211 (uint8_t)((x + y) & 0xFF),
212 (uint8_t)((2 * y - x) & 0xFF));
Brian Osmancb3d0872018-10-16 15:19:28 -0400213 SkColor4f color4f = SkColor4f::FromColor(color);
Brian Salomonbc73eb42019-12-18 14:57:45 -0500214 // We only apply delta to the r,g, and b channels. This is because we're using this
215 // to test the canTweakAlphaForCoverage() optimization. A processor is allowed
216 // to use the input color's alpha in its calculation and report this optimization.
217 for (int i = 0; i < 3; i++) {
Brian Osmancb3d0872018-10-16 15:19:28 -0400218 if (color4f[i] > 0.5) {
219 color4f[i] -= delta;
Michael Ludwig7034f152018-10-08 16:43:58 -0400220 } else {
Brian Osmancb3d0872018-10-16 15:19:28 -0400221 color4f[i] += delta;
Michael Ludwig7034f152018-10-08 16:43:58 -0400222 }
223 }
Brian Osmancb3d0872018-10-16 15:19:28 -0400224 return color4f.premul().toBytes_RGBA();
Brian Salomon0e05a822017-07-25 09:43:22 -0400225}
Brian Salomon587e08f2017-01-27 10:59:27 -0500226
John Stiles0dee9b02020-07-20 11:45:58 -0400227// The output buffer must be the same size as the render-target context.
John Stilesfa088a62021-08-12 23:01:41 -0400228static void render_fp(GrDirectContext* dContext,
229 skgpu::v1::SurfaceDrawContext* sdc,
230 std::unique_ptr<GrFragmentProcessor> fp,
231 GrColor* outBuffer) {
Robert Phillipsba701382021-07-07 14:15:12 -0400232 sdc->fillWithFP(std::move(fp));
233 std::fill_n(outBuffer, sdc->width() * sdc->height(), 0);
234 auto ii = SkImageInfo::Make(sdc->dimensions(), kRGBA_8888_SkColorType, kPremul_SkAlphaType);
235 GrPixmap resultPM(ii, outBuffer, sdc->width()*sizeof(uint32_t));
236 sdc->readPixels(dContext, resultPM, {0, 0});
Michael Ludwig7034f152018-10-08 16:43:58 -0400237}
238
John Stilesaf110302020-07-20 09:45:51 -0400239// This class is responsible for reproducibly generating a random fragment processor.
240// An identical randomly-designed FP can be generated as many times as needed.
241class TestFPGenerator {
242 public:
243 TestFPGenerator() = delete;
244 TestFPGenerator(GrDirectContext* context, GrResourceProvider* resourceProvider)
245 : fContext(context)
246 , fResourceProvider(resourceProvider)
247 , fInitialSeed(synthesizeInitialSeed())
248 , fRandomSeed(fInitialSeed) {}
Brian Osmanc35a2d42017-03-17 10:58:53 -0400249
John Stilesaf110302020-07-20 09:45:51 -0400250 uint32_t initialSeed() { return fInitialSeed; }
251
252 bool init() {
253 // Initializes the two test texture proxies that are available to the FP test factories.
254 SkRandom random{fRandomSeed};
255 static constexpr int kTestTextureSize = 256;
256
257 {
258 // Put premul data into the RGBA texture that the test FPs can optionally use.
259 GrColor* rgbaData = new GrColor[kTestTextureSize * kTestTextureSize];
260 for (int y = 0; y < kTestTextureSize; ++y) {
261 for (int x = 0; x < kTestTextureSize; ++x) {
262 rgbaData[kTestTextureSize * y + x] = input_texel_color(
263 random.nextULessThan(256), random.nextULessThan(256), 0.0f);
264 }
265 }
266
267 SkImageInfo ii = SkImageInfo::Make(kTestTextureSize, kTestTextureSize,
268 kRGBA_8888_SkColorType, kPremul_SkAlphaType);
269 SkBitmap bitmap;
270 bitmap.installPixels(
271 ii, rgbaData, ii.minRowBytes(),
272 [](void* addr, void* context) { delete[](GrColor*) addr; }, nullptr);
273 bitmap.setImmutable();
Brian Salomon27c42022021-04-28 12:39:21 -0400274 auto view = std::get<0>(GrMakeUncachedBitmapProxyView(fContext, bitmap));
275 if (!view || !view.proxy()->instantiate(fResourceProvider)) {
John Stilesaf110302020-07-20 09:45:51 -0400276 SkDebugf("Unable to instantiate RGBA8888 test texture.");
277 return false;
278 }
279 fTestViews[0] = GrProcessorTestData::ViewInfo{view, GrColorType::kRGBA_8888,
280 kPremul_SkAlphaType};
281 }
282
283 {
284 // Put random values into the alpha texture that the test FPs can optionally use.
285 uint8_t* alphaData = new uint8_t[kTestTextureSize * kTestTextureSize];
286 for (int y = 0; y < kTestTextureSize; ++y) {
287 for (int x = 0; x < kTestTextureSize; ++x) {
288 alphaData[kTestTextureSize * y + x] = random.nextULessThan(256);
289 }
290 }
291
292 SkImageInfo ii = SkImageInfo::Make(kTestTextureSize, kTestTextureSize,
293 kAlpha_8_SkColorType, kPremul_SkAlphaType);
294 SkBitmap bitmap;
295 bitmap.installPixels(
296 ii, alphaData, ii.minRowBytes(),
297 [](void* addr, void* context) { delete[](uint8_t*) addr; }, nullptr);
298 bitmap.setImmutable();
Brian Salomon27c42022021-04-28 12:39:21 -0400299 auto view = std::get<0>(GrMakeUncachedBitmapProxyView(fContext, bitmap));
300 if (!view || !view.proxy()->instantiate(fResourceProvider)) {
John Stilesaf110302020-07-20 09:45:51 -0400301 SkDebugf("Unable to instantiate A8 test texture.");
302 return false;
303 }
304 fTestViews[1] = GrProcessorTestData::ViewInfo{view, GrColorType::kAlpha_8,
305 kPremul_SkAlphaType};
306 }
307
308 return true;
309 }
310
311 void reroll() {
312 // Feed our current random seed into SkRandom to generate a new seed.
313 SkRandom random{fRandomSeed};
314 fRandomSeed = random.nextU();
315 }
316
John Stiles87d0a2f2020-08-10 13:12:41 -0400317 std::unique_ptr<GrFragmentProcessor> make(int type, int randomTreeDepth,
John Stiles0dee9b02020-07-20 11:45:58 -0400318 std::unique_ptr<GrFragmentProcessor> inputFP) {
John Stilesaf110302020-07-20 09:45:51 -0400319 // This will generate the exact same randomized FP (of each requested type) each time
320 // it's called. Call `reroll` to get a different FP.
321 SkRandom random{fRandomSeed};
John Stiles87d0a2f2020-08-10 13:12:41 -0400322 GrProcessorTestData testData{&random, fContext, randomTreeDepth,
323 SK_ARRAY_COUNT(fTestViews), fTestViews,
John Stiles0dee9b02020-07-20 11:45:58 -0400324 std::move(inputFP)};
John Stilesaf110302020-07-20 09:45:51 -0400325 return GrFragmentProcessorTestFactory::MakeIdx(type, &testData);
326 }
327
John Stiles87d0a2f2020-08-10 13:12:41 -0400328 std::unique_ptr<GrFragmentProcessor> make(int type, int randomTreeDepth,
329 GrSurfaceProxyView view,
John Stiles0dee9b02020-07-20 11:45:58 -0400330 SkAlphaType alpha = kPremul_SkAlphaType) {
John Stiles87d0a2f2020-08-10 13:12:41 -0400331 return make(type, randomTreeDepth, GrTextureEffect::Make(view, alpha));
John Stiles0dee9b02020-07-20 11:45:58 -0400332 }
333
John Stilesaf110302020-07-20 09:45:51 -0400334 private:
335 static uint32_t synthesizeInitialSeed() {
336 if (FLAGS_randomProcessorTest) {
337 std::random_device rd;
338 return rd();
339 } else {
340 return FLAGS_processorSeed;
Robert Phillips0bd24dc2018-01-16 08:06:32 -0500341 }
Brian Salomon0e05a822017-07-25 09:43:22 -0400342 }
Brian Salomon0e05a822017-07-25 09:43:22 -0400343
John Stilesaf110302020-07-20 09:45:51 -0400344 GrDirectContext* fContext; // owned by caller
345 GrResourceProvider* fResourceProvider; // owned by caller
346 const uint32_t fInitialSeed;
347 uint32_t fRandomSeed;
348 GrProcessorTestData::ViewInfo fTestViews[2];
349};
Brian Salomon0e05a822017-07-25 09:43:22 -0400350
John Stiles4ed69472020-08-11 16:04:31 -0400351// Creates an array of color values from input_texel_color(), to be used as an input texture.
John Stilesfa088a62021-08-12 23:01:41 -0400352static std::vector<GrColor> make_input_pixels(int width, int height, SkScalar delta) {
John Stiles4ed69472020-08-11 16:04:31 -0400353 std::vector<GrColor> pixel(width * height);
Brian Salomon0e05a822017-07-25 09:43:22 -0400354 for (int y = 0; y < width; ++y) {
355 for (int x = 0; x < height; ++x) {
John Stiles4ed69472020-08-11 16:04:31 -0400356 pixel[width * y + x] = input_texel_color(x, y, delta);
Brian Salomon0e05a822017-07-25 09:43:22 -0400357 }
358 }
Robert Phillips0bd24dc2018-01-16 08:06:32 -0500359
John Stiles4ed69472020-08-11 16:04:31 -0400360 return pixel;
361}
362
363// Creates a texture of premul colors used as the output of the fragment processor that precedes
364// the fragment processor under test. An array of W*H colors are passed in as the texture data.
John Stilesfa088a62021-08-12 23:01:41 -0400365static GrSurfaceProxyView make_input_texture(GrRecordingContext* context,
John Stiles4ed69472020-08-11 16:04:31 -0400366 int width, int height, GrColor* pixel) {
Brian Osman2700abc2018-09-12 10:19:41 -0400367 SkImageInfo ii = SkImageInfo::Make(width, height, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
Greg Daniel6f5441a2020-01-28 17:02:49 -0500368 SkBitmap bitmap;
John Stiles4ed69472020-08-11 16:04:31 -0400369 bitmap.installPixels(ii, pixel, ii.minRowBytes());
Greg Daniel6f5441a2020-01-28 17:02:49 -0500370 bitmap.setImmutable();
Brian Salomon27c42022021-04-28 12:39:21 -0400371 return std::get<0>(GrMakeUncachedBitmapProxyView(context, bitmap));
Brian Salomon0e05a822017-07-25 09:43:22 -0400372}
Robert Phillips0bd24dc2018-01-16 08:06:32 -0500373
John Stilesaf110302020-07-20 09:45:51 -0400374// We tag logged data as unpremul to avoid conversion when encoding as PNG. The input texture
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400375// actually contains unpremul data. Also, even though we made the result data by rendering into
Robert Phillips4dca8312021-07-28 15:13:20 -0400376// a "unpremul" SurfaceDrawContext, our input texture is unpremul and outside of the random
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400377// effect configuration, we didn't do anything to ensure the output is actually premul. We just
Brian Salomoneebe7352020-12-09 16:37:04 -0500378// don't currently allow kUnpremul GrSurfaceDrawContexts.
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400379static constexpr auto kLogAlphaType = kUnpremul_SkAlphaType;
Michael Ludwige8e10752018-10-01 12:42:53 -0400380
John Stilesfa088a62021-08-12 23:01:41 -0400381static bool log_pixels(GrColor* pixels, int widthHeight, SkString* dst) {
John Stilesaf110302020-07-20 09:45:51 -0400382 SkImageInfo info =
383 SkImageInfo::Make(widthHeight, widthHeight, kRGBA_8888_SkColorType, kLogAlphaType);
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400384 SkBitmap bmp;
385 bmp.installPixels(info, pixels, widthHeight * sizeof(GrColor));
Brian Salomon28a8f282019-10-24 20:07:39 -0400386 return BipmapToBase64DataURI(bmp, dst);
Michael Ludwige8e10752018-10-01 12:42:53 -0400387}
388
John Stilesfa088a62021-08-12 23:01:41 -0400389static bool log_texture_view(GrDirectContext* dContext, GrSurfaceProxyView src, SkString* dst) {
Greg Daniel124486b2020-02-11 11:54:55 -0500390 SkImageInfo ii = SkImageInfo::Make(src.proxy()->dimensions(), kRGBA_8888_SkColorType,
391 kLogAlphaType);
Greg Daniel3912a4b2020-01-14 09:56:04 -0500392
Robert Phillips33bf2b52021-08-02 11:14:38 -0400393 auto sContext = dContext->priv().makeSC(std::move(src), ii.colorInfo());
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400394 SkBitmap bm;
395 SkAssertResult(bm.tryAllocPixels(ii));
Brian Salomondd4087d2020-12-23 20:36:44 -0500396 SkAssertResult(sContext->readPixels(dContext, bm.pixmap(), {0, 0}));
Brian Salomon28a8f282019-10-24 20:07:39 -0400397 return BipmapToBase64DataURI(bm, dst);
Michael Ludwige8e10752018-10-01 12:42:53 -0400398}
399
John Stilesfa088a62021-08-12 23:01:41 -0400400static bool fuzzy_color_equals(const SkPMColor4f& c1, const SkPMColor4f& c2) {
Michael Ludwig7034f152018-10-08 16:43:58 -0400401 // With the loss of precision of rendering into 32-bit color, then estimating the FP's output
Brian Salomon682ba432019-12-17 20:20:23 +0000402 // 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 -0400403 // (really 1/128 ~ .0078, but frequently floating point issues make that tolerance a little
404 // too unforgiving).
Brian Salomon682ba432019-12-17 20:20:23 +0000405 static constexpr SkScalar kTolerance = 0.01f;
Michael Ludwig7034f152018-10-08 16:43:58 -0400406 for (int i = 0; i < 4; i++) {
407 if (!SkScalarNearlyEqual(c1[i], c2[i], kTolerance)) {
408 return false;
409 }
410 }
411 return true;
412}
413
Brian Salomonbc73eb42019-12-18 14:57:45 -0500414// Given three input colors (color preceding the FP being tested) provided to the FP at the same
415// local coord and the three corresponding FP outputs, this ensures that either:
416// out[0] = fp * in[0].a, out[1] = fp * in[1].a, and out[2] = fp * in[2].a
417// where fp is the pre-modulated color that should not be changing across frames (FP's state doesn't
418// change), OR:
419// out[0] = fp * in[0], out[1] = fp * in[1], and out[2] = fp * in[2]
420// (per-channel modulation instead of modulation by just the alpha channel)
421// It does this by estimating the pre-modulated fp color from one of the input/output pairs and
422// confirms the conditions hold for the other two pairs.
423// It is required that the three input colors have the same alpha as fp is allowed to be a function
424// of the input alpha (but not r, g, or b).
John Stilesfa088a62021-08-12 23:01:41 -0400425static bool legal_modulation(const GrColor inGr[3], const GrColor outGr[3]) {
Michael Ludwig7034f152018-10-08 16:43:58 -0400426 // Convert to floating point, which is the number space the FP operates in (more or less)
Brian Salomonbc73eb42019-12-18 14:57:45 -0500427 SkPMColor4f inf[3], outf[3];
428 for (int i = 0; i < 3; ++i) {
John Stilesfa088a62021-08-12 23:01:41 -0400429 inf[i] = SkPMColor4f::FromBytes_RGBA(inGr[i]);
430 outf[i] = SkPMColor4f::FromBytes_RGBA(outGr[i]);
Brian Salomonbc73eb42019-12-18 14:57:45 -0500431 }
432 // This test is only valid if all the input alphas are the same.
433 SkASSERT(inf[0].fA == inf[1].fA && inf[1].fA == inf[2].fA);
Michael Ludwig7034f152018-10-08 16:43:58 -0400434
435 // Reconstruct the output of the FP before the shader modulated its color with the input value.
436 // When the original input is very small, it may cause the final output color to round
437 // to 0, in which case we estimate the pre-modulated color using one of the stepped frames that
438 // will then have a guaranteed larger channel value (since the offset will be added to it).
Brian Salomon0a7ca7a2019-12-27 12:18:19 -0500439 SkPMColor4f fpPreColorModulation = {0,0,0,0};
440 SkPMColor4f fpPreAlphaModulation = {0,0,0,0};
Michael Ludwig7034f152018-10-08 16:43:58 -0400441 for (int i = 0; i < 4; i++) {
Brian Salomonbc73eb42019-12-18 14:57:45 -0500442 // Use the most stepped up frame
443 int maxInIdx = inf[0][i] > inf[1][i] ? 0 : 1;
444 maxInIdx = inf[maxInIdx][i] > inf[2][i] ? maxInIdx : 2;
John Stilesfe7aed62020-07-20 13:48:02 -0400445 const SkPMColor4f& in = inf[maxInIdx];
446 const SkPMColor4f& out = outf[maxInIdx];
Brian Salomon0a7ca7a2019-12-27 12:18:19 -0500447 if (in[i] > 0) {
448 fpPreColorModulation[i] = out[i] / in[i];
449 }
450 if (in[3] > 0) {
451 fpPreAlphaModulation[i] = out[i] / in[3];
452 }
Michael Ludwig7034f152018-10-08 16:43:58 -0400453 }
454
455 // With reconstructed pre-modulated FP output, derive the expected value of fp * input for each
456 // of the transformed input colors.
Brian Salomonbc73eb42019-12-18 14:57:45 -0500457 SkPMColor4f expectedForAlphaModulation[3];
458 SkPMColor4f expectedForColorModulation[3];
459 for (int i = 0; i < 3; ++i) {
460 expectedForAlphaModulation[i] = fpPreAlphaModulation * inf[i].fA;
461 expectedForColorModulation[i] = fpPreColorModulation * inf[i];
462 // If the input alpha is 0 then the other channels should also be zero
463 // since the color is assumed to be premul. Modulating zeros by anything
464 // should produce zeros.
465 if (inf[i].fA == 0) {
466 SkASSERT(inf[i].fR == 0 && inf[i].fG == 0 && inf[i].fB == 0);
467 expectedForColorModulation[i] = expectedForAlphaModulation[i] = {0, 0, 0, 0};
468 }
469 }
Michael Ludwig7034f152018-10-08 16:43:58 -0400470
Brian Salomonbc73eb42019-12-18 14:57:45 -0500471 bool isLegalColorModulation = fuzzy_color_equals(outf[0], expectedForColorModulation[0]) &&
472 fuzzy_color_equals(outf[1], expectedForColorModulation[1]) &&
473 fuzzy_color_equals(outf[2], expectedForColorModulation[2]);
474
475 bool isLegalAlphaModulation = fuzzy_color_equals(outf[0], expectedForAlphaModulation[0]) &&
476 fuzzy_color_equals(outf[1], expectedForAlphaModulation[1]) &&
477 fuzzy_color_equals(outf[2], expectedForAlphaModulation[2]);
478
479 // This can be enabled to print the values that caused this check to fail.
480 if (0 && !isLegalColorModulation && !isLegalAlphaModulation) {
481 SkDebugf("Color modulation test\n\timplied mod color: (%.03f, %.03f, %.03f, %.03f)\n",
482 fpPreColorModulation[0],
483 fpPreColorModulation[1],
484 fpPreColorModulation[2],
485 fpPreColorModulation[3]);
486 for (int i = 0; i < 3; ++i) {
487 SkDebugf("\t(%.03f, %.03f, %.03f, %.03f) -> "
488 "(%.03f, %.03f, %.03f, %.03f) | "
489 "(%.03f, %.03f, %.03f, %.03f), ok: %d\n",
490 inf[i].fR, inf[i].fG, inf[i].fB, inf[i].fA,
491 outf[i].fR, outf[i].fG, outf[i].fB, outf[i].fA,
492 expectedForColorModulation[i].fR, expectedForColorModulation[i].fG,
493 expectedForColorModulation[i].fB, expectedForColorModulation[i].fA,
494 fuzzy_color_equals(outf[i], expectedForColorModulation[i]));
495 }
496 SkDebugf("Alpha modulation test\n\timplied mod color: (%.03f, %.03f, %.03f, %.03f)\n",
497 fpPreAlphaModulation[0],
498 fpPreAlphaModulation[1],
499 fpPreAlphaModulation[2],
500 fpPreAlphaModulation[3]);
501 for (int i = 0; i < 3; ++i) {
502 SkDebugf("\t(%.03f, %.03f, %.03f, %.03f) -> "
503 "(%.03f, %.03f, %.03f, %.03f) | "
504 "(%.03f, %.03f, %.03f, %.03f), ok: %d\n",
505 inf[i].fR, inf[i].fG, inf[i].fB, inf[i].fA,
506 outf[i].fR, outf[i].fG, outf[i].fB, outf[i].fA,
507 expectedForAlphaModulation[i].fR, expectedForAlphaModulation[i].fG,
508 expectedForAlphaModulation[i].fB, expectedForAlphaModulation[i].fA,
509 fuzzy_color_equals(outf[i], expectedForAlphaModulation[i]));
510 }
511 }
512 return isLegalColorModulation || isLegalAlphaModulation;
Michael Ludwig7034f152018-10-08 16:43:58 -0400513}
514
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500515DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ProcessorOptimizationValidationTest, reporter, ctxInfo) {
John Stilesaf110302020-07-20 09:45:51 -0400516 GrDirectContext* context = ctxInfo.directContext();
517 GrResourceProvider* resourceProvider = context->priv().resourceProvider();
Brian Salomon1c053642017-07-24 10:16:19 -0400518 using FPFactory = GrFragmentProcessorTestFactory;
Brian Osmanc35a2d42017-03-17 10:58:53 -0400519
John Stilesaf110302020-07-20 09:45:51 -0400520 TestFPGenerator fpGenerator{context, resourceProvider};
521 if (!fpGenerator.init()) {
522 ERRORF(reporter, "Could not initialize TestFPGenerator");
523 return;
Brian Osmanc35a2d42017-03-17 10:58:53 -0400524 }
Brian Osmanc35a2d42017-03-17 10:58:53 -0400525
Brian Salomon0e05a822017-07-25 09:43:22 -0400526 // Make the destination context for the test.
527 static constexpr int kRenderSize = 256;
Robert Phillips4dca8312021-07-28 15:13:20 -0400528 auto sdc = skgpu::v1::SurfaceDrawContext::Make(
Greg Daniele20fcad2020-01-08 11:52:34 -0500529 context, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kExact,
Chris Daltonf5b87f92021-04-19 17:27:09 -0600530 {kRenderSize, kRenderSize}, SkSurfaceProps());
Brian Salomond1a8bdf2017-02-10 12:39:26 -0500531
Michael Ludwig7034f152018-10-08 16:43:58 -0400532 // Coverage optimization uses three frames with a linearly transformed input texture. The first
533 // frame has no offset, second frames add .2 and .4, which should then be present as a fixed
534 // difference between the frame outputs if the FP is properly following the modulation
535 // requirements of the coverage optimization.
536 static constexpr SkScalar kInputDelta = 0.2f;
John Stiles4ed69472020-08-11 16:04:31 -0400537 std::vector<GrColor> inputPixels1 = make_input_pixels(kRenderSize, kRenderSize, 0.0f);
538 std::vector<GrColor> inputPixels2 =
539 make_input_pixels(kRenderSize, kRenderSize, 1 * kInputDelta);
540 std::vector<GrColor> inputPixels3 =
541 make_input_pixels(kRenderSize, kRenderSize, 2 * kInputDelta);
542 GrSurfaceProxyView inputTexture1 =
543 make_input_texture(context, kRenderSize, kRenderSize, inputPixels1.data());
544 GrSurfaceProxyView inputTexture2 =
545 make_input_texture(context, kRenderSize, kRenderSize, inputPixels2.data());
546 GrSurfaceProxyView inputTexture3 =
547 make_input_texture(context, kRenderSize, kRenderSize, inputPixels3.data());
Robert Phillips30f9bc62017-02-22 15:28:38 -0500548
Michael Ludwige8e10752018-10-01 12:42:53 -0400549 // Encoded images are very verbose and this tests many potential images, so only export the
550 // first failure (subsequent failures have a reasonable chance of being related).
551 bool loggedFirstFailure = false;
Michael Ludwig314d3772018-10-03 16:04:38 -0400552 bool loggedFirstWarning = false;
Michael Ludwig7034f152018-10-08 16:43:58 -0400553
John Stilesaf110302020-07-20 09:45:51 -0400554 // Storage for the three frames required for coverage compatibility optimization testing.
555 // Each frame uses the correspondingly numbered inputTextureX.
556 std::vector<GrColor> readData1(kRenderSize * kRenderSize);
557 std::vector<GrColor> readData2(kRenderSize * kRenderSize);
558 std::vector<GrColor> readData3(kRenderSize * kRenderSize);
Michael Ludwig7034f152018-10-08 16:43:58 -0400559
Brian Salomon0e05a822017-07-25 09:43:22 -0400560 // Because processor factories configure themselves in random ways, this is not exhaustive.
Brian Salomon587e08f2017-01-27 10:59:27 -0500561 for (int i = 0; i < FPFactory::Count(); ++i) {
John Stilesfe7aed62020-07-20 13:48:02 -0400562 int optimizedForOpaqueInput = 0;
563 int optimizedForCoverageAsAlpha = 0;
564 int optimizedForConstantOutputForInput = 0;
John Stilesaf110302020-07-20 09:45:51 -0400565
John Stilesfe7aed62020-07-20 13:48:02 -0400566#ifdef __MSVC_RUNTIME_CHECKS
Brian Osman50ea3c02019-02-04 10:01:53 -0500567 // This test is infuriatingly slow with MSVC runtime checks enabled
John Stilesfe7aed62020-07-20 13:48:02 -0400568 static constexpr int kMinimumTrials = 1;
569 static constexpr int kMaximumTrials = 1;
570 static constexpr int kExpectedSuccesses = 1;
571#else
572 // We start by testing each fragment-processor 100 times, watching the optimization bits
573 // that appear. If we see an optimization bit appear in those first 100 trials, we keep
574 // running tests until we see at least five successful trials that have this optimization
575 // bit enabled. If we never see a particular optimization bit after 100 trials, we assume
576 // that this FP doesn't support that optimization at all.
577 static constexpr int kMinimumTrials = 100;
578 static constexpr int kMaximumTrials = 2000;
579 static constexpr int kExpectedSuccesses = 5;
Brian Osman50ea3c02019-02-04 10:01:53 -0500580#endif
Robert Phillipsa91e0b72017-05-01 13:12:20 -0400581
John Stilesfe7aed62020-07-20 13:48:02 -0400582 for (int trial = 0;; ++trial) {
John Stilesaf110302020-07-20 09:45:51 -0400583 // Create a randomly-configured FP.
584 fpGenerator.reroll();
John Stiles87d0a2f2020-08-10 13:12:41 -0400585 std::unique_ptr<GrFragmentProcessor> fp =
John Stiles9fbe9e92020-08-10 16:35:01 -0400586 fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture1);
John Stilesaf110302020-07-20 09:45:51 -0400587
John Stilesfe7aed62020-07-20 13:48:02 -0400588 // If we have iterated enough times and seen a sufficient number of successes on each
589 // optimization bit that can be returned, stop running trials.
590 if (trial >= kMinimumTrials) {
591 bool moreTrialsNeeded = (optimizedForOpaqueInput > 0 &&
592 optimizedForOpaqueInput < kExpectedSuccesses) ||
593 (optimizedForCoverageAsAlpha > 0 &&
594 optimizedForCoverageAsAlpha < kExpectedSuccesses) ||
595 (optimizedForConstantOutputForInput > 0 &&
596 optimizedForConstantOutputForInput < kExpectedSuccesses);
597 if (!moreTrialsNeeded) break;
598
599 if (trial >= kMaximumTrials) {
600 SkDebugf("Abandoning ProcessorOptimizationValidationTest after %d trials. "
John Stilesba1879d2020-08-11 13:58:32 -0400601 "Seed: 0x%08x, processor:\n%s",
602 kMaximumTrials, fpGenerator.initialSeed(), fp->dumpTreeInfo().c_str());
John Stilesfe7aed62020-07-20 13:48:02 -0400603 break;
604 }
605 }
606
607 // Skip further testing if this trial has no optimization bits enabled.
Brian Salomon587e08f2017-01-27 10:59:27 -0500608 if (!fp->hasConstantOutputForConstantInput() && !fp->preservesOpaqueInput() &&
Brian Salomonf3b995b2017-02-15 10:22:23 -0500609 !fp->compatibleWithCoverageAsAlpha()) {
Brian Salomon587e08f2017-01-27 10:59:27 -0500610 continue;
611 }
Brian Salomonaff329b2017-08-11 09:40:37 -0400612
John Stilesaf110302020-07-20 09:45:51 -0400613 // We can make identical copies of the test FP in order to test coverage-as-alpha.
Michael Ludwig7034f152018-10-08 16:43:58 -0400614 if (fp->compatibleWithCoverageAsAlpha()) {
John Stiles0dee9b02020-07-20 11:45:58 -0400615 // Create and render two identical versions of this FP, but using different input
616 // textures, to check coverage optimization. We don't need to do this step for
617 // constant-output or preserving-opacity tests.
Robert Phillips4dca8312021-07-28 15:13:20 -0400618 render_fp(context, sdc.get(),
John Stiles9fbe9e92020-08-10 16:35:01 -0400619 fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture2),
John Stiles87d0a2f2020-08-10 13:12:41 -0400620 readData2.data());
Robert Phillips4dca8312021-07-28 15:13:20 -0400621 render_fp(context, sdc.get(),
John Stiles9fbe9e92020-08-10 16:35:01 -0400622 fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture3),
John Stiles87d0a2f2020-08-10 13:12:41 -0400623 readData3.data());
John Stilesfe7aed62020-07-20 13:48:02 -0400624 ++optimizedForCoverageAsAlpha;
625 }
626
627 if (fp->hasConstantOutputForConstantInput()) {
628 ++optimizedForConstantOutputForInput;
629 }
630
631 if (fp->preservesOpaqueInput()) {
632 ++optimizedForOpaqueInput;
Michael Ludwig7034f152018-10-08 16:43:58 -0400633 }
Brian Salomon3f4de782020-06-18 14:16:00 -0400634
John Stiles0dee9b02020-07-20 11:45:58 -0400635 // Draw base frame last so that rtc holds the original FP behavior if we need to dump
636 // the image to the log.
Robert Phillips4dca8312021-07-28 15:13:20 -0400637 render_fp(context, sdc.get(), fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture1),
John Stiles87d0a2f2020-08-10 13:12:41 -0400638 readData1.data());
Brian Salomonaff329b2017-08-11 09:40:37 -0400639
Michael Ludwig314d3772018-10-03 16:04:38 -0400640 // This test has a history of being flaky on a number of devices. If an FP is logically
641 // violating the optimizations, it's reasonable to expect it to violate requirements on
642 // a large number of pixels in the image. Sporadic pixel violations are more indicative
643 // of device errors and represents a separate problem.
Michael Ludwig72ab3462018-12-10 12:43:36 -0500644#if defined(SK_BUILD_FOR_SKQP)
Michael Ludwig314d3772018-10-03 16:04:38 -0400645 static constexpr int kMaxAcceptableFailedPixels = 0; // Strict when running as SKQP
646#else
647 static constexpr int kMaxAcceptableFailedPixels = 2 * kRenderSize; // ~0.7% of the image
648#endif
649
Michael Ludwig314d3772018-10-03 16:04:38 -0400650 // Collect first optimization failure message, to be output later as a warning or an
651 // error depending on whether the rendering "passed" or failed.
John Stilesaf110302020-07-20 09:45:51 -0400652 int failedPixelCount = 0;
Michael Ludwig314d3772018-10-03 16:04:38 -0400653 SkString coverageMessage;
654 SkString opaqueMessage;
655 SkString constMessage;
656 for (int y = 0; y < kRenderSize; ++y) {
657 for (int x = 0; x < kRenderSize; ++x) {
658 bool passing = true;
John Stiles4ed69472020-08-11 16:04:31 -0400659 GrColor input = inputPixels1[y * kRenderSize + x];
John Stilesaf110302020-07-20 09:45:51 -0400660 GrColor output = readData1[y * kRenderSize + x];
Michael Ludwig7034f152018-10-08 16:43:58 -0400661
662 if (fp->compatibleWithCoverageAsAlpha()) {
Brian Salomonbc73eb42019-12-18 14:57:45 -0500663 GrColor ins[3];
664 ins[0] = input;
John Stiles4ed69472020-08-11 16:04:31 -0400665 ins[1] = inputPixels2[y * kRenderSize + x];
666 ins[2] = inputPixels3[y * kRenderSize + x];
Michael Ludwig7034f152018-10-08 16:43:58 -0400667
Brian Salomonbc73eb42019-12-18 14:57:45 -0500668 GrColor outs[3];
669 outs[0] = output;
John Stilesaf110302020-07-20 09:45:51 -0400670 outs[1] = readData2[y * kRenderSize + x];
671 outs[2] = readData3[y * kRenderSize + x];
Michael Ludwig7034f152018-10-08 16:43:58 -0400672
Brian Salomonbc73eb42019-12-18 14:57:45 -0500673 if (!legal_modulation(ins, outs)) {
Brian Salomon587e08f2017-01-27 10:59:27 -0500674 passing = false;
Michael Ludwig314d3772018-10-03 16:04:38 -0400675 if (coverageMessage.isEmpty()) {
Brian Salomonbc73eb42019-12-18 14:57:45 -0500676 coverageMessage.printf(
John Stilesba1879d2020-08-11 13:58:32 -0400677 "\"Modulating\" processor did not match alpha-modulation "
678 "nor color-modulation rules.\n"
Michael Ludwig7034f152018-10-08 16:43:58 -0400679 "Input: 0x%08x, Output: 0x%08x, pixel (%d, %d).",
John Stilesba1879d2020-08-11 13:58:32 -0400680 input, output, x, y);
Michael Ludwig314d3772018-10-03 16:04:38 -0400681 }
Brian Salomon587e08f2017-01-27 10:59:27 -0500682 }
683 }
Michael Ludwig7034f152018-10-08 16:43:58 -0400684
Brian Osmancb3d0872018-10-16 15:19:28 -0400685 SkPMColor4f input4f = SkPMColor4f::FromBytes_RGBA(input);
686 SkPMColor4f output4f = SkPMColor4f::FromBytes_RGBA(output);
Brian Osman1d5b5982018-10-01 13:41:39 -0400687 SkPMColor4f expected4f;
Michael Ludwig7034f152018-10-08 16:43:58 -0400688 if (fp->hasConstantOutputForConstantInput(input4f, &expected4f)) {
Brian Osmancb3d0872018-10-16 15:19:28 -0400689 float rDiff = fabsf(output4f.fR - expected4f.fR);
690 float gDiff = fabsf(output4f.fG - expected4f.fG);
691 float bDiff = fabsf(output4f.fB - expected4f.fB);
692 float aDiff = fabsf(output4f.fA - expected4f.fA);
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500693 static constexpr float kTol = 4 / 255.f;
Brian Salomon587e08f2017-01-27 10:59:27 -0500694 if (rDiff > kTol || gDiff > kTol || bDiff > kTol || aDiff > kTol) {
Michael Ludwig314d3772018-10-03 16:04:38 -0400695 if (constMessage.isEmpty()) {
696 passing = false;
697
John Stilesba1879d2020-08-11 13:58:32 -0400698 constMessage.printf(
699 "Processor claimed output for const input doesn't match "
700 "actual output.\n"
701 "Error: %f, Tolerance: %f, input: (%f, %f, %f, %f), "
702 "actual: (%f, %f, %f, %f), expected(%f, %f, %f, %f).",
703 std::max(rDiff, std::max(gDiff, std::max(bDiff, aDiff))),
704 kTol, input4f.fR, input4f.fG, input4f.fB, input4f.fA,
Brian Osmancb3d0872018-10-16 15:19:28 -0400705 output4f.fR, output4f.fG, output4f.fB, output4f.fA,
706 expected4f.fR, expected4f.fG, expected4f.fB, expected4f.fA);
Michael Ludwig314d3772018-10-03 16:04:38 -0400707 }
Brian Salomon587e08f2017-01-27 10:59:27 -0500708 }
709 }
Brian Osman00b29392018-11-05 15:42:43 -0500710 if (input4f.isOpaque() && fp->preservesOpaqueInput() && !output4f.isOpaque()) {
Brian Salomon587e08f2017-01-27 10:59:27 -0500711 passing = false;
Michael Ludwig314d3772018-10-03 16:04:38 -0400712
713 if (opaqueMessage.isEmpty()) {
John Stilesba1879d2020-08-11 13:58:32 -0400714 opaqueMessage.printf(
715 "Processor claimed opaqueness is preserved but "
Michael Ludwig314d3772018-10-03 16:04:38 -0400716 "it is not. Input: 0x%08x, Output: 0x%08x.",
John Stilesba1879d2020-08-11 13:58:32 -0400717 input, output);
Michael Ludwige8e10752018-10-01 12:42:53 -0400718 }
Brian Osmanbd1f76f2017-03-15 11:33:12 -0400719 }
Michael Ludwig314d3772018-10-03 16:04:38 -0400720
721 if (!passing) {
722 // Regardless of how many optimizations the pixel violates, count it as a
723 // single bad pixel.
724 failedPixelCount++;
725 }
726 }
727 }
728
729 // Finished analyzing the entire image, see if the number of pixel failures meets the
730 // threshold for an FP violating the optimization requirements.
731 if (failedPixelCount > kMaxAcceptableFailedPixels) {
John Stilesba1879d2020-08-11 13:58:32 -0400732 ERRORF(reporter,
733 "Processor violated %d of %d pixels, seed: 0x%08x.\n"
734 "Processor:\n%s\nFirst failing pixel details are below:",
John Stilesaf110302020-07-20 09:45:51 -0400735 failedPixelCount, kRenderSize * kRenderSize, fpGenerator.initialSeed(),
John Stilesba1879d2020-08-11 13:58:32 -0400736 fp->dumpTreeInfo().c_str());
Michael Ludwig314d3772018-10-03 16:04:38 -0400737
738 // Print first failing pixel's details.
739 if (!coverageMessage.isEmpty()) {
740 ERRORF(reporter, coverageMessage.c_str());
741 }
742 if (!constMessage.isEmpty()) {
743 ERRORF(reporter, constMessage.c_str());
744 }
745 if (!opaqueMessage.isEmpty()) {
746 ERRORF(reporter, opaqueMessage.c_str());
747 }
748
749 if (!loggedFirstFailure) {
750 // Print with ERRORF to make sure the encoded image is output
751 SkString input;
Greg Daniel124486b2020-02-11 11:54:55 -0500752 log_texture_view(context, inputTexture1, &input);
Michael Ludwig314d3772018-10-03 16:04:38 -0400753 SkString output;
John Stilesaf110302020-07-20 09:45:51 -0400754 log_pixels(readData1.data(), kRenderSize, &output);
Michael Ludwig314d3772018-10-03 16:04:38 -0400755 ERRORF(reporter, "Input image: %s\n\n"
756 "===========================================================\n\n"
757 "Output image: %s\n", input.c_str(), output.c_str());
758 loggedFirstFailure = true;
759 }
John Stilesaf110302020-07-20 09:45:51 -0400760 } else if (failedPixelCount > 0) {
Michael Ludwig314d3772018-10-03 16:04:38 -0400761 // Don't trigger an error, but don't just hide the failures either.
762 INFOF(reporter, "Processor violated %d of %d pixels (below error threshold), seed: "
763 "0x%08x, processor: %s", failedPixelCount, kRenderSize * kRenderSize,
John Stilesaf110302020-07-20 09:45:51 -0400764 fpGenerator.initialSeed(), fp->dumpInfo().c_str());
Michael Ludwig314d3772018-10-03 16:04:38 -0400765 if (!coverageMessage.isEmpty()) {
John Stiles7bf79992021-06-25 11:05:20 -0400766 INFOF(reporter, "%s", coverageMessage.c_str());
Michael Ludwig314d3772018-10-03 16:04:38 -0400767 }
768 if (!constMessage.isEmpty()) {
John Stiles7bf79992021-06-25 11:05:20 -0400769 INFOF(reporter, "%s", constMessage.c_str());
Michael Ludwig314d3772018-10-03 16:04:38 -0400770 }
771 if (!opaqueMessage.isEmpty()) {
John Stiles7bf79992021-06-25 11:05:20 -0400772 INFOF(reporter, "%s", opaqueMessage.c_str());
Michael Ludwig314d3772018-10-03 16:04:38 -0400773 }
774 if (!loggedFirstWarning) {
775 SkString input;
Greg Daniel124486b2020-02-11 11:54:55 -0500776 log_texture_view(context, inputTexture1, &input);
Michael Ludwig314d3772018-10-03 16:04:38 -0400777 SkString output;
John Stilesaf110302020-07-20 09:45:51 -0400778 log_pixels(readData1.data(), kRenderSize, &output);
Michael Ludwig314d3772018-10-03 16:04:38 -0400779 INFOF(reporter, "Input image: %s\n\n"
780 "===========================================================\n\n"
781 "Output image: %s\n", input.c_str(), output.c_str());
782 loggedFirstWarning = true;
Brian Salomon587e08f2017-01-27 10:59:27 -0500783 }
784 }
785 }
786 }
787}
Robert Phillips18166ee2017-06-01 12:55:44 -0400788
John Stilesea8be212020-08-10 11:38:41 -0400789static void assert_processor_equality(skiatest::Reporter* reporter,
790 const GrFragmentProcessor& fp,
791 const GrFragmentProcessor& clone) {
792 REPORTER_ASSERT(reporter, !strcmp(fp.name(), clone.name()),
John Stilesba1879d2020-08-11 13:58:32 -0400793 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400794 REPORTER_ASSERT(reporter, fp.compatibleWithCoverageAsAlpha() ==
795 clone.compatibleWithCoverageAsAlpha(),
John Stilesba1879d2020-08-11 13:58:32 -0400796 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400797 REPORTER_ASSERT(reporter, fp.isEqual(clone),
John Stilesba1879d2020-08-11 13:58:32 -0400798 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400799 REPORTER_ASSERT(reporter, fp.preservesOpaqueInput() == clone.preservesOpaqueInput(),
John Stilesba1879d2020-08-11 13:58:32 -0400800 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400801 REPORTER_ASSERT(reporter, fp.hasConstantOutputForConstantInput() ==
802 clone.hasConstantOutputForConstantInput(),
John Stilesba1879d2020-08-11 13:58:32 -0400803 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400804 REPORTER_ASSERT(reporter, fp.numChildProcessors() == clone.numChildProcessors(),
John Stilesba1879d2020-08-11 13:58:32 -0400805 "\n%s", fp.dumpTreeInfo().c_str());
Brian Salomon66b500a2021-08-02 12:37:14 -0400806 REPORTER_ASSERT(reporter, fp.sampleUsage() == clone.sampleUsage(),
John Stilesba1879d2020-08-11 13:58:32 -0400807 "\n%s", fp.dumpTreeInfo().c_str());
Brian Salomon66b500a2021-08-02 12:37:14 -0400808 REPORTER_ASSERT(reporter, fp.usesSampleCoords() == clone.usesSampleCoords(),
John Stilesba1879d2020-08-11 13:58:32 -0400809 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400810}
811
812static bool verify_identical_render(skiatest::Reporter* reporter, int renderSize,
813 const char* processorType,
814 const GrColor readData1[], const GrColor readData2[]) {
815 // The ProcessorClone test has a history of being flaky on a number of devices. If an FP clone
816 // is logically wrong, it's reasonable to expect it produce a large number of pixel differences
817 // in the image. Sporadic pixel violations are more indicative device errors and represents a
818 // separate problem.
819#if defined(SK_BUILD_FOR_SKQP)
820 const int maxAcceptableFailedPixels = 0; // Strict when running as SKQP
821#else
822 const int maxAcceptableFailedPixels = 2 * renderSize; // ~0.002% of the pixels (size 1024*1024)
823#endif
824
825 int failedPixelCount = 0;
826 int firstWrongX = 0;
827 int firstWrongY = 0;
828 int idx = 0;
829 for (int y = 0; y < renderSize; ++y) {
830 for (int x = 0; x < renderSize; ++x, ++idx) {
831 if (readData1[idx] != readData2[idx]) {
832 if (!failedPixelCount) {
833 firstWrongX = x;
834 firstWrongY = y;
835 }
836 ++failedPixelCount;
837 }
838 if (failedPixelCount > maxAcceptableFailedPixels) {
839 idx = firstWrongY * renderSize + firstWrongX;
840 ERRORF(reporter,
841 "%s produced different output at (%d, %d). "
842 "Input color: 0x%08x, Original Output Color: 0x%08x, "
843 "Clone Output Color: 0x%08x.",
844 processorType, firstWrongX, firstWrongY, input_texel_color(x, y, 0.0f),
845 readData1[idx], readData2[idx]);
846
847 return false;
848 }
849 }
850 }
851
852 return true;
853}
854
855static void log_clone_failure(skiatest::Reporter* reporter, int renderSize,
856 GrDirectContext* context, const GrSurfaceProxyView& inputTexture,
857 GrColor pixelsFP[], GrColor pixelsClone[], GrColor pixelsRegen[]) {
858 // Write the images out as data URLs for inspection.
859 SkString inputURL, origURL, cloneURL, regenURL;
860 if (log_texture_view(context, inputTexture, &inputURL) &&
861 log_pixels(pixelsFP, renderSize, &origURL) &&
862 log_pixels(pixelsClone, renderSize, &cloneURL) &&
863 log_pixels(pixelsRegen, renderSize, &regenURL)) {
864 ERRORF(reporter,
865 "\nInput image:\n%s\n\n"
866 "==========================================================="
867 "\n\n"
868 "Orig output image:\n%s\n"
869 "==========================================================="
870 "\n\n"
871 "Clone output image:\n%s\n"
872 "==========================================================="
873 "\n\n"
874 "Regen output image:\n%s\n",
875 inputURL.c_str(), origURL.c_str(), cloneURL.c_str(), regenURL.c_str());
876 }
877}
878
Brian Salomon3f4de782020-06-18 14:16:00 -0400879// Tests that a fragment processor returned by GrFragmentProcessor::clone() is equivalent to its
880// progenitor.
Brian Salomon0e05a822017-07-25 09:43:22 -0400881DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ProcessorCloneTest, reporter, ctxInfo) {
John Stilesaf110302020-07-20 09:45:51 -0400882 GrDirectContext* context = ctxInfo.directContext();
883 GrResourceProvider* resourceProvider = context->priv().resourceProvider();
Brian Salomon0e05a822017-07-25 09:43:22 -0400884
John Stilesaf110302020-07-20 09:45:51 -0400885 TestFPGenerator fpGenerator{context, resourceProvider};
886 if (!fpGenerator.init()) {
887 ERRORF(reporter, "Could not initialize TestFPGenerator");
888 return;
889 }
Brian Salomon0e05a822017-07-25 09:43:22 -0400890
891 // Make the destination context for the test.
892 static constexpr int kRenderSize = 1024;
Robert Phillips4dca8312021-07-28 15:13:20 -0400893 auto sdc = skgpu::v1::SurfaceDrawContext::Make(
Greg Daniele20fcad2020-01-08 11:52:34 -0500894 context, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kExact,
Chris Daltonf5b87f92021-04-19 17:27:09 -0600895 {kRenderSize, kRenderSize}, SkSurfaceProps());
Brian Salomon0e05a822017-07-25 09:43:22 -0400896
John Stiles4ed69472020-08-11 16:04:31 -0400897 std::vector<GrColor> inputPixels = make_input_pixels(kRenderSize, kRenderSize, 0.0f);
898 GrSurfaceProxyView inputTexture =
899 make_input_texture(context, kRenderSize, kRenderSize, inputPixels.data());
John Stilesaf110302020-07-20 09:45:51 -0400900
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400901 // On failure we write out images, but just write the first failing set as the print is very
902 // large.
903 bool loggedFirstFailure = false;
904
John Stilesaf110302020-07-20 09:45:51 -0400905 // Storage for the original frame's readback and the readback of its clone.
John Stilesea8be212020-08-10 11:38:41 -0400906 std::vector<GrColor> readDataFP(kRenderSize * kRenderSize);
907 std::vector<GrColor> readDataClone(kRenderSize * kRenderSize);
908 std::vector<GrColor> readDataRegen(kRenderSize * kRenderSize);
Brian Salomon0e05a822017-07-25 09:43:22 -0400909
910 // Because processor factories configure themselves in random ways, this is not exhaustive.
911 for (int i = 0; i < GrFragmentProcessorTestFactory::Count(); ++i) {
912 static constexpr int kTimesToInvokeFactory = 10;
913 for (int j = 0; j < kTimesToInvokeFactory; ++j) {
John Stilesaf110302020-07-20 09:45:51 -0400914 fpGenerator.reroll();
John Stiles87d0a2f2020-08-10 13:12:41 -0400915 std::unique_ptr<GrFragmentProcessor> fp =
John Stiles9fbe9e92020-08-10 16:35:01 -0400916 fpGenerator.make(i, /*randomTreeDepth=*/1, /*inputFP=*/nullptr);
John Stiles87d0a2f2020-08-10 13:12:41 -0400917 std::unique_ptr<GrFragmentProcessor> regen =
John Stiles9fbe9e92020-08-10 16:35:01 -0400918 fpGenerator.make(i, /*randomTreeDepth=*/1, /*inputFP=*/nullptr);
John Stiles8c71f3e2020-06-15 15:07:19 -0400919 std::unique_ptr<GrFragmentProcessor> clone = fp->clone();
Brian Salomon0e05a822017-07-25 09:43:22 -0400920 if (!clone) {
John Stilesba1879d2020-08-11 13:58:32 -0400921 ERRORF(reporter, "Clone of processor %s failed.", fp->dumpTreeInfo().c_str());
Brian Salomon0e05a822017-07-25 09:43:22 -0400922 continue;
923 }
John Stilesea8be212020-08-10 11:38:41 -0400924 assert_processor_equality(reporter, *fp, *clone);
925
Brian Salomon0e05a822017-07-25 09:43:22 -0400926 // Draw with original and read back the results.
Robert Phillips4dca8312021-07-28 15:13:20 -0400927 render_fp(context, sdc.get(), std::move(fp), readDataFP.data());
Brian Salomon0e05a822017-07-25 09:43:22 -0400928
929 // Draw with clone and read back the results.
Robert Phillips4dca8312021-07-28 15:13:20 -0400930 render_fp(context, sdc.get(), std::move(clone), readDataClone.data());
Brian Salomon0e05a822017-07-25 09:43:22 -0400931
932 // Check that the results are the same.
John Stilesea8be212020-08-10 11:38:41 -0400933 if (!verify_identical_render(reporter, kRenderSize, "Processor clone",
934 readDataFP.data(), readDataClone.data())) {
935 // Dump a description from the regenerated processor (since the original FP has
936 // already been consumed).
John Stilesba1879d2020-08-11 13:58:32 -0400937 ERRORF(reporter, "FP hierarchy:\n%s", regen->dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400938
939 // Render and readback output from the regenerated FP. If this also mismatches, the
940 // FP itself doesn't generate consistent output. This could happen if:
941 // - the FP's TestCreate() does not always generate the same FP from a given seed
942 // - the FP's Make() does not always generate the same FP when given the same inputs
943 // - the FP itself generates inconsistent pixels (shader UB?)
944 // - the driver has a bug
Robert Phillips4dca8312021-07-28 15:13:20 -0400945 render_fp(context, sdc.get(), std::move(regen), readDataRegen.data());
John Stilesea8be212020-08-10 11:38:41 -0400946
947 if (!verify_identical_render(reporter, kRenderSize, "Regenerated processor",
948 readDataFP.data(), readDataRegen.data())) {
949 ERRORF(reporter, "Output from regen did not match original!\n");
950 } else {
951 ERRORF(reporter, "Regenerated processor output matches original results.\n");
952 }
953
954 // If this is the first time we've encountered a cloning failure, log the generated
955 // images to the reporter as data URLs.
956 if (!loggedFirstFailure) {
957 log_clone_failure(reporter, kRenderSize, context, inputTexture,
958 readDataFP.data(), readDataClone.data(),
959 readDataRegen.data());
960 loggedFirstFailure = true;
Brian Salomon0e05a822017-07-25 09:43:22 -0400961 }
962 }
963 }
964 }
965}
966
Hal Canary6f6961e2017-01-31 13:50:44 -0500967#endif // GR_TEST_UTILS