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