blob: 92b632adc3f6459efbfdd3225af8d34c96c505e0 [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"
18#include "src/gpu/GrRenderTargetContext.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "src/gpu/GrResourceProvider.h"
20#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"
Mike Klein0ec1c572018-12-04 11:52:51 -050025#include <atomic>
Hal Canary8a001442018-09-19 11:31:27 -040026#include <random>
27
Brian Salomonbc6b99d2017-01-11 10:32:34 -050028namespace {
Brian Salomon82ddc942017-07-14 12:00:13 -040029class TestOp : public GrMeshDrawOp {
Brian Salomonbc6b99d2017-01-11 10:32:34 -050030public:
31 DEFINE_OP_CLASS_ID
Herb Derbyc76d4092020-10-07 16:46:15 -040032 static GrOp::Owner Make(GrRecordingContext* rContext,
33 std::unique_ptr<GrFragmentProcessor> fp) {
34 return GrOp::Make<TestOp>(rContext, std::move(fp));
Brian Salomon82ddc942017-07-14 12:00:13 -040035 }
36
Robert Phillips5f567c72017-09-14 08:27:37 -040037 const char* name() const override { return "TestOp"; }
38
Chris Dalton1706cbf2019-05-21 19:35:29 -060039 void visitProxies(const VisitProxyFunc& func) const override {
Robert Phillips5f567c72017-09-14 08:27:37 -040040 fProcessors.visitProxies(func);
41 }
42
Brian Salomon82ddc942017-07-14 12:00:13 -040043 FixedFunctionFlags fixedFunctionFlags() const override { return FixedFunctionFlags::kNone; }
44
Chris Dalton6ce447a2019-06-23 18:07:38 -060045 GrProcessorSet::Analysis finalize(
46 const GrCaps& caps, const GrAppliedClip* clip, bool hasMixedSampledCoverage,
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 Dalton6ce447a2019-06-23 18:07:38 -060052 &GrUserStencilSettings::kUnused, hasMixedSampledCoverage, caps, clampType,
53 &overrideColor);
Brian Salomon649a3412017-03-09 13:50:43 -050054 }
Brian Salomonbc6b99d2017-01-11 10:32:34 -050055
56private:
Herb Derbyc76d4092020-10-07 16:46:15 -040057 friend class ::GrOp; // for ctor
Robert Phillips7c525e62018-06-12 10:11:12 -040058
Brian Salomonaff329b2017-08-11 09:40:37 -040059 TestOp(std::unique_ptr<GrFragmentProcessor> fp)
60 : INHERITED(ClassID()), fProcessors(std::move(fp)) {
Greg Daniel5faf4742019-10-01 15:14:44 -040061 this->setBounds(SkRect::MakeWH(100, 100), HasAABloat::kNo, IsHairline::kNo);
Brian Salomon82ddc942017-07-14 12:00:13 -040062 }
Brian Salomonbc6b99d2017-01-11 10:32:34 -050063
Robert Phillips2669a7b2020-03-12 12:07:19 -040064 GrProgramInfo* programInfo() override { return nullptr; }
Robert Phillips4133dc42020-03-11 15:55:55 -040065 void onCreateProgramInfo(const GrCaps*,
66 SkArenaAlloc*,
Adlai Hollere2296f72020-11-19 13:41:26 -050067 const GrSurfaceProxyView& writeView,
Robert Phillips4133dc42020-03-11 15:55:55 -040068 GrAppliedClip&&,
Greg Danield358cbe2020-09-11 09:33:54 -040069 const GrXferProcessor::DstProxyView&,
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*,
Greg Danield358cbe2020-09-11 09:33:54 -040075 const GrXferProcessor::DstProxyView&,
Greg Daniel42dbca52020-11-20 10:22:43 -050076 GrXferBarrierFlags renderPassXferBarriers,
77 GrLoadOp colorLoadOp) override {}
Brian Salomon91326c32017-08-09 16:02:19 -040078 void onPrepareDraws(Target* target) 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
101 void onGetGLSLProcessorKey(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
Brian Salomon92b9ccf2020-06-17 14:19:19 -0400123 explicit TestFP(const TestFP& that) : INHERITED(kTestFP_ClassID, that.optimizationFlags()) {
124 this->cloneAndRegisterAllChildProcessors(that);
Brian Salomonb17e6392017-07-28 13:41:51 -0400125 }
126
John Stiles1cf2c8d2020-08-13 22:58:04 -0400127 GrGLSLFragmentProcessor* onCreateGLSLInstance() const override {
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500128 class TestGLSLFP : public GrGLSLFragmentProcessor {
129 public:
130 TestGLSLFP() {}
131 void emitCode(EmitArgs& args) override {
Brian Osman03f9e2a2020-12-08 11:17:26 -0500132 args.fFragBuilder->codeAppendf("%s = half4(1);", args.fOutputColor);
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500133 }
134
135 private:
136 };
137 return new TestGLSLFP();
138 }
139
140 bool onIsEqual(const GrFragmentProcessor&) const override { return false; }
141
John Stiles7571f9e2020-09-02 22:42:33 -0400142 using INHERITED = GrFragmentProcessor;
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500143};
John Stilesa6841be2020-08-06 14:11:56 -0400144} // namespace
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500145
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500146DEF_GPUTEST_FOR_ALL_CONTEXTS(ProcessorRefTest, reporter, ctxInfo) {
Robert Phillips6d344c32020-07-06 10:56:46 -0400147 auto context = ctxInfo.directContext();
Robert Phillips9da87e02019-02-04 13:26:26 -0500148 GrProxyProvider* proxyProvider = context->priv().proxyProvider();
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500149
Brian Salomona56a7462020-02-07 14:17:25 -0500150 static constexpr SkISize kDims = {10, 10};
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500151
Greg Daniel4065d452018-11-16 15:43:41 -0500152 const GrBackendFormat format =
Robert Phillips0a15cc62019-07-30 12:49:10 -0400153 context->priv().caps()->getDefaultBackendFormat(GrColorType::kRGBA_8888,
154 GrRenderable::kNo);
Greg Daniel47c20e82020-01-21 14:29:57 -0500155 GrSwizzle swizzle = context->priv().caps()->getReadSwizzle(format, GrColorType::kRGBA_8888);
Greg Daniel4065d452018-11-16 15:43:41 -0500156
Brian Salomonb17e6392017-07-28 13:41:51 -0400157 for (bool makeClone : {false, true}) {
158 for (int parentCnt = 0; parentCnt < 2; parentCnt++) {
Greg Daniele20fcad2020-01-08 11:52:34 -0500159 auto renderTargetContext = GrRenderTargetContext::Make(
160 context, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kApprox, {1, 1});
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500161 {
Robert Phillips3d4cac52019-06-11 08:08:08 -0400162 sk_sp<GrTextureProxy> proxy = proxyProvider->createProxy(
Brian Salomon7e67dca2020-07-21 09:27:25 -0400163 format, kDims, GrRenderable::kNo, 1, GrMipmapped::kNo, SkBackingFit::kExact,
Brian Salomondf1bd6d2020-03-26 20:37:01 -0400164 SkBudgeted::kYes, GrProtected::kNo);
Robert Phillips3d4cac52019-06-11 08:08:08 -0400165
Brian Salomonb17e6392017-07-28 13:41:51 -0400166 {
Greg Daniel026a60c2020-02-12 10:53:51 -0500167 SkTArray<GrSurfaceProxyView> views;
Greg Daniel026a60c2020-02-12 10:53:51 -0500168 views.push_back({proxy, kTopLeft_GrSurfaceOrigin, swizzle});
Brian Salomon92b9ccf2020-06-17 14:19:19 -0400169 auto fp = TestFP::Make(std::move(views));
Brian Salomonb17e6392017-07-28 13:41:51 -0400170 for (int i = 0; i < parentCnt; ++i) {
171 fp = TestFP::Make(std::move(fp));
172 }
Brian Salomonaff329b2017-08-11 09:40:37 -0400173 std::unique_ptr<GrFragmentProcessor> clone;
Brian Salomonb17e6392017-07-28 13:41:51 -0400174 if (makeClone) {
175 clone = fp->clone();
176 }
Herb Derbyc76d4092020-10-07 16:46:15 -0400177 GrOp::Owner op = TestOp::Make(context, std::move(fp));
Brian Salomon70fe17e2020-11-30 14:33:58 -0500178 renderTargetContext->addDrawOp(std::move(op));
Brian Salomonb17e6392017-07-28 13:41:51 -0400179 if (clone) {
Robert Phillips7c525e62018-06-12 10:11:12 -0400180 op = TestOp::Make(context, std::move(clone));
Brian Salomon70fe17e2020-11-30 14:33:58 -0500181 renderTargetContext->addDrawOp(std::move(op));
Brian Salomonb17e6392017-07-28 13:41:51 -0400182 }
183 }
Brian Salomonb17e6392017-07-28 13:41:51 -0400184
Robert Phillips3d4cac52019-06-11 08:08:08 -0400185 // If the fp is cloned the number of refs should increase by one (for the clone)
186 int expectedProxyRefs = makeClone ? 3 : 2;
187
Brian Salomon28a8f282019-10-24 20:07:39 -0400188 CheckSingleThreadedProxyRefs(reporter, proxy.get(), expectedProxyRefs, -1);
Brian Salomonb17e6392017-07-28 13:41:51 -0400189
Greg Daniel0a2464f2020-05-14 15:45:44 -0400190 context->flushAndSubmit();
Brian Salomonb17e6392017-07-28 13:41:51 -0400191
Brian Salomon557e8122019-10-24 10:37:08 -0400192 // just one from the 'proxy' sk_sp
Brian Salomon28a8f282019-10-24 20:07:39 -0400193 CheckSingleThreadedProxyRefs(reporter, proxy.get(), 1, 1);
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500194 }
195 }
196 }
197}
Brian Salomon587e08f2017-01-27 10:59:27 -0500198
Mike Kleinc0bd9f92019-04-23 12:05:21 -0500199#include "tools/flags/CommandLineFlags.h"
Mike Klein84836b72019-03-21 11:31:36 -0500200static DEFINE_bool(randomProcessorTest, false,
201 "Use non-deterministic seed for random processor tests?");
Mike Klein5b3f3432019-03-21 11:42:21 -0500202static DEFINE_int(processorSeed, 0,
203 "Use specific seed for processor tests. Overridden by --randomProcessorTest.");
Brian Salomon0e05a822017-07-25 09:43:22 -0400204
205#if GR_TEST_UTILS
206
Michael Ludwig7034f152018-10-08 16:43:58 -0400207static GrColor input_texel_color(int i, int j, SkScalar delta) {
208 // Delta must be less than 0.5 to prevent over/underflow issues with the input color
209 SkASSERT(delta <= 0.5);
Brian Salomon587e08f2017-01-27 10:59:27 -0500210
Brian Osman50ea3c02019-02-04 10:01:53 -0500211 SkColor color = SkColorSetARGB((uint8_t)(i & 0xFF),
212 (uint8_t)(j & 0xFF),
213 (uint8_t)((i + j) & 0xFF),
214 (uint8_t)((2 * j - i) & 0xFF));
Brian Osmancb3d0872018-10-16 15:19:28 -0400215 SkColor4f color4f = SkColor4f::FromColor(color);
Brian Salomonbc73eb42019-12-18 14:57:45 -0500216 // We only apply delta to the r,g, and b channels. This is because we're using this
217 // to test the canTweakAlphaForCoverage() optimization. A processor is allowed
218 // to use the input color's alpha in its calculation and report this optimization.
219 for (int i = 0; i < 3; i++) {
Brian Osmancb3d0872018-10-16 15:19:28 -0400220 if (color4f[i] > 0.5) {
221 color4f[i] -= delta;
Michael Ludwig7034f152018-10-08 16:43:58 -0400222 } else {
Brian Osmancb3d0872018-10-16 15:19:28 -0400223 color4f[i] += delta;
Michael Ludwig7034f152018-10-08 16:43:58 -0400224 }
225 }
Brian Osmancb3d0872018-10-16 15:19:28 -0400226 return color4f.premul().toBytes_RGBA();
Brian Salomon0e05a822017-07-25 09:43:22 -0400227}
Brian Salomon587e08f2017-01-27 10:59:27 -0500228
Robert Phillips58adb342020-07-23 09:41:57 -0400229void test_draw_op(GrRecordingContext* rContext,
230 GrRenderTargetContext* rtc,
John Stiles0dee9b02020-07-20 11:45:58 -0400231 std::unique_ptr<GrFragmentProcessor> fp) {
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500232 GrPaint paint;
John Stiles5933d7d2020-07-21 12:28:35 -0400233 paint.setColorFragmentProcessor(std::move(fp));
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500234 paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
Brian Salomonac70f842017-05-08 10:43:33 -0400235
Robert Phillips58adb342020-07-23 09:41:57 -0400236 auto op = GrFillRectOp::MakeNonAARect(rContext, std::move(paint), SkMatrix::I(),
Michael Ludwigaa1b6b32019-05-29 14:43:13 -0400237 SkRect::MakeWH(rtc->width(), rtc->height()));
Brian Salomon70fe17e2020-11-30 14:33:58 -0500238 rtc->addDrawOp(std::move(op));
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500239}
240
John Stiles0dee9b02020-07-20 11:45:58 -0400241// The output buffer must be the same size as the render-target context.
Adlai Hollerc95b5892020-08-11 12:02:22 -0400242void render_fp(GrDirectContext* dContext,
Robert Phillips58adb342020-07-23 09:41:57 -0400243 GrRenderTargetContext* rtc,
Brian Salomon3f4de782020-06-18 14:16:00 -0400244 std::unique_ptr<GrFragmentProcessor> fp,
John Stiles0dee9b02020-07-20 11:45:58 -0400245 GrColor* outBuffer) {
Adlai Hollerc95b5892020-08-11 12:02:22 -0400246 test_draw_op(dContext, rtc, std::move(fp));
John Stiles0dee9b02020-07-20 11:45:58 -0400247 std::fill_n(outBuffer, rtc->width() * rtc->height(), 0);
Adlai Hollerc95b5892020-08-11 12:02:22 -0400248 rtc->readPixels(dContext, SkImageInfo::Make(rtc->width(), rtc->height(), kRGBA_8888_SkColorType,
Brian Salomon9f2b86c2019-10-22 10:37:46 -0400249 kPremul_SkAlphaType),
John Stiles0dee9b02020-07-20 11:45:58 -0400250 outBuffer, /*rowBytes=*/0, /*srcPt=*/{0, 0});
Michael Ludwig7034f152018-10-08 16:43:58 -0400251}
252
John Stilesaf110302020-07-20 09:45:51 -0400253// This class is responsible for reproducibly generating a random fragment processor.
254// An identical randomly-designed FP can be generated as many times as needed.
255class TestFPGenerator {
256 public:
257 TestFPGenerator() = delete;
258 TestFPGenerator(GrDirectContext* context, GrResourceProvider* resourceProvider)
259 : fContext(context)
260 , fResourceProvider(resourceProvider)
261 , fInitialSeed(synthesizeInitialSeed())
262 , fRandomSeed(fInitialSeed) {}
Brian Osmanc35a2d42017-03-17 10:58:53 -0400263
John Stilesaf110302020-07-20 09:45:51 -0400264 uint32_t initialSeed() { return fInitialSeed; }
265
266 bool init() {
267 // Initializes the two test texture proxies that are available to the FP test factories.
268 SkRandom random{fRandomSeed};
269 static constexpr int kTestTextureSize = 256;
270
271 {
272 // Put premul data into the RGBA texture that the test FPs can optionally use.
273 GrColor* rgbaData = new GrColor[kTestTextureSize * kTestTextureSize];
274 for (int y = 0; y < kTestTextureSize; ++y) {
275 for (int x = 0; x < kTestTextureSize; ++x) {
276 rgbaData[kTestTextureSize * y + x] = input_texel_color(
277 random.nextULessThan(256), random.nextULessThan(256), 0.0f);
278 }
279 }
280
281 SkImageInfo ii = SkImageInfo::Make(kTestTextureSize, kTestTextureSize,
282 kRGBA_8888_SkColorType, kPremul_SkAlphaType);
283 SkBitmap bitmap;
284 bitmap.installPixels(
285 ii, rgbaData, ii.minRowBytes(),
286 [](void* addr, void* context) { delete[](GrColor*) addr; }, nullptr);
287 bitmap.setImmutable();
288 GrBitmapTextureMaker maker(fContext, bitmap,
289 GrImageTexGenPolicy::kNew_Uncached_Budgeted);
Brian Salomon7e67dca2020-07-21 09:27:25 -0400290 GrSurfaceProxyView view = maker.view(GrMipmapped::kNo);
John Stilesaf110302020-07-20 09:45:51 -0400291 if (!view.proxy() || !view.proxy()->instantiate(fResourceProvider)) {
292 SkDebugf("Unable to instantiate RGBA8888 test texture.");
293 return false;
294 }
295 fTestViews[0] = GrProcessorTestData::ViewInfo{view, GrColorType::kRGBA_8888,
296 kPremul_SkAlphaType};
297 }
298
299 {
300 // Put random values into the alpha texture that the test FPs can optionally use.
301 uint8_t* alphaData = new uint8_t[kTestTextureSize * kTestTextureSize];
302 for (int y = 0; y < kTestTextureSize; ++y) {
303 for (int x = 0; x < kTestTextureSize; ++x) {
304 alphaData[kTestTextureSize * y + x] = random.nextULessThan(256);
305 }
306 }
307
308 SkImageInfo ii = SkImageInfo::Make(kTestTextureSize, kTestTextureSize,
309 kAlpha_8_SkColorType, kPremul_SkAlphaType);
310 SkBitmap bitmap;
311 bitmap.installPixels(
312 ii, alphaData, ii.minRowBytes(),
313 [](void* addr, void* context) { delete[](uint8_t*) addr; }, nullptr);
314 bitmap.setImmutable();
315 GrBitmapTextureMaker maker(fContext, bitmap,
316 GrImageTexGenPolicy::kNew_Uncached_Budgeted);
Brian Salomon7e67dca2020-07-21 09:27:25 -0400317 GrSurfaceProxyView view = maker.view(GrMipmapped::kNo);
John Stilesaf110302020-07-20 09:45:51 -0400318 if (!view.proxy() || !view.proxy()->instantiate(fResourceProvider)) {
319 SkDebugf("Unable to instantiate A8 test texture.");
320 return false;
321 }
322 fTestViews[1] = GrProcessorTestData::ViewInfo{view, GrColorType::kAlpha_8,
323 kPremul_SkAlphaType};
324 }
325
326 return true;
327 }
328
329 void reroll() {
330 // Feed our current random seed into SkRandom to generate a new seed.
331 SkRandom random{fRandomSeed};
332 fRandomSeed = random.nextU();
333 }
334
John Stiles87d0a2f2020-08-10 13:12:41 -0400335 std::unique_ptr<GrFragmentProcessor> make(int type, int randomTreeDepth,
John Stiles0dee9b02020-07-20 11:45:58 -0400336 std::unique_ptr<GrFragmentProcessor> inputFP) {
John Stilesaf110302020-07-20 09:45:51 -0400337 // This will generate the exact same randomized FP (of each requested type) each time
338 // it's called. Call `reroll` to get a different FP.
339 SkRandom random{fRandomSeed};
John Stiles87d0a2f2020-08-10 13:12:41 -0400340 GrProcessorTestData testData{&random, fContext, randomTreeDepth,
341 SK_ARRAY_COUNT(fTestViews), fTestViews,
John Stiles0dee9b02020-07-20 11:45:58 -0400342 std::move(inputFP)};
John Stilesaf110302020-07-20 09:45:51 -0400343 return GrFragmentProcessorTestFactory::MakeIdx(type, &testData);
344 }
345
John Stiles87d0a2f2020-08-10 13:12:41 -0400346 std::unique_ptr<GrFragmentProcessor> make(int type, int randomTreeDepth,
347 GrSurfaceProxyView view,
John Stiles0dee9b02020-07-20 11:45:58 -0400348 SkAlphaType alpha = kPremul_SkAlphaType) {
John Stiles87d0a2f2020-08-10 13:12:41 -0400349 return make(type, randomTreeDepth, GrTextureEffect::Make(view, alpha));
John Stiles0dee9b02020-07-20 11:45:58 -0400350 }
351
John Stilesaf110302020-07-20 09:45:51 -0400352 private:
353 static uint32_t synthesizeInitialSeed() {
354 if (FLAGS_randomProcessorTest) {
355 std::random_device rd;
356 return rd();
357 } else {
358 return FLAGS_processorSeed;
Robert Phillips0bd24dc2018-01-16 08:06:32 -0500359 }
Brian Salomon0e05a822017-07-25 09:43:22 -0400360 }
Brian Salomon0e05a822017-07-25 09:43:22 -0400361
John Stilesaf110302020-07-20 09:45:51 -0400362 GrDirectContext* fContext; // owned by caller
363 GrResourceProvider* fResourceProvider; // owned by caller
364 const uint32_t fInitialSeed;
365 uint32_t fRandomSeed;
366 GrProcessorTestData::ViewInfo fTestViews[2];
367};
Brian Salomon0e05a822017-07-25 09:43:22 -0400368
John Stiles4ed69472020-08-11 16:04:31 -0400369// Creates an array of color values from input_texel_color(), to be used as an input texture.
370std::vector<GrColor> make_input_pixels(int width, int height, SkScalar delta) {
371 std::vector<GrColor> pixel(width * height);
Brian Salomon0e05a822017-07-25 09:43:22 -0400372 for (int y = 0; y < width; ++y) {
373 for (int x = 0; x < height; ++x) {
John Stiles4ed69472020-08-11 16:04:31 -0400374 pixel[width * y + x] = input_texel_color(x, y, delta);
Brian Salomon0e05a822017-07-25 09:43:22 -0400375 }
376 }
Robert Phillips0bd24dc2018-01-16 08:06:32 -0500377
John Stiles4ed69472020-08-11 16:04:31 -0400378 return pixel;
379}
380
381// Creates a texture of premul colors used as the output of the fragment processor that precedes
382// the fragment processor under test. An array of W*H colors are passed in as the texture data.
383GrSurfaceProxyView make_input_texture(GrRecordingContext* context,
384 int width, int height, GrColor* pixel) {
Brian Osman2700abc2018-09-12 10:19:41 -0400385 SkImageInfo ii = SkImageInfo::Make(width, height, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
Greg Daniel6f5441a2020-01-28 17:02:49 -0500386 SkBitmap bitmap;
John Stiles4ed69472020-08-11 16:04:31 -0400387 bitmap.installPixels(ii, pixel, ii.minRowBytes());
Greg Daniel6f5441a2020-01-28 17:02:49 -0500388 bitmap.setImmutable();
Brian Salomonbc074a62020-03-18 10:06:13 -0400389 GrBitmapTextureMaker maker(context, bitmap, GrImageTexGenPolicy::kNew_Uncached_Budgeted);
Brian Salomon7e67dca2020-07-21 09:27:25 -0400390 return maker.view(GrMipmapped::kNo);
Brian Salomon0e05a822017-07-25 09:43:22 -0400391}
Robert Phillips0bd24dc2018-01-16 08:06:32 -0500392
John Stilesaf110302020-07-20 09:45:51 -0400393// We tag logged data as unpremul to avoid conversion when encoding as PNG. The input texture
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400394// actually contains unpremul data. Also, even though we made the result data by rendering into
395// a "unpremul" GrRenderTargetContext, our input texture is unpremul and outside of the random
396// effect configuration, we didn't do anything to ensure the output is actually premul. We just
397// don't currently allow kUnpremul GrRenderTargetContexts.
398static constexpr auto kLogAlphaType = kUnpremul_SkAlphaType;
Michael Ludwige8e10752018-10-01 12:42:53 -0400399
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400400bool log_pixels(GrColor* pixels, int widthHeight, SkString* dst) {
John Stilesaf110302020-07-20 09:45:51 -0400401 SkImageInfo info =
402 SkImageInfo::Make(widthHeight, widthHeight, kRGBA_8888_SkColorType, kLogAlphaType);
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400403 SkBitmap bmp;
404 bmp.installPixels(info, pixels, widthHeight * sizeof(GrColor));
Brian Salomon28a8f282019-10-24 20:07:39 -0400405 return BipmapToBase64DataURI(bmp, dst);
Michael Ludwige8e10752018-10-01 12:42:53 -0400406}
407
Adlai Hollerc95b5892020-08-11 12:02:22 -0400408bool log_texture_view(GrDirectContext* dContext, GrSurfaceProxyView src, SkString* dst) {
Greg Daniel124486b2020-02-11 11:54:55 -0500409 SkImageInfo ii = SkImageInfo::Make(src.proxy()->dimensions(), kRGBA_8888_SkColorType,
410 kLogAlphaType);
Greg Daniel3912a4b2020-01-14 09:56:04 -0500411
Brian Salomon14f99fc2020-12-07 12:19:47 -0500412 auto sContext = GrSurfaceContext::Make(dContext, std::move(src), ii.colorInfo());
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400413 SkBitmap bm;
414 SkAssertResult(bm.tryAllocPixels(ii));
Adlai Hollerc95b5892020-08-11 12:02:22 -0400415 SkAssertResult(sContext->readPixels(dContext, ii, bm.getPixels(), bm.rowBytes(), {0, 0}));
Brian Salomon28a8f282019-10-24 20:07:39 -0400416 return BipmapToBase64DataURI(bm, dst);
Michael Ludwige8e10752018-10-01 12:42:53 -0400417}
418
Michael Ludwig7034f152018-10-08 16:43:58 -0400419bool fuzzy_color_equals(const SkPMColor4f& c1, const SkPMColor4f& c2) {
420 // With the loss of precision of rendering into 32-bit color, then estimating the FP's output
Brian Salomon682ba432019-12-17 20:20:23 +0000421 // 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 -0400422 // (really 1/128 ~ .0078, but frequently floating point issues make that tolerance a little
423 // too unforgiving).
Brian Salomon682ba432019-12-17 20:20:23 +0000424 static constexpr SkScalar kTolerance = 0.01f;
Michael Ludwig7034f152018-10-08 16:43:58 -0400425 for (int i = 0; i < 4; i++) {
426 if (!SkScalarNearlyEqual(c1[i], c2[i], kTolerance)) {
427 return false;
428 }
429 }
430 return true;
431}
432
Brian Salomonbc73eb42019-12-18 14:57:45 -0500433// Given three input colors (color preceding the FP being tested) provided to the FP at the same
434// local coord and the three corresponding FP outputs, this ensures that either:
435// out[0] = fp * in[0].a, out[1] = fp * in[1].a, and out[2] = fp * in[2].a
436// where fp is the pre-modulated color that should not be changing across frames (FP's state doesn't
437// change), OR:
438// out[0] = fp * in[0], out[1] = fp * in[1], and out[2] = fp * in[2]
439// (per-channel modulation instead of modulation by just the alpha channel)
440// It does this by estimating the pre-modulated fp color from one of the input/output pairs and
441// confirms the conditions hold for the other two pairs.
442// It is required that the three input colors have the same alpha as fp is allowed to be a function
443// of the input alpha (but not r, g, or b).
444bool legal_modulation(const GrColor in[3], const GrColor out[3]) {
Michael Ludwig7034f152018-10-08 16:43:58 -0400445 // Convert to floating point, which is the number space the FP operates in (more or less)
Brian Salomonbc73eb42019-12-18 14:57:45 -0500446 SkPMColor4f inf[3], outf[3];
447 for (int i = 0; i < 3; ++i) {
448 inf[i] = SkPMColor4f::FromBytes_RGBA(in[i]);
449 outf[i] = SkPMColor4f::FromBytes_RGBA(out[i]);
450 }
451 // This test is only valid if all the input alphas are the same.
452 SkASSERT(inf[0].fA == inf[1].fA && inf[1].fA == inf[2].fA);
Michael Ludwig7034f152018-10-08 16:43:58 -0400453
454 // Reconstruct the output of the FP before the shader modulated its color with the input value.
455 // When the original input is very small, it may cause the final output color to round
456 // to 0, in which case we estimate the pre-modulated color using one of the stepped frames that
457 // will then have a guaranteed larger channel value (since the offset will be added to it).
Brian Salomon0a7ca7a2019-12-27 12:18:19 -0500458 SkPMColor4f fpPreColorModulation = {0,0,0,0};
459 SkPMColor4f fpPreAlphaModulation = {0,0,0,0};
Michael Ludwig7034f152018-10-08 16:43:58 -0400460 for (int i = 0; i < 4; i++) {
Brian Salomonbc73eb42019-12-18 14:57:45 -0500461 // Use the most stepped up frame
462 int maxInIdx = inf[0][i] > inf[1][i] ? 0 : 1;
463 maxInIdx = inf[maxInIdx][i] > inf[2][i] ? maxInIdx : 2;
John Stilesfe7aed62020-07-20 13:48:02 -0400464 const SkPMColor4f& in = inf[maxInIdx];
465 const SkPMColor4f& out = outf[maxInIdx];
Brian Salomon0a7ca7a2019-12-27 12:18:19 -0500466 if (in[i] > 0) {
467 fpPreColorModulation[i] = out[i] / in[i];
468 }
469 if (in[3] > 0) {
470 fpPreAlphaModulation[i] = out[i] / in[3];
471 }
Michael Ludwig7034f152018-10-08 16:43:58 -0400472 }
473
474 // With reconstructed pre-modulated FP output, derive the expected value of fp * input for each
475 // of the transformed input colors.
Brian Salomonbc73eb42019-12-18 14:57:45 -0500476 SkPMColor4f expectedForAlphaModulation[3];
477 SkPMColor4f expectedForColorModulation[3];
478 for (int i = 0; i < 3; ++i) {
479 expectedForAlphaModulation[i] = fpPreAlphaModulation * inf[i].fA;
480 expectedForColorModulation[i] = fpPreColorModulation * inf[i];
481 // If the input alpha is 0 then the other channels should also be zero
482 // since the color is assumed to be premul. Modulating zeros by anything
483 // should produce zeros.
484 if (inf[i].fA == 0) {
485 SkASSERT(inf[i].fR == 0 && inf[i].fG == 0 && inf[i].fB == 0);
486 expectedForColorModulation[i] = expectedForAlphaModulation[i] = {0, 0, 0, 0};
487 }
488 }
Michael Ludwig7034f152018-10-08 16:43:58 -0400489
Brian Salomonbc73eb42019-12-18 14:57:45 -0500490 bool isLegalColorModulation = fuzzy_color_equals(outf[0], expectedForColorModulation[0]) &&
491 fuzzy_color_equals(outf[1], expectedForColorModulation[1]) &&
492 fuzzy_color_equals(outf[2], expectedForColorModulation[2]);
493
494 bool isLegalAlphaModulation = fuzzy_color_equals(outf[0], expectedForAlphaModulation[0]) &&
495 fuzzy_color_equals(outf[1], expectedForAlphaModulation[1]) &&
496 fuzzy_color_equals(outf[2], expectedForAlphaModulation[2]);
497
498 // This can be enabled to print the values that caused this check to fail.
499 if (0 && !isLegalColorModulation && !isLegalAlphaModulation) {
500 SkDebugf("Color modulation test\n\timplied mod color: (%.03f, %.03f, %.03f, %.03f)\n",
501 fpPreColorModulation[0],
502 fpPreColorModulation[1],
503 fpPreColorModulation[2],
504 fpPreColorModulation[3]);
505 for (int i = 0; i < 3; ++i) {
506 SkDebugf("\t(%.03f, %.03f, %.03f, %.03f) -> "
507 "(%.03f, %.03f, %.03f, %.03f) | "
508 "(%.03f, %.03f, %.03f, %.03f), ok: %d\n",
509 inf[i].fR, inf[i].fG, inf[i].fB, inf[i].fA,
510 outf[i].fR, outf[i].fG, outf[i].fB, outf[i].fA,
511 expectedForColorModulation[i].fR, expectedForColorModulation[i].fG,
512 expectedForColorModulation[i].fB, expectedForColorModulation[i].fA,
513 fuzzy_color_equals(outf[i], expectedForColorModulation[i]));
514 }
515 SkDebugf("Alpha modulation test\n\timplied mod color: (%.03f, %.03f, %.03f, %.03f)\n",
516 fpPreAlphaModulation[0],
517 fpPreAlphaModulation[1],
518 fpPreAlphaModulation[2],
519 fpPreAlphaModulation[3]);
520 for (int i = 0; i < 3; ++i) {
521 SkDebugf("\t(%.03f, %.03f, %.03f, %.03f) -> "
522 "(%.03f, %.03f, %.03f, %.03f) | "
523 "(%.03f, %.03f, %.03f, %.03f), ok: %d\n",
524 inf[i].fR, inf[i].fG, inf[i].fB, inf[i].fA,
525 outf[i].fR, outf[i].fG, outf[i].fB, outf[i].fA,
526 expectedForAlphaModulation[i].fR, expectedForAlphaModulation[i].fG,
527 expectedForAlphaModulation[i].fB, expectedForAlphaModulation[i].fA,
528 fuzzy_color_equals(outf[i], expectedForAlphaModulation[i]));
529 }
530 }
531 return isLegalColorModulation || isLegalAlphaModulation;
Michael Ludwig7034f152018-10-08 16:43:58 -0400532}
533
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500534DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ProcessorOptimizationValidationTest, reporter, ctxInfo) {
John Stilesaf110302020-07-20 09:45:51 -0400535 GrDirectContext* context = ctxInfo.directContext();
536 GrResourceProvider* resourceProvider = context->priv().resourceProvider();
Brian Salomon1c053642017-07-24 10:16:19 -0400537 using FPFactory = GrFragmentProcessorTestFactory;
Brian Osmanc35a2d42017-03-17 10:58:53 -0400538
John Stilesaf110302020-07-20 09:45:51 -0400539 TestFPGenerator fpGenerator{context, resourceProvider};
540 if (!fpGenerator.init()) {
541 ERRORF(reporter, "Could not initialize TestFPGenerator");
542 return;
Brian Osmanc35a2d42017-03-17 10:58:53 -0400543 }
Brian Osmanc35a2d42017-03-17 10:58:53 -0400544
Brian Salomon0e05a822017-07-25 09:43:22 -0400545 // Make the destination context for the test.
546 static constexpr int kRenderSize = 256;
Greg Daniele20fcad2020-01-08 11:52:34 -0500547 auto rtc = GrRenderTargetContext::Make(
548 context, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kExact,
549 {kRenderSize, kRenderSize});
Brian Salomond1a8bdf2017-02-10 12:39:26 -0500550
Michael Ludwig7034f152018-10-08 16:43:58 -0400551 // Coverage optimization uses three frames with a linearly transformed input texture. The first
552 // frame has no offset, second frames add .2 and .4, which should then be present as a fixed
553 // difference between the frame outputs if the FP is properly following the modulation
554 // requirements of the coverage optimization.
555 static constexpr SkScalar kInputDelta = 0.2f;
John Stiles4ed69472020-08-11 16:04:31 -0400556 std::vector<GrColor> inputPixels1 = make_input_pixels(kRenderSize, kRenderSize, 0.0f);
557 std::vector<GrColor> inputPixels2 =
558 make_input_pixels(kRenderSize, kRenderSize, 1 * kInputDelta);
559 std::vector<GrColor> inputPixels3 =
560 make_input_pixels(kRenderSize, kRenderSize, 2 * kInputDelta);
561 GrSurfaceProxyView inputTexture1 =
562 make_input_texture(context, kRenderSize, kRenderSize, inputPixels1.data());
563 GrSurfaceProxyView inputTexture2 =
564 make_input_texture(context, kRenderSize, kRenderSize, inputPixels2.data());
565 GrSurfaceProxyView inputTexture3 =
566 make_input_texture(context, kRenderSize, kRenderSize, inputPixels3.data());
Robert Phillips30f9bc62017-02-22 15:28:38 -0500567
Michael Ludwige8e10752018-10-01 12:42:53 -0400568 // Encoded images are very verbose and this tests many potential images, so only export the
569 // first failure (subsequent failures have a reasonable chance of being related).
570 bool loggedFirstFailure = false;
Michael Ludwig314d3772018-10-03 16:04:38 -0400571 bool loggedFirstWarning = false;
Michael Ludwig7034f152018-10-08 16:43:58 -0400572
John Stilesaf110302020-07-20 09:45:51 -0400573 // Storage for the three frames required for coverage compatibility optimization testing.
574 // Each frame uses the correspondingly numbered inputTextureX.
575 std::vector<GrColor> readData1(kRenderSize * kRenderSize);
576 std::vector<GrColor> readData2(kRenderSize * kRenderSize);
577 std::vector<GrColor> readData3(kRenderSize * kRenderSize);
Michael Ludwig7034f152018-10-08 16:43:58 -0400578
Brian Salomon0e05a822017-07-25 09:43:22 -0400579 // Because processor factories configure themselves in random ways, this is not exhaustive.
Brian Salomon587e08f2017-01-27 10:59:27 -0500580 for (int i = 0; i < FPFactory::Count(); ++i) {
John Stilesfe7aed62020-07-20 13:48:02 -0400581 int optimizedForOpaqueInput = 0;
582 int optimizedForCoverageAsAlpha = 0;
583 int optimizedForConstantOutputForInput = 0;
John Stilesaf110302020-07-20 09:45:51 -0400584
John Stilesfe7aed62020-07-20 13:48:02 -0400585#ifdef __MSVC_RUNTIME_CHECKS
Brian Osman50ea3c02019-02-04 10:01:53 -0500586 // This test is infuriatingly slow with MSVC runtime checks enabled
John Stilesfe7aed62020-07-20 13:48:02 -0400587 static constexpr int kMinimumTrials = 1;
588 static constexpr int kMaximumTrials = 1;
589 static constexpr int kExpectedSuccesses = 1;
590#else
591 // We start by testing each fragment-processor 100 times, watching the optimization bits
592 // that appear. If we see an optimization bit appear in those first 100 trials, we keep
593 // running tests until we see at least five successful trials that have this optimization
594 // bit enabled. If we never see a particular optimization bit after 100 trials, we assume
595 // that this FP doesn't support that optimization at all.
596 static constexpr int kMinimumTrials = 100;
597 static constexpr int kMaximumTrials = 2000;
598 static constexpr int kExpectedSuccesses = 5;
Brian Osman50ea3c02019-02-04 10:01:53 -0500599#endif
Robert Phillipsa91e0b72017-05-01 13:12:20 -0400600
John Stilesfe7aed62020-07-20 13:48:02 -0400601 for (int trial = 0;; ++trial) {
John Stilesaf110302020-07-20 09:45:51 -0400602 // Create a randomly-configured FP.
603 fpGenerator.reroll();
John Stiles87d0a2f2020-08-10 13:12:41 -0400604 std::unique_ptr<GrFragmentProcessor> fp =
John Stiles9fbe9e92020-08-10 16:35:01 -0400605 fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture1);
John Stilesaf110302020-07-20 09:45:51 -0400606
John Stilesfe7aed62020-07-20 13:48:02 -0400607 // If we have iterated enough times and seen a sufficient number of successes on each
608 // optimization bit that can be returned, stop running trials.
609 if (trial >= kMinimumTrials) {
610 bool moreTrialsNeeded = (optimizedForOpaqueInput > 0 &&
611 optimizedForOpaqueInput < kExpectedSuccesses) ||
612 (optimizedForCoverageAsAlpha > 0 &&
613 optimizedForCoverageAsAlpha < kExpectedSuccesses) ||
614 (optimizedForConstantOutputForInput > 0 &&
615 optimizedForConstantOutputForInput < kExpectedSuccesses);
616 if (!moreTrialsNeeded) break;
617
618 if (trial >= kMaximumTrials) {
619 SkDebugf("Abandoning ProcessorOptimizationValidationTest after %d trials. "
John Stilesba1879d2020-08-11 13:58:32 -0400620 "Seed: 0x%08x, processor:\n%s",
621 kMaximumTrials, fpGenerator.initialSeed(), fp->dumpTreeInfo().c_str());
John Stilesfe7aed62020-07-20 13:48:02 -0400622 break;
623 }
624 }
625
626 // Skip further testing if this trial has no optimization bits enabled.
Brian Salomon587e08f2017-01-27 10:59:27 -0500627 if (!fp->hasConstantOutputForConstantInput() && !fp->preservesOpaqueInput() &&
Brian Salomonf3b995b2017-02-15 10:22:23 -0500628 !fp->compatibleWithCoverageAsAlpha()) {
Brian Salomon587e08f2017-01-27 10:59:27 -0500629 continue;
630 }
Brian Salomonaff329b2017-08-11 09:40:37 -0400631
John Stilesaf110302020-07-20 09:45:51 -0400632 // We can make identical copies of the test FP in order to test coverage-as-alpha.
Michael Ludwig7034f152018-10-08 16:43:58 -0400633 if (fp->compatibleWithCoverageAsAlpha()) {
John Stiles0dee9b02020-07-20 11:45:58 -0400634 // Create and render two identical versions of this FP, but using different input
635 // textures, to check coverage optimization. We don't need to do this step for
636 // constant-output or preserving-opacity tests.
John Stiles87d0a2f2020-08-10 13:12:41 -0400637 render_fp(context, rtc.get(),
John Stiles9fbe9e92020-08-10 16:35:01 -0400638 fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture2),
John Stiles87d0a2f2020-08-10 13:12:41 -0400639 readData2.data());
640 render_fp(context, rtc.get(),
John Stiles9fbe9e92020-08-10 16:35:01 -0400641 fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture3),
John Stiles87d0a2f2020-08-10 13:12:41 -0400642 readData3.data());
John Stilesfe7aed62020-07-20 13:48:02 -0400643 ++optimizedForCoverageAsAlpha;
644 }
645
646 if (fp->hasConstantOutputForConstantInput()) {
647 ++optimizedForConstantOutputForInput;
648 }
649
650 if (fp->preservesOpaqueInput()) {
651 ++optimizedForOpaqueInput;
Michael Ludwig7034f152018-10-08 16:43:58 -0400652 }
Brian Salomon3f4de782020-06-18 14:16:00 -0400653
John Stiles0dee9b02020-07-20 11:45:58 -0400654 // Draw base frame last so that rtc holds the original FP behavior if we need to dump
655 // the image to the log.
John Stiles9fbe9e92020-08-10 16:35:01 -0400656 render_fp(context, rtc.get(), fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture1),
John Stiles87d0a2f2020-08-10 13:12:41 -0400657 readData1.data());
Brian Salomonaff329b2017-08-11 09:40:37 -0400658
Michael Ludwig314d3772018-10-03 16:04:38 -0400659 // This test has a history of being flaky on a number of devices. If an FP is logically
660 // violating the optimizations, it's reasonable to expect it to violate requirements on
661 // a large number of pixels in the image. Sporadic pixel violations are more indicative
662 // of device errors and represents a separate problem.
Michael Ludwig72ab3462018-12-10 12:43:36 -0500663#if defined(SK_BUILD_FOR_SKQP)
Michael Ludwig314d3772018-10-03 16:04:38 -0400664 static constexpr int kMaxAcceptableFailedPixels = 0; // Strict when running as SKQP
665#else
666 static constexpr int kMaxAcceptableFailedPixels = 2 * kRenderSize; // ~0.7% of the image
667#endif
668
Michael Ludwig314d3772018-10-03 16:04:38 -0400669 // Collect first optimization failure message, to be output later as a warning or an
670 // error depending on whether the rendering "passed" or failed.
John Stilesaf110302020-07-20 09:45:51 -0400671 int failedPixelCount = 0;
Michael Ludwig314d3772018-10-03 16:04:38 -0400672 SkString coverageMessage;
673 SkString opaqueMessage;
674 SkString constMessage;
675 for (int y = 0; y < kRenderSize; ++y) {
676 for (int x = 0; x < kRenderSize; ++x) {
677 bool passing = true;
John Stiles4ed69472020-08-11 16:04:31 -0400678 GrColor input = inputPixels1[y * kRenderSize + x];
John Stilesaf110302020-07-20 09:45:51 -0400679 GrColor output = readData1[y * kRenderSize + x];
Michael Ludwig7034f152018-10-08 16:43:58 -0400680
681 if (fp->compatibleWithCoverageAsAlpha()) {
Brian Salomonbc73eb42019-12-18 14:57:45 -0500682 GrColor ins[3];
683 ins[0] = input;
John Stiles4ed69472020-08-11 16:04:31 -0400684 ins[1] = inputPixels2[y * kRenderSize + x];
685 ins[2] = inputPixels3[y * kRenderSize + x];
Michael Ludwig7034f152018-10-08 16:43:58 -0400686
Brian Salomonbc73eb42019-12-18 14:57:45 -0500687 GrColor outs[3];
688 outs[0] = output;
John Stilesaf110302020-07-20 09:45:51 -0400689 outs[1] = readData2[y * kRenderSize + x];
690 outs[2] = readData3[y * kRenderSize + x];
Michael Ludwig7034f152018-10-08 16:43:58 -0400691
Brian Salomonbc73eb42019-12-18 14:57:45 -0500692 if (!legal_modulation(ins, outs)) {
Brian Salomon587e08f2017-01-27 10:59:27 -0500693 passing = false;
Michael Ludwig314d3772018-10-03 16:04:38 -0400694 if (coverageMessage.isEmpty()) {
Brian Salomonbc73eb42019-12-18 14:57:45 -0500695 coverageMessage.printf(
John Stilesba1879d2020-08-11 13:58:32 -0400696 "\"Modulating\" processor did not match alpha-modulation "
697 "nor color-modulation rules.\n"
Michael Ludwig7034f152018-10-08 16:43:58 -0400698 "Input: 0x%08x, Output: 0x%08x, pixel (%d, %d).",
John Stilesba1879d2020-08-11 13:58:32 -0400699 input, output, x, y);
Michael Ludwig314d3772018-10-03 16:04:38 -0400700 }
Brian Salomon587e08f2017-01-27 10:59:27 -0500701 }
702 }
Michael Ludwig7034f152018-10-08 16:43:58 -0400703
Brian Osmancb3d0872018-10-16 15:19:28 -0400704 SkPMColor4f input4f = SkPMColor4f::FromBytes_RGBA(input);
705 SkPMColor4f output4f = SkPMColor4f::FromBytes_RGBA(output);
Brian Osman1d5b5982018-10-01 13:41:39 -0400706 SkPMColor4f expected4f;
Michael Ludwig7034f152018-10-08 16:43:58 -0400707 if (fp->hasConstantOutputForConstantInput(input4f, &expected4f)) {
Brian Osmancb3d0872018-10-16 15:19:28 -0400708 float rDiff = fabsf(output4f.fR - expected4f.fR);
709 float gDiff = fabsf(output4f.fG - expected4f.fG);
710 float bDiff = fabsf(output4f.fB - expected4f.fB);
711 float aDiff = fabsf(output4f.fA - expected4f.fA);
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500712 static constexpr float kTol = 4 / 255.f;
Brian Salomon587e08f2017-01-27 10:59:27 -0500713 if (rDiff > kTol || gDiff > kTol || bDiff > kTol || aDiff > kTol) {
Michael Ludwig314d3772018-10-03 16:04:38 -0400714 if (constMessage.isEmpty()) {
715 passing = false;
716
John Stilesba1879d2020-08-11 13:58:32 -0400717 constMessage.printf(
718 "Processor claimed output for const input doesn't match "
719 "actual output.\n"
720 "Error: %f, Tolerance: %f, input: (%f, %f, %f, %f), "
721 "actual: (%f, %f, %f, %f), expected(%f, %f, %f, %f).",
722 std::max(rDiff, std::max(gDiff, std::max(bDiff, aDiff))),
723 kTol, input4f.fR, input4f.fG, input4f.fB, input4f.fA,
Brian Osmancb3d0872018-10-16 15:19:28 -0400724 output4f.fR, output4f.fG, output4f.fB, output4f.fA,
725 expected4f.fR, expected4f.fG, expected4f.fB, expected4f.fA);
Michael Ludwig314d3772018-10-03 16:04:38 -0400726 }
Brian Salomon587e08f2017-01-27 10:59:27 -0500727 }
728 }
Brian Osman00b29392018-11-05 15:42:43 -0500729 if (input4f.isOpaque() && fp->preservesOpaqueInput() && !output4f.isOpaque()) {
Brian Salomon587e08f2017-01-27 10:59:27 -0500730 passing = false;
Michael Ludwig314d3772018-10-03 16:04:38 -0400731
732 if (opaqueMessage.isEmpty()) {
John Stilesba1879d2020-08-11 13:58:32 -0400733 opaqueMessage.printf(
734 "Processor claimed opaqueness is preserved but "
Michael Ludwig314d3772018-10-03 16:04:38 -0400735 "it is not. Input: 0x%08x, Output: 0x%08x.",
John Stilesba1879d2020-08-11 13:58:32 -0400736 input, output);
Michael Ludwige8e10752018-10-01 12:42:53 -0400737 }
Brian Osmanbd1f76f2017-03-15 11:33:12 -0400738 }
Michael Ludwig314d3772018-10-03 16:04:38 -0400739
740 if (!passing) {
741 // Regardless of how many optimizations the pixel violates, count it as a
742 // single bad pixel.
743 failedPixelCount++;
744 }
745 }
746 }
747
748 // Finished analyzing the entire image, see if the number of pixel failures meets the
749 // threshold for an FP violating the optimization requirements.
750 if (failedPixelCount > kMaxAcceptableFailedPixels) {
John Stilesba1879d2020-08-11 13:58:32 -0400751 ERRORF(reporter,
752 "Processor violated %d of %d pixels, seed: 0x%08x.\n"
753 "Processor:\n%s\nFirst failing pixel details are below:",
John Stilesaf110302020-07-20 09:45:51 -0400754 failedPixelCount, kRenderSize * kRenderSize, fpGenerator.initialSeed(),
John Stilesba1879d2020-08-11 13:58:32 -0400755 fp->dumpTreeInfo().c_str());
Michael Ludwig314d3772018-10-03 16:04:38 -0400756
757 // Print first failing pixel's details.
758 if (!coverageMessage.isEmpty()) {
759 ERRORF(reporter, coverageMessage.c_str());
760 }
761 if (!constMessage.isEmpty()) {
762 ERRORF(reporter, constMessage.c_str());
763 }
764 if (!opaqueMessage.isEmpty()) {
765 ERRORF(reporter, opaqueMessage.c_str());
766 }
767
768 if (!loggedFirstFailure) {
769 // Print with ERRORF to make sure the encoded image is output
770 SkString input;
Greg Daniel124486b2020-02-11 11:54:55 -0500771 log_texture_view(context, inputTexture1, &input);
Michael Ludwig314d3772018-10-03 16:04:38 -0400772 SkString output;
John Stilesaf110302020-07-20 09:45:51 -0400773 log_pixels(readData1.data(), kRenderSize, &output);
Michael Ludwig314d3772018-10-03 16:04:38 -0400774 ERRORF(reporter, "Input image: %s\n\n"
775 "===========================================================\n\n"
776 "Output image: %s\n", input.c_str(), output.c_str());
777 loggedFirstFailure = true;
778 }
John Stilesaf110302020-07-20 09:45:51 -0400779 } else if (failedPixelCount > 0) {
Michael Ludwig314d3772018-10-03 16:04:38 -0400780 // Don't trigger an error, but don't just hide the failures either.
781 INFOF(reporter, "Processor violated %d of %d pixels (below error threshold), seed: "
782 "0x%08x, processor: %s", failedPixelCount, kRenderSize * kRenderSize,
John Stilesaf110302020-07-20 09:45:51 -0400783 fpGenerator.initialSeed(), fp->dumpInfo().c_str());
Michael Ludwig314d3772018-10-03 16:04:38 -0400784 if (!coverageMessage.isEmpty()) {
785 INFOF(reporter, coverageMessage.c_str());
786 }
787 if (!constMessage.isEmpty()) {
788 INFOF(reporter, constMessage.c_str());
789 }
790 if (!opaqueMessage.isEmpty()) {
791 INFOF(reporter, opaqueMessage.c_str());
792 }
793 if (!loggedFirstWarning) {
794 SkString input;
Greg Daniel124486b2020-02-11 11:54:55 -0500795 log_texture_view(context, inputTexture1, &input);
Michael Ludwig314d3772018-10-03 16:04:38 -0400796 SkString output;
John Stilesaf110302020-07-20 09:45:51 -0400797 log_pixels(readData1.data(), kRenderSize, &output);
Michael Ludwig314d3772018-10-03 16:04:38 -0400798 INFOF(reporter, "Input image: %s\n\n"
799 "===========================================================\n\n"
800 "Output image: %s\n", input.c_str(), output.c_str());
801 loggedFirstWarning = true;
Brian Salomon587e08f2017-01-27 10:59:27 -0500802 }
803 }
804 }
805 }
806}
Robert Phillips18166ee2017-06-01 12:55:44 -0400807
John Stilesea8be212020-08-10 11:38:41 -0400808static void assert_processor_equality(skiatest::Reporter* reporter,
809 const GrFragmentProcessor& fp,
810 const GrFragmentProcessor& clone) {
811 REPORTER_ASSERT(reporter, !strcmp(fp.name(), clone.name()),
John Stilesba1879d2020-08-11 13:58:32 -0400812 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400813 REPORTER_ASSERT(reporter, fp.compatibleWithCoverageAsAlpha() ==
814 clone.compatibleWithCoverageAsAlpha(),
John Stilesba1879d2020-08-11 13:58:32 -0400815 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400816 REPORTER_ASSERT(reporter, fp.isEqual(clone),
John Stilesba1879d2020-08-11 13:58:32 -0400817 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400818 REPORTER_ASSERT(reporter, fp.preservesOpaqueInput() == clone.preservesOpaqueInput(),
John Stilesba1879d2020-08-11 13:58:32 -0400819 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400820 REPORTER_ASSERT(reporter, fp.hasConstantOutputForConstantInput() ==
821 clone.hasConstantOutputForConstantInput(),
John Stilesba1879d2020-08-11 13:58:32 -0400822 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400823 REPORTER_ASSERT(reporter, fp.numChildProcessors() == clone.numChildProcessors(),
John Stilesba1879d2020-08-11 13:58:32 -0400824 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400825 REPORTER_ASSERT(reporter, fp.usesVaryingCoords() == clone.usesVaryingCoords(),
John Stilesba1879d2020-08-11 13:58:32 -0400826 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400827 REPORTER_ASSERT(reporter, fp.referencesSampleCoords() == clone.referencesSampleCoords(),
John Stilesba1879d2020-08-11 13:58:32 -0400828 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400829}
830
831static bool verify_identical_render(skiatest::Reporter* reporter, int renderSize,
832 const char* processorType,
833 const GrColor readData1[], const GrColor readData2[]) {
834 // The ProcessorClone test has a history of being flaky on a number of devices. If an FP clone
835 // is logically wrong, it's reasonable to expect it produce a large number of pixel differences
836 // in the image. Sporadic pixel violations are more indicative device errors and represents a
837 // separate problem.
838#if defined(SK_BUILD_FOR_SKQP)
839 const int maxAcceptableFailedPixels = 0; // Strict when running as SKQP
840#else
841 const int maxAcceptableFailedPixels = 2 * renderSize; // ~0.002% of the pixels (size 1024*1024)
842#endif
843
844 int failedPixelCount = 0;
845 int firstWrongX = 0;
846 int firstWrongY = 0;
847 int idx = 0;
848 for (int y = 0; y < renderSize; ++y) {
849 for (int x = 0; x < renderSize; ++x, ++idx) {
850 if (readData1[idx] != readData2[idx]) {
851 if (!failedPixelCount) {
852 firstWrongX = x;
853 firstWrongY = y;
854 }
855 ++failedPixelCount;
856 }
857 if (failedPixelCount > maxAcceptableFailedPixels) {
858 idx = firstWrongY * renderSize + firstWrongX;
859 ERRORF(reporter,
860 "%s produced different output at (%d, %d). "
861 "Input color: 0x%08x, Original Output Color: 0x%08x, "
862 "Clone Output Color: 0x%08x.",
863 processorType, firstWrongX, firstWrongY, input_texel_color(x, y, 0.0f),
864 readData1[idx], readData2[idx]);
865
866 return false;
867 }
868 }
869 }
870
871 return true;
872}
873
874static void log_clone_failure(skiatest::Reporter* reporter, int renderSize,
875 GrDirectContext* context, const GrSurfaceProxyView& inputTexture,
876 GrColor pixelsFP[], GrColor pixelsClone[], GrColor pixelsRegen[]) {
877 // Write the images out as data URLs for inspection.
878 SkString inputURL, origURL, cloneURL, regenURL;
879 if (log_texture_view(context, inputTexture, &inputURL) &&
880 log_pixels(pixelsFP, renderSize, &origURL) &&
881 log_pixels(pixelsClone, renderSize, &cloneURL) &&
882 log_pixels(pixelsRegen, renderSize, &regenURL)) {
883 ERRORF(reporter,
884 "\nInput image:\n%s\n\n"
885 "==========================================================="
886 "\n\n"
887 "Orig output image:\n%s\n"
888 "==========================================================="
889 "\n\n"
890 "Clone output image:\n%s\n"
891 "==========================================================="
892 "\n\n"
893 "Regen output image:\n%s\n",
894 inputURL.c_str(), origURL.c_str(), cloneURL.c_str(), regenURL.c_str());
895 }
896}
897
Brian Salomon3f4de782020-06-18 14:16:00 -0400898// Tests that a fragment processor returned by GrFragmentProcessor::clone() is equivalent to its
899// progenitor.
Brian Salomon0e05a822017-07-25 09:43:22 -0400900DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ProcessorCloneTest, reporter, ctxInfo) {
John Stilesaf110302020-07-20 09:45:51 -0400901 GrDirectContext* context = ctxInfo.directContext();
902 GrResourceProvider* resourceProvider = context->priv().resourceProvider();
Brian Salomon0e05a822017-07-25 09:43:22 -0400903
John Stilesaf110302020-07-20 09:45:51 -0400904 TestFPGenerator fpGenerator{context, resourceProvider};
905 if (!fpGenerator.init()) {
906 ERRORF(reporter, "Could not initialize TestFPGenerator");
907 return;
908 }
Brian Salomon0e05a822017-07-25 09:43:22 -0400909
910 // Make the destination context for the test.
911 static constexpr int kRenderSize = 1024;
Greg Daniele20fcad2020-01-08 11:52:34 -0500912 auto rtc = GrRenderTargetContext::Make(
913 context, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kExact,
914 {kRenderSize, kRenderSize});
Brian Salomon0e05a822017-07-25 09:43:22 -0400915
John Stiles4ed69472020-08-11 16:04:31 -0400916 std::vector<GrColor> inputPixels = make_input_pixels(kRenderSize, kRenderSize, 0.0f);
917 GrSurfaceProxyView inputTexture =
918 make_input_texture(context, kRenderSize, kRenderSize, inputPixels.data());
John Stilesaf110302020-07-20 09:45:51 -0400919
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400920 // On failure we write out images, but just write the first failing set as the print is very
921 // large.
922 bool loggedFirstFailure = false;
923
John Stilesaf110302020-07-20 09:45:51 -0400924 // Storage for the original frame's readback and the readback of its clone.
John Stilesea8be212020-08-10 11:38:41 -0400925 std::vector<GrColor> readDataFP(kRenderSize * kRenderSize);
926 std::vector<GrColor> readDataClone(kRenderSize * kRenderSize);
927 std::vector<GrColor> readDataRegen(kRenderSize * kRenderSize);
Brian Salomon0e05a822017-07-25 09:43:22 -0400928
929 // Because processor factories configure themselves in random ways, this is not exhaustive.
930 for (int i = 0; i < GrFragmentProcessorTestFactory::Count(); ++i) {
931 static constexpr int kTimesToInvokeFactory = 10;
932 for (int j = 0; j < kTimesToInvokeFactory; ++j) {
John Stilesaf110302020-07-20 09:45:51 -0400933 fpGenerator.reroll();
John Stiles87d0a2f2020-08-10 13:12:41 -0400934 std::unique_ptr<GrFragmentProcessor> fp =
John Stiles9fbe9e92020-08-10 16:35:01 -0400935 fpGenerator.make(i, /*randomTreeDepth=*/1, /*inputFP=*/nullptr);
John Stiles87d0a2f2020-08-10 13:12:41 -0400936 std::unique_ptr<GrFragmentProcessor> regen =
John Stiles9fbe9e92020-08-10 16:35:01 -0400937 fpGenerator.make(i, /*randomTreeDepth=*/1, /*inputFP=*/nullptr);
John Stiles8c71f3e2020-06-15 15:07:19 -0400938 std::unique_ptr<GrFragmentProcessor> clone = fp->clone();
Brian Salomon0e05a822017-07-25 09:43:22 -0400939 if (!clone) {
John Stilesba1879d2020-08-11 13:58:32 -0400940 ERRORF(reporter, "Clone of processor %s failed.", fp->dumpTreeInfo().c_str());
Brian Salomon0e05a822017-07-25 09:43:22 -0400941 continue;
942 }
John Stilesea8be212020-08-10 11:38:41 -0400943 assert_processor_equality(reporter, *fp, *clone);
944
Brian Salomon0e05a822017-07-25 09:43:22 -0400945 // Draw with original and read back the results.
John Stilesea8be212020-08-10 11:38:41 -0400946 render_fp(context, rtc.get(), std::move(fp), readDataFP.data());
Brian Salomon0e05a822017-07-25 09:43:22 -0400947
948 // Draw with clone and read back the results.
John Stilesea8be212020-08-10 11:38:41 -0400949 render_fp(context, rtc.get(), std::move(clone), readDataClone.data());
Brian Salomon0e05a822017-07-25 09:43:22 -0400950
951 // Check that the results are the same.
John Stilesea8be212020-08-10 11:38:41 -0400952 if (!verify_identical_render(reporter, kRenderSize, "Processor clone",
953 readDataFP.data(), readDataClone.data())) {
954 // Dump a description from the regenerated processor (since the original FP has
955 // already been consumed).
John Stilesba1879d2020-08-11 13:58:32 -0400956 ERRORF(reporter, "FP hierarchy:\n%s", regen->dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400957
958 // Render and readback output from the regenerated FP. If this also mismatches, the
959 // FP itself doesn't generate consistent output. This could happen if:
960 // - the FP's TestCreate() does not always generate the same FP from a given seed
961 // - the FP's Make() does not always generate the same FP when given the same inputs
962 // - the FP itself generates inconsistent pixels (shader UB?)
963 // - the driver has a bug
964 render_fp(context, rtc.get(), std::move(regen), readDataRegen.data());
965
966 if (!verify_identical_render(reporter, kRenderSize, "Regenerated processor",
967 readDataFP.data(), readDataRegen.data())) {
968 ERRORF(reporter, "Output from regen did not match original!\n");
969 } else {
970 ERRORF(reporter, "Regenerated processor output matches original results.\n");
971 }
972
973 // If this is the first time we've encountered a cloning failure, log the generated
974 // images to the reporter as data URLs.
975 if (!loggedFirstFailure) {
976 log_clone_failure(reporter, kRenderSize, context, inputTexture,
977 readDataFP.data(), readDataClone.data(),
978 readDataRegen.data());
979 loggedFirstFailure = true;
Brian Salomon0e05a822017-07-25 09:43:22 -0400980 }
981 }
982 }
983 }
984}
985
Hal Canary6f6961e2017-01-31 13:50:44 -0500986#endif // GR_TEST_UTILS