1 /*
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 #include <array>
12 #include <vector>
13 #include "GrCaps.h"
14 #include "GrContext.h"
15 #include "GrContextPriv.h"
16 #include "GrGeometryProcessor.h"
17 #include "GrGpuCommandBuffer.h"
18 #include "GrMemoryPool.h"
19 #include "GrOpFlushState.h"
20 #include "GrRenderTargetContext.h"
21 #include "GrRenderTargetContextPriv.h"
22 #include "GrResourceKey.h"
23 #include "GrResourceProvider.h"
24 #include "SkBitmap.h"
25 #include "SkMakeUnique.h"
26 #include "glsl/GrGLSLFragmentShaderBuilder.h"
27 #include "glsl/GrGLSLGeometryProcessor.h"
28 #include "glsl/GrGLSLVarying.h"
29 #include "glsl/GrGLSLVertexGeoBuilder.h"
30
31 GR_DECLARE_STATIC_UNIQUE_KEY(gIndexBufferKey);
32
33 static constexpr int kBoxSize = 2;
34 static constexpr int kBoxCountY = 8;
35 static constexpr int kBoxCountX = 8;
36 static constexpr int kBoxCount = kBoxCountY * kBoxCountX;
37
38 static constexpr int kImageWidth = kBoxCountY * kBoxSize;
39 static constexpr int kImageHeight = kBoxCountX * kBoxSize;
40
41 static constexpr int kIndexPatternRepeatCount = 3;
42 constexpr uint16_t kIndexPattern[6] = {0, 1, 2, 1, 2, 3};
43
44
45 class DrawMeshHelper {
46 public:
DrawMeshHelper(GrOpFlushState * state)47 DrawMeshHelper(GrOpFlushState* state) : fState(state) {}
48
49 sk_sp<const GrBuffer> getIndexBuffer();
50
makeVertexBuffer(const SkTArray<T> & data)51 template<typename T> sk_sp<const GrBuffer> makeVertexBuffer(const SkTArray<T>& data) {
52 return this->makeVertexBuffer(data.begin(), data.count());
53 }
makeVertexBuffer(const std::vector<T> & data)54 template<typename T> sk_sp<const GrBuffer> makeVertexBuffer(const std::vector<T>& data) {
55 return this->makeVertexBuffer(data.data(), data.size());
56 }
57 template<typename T> sk_sp<const GrBuffer> makeVertexBuffer(const T* data, int count);
58
59 void drawMesh(const GrMesh& mesh);
60
61 private:
62 GrOpFlushState* fState;
63 };
64
65 struct Box {
66 float fX, fY;
67 GrColor fColor;
68 };
69
70 ////////////////////////////////////////////////////////////////////////////////////////////////////
71
72 /**
73 * This is a GPU-backend specific test. It tries to test all possible usecases of GrMesh. The test
74 * works by drawing checkerboards of colored boxes, reading back the pixels, and comparing with
75 * expected results. The boxes are drawn on integer boundaries and the (opaque) colors are chosen
76 * from the set (r,g,b) = (0,255)^3, so the GPU renderings ought to produce exact matches.
77 */
78
79 static void run_test(GrContext* context, const char* testName, skiatest::Reporter*,
80 const sk_sp<GrRenderTargetContext>&, const SkBitmap& gold,
81 std::function<void(DrawMeshHelper*)> testFn);
82
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrMeshTest,reporter,ctxInfo)83 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrMeshTest, reporter, ctxInfo) {
84 GrContext* context = ctxInfo.grContext();
85
86 const GrBackendFormat format =
87 context->contextPriv().caps()->getBackendFormatFromColorType(kRGBA_8888_SkColorType);
88
89 sk_sp<GrRenderTargetContext> rtc(context->contextPriv().makeDeferredRenderTargetContext(
90 format, SkBackingFit::kExact, kImageWidth, kImageHeight, kRGBA_8888_GrPixelConfig,
91 nullptr));
92 if (!rtc) {
93 ERRORF(reporter, "could not create render target context.");
94 return;
95 }
96
97 SkTArray<Box> boxes;
98 SkTArray<std::array<Box, 4>> vertexData;
99 SkBitmap gold;
100
101 // ---- setup ----------
102
103 SkPaint paint;
104 paint.setBlendMode(SkBlendMode::kSrc);
105 gold.allocN32Pixels(kImageWidth, kImageHeight);
106
107 SkCanvas goldCanvas(gold);
108
109 for (int y = 0; y < kBoxCountY; ++y) {
110 for (int x = 0; x < kBoxCountX; ++x) {
111 int c = y + x;
112 int rgb[3] = {-(c & 1) & 0xff, -((c >> 1) & 1) & 0xff, -((c >> 2) & 1) & 0xff};
113
114 const Box box = boxes.push_back() = {
115 float(x * kBoxSize),
116 float(y * kBoxSize),
117 GrColorPackRGBA(rgb[0], rgb[1], rgb[2], 255)
118 };
119
120 std::array<Box, 4>& boxVertices = vertexData.push_back();
121 for (int i = 0; i < 4; ++i) {
122 boxVertices[i] = {
123 box.fX + (i / 2) * kBoxSize,
124 box.fY + (i % 2) * kBoxSize,
125 box.fColor
126 };
127 }
128
129 paint.setARGB(255, rgb[0], rgb[1], rgb[2]);
130 goldCanvas.drawRect(SkRect::MakeXYWH(box.fX, box.fY, kBoxSize, kBoxSize), paint);
131 }
132 }
133
134 goldCanvas.flush();
135
136 // ---- tests ----------
137
138 #define VALIDATE(buff) \
139 do { \
140 if (!buff) { \
141 ERRORF(reporter, #buff " is null."); \
142 return; \
143 } \
144 } while (0)
145
146 run_test(context, "setNonIndexedNonInstanced", reporter, rtc, gold,
147 [&](DrawMeshHelper* helper) {
148 SkTArray<Box> expandedVertexData;
149 for (int i = 0; i < kBoxCount; ++i) {
150 for (int j = 0; j < 6; ++j) {
151 expandedVertexData.push_back(vertexData[i][kIndexPattern[j]]);
152 }
153 }
154
155 // Draw boxes one line at a time to exercise base vertex.
156 auto vbuff = helper->makeVertexBuffer(expandedVertexData);
157 VALIDATE(vbuff);
158 for (int y = 0; y < kBoxCountY; ++y) {
159 GrMesh mesh(GrPrimitiveType::kTriangles);
160 mesh.setNonIndexedNonInstanced(kBoxCountX * 6);
161 mesh.setVertexData(vbuff, y * kBoxCountX * 6);
162 helper->drawMesh(mesh);
163 }
164 });
165
166 run_test(context, "setIndexed", reporter, rtc, gold, [&](DrawMeshHelper* helper) {
167 auto ibuff = helper->getIndexBuffer();
168 VALIDATE(ibuff);
169 auto vbuff = helper->makeVertexBuffer(vertexData);
170 VALIDATE(vbuff);
171 int baseRepetition = 0;
172 int i = 0;
173
174 // Start at various repetitions within the patterned index buffer to exercise base index.
175 while (i < kBoxCount) {
176 GR_STATIC_ASSERT(kIndexPatternRepeatCount >= 3);
177 int repetitionCount = SkTMin(3 - baseRepetition, kBoxCount - i);
178
179 GrMesh mesh(GrPrimitiveType::kTriangles);
180 mesh.setIndexed(ibuff, repetitionCount * 6, baseRepetition * 6, baseRepetition * 4,
181 (baseRepetition + repetitionCount) * 4 - 1, GrPrimitiveRestart::kNo);
182 mesh.setVertexData(vbuff, (i - baseRepetition) * 4);
183 helper->drawMesh(mesh);
184
185 baseRepetition = (baseRepetition + 1) % 3;
186 i += repetitionCount;
187 }
188 });
189
190 run_test(context, "setIndexedPatterned", reporter, rtc, gold, [&](DrawMeshHelper* helper) {
191 auto ibuff = helper->getIndexBuffer();
192 VALIDATE(ibuff);
193 auto vbuff = helper->makeVertexBuffer(vertexData);
194 VALIDATE(vbuff);
195
196 // Draw boxes one line at a time to exercise base vertex. setIndexedPatterned does not
197 // support a base index.
198 for (int y = 0; y < kBoxCountY; ++y) {
199 GrMesh mesh(GrPrimitiveType::kTriangles);
200 mesh.setIndexedPatterned(ibuff, 6, 4, kBoxCountX, kIndexPatternRepeatCount);
201 mesh.setVertexData(vbuff, y * kBoxCountX * 4);
202 helper->drawMesh(mesh);
203 }
204 });
205
206 for (bool indexed : {false, true}) {
207 if (!context->contextPriv().caps()->instanceAttribSupport()) {
208 break;
209 }
210
211 run_test(context, indexed ? "setIndexedInstanced" : "setInstanced",
212 reporter, rtc, gold, [&](DrawMeshHelper* helper) {
213 auto idxbuff = indexed ? helper->getIndexBuffer() : nullptr;
214 auto instbuff = helper->makeVertexBuffer(boxes);
215 VALIDATE(instbuff);
216 auto vbuff = helper->makeVertexBuffer(std::vector<float>{0,0, 0,1, 1,0, 1,1});
217 VALIDATE(vbuff);
218 auto vbuff2 = helper->makeVertexBuffer( // for testing base vertex.
219 std::vector<float>{-1,-1, -1,-1, 0,0, 0,1, 1,0, 1,1});
220 VALIDATE(vbuff2);
221
222 // Draw boxes one line at a time to exercise base instance, base vertex, and null vertex
223 // buffer. setIndexedInstanced intentionally does not support a base index.
224 for (int y = 0; y < kBoxCountY; ++y) {
225 GrMesh mesh(indexed ? GrPrimitiveType::kTriangles
226 : GrPrimitiveType::kTriangleStrip);
227 if (indexed) {
228 VALIDATE(idxbuff);
229 mesh.setIndexedInstanced(idxbuff, 6, instbuff, kBoxCountX, y * kBoxCountX,
230 GrPrimitiveRestart::kNo);
231 } else {
232 mesh.setInstanced(instbuff, kBoxCountX, y * kBoxCountX, 4);
233 }
234 switch (y % 3) {
235 case 0:
236 if (context->contextPriv().caps()->shaderCaps()->vertexIDSupport()) {
237 if (y % 2) {
238 // We don't need this call because it's the initial state of GrMesh.
239 mesh.setVertexData(nullptr);
240 }
241 break;
242 }
243 // Fallthru.
244 case 1:
245 mesh.setVertexData(vbuff);
246 break;
247 case 2:
248 mesh.setVertexData(vbuff2, 2);
249 break;
250 }
251 helper->drawMesh(mesh);
252 }
253 });
254 }
255 }
256
257 ////////////////////////////////////////////////////////////////////////////////////////////////////
258
259 class GrMeshTestOp : public GrDrawOp {
260 public:
261 DEFINE_OP_CLASS_ID
262
Make(GrContext * context,std::function<void (DrawMeshHelper *)> testFn)263 static std::unique_ptr<GrDrawOp> Make(GrContext* context,
264 std::function<void(DrawMeshHelper*)> testFn) {
265 GrOpMemoryPool* pool = context->contextPriv().opMemoryPool();
266
267 return pool->allocate<GrMeshTestOp>(testFn);
268 }
269
270 private:
271 friend class GrOpMemoryPool; // for ctor
272
GrMeshTestOp(std::function<void (DrawMeshHelper *)> testFn)273 GrMeshTestOp(std::function<void(DrawMeshHelper*)> testFn)
274 : INHERITED(ClassID())
275 , fTestFn(testFn) {
276 this->setBounds(SkRect::MakeIWH(kImageWidth, kImageHeight),
277 HasAABloat::kNo, IsZeroArea::kNo);
278 }
279
name() const280 const char* name() const override { return "GrMeshTestOp"; }
fixedFunctionFlags() const281 FixedFunctionFlags fixedFunctionFlags() const override { return FixedFunctionFlags::kNone; }
finalize(const GrCaps &,const GrAppliedClip *)282 GrProcessorSet::Analysis finalize(const GrCaps&, const GrAppliedClip*) override {
283 return GrProcessorSet::EmptySetAnalysis();
284 }
onPrepare(GrOpFlushState *)285 void onPrepare(GrOpFlushState*) override {}
onExecute(GrOpFlushState * state,const SkRect & chainBounds)286 void onExecute(GrOpFlushState* state, const SkRect& chainBounds) override {
287 DrawMeshHelper helper(state);
288 fTestFn(&helper);
289 }
290
291 std::function<void(DrawMeshHelper*)> fTestFn;
292
293 typedef GrDrawOp INHERITED;
294 };
295
296 class GrMeshTestProcessor : public GrGeometryProcessor {
297 public:
GrMeshTestProcessor(bool instanced,bool hasVertexBuffer)298 GrMeshTestProcessor(bool instanced, bool hasVertexBuffer)
299 : INHERITED(kGrMeshTestProcessor_ClassID) {
300 if (instanced) {
301 fInstanceLocation = {"location", kFloat2_GrVertexAttribType, kHalf2_GrSLType};
302 fInstanceColor = {"color", kUByte4_norm_GrVertexAttribType, kHalf4_GrSLType};
303 this->setInstanceAttributes(&fInstanceLocation, 2);
304 if (hasVertexBuffer) {
305 fVertexPosition = {"vertex", kFloat2_GrVertexAttribType, kHalf2_GrSLType};
306 this->setVertexAttributes(&fVertexPosition, 1);
307 }
308 } else {
309 fVertexPosition = {"vertex", kFloat2_GrVertexAttribType, kHalf2_GrSLType};
310 fVertexColor = {"color", kUByte4_norm_GrVertexAttribType, kHalf4_GrSLType};
311 this->setVertexAttributes(&fVertexPosition, 2);
312 }
313 }
314
name() const315 const char* name() const override { return "GrMeshTest Processor"; }
316
inColor() const317 const Attribute& inColor() const {
318 return fVertexColor.isInitialized() ? fVertexColor : fInstanceColor;
319 }
320
getGLSLProcessorKey(const GrShaderCaps &,GrProcessorKeyBuilder * b) const321 void getGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const final {
322 b->add32(fInstanceLocation.isInitialized());
323 b->add32(fVertexPosition.isInitialized());
324 }
325
326 GrGLSLPrimitiveProcessor* createGLSLInstance(const GrShaderCaps&) const final;
327
328 private:
329 Attribute fVertexPosition;
330 Attribute fVertexColor;
331
332 Attribute fInstanceLocation;
333 Attribute fInstanceColor;
334
335 friend class GLSLMeshTestProcessor;
336 typedef GrGeometryProcessor INHERITED;
337 };
338
339 class GLSLMeshTestProcessor : public GrGLSLGeometryProcessor {
setData(const GrGLSLProgramDataManager & pdman,const GrPrimitiveProcessor &,FPCoordTransformIter && transformIter)340 void setData(const GrGLSLProgramDataManager& pdman, const GrPrimitiveProcessor&,
341 FPCoordTransformIter&& transformIter) final {}
342
onEmitCode(EmitArgs & args,GrGPArgs * gpArgs)343 void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) final {
344 const GrMeshTestProcessor& mp = args.fGP.cast<GrMeshTestProcessor>();
345
346 GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
347 varyingHandler->emitAttributes(mp);
348 varyingHandler->addPassThroughAttribute(mp.inColor(), args.fOutputColor);
349
350 GrGLSLVertexBuilder* v = args.fVertBuilder;
351 if (!mp.fInstanceLocation.isInitialized()) {
352 v->codeAppendf("float2 vertex = %s;", mp.fVertexPosition.name());
353 } else {
354 if (mp.fVertexPosition.isInitialized()) {
355 v->codeAppendf("float2 offset = %s;", mp.fVertexPosition.name());
356 } else {
357 v->codeAppend ("float2 offset = float2(sk_VertexID / 2, sk_VertexID % 2);");
358 }
359 v->codeAppendf("float2 vertex = %s + offset * %i;", mp.fInstanceLocation.name(),
360 kBoxSize);
361 }
362 gpArgs->fPositionVar.set(kFloat2_GrSLType, "vertex");
363
364 GrGLSLFPFragmentBuilder* f = args.fFragBuilder;
365 f->codeAppendf("%s = half4(1);", args.fOutputCoverage);
366 }
367 };
368
createGLSLInstance(const GrShaderCaps &) const369 GrGLSLPrimitiveProcessor* GrMeshTestProcessor::createGLSLInstance(const GrShaderCaps&) const {
370 return new GLSLMeshTestProcessor;
371 }
372
373 ////////////////////////////////////////////////////////////////////////////////////////////////////
374
375 template<typename T>
makeVertexBuffer(const T * data,int count)376 sk_sp<const GrBuffer> DrawMeshHelper::makeVertexBuffer(const T* data, int count) {
377 return sk_sp<const GrBuffer>(
378 fState->resourceProvider()->createBuffer(
379 count * sizeof(T), kVertex_GrBufferType, kDynamic_GrAccessPattern,
380 GrResourceProvider::Flags::kRequireGpuMemory, data));
381 }
382
getIndexBuffer()383 sk_sp<const GrBuffer> DrawMeshHelper::getIndexBuffer() {
384 GR_DEFINE_STATIC_UNIQUE_KEY(gIndexBufferKey);
385 return fState->resourceProvider()->findOrCreatePatternedIndexBuffer(
386 kIndexPattern, 6, kIndexPatternRepeatCount, 4, gIndexBufferKey);
387 }
388
drawMesh(const GrMesh & mesh)389 void DrawMeshHelper::drawMesh(const GrMesh& mesh) {
390 GrPipeline pipeline(GrScissorTest::kDisabled, SkBlendMode::kSrc);
391 GrMeshTestProcessor mtp(mesh.isInstanced(), mesh.hasVertexData());
392 fState->rtCommandBuffer()->draw(mtp, pipeline, nullptr, nullptr, &mesh, 1,
393 SkRect::MakeIWH(kImageWidth, kImageHeight));
394 }
395
run_test(GrContext * context,const char * testName,skiatest::Reporter * reporter,const sk_sp<GrRenderTargetContext> & rtc,const SkBitmap & gold,std::function<void (DrawMeshHelper *)> testFn)396 static void run_test(GrContext* context, const char* testName, skiatest::Reporter* reporter,
397 const sk_sp<GrRenderTargetContext>& rtc, const SkBitmap& gold,
398 std::function<void(DrawMeshHelper*)> testFn) {
399 const int w = gold.width(), h = gold.height(), rowBytes = gold.rowBytes();
400 const uint32_t* goldPx = reinterpret_cast<const uint32_t*>(gold.getPixels());
401 if (h != rtc->height() || w != rtc->width()) {
402 ERRORF(reporter, "[%s] expectation and rtc not compatible (?).", testName);
403 return;
404 }
405 if (sizeof(uint32_t) * kImageWidth != gold.rowBytes()) {
406 ERRORF(reporter, "unexpected row bytes in gold image.", testName);
407 return;
408 }
409
410 SkAutoSTMalloc<kImageHeight * kImageWidth, uint32_t> resultPx(h * rowBytes);
411 rtc->clear(nullptr, SkPMColor4f::FromBytes_RGBA(0xbaaaaaad),
412 GrRenderTargetContext::CanClearFullscreen::kYes);
413 rtc->priv().testingOnly_addDrawOp(GrMeshTestOp::Make(context, testFn));
414 rtc->readPixels(gold.info(), resultPx, rowBytes, 0, 0, 0);
415 for (int y = 0; y < h; ++y) {
416 for (int x = 0; x < w; ++x) {
417 uint32_t expected = goldPx[y * kImageWidth + x];
418 uint32_t actual = resultPx[y * kImageWidth + x];
419 if (expected != actual) {
420 ERRORF(reporter, "[%s] pixel (%i,%i): got 0x%x expected 0x%x",
421 testName, x, y, actual, expected);
422 return;
423 }
424 }
425 }
426 }
427