blob: e4663e1af0b787e6a3acfca3d90a8f41c4f017ba [file] [log] [blame]
Chris Dalton114a3c02017-05-26 15:17:19 -06001/*
2 * Copyright 2017 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
8#include "SkTypes.h"
9#include "Test.h"
10
11#if SK_SUPPORT_GPU
12
13#include "GrContext.h"
14#include "GrGeometryProcessor.h"
Robert Phillips009e9af2017-06-15 14:01:04 -040015#include "GrGpuCommandBuffer.h"
Chris Dalton114a3c02017-05-26 15:17:19 -060016#include "GrOpFlushState.h"
17#include "GrRenderTargetContext.h"
18#include "GrRenderTargetContextPriv.h"
19#include "GrResourceProvider.h"
20#include "GrResourceKey.h"
21#include "SkMakeUnique.h"
22#include "glsl/GrGLSLVertexShaderBuilder.h"
23#include "glsl/GrGLSLFragmentShaderBuilder.h"
24#include "glsl/GrGLSLGeometryProcessor.h"
25#include "glsl/GrGLSLVarying.h"
26#include <array>
Chris Dalton1d616352017-05-31 12:51:23 -060027#include <vector>
Chris Dalton114a3c02017-05-26 15:17:19 -060028
29
30GR_DECLARE_STATIC_UNIQUE_KEY(gIndexBufferKey);
31
32static constexpr int kBoxSize = 2;
33static constexpr int kBoxCountY = 8;
34static constexpr int kBoxCountX = 8;
35static constexpr int kBoxCount = kBoxCountY * kBoxCountX;
36
37static constexpr int kImageWidth = kBoxCountY * kBoxSize;
38static constexpr int kImageHeight = kBoxCountX * kBoxSize;
39
40static constexpr int kIndexPatternRepeatCount = 3;
41constexpr uint16_t kIndexPattern[6] = {0, 1, 2, 1, 2, 3};
42
43
44class DrawMeshHelper {
45public:
46 DrawMeshHelper(GrOpFlushState* state) : fState(state) {}
47
48 sk_sp<const GrBuffer> getIndexBuffer();
49
50 template<typename T> sk_sp<const GrBuffer> makeVertexBuffer(const SkTArray<T>& data) {
51 return this->makeVertexBuffer(data.begin(), data.count());
52 }
Chris Dalton1d616352017-05-31 12:51:23 -060053 template<typename T> sk_sp<const GrBuffer> makeVertexBuffer(const std::vector<T>& data) {
54 return this->makeVertexBuffer(data.data(), data.size());
55 }
Chris Dalton114a3c02017-05-26 15:17:19 -060056 template<typename T> sk_sp<const GrBuffer> makeVertexBuffer(const T* data, int count);
57
58 void drawMesh(const GrMesh& mesh);
59
60private:
61 GrOpFlushState* fState;
62};
63
64struct Box {
65 float fX, fY;
66 GrColor fColor;
67};
68
69////////////////////////////////////////////////////////////////////////////////////////////////////
70
71/**
72 * This is a GPU-backend specific test. It tries to test all possible usecases of GrMesh. The test
73 * works by drawing checkerboards of colored boxes, reading back the pixels, and comparing with
74 * expected results. The boxes are drawn on integer boundaries and the (opaque) colors are chosen
75 * from the set (r,g,b) = (0,255)^3, so the GPU renderings ought to produce exact matches.
76 */
77
78static void run_test(const char* testName, skiatest::Reporter*, const sk_sp<GrRenderTargetContext>&,
79 const SkBitmap& gold, std::function<void(DrawMeshHelper*)> testFn);
80
81DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrMeshTest, reporter, ctxInfo) {
82 GrContext* const context = ctxInfo.grContext();
83
84 sk_sp<GrRenderTargetContext> rtc(
85 context->makeDeferredRenderTargetContext(SkBackingFit::kExact, kImageWidth, kImageHeight,
86 kRGBA_8888_GrPixelConfig, nullptr));
87 if (!rtc) {
88 ERRORF(reporter, "could not create render target context.");
89 return;
90 }
91
92 SkTArray<Box> boxes;
93 SkTArray<std::array<Box, 4>> vertexData;
94 SkBitmap gold;
95
96 // ---- setup ----------
97
98 SkPaint paint;
99 paint.setBlendMode(SkBlendMode::kSrc);
100 gold.allocN32Pixels(kImageWidth, kImageHeight);
101
102 SkCanvas goldCanvas(gold);
103
104 for (int y = 0; y < kBoxCountY; ++y) {
105 for (int x = 0; x < kBoxCountX; ++x) {
106 int c = y + x;
107 int rgb[3] = {-(c & 1) & 0xff, -((c >> 1) & 1) & 0xff, -((c >> 2) & 1) & 0xff};
108
109 const Box box = boxes.push_back() = {
110 float(x * kBoxSize),
111 float(y * kBoxSize),
112 GrColorPackRGBA(rgb[0], rgb[1], rgb[2], 255)
113 };
114
115 std::array<Box, 4>& boxVertices = vertexData.push_back();
116 for (int i = 0; i < 4; ++i) {
117 boxVertices[i] = {
118 box.fX + (i/2) * kBoxSize,
119 box.fY + (i%2) * kBoxSize,
120 box.fColor
121 };
122 }
123
124 paint.setARGB(255, rgb[0], rgb[1], rgb[2]);
125 goldCanvas.drawRect(SkRect::MakeXYWH(box.fX, box.fY, kBoxSize, kBoxSize), paint);
126 }
127 }
128
129 goldCanvas.flush();
130
131 // ---- tests ----------
132
133#define VALIDATE(buff) \
134 if (!buff) { \
135 ERRORF(reporter, #buff " is null."); \
136 return; \
137 }
138
139 run_test("setNonIndexedNonInstanced", reporter, rtc, gold, [&](DrawMeshHelper* helper) {
140 SkTArray<Box> expandedVertexData;
141 for (int i = 0; i < kBoxCount; ++i) {
142 for (int j = 0; j < 6; ++j) {
143 expandedVertexData.push_back(vertexData[i][kIndexPattern[j]]);
144 }
145 }
146
147 // Draw boxes one line at a time to exercise base vertex.
148 auto vbuff = helper->makeVertexBuffer(expandedVertexData);
149 VALIDATE(vbuff);
150 for (int y = 0; y < kBoxCountY; ++y) {
Chris Dalton3809bab2017-06-13 10:55:06 -0600151 GrMesh mesh(GrPrimitiveType::kTriangles);
Chris Dalton1d616352017-05-31 12:51:23 -0600152 mesh.setNonIndexedNonInstanced(kBoxCountX * 6);
Chris Dalton114a3c02017-05-26 15:17:19 -0600153 mesh.setVertexData(vbuff.get(), y * kBoxCountX * 6);
154 helper->drawMesh(mesh);
155 }
156 });
157
158 run_test("setIndexed", reporter, rtc, gold, [&](DrawMeshHelper* helper) {
159 auto ibuff = helper->getIndexBuffer();
160 VALIDATE(ibuff);
161 auto vbuff = helper->makeVertexBuffer(vertexData);
162 VALIDATE(vbuff);
163 int baseRepetition = 0;
164 int i = 0;
165
166 // Start at various repetitions within the patterned index buffer to exercise base index.
167 while (i < kBoxCount) {
168 GR_STATIC_ASSERT(kIndexPatternRepeatCount >= 3);
169 int repetitionCount = SkTMin(3 - baseRepetition, kBoxCount - i);
170
Chris Dalton3809bab2017-06-13 10:55:06 -0600171 GrMesh mesh(GrPrimitiveType::kTriangles);
Chris Dalton114a3c02017-05-26 15:17:19 -0600172 mesh.setIndexed(ibuff.get(), repetitionCount * 6, baseRepetition * 6,
173 baseRepetition * 4, (baseRepetition + repetitionCount) * 4 - 1);
174 mesh.setVertexData(vbuff.get(), (i - baseRepetition) * 4);
175 helper->drawMesh(mesh);
176
177 baseRepetition = (baseRepetition + 1) % 3;
178 i += repetitionCount;
179 }
180 });
181
182 run_test("setIndexedPatterned", reporter, rtc, gold, [&](DrawMeshHelper* helper) {
183 auto ibuff = helper->getIndexBuffer();
184 VALIDATE(ibuff);
185 auto vbuff = helper->makeVertexBuffer(vertexData);
186 VALIDATE(vbuff);
187
188 // Draw boxes one line at a time to exercise base vertex. setIndexedPatterned does not
189 // support a base index.
190 for (int y = 0; y < kBoxCountY; ++y) {
Chris Dalton3809bab2017-06-13 10:55:06 -0600191 GrMesh mesh(GrPrimitiveType::kTriangles);
Chris Dalton114a3c02017-05-26 15:17:19 -0600192 mesh.setIndexedPatterned(ibuff.get(), 6, 4, kBoxCountX, kIndexPatternRepeatCount);
193 mesh.setVertexData(vbuff.get(), y * kBoxCountX * 4);
194 helper->drawMesh(mesh);
195 }
196 });
Chris Dalton1d616352017-05-31 12:51:23 -0600197
198 for (bool indexed : {false, true}) {
199 if (!context->caps()->instanceAttribSupport()) {
200 break;
201 }
202
203 run_test(indexed ? "setIndexedInstanced" : "setInstanced",
204 reporter, rtc, gold, [&](DrawMeshHelper* helper) {
205 auto idxbuff = indexed ? helper->getIndexBuffer() : nullptr;
206 auto instbuff = helper->makeVertexBuffer(boxes);
207 VALIDATE(instbuff);
208 auto vbuff = helper->makeVertexBuffer(std::vector<float>{0,0, 0,1, 1,0, 1,1});
209 VALIDATE(vbuff);
210 auto vbuff2 = helper->makeVertexBuffer( // for testing base vertex.
211 std::vector<float>{-1,-1, -1,-1, 0,0, 0,1, 1,0, 1,1});
212 VALIDATE(vbuff2);
213
214 // Draw boxes one line at a time to exercise base instance, base vertex, and null vertex
215 // buffer. setIndexedInstanced intentionally does not support a base index.
216 for (int y = 0; y < kBoxCountY; ++y) {
Chris Dalton3809bab2017-06-13 10:55:06 -0600217 GrMesh mesh(indexed ? GrPrimitiveType::kTriangles
218 : GrPrimitiveType::kTriangleStrip);
Chris Dalton1d616352017-05-31 12:51:23 -0600219 if (indexed) {
220 VALIDATE(idxbuff);
221 mesh.setIndexedInstanced(idxbuff.get(), 6,
222 instbuff.get(), kBoxCountX, y * kBoxCountX);
223 } else {
224 mesh.setInstanced(instbuff.get(), kBoxCountX, y * kBoxCountX, 4);
225 }
226 switch (y % 3) {
227 case 0:
228 if (context->caps()->shaderCaps()->vertexIDSupport()) {
229 if (y % 2) {
230 // We don't need this call because it's the initial state of GrMesh.
231 mesh.setVertexData(nullptr);
232 }
233 break;
234 }
235 // Fallthru.
236 case 1:
237 mesh.setVertexData(vbuff.get());
238 break;
239 case 2:
240 mesh.setVertexData(vbuff2.get(), 2);
241 break;
242 }
243 helper->drawMesh(mesh);
244 }
245 });
246 }
Chris Dalton114a3c02017-05-26 15:17:19 -0600247}
248
249////////////////////////////////////////////////////////////////////////////////////////////////////
250
251class GrMeshTestOp : public GrDrawOp {
252public:
253 DEFINE_OP_CLASS_ID
254
255 GrMeshTestOp(std::function<void(DrawMeshHelper*)> testFn)
256 : INHERITED(ClassID())
257 , fTestFn(testFn) {
258 this->setBounds(SkRect::MakeIWH(kImageWidth, kImageHeight),
259 HasAABloat::kNo, IsZeroArea::kNo);
260 }
261
262private:
263 const char* name() const override { return "GrMeshTestOp"; }
264 FixedFunctionFlags fixedFunctionFlags() const override { return FixedFunctionFlags::kNone; }
265 bool xpRequiresDstTexture(const GrCaps&, const GrAppliedClip*) override { return false; }
266 bool onCombineIfPossible(GrOp* other, const GrCaps& caps) override { return false; }
267 void onPrepare(GrOpFlushState*) override {}
268 void onExecute(GrOpFlushState* state) override {
269 DrawMeshHelper helper(state);
270 fTestFn(&helper);
271 }
272
273 std::function<void(DrawMeshHelper*)> fTestFn;
274
275 typedef GrDrawOp INHERITED;
276};
277
278class GrMeshTestProcessor : public GrGeometryProcessor {
279public:
Chris Dalton1d616352017-05-31 12:51:23 -0600280 GrMeshTestProcessor(bool instanced, bool hasVertexBuffer)
281 : fInstanceLocation(nullptr)
282 , fVertex(nullptr)
283 , fColor(nullptr) {
284 if (instanced) {
285 fInstanceLocation = &this->addInstanceAttrib("location", kVec2f_GrVertexAttribType);
286 if (hasVertexBuffer) {
287 fVertex = &this->addVertexAttrib("vertex", kVec2f_GrVertexAttribType);
288 }
289 fColor = &this->addInstanceAttrib("color", kVec4ub_GrVertexAttribType);
290 } else {
291 fVertex = &this->addVertexAttrib("vertex", kVec2f_GrVertexAttribType);
292 fColor = &this->addVertexAttrib("color", kVec4ub_GrVertexAttribType);
293 }
Chris Dalton114a3c02017-05-26 15:17:19 -0600294 this->initClassID<GrMeshTestProcessor>();
295 }
296
297 const char* name() const override { return "GrMeshTest Processor"; }
298
Chris Dalton1d616352017-05-31 12:51:23 -0600299 void getGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const final {
300 b->add32(SkToBool(fInstanceLocation));
301 b->add32(SkToBool(fVertex));
302 }
Chris Dalton114a3c02017-05-26 15:17:19 -0600303
304 GrGLSLPrimitiveProcessor* createGLSLInstance(const GrShaderCaps&) const final;
305
306protected:
Chris Dalton1d616352017-05-31 12:51:23 -0600307 const Attribute* fInstanceLocation;
308 const Attribute* fVertex;
309 const Attribute* fColor;
Chris Dalton114a3c02017-05-26 15:17:19 -0600310
311 friend class GLSLMeshTestProcessor;
312 typedef GrGeometryProcessor INHERITED;
313};
314
315class GLSLMeshTestProcessor : public GrGLSLGeometryProcessor {
316 void setData(const GrGLSLProgramDataManager& pdman, const GrPrimitiveProcessor&,
317 FPCoordTransformIter&& transformIter) final {}
318
319 void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) final {
320 const GrMeshTestProcessor& mp = args.fGP.cast<GrMeshTestProcessor>();
321
322 GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
323 varyingHandler->emitAttributes(mp);
Chris Dalton1d616352017-05-31 12:51:23 -0600324 varyingHandler->addPassThroughAttribute(mp.fColor, args.fOutputColor);
Chris Dalton114a3c02017-05-26 15:17:19 -0600325
326 GrGLSLVertexBuilder* v = args.fVertBuilder;
Chris Dalton1d616352017-05-31 12:51:23 -0600327 if (!mp.fInstanceLocation) {
328 v->codeAppendf("vec2 vertex = %s;", mp.fVertex->fName);
329 } else {
330 if (mp.fVertex) {
331 v->codeAppendf("vec2 offset = %s;", mp.fVertex->fName);
332 } else {
333 v->codeAppend ("vec2 offset = vec2(sk_VertexID / 2, sk_VertexID % 2);");
334 }
335 v->codeAppendf("vec2 vertex = %s + offset * %i;",
336 mp.fInstanceLocation->fName, kBoxSize);
337 }
Chris Dalton114a3c02017-05-26 15:17:19 -0600338 gpArgs->fPositionVar.set(kVec2f_GrSLType, "vertex");
339
340 GrGLSLPPFragmentBuilder* f = args.fFragBuilder;
341 f->codeAppendf("%s = vec4(1);", args.fOutputCoverage);
342 }
343};
344
345GrGLSLPrimitiveProcessor* GrMeshTestProcessor::createGLSLInstance(const GrShaderCaps&) const {
346 return new GLSLMeshTestProcessor;
347}
348
349////////////////////////////////////////////////////////////////////////////////////////////////////
350
351template<typename T>
352sk_sp<const GrBuffer> DrawMeshHelper::makeVertexBuffer(const T* data, int count) {
353 return sk_sp<const GrBuffer>(
354 fState->resourceProvider()->createBuffer(
355 count * sizeof(T), kVertex_GrBufferType, kDynamic_GrAccessPattern,
356 GrResourceProvider::kNoPendingIO_Flag |
357 GrResourceProvider::kRequireGpuMemory_Flag, data));
358}
359
360sk_sp<const GrBuffer> DrawMeshHelper::getIndexBuffer() {
361 GR_DEFINE_STATIC_UNIQUE_KEY(gIndexBufferKey);
362 return sk_sp<const GrBuffer>(
363 fState->resourceProvider()->findOrCreatePatternedIndexBuffer(
364 kIndexPattern, 6, kIndexPatternRepeatCount, 4, gIndexBufferKey));
365}
366
367void DrawMeshHelper::drawMesh(const GrMesh& mesh) {
368 GrRenderTarget* rt = fState->drawOpArgs().fRenderTarget;
Chris Dalton46983b72017-06-06 12:27:16 -0600369 GrPipeline pipeline(rt, GrPipeline::ScissorState::kDisabled, SkBlendMode::kSrc);
Chris Dalton1d616352017-05-31 12:51:23 -0600370 GrMeshTestProcessor mtp(mesh.isInstanced(), mesh.hasVertexData());
Chris Dalton46983b72017-06-06 12:27:16 -0600371 fState->commandBuffer()->draw(pipeline, mtp, &mesh, nullptr, 1,
Chris Dalton114a3c02017-05-26 15:17:19 -0600372 SkRect::MakeIWH(kImageWidth, kImageHeight));
373}
374
375static void run_test(const char* testName, skiatest::Reporter* reporter,
376 const sk_sp<GrRenderTargetContext>& rtc, const SkBitmap& gold,
377 std::function<void(DrawMeshHelper*)> testFn) {
378 const int w = gold.width(), h = gold.height(), rowBytes = gold.rowBytes();
379 const uint32_t* goldPx = reinterpret_cast<const uint32_t*>(gold.getPixels());
380 if (h != rtc->height() || w != rtc->width()) {
381 ERRORF(reporter, "[%s] expectation and rtc not compatible (?).", testName);
382 return;
383 }
384 if (sizeof(uint32_t) * kImageWidth != gold.rowBytes()) {
385 ERRORF(reporter, "unexpected row bytes in gold image.", testName);
386 return;
387 }
388
389 SkAutoSTMalloc<kImageHeight * kImageWidth, uint32_t> resultPx(h * rowBytes);
390 rtc->clear(nullptr, 0xbaaaaaad, true);
391 rtc->priv().testingOnly_addDrawOp(skstd::make_unique<GrMeshTestOp>(testFn));
392 rtc->readPixels(gold.info(), resultPx, rowBytes, 0, 0, 0);
393 for (int y = 0; y < h; ++y) {
394 for (int x = 0; x < w; ++x) {
395 uint32_t expected = goldPx[y * kImageWidth + x];
396 uint32_t actual = resultPx[y * kImageWidth + x];
397 if (expected != actual) {
398 ERRORF(reporter, "[%s] pixel (%i,%i): got 0x%x expected 0x%x",
399 testName, x, y, actual, expected);
400 return;
401 }
402 }
403 }
404}
405
406#endif