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/SkBitmap.h"
9 #include "include/core/SkBlendMode.h"
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkColorSpace.h"
12 #include "include/core/SkPaint.h"
13 #include "include/core/SkRect.h"
14 #include "include/core/SkRefCnt.h"
15 #include "include/core/SkSurfaceProps.h"
16 #include "include/core/SkTypes.h"
17 #include "include/gpu/ganesh/GrDirectContext.h"
18 #include "include/private/SkColorData.h"
19 #include "include/private/base/SkAlignedStorage.h"
20 #include "include/private/base/SkOnce.h"
21 #include "include/private/base/SkTArray.h"
22 #include "include/private/base/SkTo.h"
23 #include "include/private/gpu/ganesh/GrTypesPriv.h"
24 #include "src/base/SkArenaAlloc.h"
25 #include "src/core/SkSLTypeShared.h"
26 #include "src/gpu/KeyBuilder.h"
27 #include "src/gpu/ResourceKey.h"
28 #include "src/gpu/SkBackingFit.h"
29 #include "src/gpu/ganesh/GrBuffer.h"
30 #include "src/gpu/ganesh/GrCaps.h"
31 #include "src/gpu/ganesh/GrColor.h"
32 #include "src/gpu/ganesh/GrDirectContextPriv.h"
33 #include "src/gpu/ganesh/GrDrawIndirectCommand.h"
34 #include "src/gpu/ganesh/GrGeometryProcessor.h"
35 #include "src/gpu/ganesh/GrMeshDrawTarget.h"
36 #include "src/gpu/ganesh/GrOpFlushState.h"
37 #include "src/gpu/ganesh/GrOpsRenderPass.h"
38 #include "src/gpu/ganesh/GrPipeline.h"
39 #include "src/gpu/ganesh/GrPixmap.h"
40 #include "src/gpu/ganesh/GrProcessorAnalysis.h"
41 #include "src/gpu/ganesh/GrProcessorSet.h"
42 #include "src/gpu/ganesh/GrProgramInfo.h"
43 #include "src/gpu/ganesh/GrResourceProvider.h"
44 #include "src/gpu/ganesh/GrShaderCaps.h"
45 #include "src/gpu/ganesh/GrShaderVar.h"
46 #include "src/gpu/ganesh/GrUserStencilSettings.h"
47 #include "src/gpu/ganesh/SurfaceDrawContext.h"
48 #include "src/gpu/ganesh/glsl/GrGLSLFragmentShaderBuilder.h"
49 #include "src/gpu/ganesh/glsl/GrGLSLVarying.h"
50 #include "src/gpu/ganesh/glsl/GrGLSLVertexGeoBuilder.h"
51 #include "src/gpu/ganesh/ops/GrDrawOp.h"
52 #include "src/gpu/ganesh/ops/GrOp.h"
53 #include "src/gpu/ganesh/ops/GrSimpleMeshDrawOpHelper.h"
54 #include "tests/CtsEnforcement.h"
55 #include "tests/Test.h"
56
57 #include <algorithm>
58 #include <array>
59 #include <cstddef>
60 #include <cstdint>
61 #include <functional>
62 #include <initializer_list>
63 #include <memory>
64 #include <utility>
65 #include <vector>
66
67 class GrAppliedClip;
68 class GrDstProxyView;
69 class GrGLSLProgramDataManager;
70 class GrRecordingContext;
71 class GrSurfaceProxyView;
72 enum class GrXferBarrierFlags;
73 struct GrContextOptions;
74
75 using namespace skia_private;
76
77 #if 0
78 #include "tools/ToolUtils.h"
79 #define WRITE_PNG_CONTEXT_TYPE kANGLE_D3D11_ES3
80 #endif
81
82 SKGPU_DECLARE_STATIC_UNIQUE_KEY(gIndexBufferKey);
83
84 static constexpr int kBoxSize = 2;
85 static constexpr int kBoxCountY = 8;
86 static constexpr int kBoxCountX = 8;
87 static constexpr int kBoxCount = kBoxCountY * kBoxCountX;
88
89 static constexpr int kImageWidth = kBoxCountY * kBoxSize;
90 static constexpr int kImageHeight = kBoxCountX * kBoxSize;
91
92 static constexpr int kIndexPatternRepeatCount = 3;
93 constexpr uint16_t kIndexPattern[6] = {0, 1, 2, 1, 2, 3};
94
95
96 class DrawMeshHelper {
97 public:
DrawMeshHelper(GrOpFlushState * state)98 DrawMeshHelper(GrOpFlushState* state) : fState(state) {}
99
100 sk_sp<const GrBuffer> getIndexBuffer();
101
102 sk_sp<const GrBuffer> makeIndexBuffer(const uint16_t[], int count);
103
makeVertexBuffer(const TArray<T> & data)104 template<typename T> sk_sp<const GrBuffer> makeVertexBuffer(const TArray<T>& data) {
105 return this->makeVertexBuffer(data.begin(), data.size());
106 }
makeVertexBuffer(const std::vector<T> & data)107 template<typename T> sk_sp<const GrBuffer> makeVertexBuffer(const std::vector<T>& data) {
108 return this->makeVertexBuffer(data.data(), data.size());
109 }
110 template<typename T> sk_sp<const GrBuffer> makeVertexBuffer(const T* data, int count);
111
target()112 GrMeshDrawTarget* target() { return fState; }
113
114 sk_sp<const GrBuffer> fIndexBuffer;
115 sk_sp<const GrBuffer> fIndexBuffer2;
116 sk_sp<const GrBuffer> fInstBuffer;
117 sk_sp<const GrBuffer> fVertBuffer;
118 sk_sp<const GrBuffer> fVertBuffer2;
119 sk_sp<const GrBuffer> fDrawIndirectBuffer;
120 size_t fDrawIndirectBufferOffset;
121
122 GrOpsRenderPass* bindPipeline(GrPrimitiveType, bool isInstanced, bool hasVertexBuffer);
123
124 private:
125 GrOpFlushState* fState;
126 };
127
128 struct Box {
129 float fX, fY;
130 GrColor fColor;
131 };
132
133 ////////////////////////////////////////////////////////////////////////////////////////////////////
134
135 /**
136 * This is a GPU-backend specific test. It tries to test all possible usecases of
137 * GrOpsRenderPass::draw*. The test works by drawing checkerboards of colored boxes, reading back
138 * the pixels, and comparing with expected results. The boxes are drawn on integer boundaries and
139 * the (opaque) colors are chosen from the set (r,g,b) = (0,255)^3, so the GPU renderings ought to
140 * produce exact matches.
141 */
142
143 static void run_test(GrDirectContext*,
144 const char* testName,
145 skiatest::Reporter*,
146 const std::unique_ptr<skgpu::ganesh::SurfaceDrawContext>&,
147 const SkBitmap& gold,
148 std::function<void(DrawMeshHelper*)> prepareFn,
149 std::function<void(DrawMeshHelper*)> executeFn);
150
151 #ifdef WRITE_PNG_CONTEXT_TYPE
IsContextTypeForOutputPNGs(skgpu::ContextType type)152 static bool IsContextTypeForOutputPNGs(skgpu::ContextType type) {
153 return type == skgpu::ContextType::WRITE_PNG_CONTEXT_TYPE;
154 }
DEF_GANESH_TEST_FOR_CONTEXTS(GrMeshTest,IsContextTypeForOutputPNGs,reporter,ctxInfo,nullptr)155 DEF_GANESH_TEST_FOR_CONTEXTS(GrMeshTest, IsContextTypeForOutputPNGs, reporter, ctxInfo, nullptr) {
156 #else
157 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(GrMeshTest, reporter, ctxInfo, CtsEnforcement::kApiLevel_T) {
158 #endif
159 auto dContext = ctxInfo.directContext();
160
161 auto sdc = skgpu::ganesh::SurfaceDrawContext::Make(dContext,
162 GrColorType::kRGBA_8888,
163 nullptr,
164 SkBackingFit::kExact,
165 {kImageWidth, kImageHeight},
166 SkSurfaceProps(),
167 /*label=*/{});
168 if (!sdc) {
169 ERRORF(reporter, "could not create render target context.");
170 return;
171 }
172
173 TArray<Box> boxes;
174 TArray<std::array<Box, 4>> vertexData;
175 SkBitmap gold;
176
177 // ---- setup ----------
178
179 SkPaint paint;
180 paint.setBlendMode(SkBlendMode::kSrc);
181 gold.allocN32Pixels(kImageWidth, kImageHeight);
182
183 SkCanvas goldCanvas(gold);
184
185 for (int y = 0; y < kBoxCountY; ++y) {
186 for (int x = 0; x < kBoxCountX; ++x) {
187 int c = y + x;
188 int rgb[3] = {-(c & 1) & 0xff, -((c >> 1) & 1) & 0xff, -((c >> 2) & 1) & 0xff};
189
190 const Box box = boxes.push_back() = {
191 float(x * kBoxSize),
192 float(y * kBoxSize),
193 GrColorPackRGBA(rgb[0], rgb[1], rgb[2], 255)
194 };
195
196 std::array<Box, 4>& boxVertices = vertexData.push_back();
197 for (int i = 0; i < 4; ++i) {
198 boxVertices[i] = {
199 box.fX + (i / 2) * kBoxSize,
200 box.fY + (i % 2) * kBoxSize,
201 box.fColor
202 };
203 }
204
205 paint.setARGB(255, rgb[0], rgb[1], rgb[2]);
206 goldCanvas.drawRect(SkRect::MakeXYWH(box.fX, box.fY, kBoxSize, kBoxSize), paint);
207 }
208 }
209
210 // ---- tests ----------
211
212 #define VALIDATE(buff) \
213 do { \
214 if (!buff) { \
215 ERRORF(reporter, #buff " is null."); \
216 return; \
217 } \
218 } while (0)
219
220 run_test(dContext, "draw", reporter, sdc, gold,
221 [&](DrawMeshHelper* helper) {
222 TArray<Box> expandedVertexData;
223 for (int i = 0; i < kBoxCount; ++i) {
224 for (int j = 0; j < 6; ++j) {
225 expandedVertexData.push_back(vertexData[i][kIndexPattern[j]]);
226 }
227 }
228
229 // Draw boxes one line at a time to exercise base vertex.
230 helper->fVertBuffer = helper->makeVertexBuffer(expandedVertexData);
231 VALIDATE(helper->fVertBuffer);
232 },
233 [&](DrawMeshHelper* helper) {
234 for (int y = 0; y < kBoxCountY; ++y) {
235 auto pass = helper->bindPipeline(GrPrimitiveType::kTriangles, false, true);
236 pass->bindBuffers(nullptr, nullptr, helper->fVertBuffer);
237 pass->draw(kBoxCountX * 6, y * kBoxCountX * 6);
238 }
239 });
240
241 run_test(dContext, "drawIndexed", reporter, sdc, gold,
242 [&](DrawMeshHelper* helper) {
243 helper->fIndexBuffer = helper->getIndexBuffer();
244 VALIDATE(helper->fIndexBuffer);
245 helper->fVertBuffer = helper->makeVertexBuffer(vertexData);
246 VALIDATE(helper->fVertBuffer);
247 },
248 [&](DrawMeshHelper* helper) {
249 int baseRepetition = 0;
250 int i = 0;
251 // Start at various repetitions within the patterned index buffer to exercise base
252 // index.
253 while (i < kBoxCount) {
254 static_assert(kIndexPatternRepeatCount >= 3);
255 int repetitionCount = std::min(3 - baseRepetition, kBoxCount - i);
256
257 auto pass = helper->bindPipeline(GrPrimitiveType::kTriangles, false, true);
258 pass->bindBuffers(helper->fIndexBuffer, nullptr, helper->fVertBuffer);
259 pass->drawIndexed(repetitionCount * 6, baseRepetition * 6, baseRepetition * 4,
260 (baseRepetition + repetitionCount) * 4 - 1,
261 (i - baseRepetition) * 4);
262
263 baseRepetition = (baseRepetition + 1) % 3;
264 i += repetitionCount;
265 }
266 });
267
268 run_test(dContext, "drawIndexPattern", reporter, sdc, gold,
269 [&](DrawMeshHelper* helper) {
270 helper->fIndexBuffer = helper->getIndexBuffer();
271 VALIDATE(helper->fIndexBuffer);
272 helper->fVertBuffer = helper->makeVertexBuffer(vertexData);
273 VALIDATE(helper->fVertBuffer);
274 },
275 [&](DrawMeshHelper* helper) {
276 // Draw boxes one line at a time to exercise base vertex. drawIndexPattern does
277 // not support a base index.
278 for (int y = 0; y < kBoxCountY; ++y) {
279 auto pass = helper->bindPipeline(GrPrimitiveType::kTriangles, false, true);
280 pass->bindBuffers(helper->fIndexBuffer, nullptr, helper->fVertBuffer);
281 pass->drawIndexPattern(6, kBoxCountX, kIndexPatternRepeatCount, 4,
282 y * kBoxCountX * 4);
283
284 }
285 });
286
287 for (bool indexed : {false, true}) {
288 if (!dContext->priv().caps()->drawInstancedSupport()) {
289 break;
290 }
291
292 run_test(dContext, indexed ? "drawIndexedInstanced" : "drawInstanced",
293 reporter, sdc, gold,
294 [&](DrawMeshHelper* helper) {
295 helper->fIndexBuffer = indexed ? helper->getIndexBuffer() : nullptr;
296 TArray<uint16_t> baseIndexData;
297 baseIndexData.push_back(kBoxCountX/2 * 6); // for testing base index.
298 for (int i = 0; i < 6; ++i) {
299 baseIndexData.push_back(kIndexPattern[i]);
300 }
301 helper->fIndexBuffer2 = helper->makeIndexBuffer(baseIndexData.begin(),
302 baseIndexData.size());
303 helper->fInstBuffer = helper->makeVertexBuffer(boxes);
304 VALIDATE(helper->fInstBuffer);
305 helper->fVertBuffer =
306 helper->makeVertexBuffer(std::vector<float>{0,0, 0,1, 1,0, 1,1});
307 VALIDATE(helper->fVertBuffer);
308 helper->fVertBuffer2 = helper->makeVertexBuffer( // for testing base vertex.
309 std::vector<float>{-1,-1, -1,-1, 0,0, 0,1, 1,0, 1,1});
310 VALIDATE(helper->fVertBuffer2);
311 },
312 [&](DrawMeshHelper* helper) {
313 // Draw boxes one line at a time to exercise base instance, base vertex, and
314 // null vertex buffer.
315 for (int y = 0; y < kBoxCountY; ++y) {
316 sk_sp<const GrBuffer> vertexBuffer;
317 int baseVertex = 0;
318 switch (y % 3) {
319 case 0:
320 if (dContext->priv().caps()->shaderCaps()->fVertexIDSupport) {
321 break;
322 }
323 [[fallthrough]];
324 case 1:
325 vertexBuffer = helper->fVertBuffer;
326 break;
327 case 2:
328 vertexBuffer = helper->fVertBuffer2;
329 baseVertex = 2;
330 break;
331 }
332
333 GrPrimitiveType primitiveType = indexed ? GrPrimitiveType::kTriangles
334 : GrPrimitiveType::kTriangleStrip;
335 auto pass = helper->bindPipeline(primitiveType, true,
336 SkToBool(vertexBuffer));
337 if (indexed) {
338 sk_sp<const GrBuffer> indexBuffer = (y % 2) ?
339 helper->fIndexBuffer2 : helper->fIndexBuffer;
340 VALIDATE(indexBuffer);
341 int baseIndex = (y % 2);
342 pass->bindBuffers(std::move(indexBuffer), helper->fInstBuffer,
343 std::move(vertexBuffer));
344 pass->drawIndexedInstanced(6, baseIndex, kBoxCountX, y * kBoxCountX,
345 baseVertex);
346 } else {
347 pass->bindBuffers(nullptr, helper->fInstBuffer,
348 std::move(vertexBuffer));
349 pass->drawInstanced(kBoxCountX, y * kBoxCountY, 4, baseVertex);
350 }
351 }
352 });
353 }
354
355 for (bool indexed : {false, true}) {
356 if (!dContext->priv().caps()->drawInstancedSupport()) {
357 break;
358 }
359
360 run_test(dContext, (indexed) ? "drawIndexedIndirect" : "drawIndirect",
361 reporter, sdc, gold,
362 [&](DrawMeshHelper* helper) {
363 TArray<uint16_t> baseIndexData;
364 baseIndexData.push_back(kBoxCountX/2 * 6); // for testing base index.
365 for (int j = 0; j < kBoxCountY; ++j) {
366 for (int i = 0; i < 6; ++i) {
367 baseIndexData.push_back(kIndexPattern[i]);
368 }
369 }
370 helper->fIndexBuffer2 = helper->makeIndexBuffer(baseIndexData.begin(),
371 baseIndexData.size());
372 VALIDATE(helper->fIndexBuffer2);
373 helper->fInstBuffer = helper->makeVertexBuffer(boxes);
374 VALIDATE(helper->fInstBuffer);
375 helper->fVertBuffer = helper->makeVertexBuffer(std::vector<float>{
376 -1,-1, 0,0, 0,1, 1,0, 1,1, -1,-1, 0,0, 1,0, 0,1, 1,1});
377 VALIDATE(helper->fVertBuffer);
378
379 GrDrawIndirectWriter indirectWriter;
380 GrDrawIndexedIndirectWriter indexedIndirectWriter;
381 if (indexed) {
382 // Make helper->fDrawIndirectBufferOffset nonzero.
383 sk_sp<const GrBuffer> ignoredBuff;
384 size_t ignoredOffset;
385 // Make a superfluous call to makeDrawIndirectSpace in order to test
386 // "offsetInBytes!=0" for the actual call to makeDrawIndexedIndirectSpace.
387 helper->target()->makeDrawIndirectSpace(29, &ignoredBuff, &ignoredOffset);
388 indexedIndirectWriter = helper->target()->makeDrawIndexedIndirectSpace(
389 kBoxCountY, &helper->fDrawIndirectBuffer,
390 &helper->fDrawIndirectBufferOffset);
391 } else {
392 // Make helper->fDrawIndirectBufferOffset nonzero.
393 sk_sp<const GrBuffer> ignoredBuff;
394 size_t ignoredOffset;
395 // Make a superfluous call to makeDrawIndexedIndirectSpace in order to test
396 // "offsetInBytes!=0" for the actual call to makeDrawIndirectSpace.
397 helper->target()->makeDrawIndexedIndirectSpace(7, &ignoredBuff,
398 &ignoredOffset);
399 indirectWriter = helper->target()->makeDrawIndirectSpace(
400 kBoxCountY, &helper->fDrawIndirectBuffer,
401 &helper->fDrawIndirectBufferOffset);
402 }
403
404 // Draw boxes one line at a time to exercise multiple draws.
405 for (int y = 0; y < kBoxCountY; ++y) {
406 int baseVertex = (y % 2) ? 1 : 6;
407 if (indexed) {
408 int baseIndex = 1 + y * 6;
409 indexedIndirectWriter.writeIndexed(6, baseIndex, kBoxCountX,
410 y * kBoxCountX, baseVertex);
411 } else {
412 indirectWriter.write(kBoxCountX, y * kBoxCountX, 4, baseVertex);
413 }
414 }
415 },
416 [&](DrawMeshHelper* helper) {
417 GrOpsRenderPass* pass;
418 if (indexed) {
419 pass = helper->bindPipeline(GrPrimitiveType::kTriangles, true, true);
420 pass->bindBuffers(helper->fIndexBuffer2, helper->fInstBuffer,
421 helper->fVertBuffer);
422 for (int i = 0; i < 3; ++i) {
423 int start = kBoxCountY * i / 3;
424 int end = kBoxCountY * (i + 1) / 3;
425 size_t offset = helper->fDrawIndirectBufferOffset + start *
426 sizeof(GrDrawIndexedIndirectCommand);
427 pass->drawIndexedIndirect(helper->fDrawIndirectBuffer.get(), offset,
428 end - start);
429 }
430 } else {
431 pass = helper->bindPipeline(GrPrimitiveType::kTriangleStrip, true, true);
432 pass->bindBuffers(nullptr, helper->fInstBuffer, helper->fVertBuffer);
433 for (int i = 0; i < 2; ++i) {
434 int start = kBoxCountY * i / 2;
435 int end = kBoxCountY * (i + 1) / 2;
436 size_t offset = helper->fDrawIndirectBufferOffset + start *
437 sizeof(GrDrawIndirectCommand);
438 pass->drawIndirect(helper->fDrawIndirectBuffer.get(), offset,
439 end - start);
440 }
441 }
442 });
443 }
444 }
445
446 ////////////////////////////////////////////////////////////////////////////////////////////////////
447
448 namespace {
449 class MeshTestOp : public GrDrawOp {
450 public:
451 DEFINE_OP_CLASS_ID
452
453 static GrOp::Owner Make(GrRecordingContext* rContext,
454 std::function<void(DrawMeshHelper*)> prepareFn,
455 std::function<void(DrawMeshHelper*)> executeFn) {
456 return GrOp::Make<MeshTestOp>(rContext, prepareFn, executeFn);
457 }
458
459 private:
460 friend class GrOp; // for ctor
461
462 MeshTestOp(std::function<void(DrawMeshHelper*)> prepareFn,
463 std::function<void(DrawMeshHelper*)> executeFn)
464 : INHERITED(ClassID()), fPrepareFn(prepareFn), fExecuteFn(executeFn) {
465 this->setBounds(
466 SkRect::MakeIWH(kImageWidth, kImageHeight), HasAABloat::kNo, IsHairline::kNo);
467 }
468
469 const char* name() const override { return "GrMeshTestOp"; }
470 FixedFunctionFlags fixedFunctionFlags() const override { return FixedFunctionFlags::kNone; }
471 GrProcessorSet::Analysis finalize(const GrCaps&, const GrAppliedClip*, GrClampType) override {
472 return GrProcessorSet::EmptySetAnalysis();
473 }
474
475 void onPrePrepare(GrRecordingContext*,
476 const GrSurfaceProxyView& writeView,
477 GrAppliedClip*,
478 const GrDstProxyView&,
479 GrXferBarrierFlags renderPassXferBarriers,
480 GrLoadOp colorLoadOp) override {}
481 void onPrepare(GrOpFlushState* state) override {
482 fHelper = std::make_unique<DrawMeshHelper>(state);
483 fPrepareFn(fHelper.get());
484 }
485 void onExecute(GrOpFlushState* state, const SkRect& chainBounds) override {
486 fExecuteFn(fHelper.get());
487 }
488
489 std::unique_ptr<DrawMeshHelper> fHelper;
490 std::function<void(DrawMeshHelper*)> fPrepareFn;
491 std::function<void(DrawMeshHelper*)> fExecuteFn;
492
493 using INHERITED = GrDrawOp;
494 };
495
496 class MeshTestProcessor : public GrGeometryProcessor {
497 public:
498 static GrGeometryProcessor* Make(SkArenaAlloc* arena, bool instanced, bool hasVertexBuffer) {
499 return arena->make([&](void* ptr) {
500 return new (ptr) MeshTestProcessor(instanced, hasVertexBuffer);
501 });
502 }
503
504 const char* name() const override { return "GrMeshTestProcessor"; }
505
506 void addToKey(const GrShaderCaps&, skgpu::KeyBuilder* b) const final {
507 b->add32(fInstanceLocation.isInitialized());
508 b->add32(fVertexPosition.isInitialized());
509 }
510
511 std::unique_ptr<ProgramImpl> makeProgramImpl(const GrShaderCaps&) const final;
512
513 private:
514 class Impl;
515
516 const Attribute& inColor() const {
517 return fVertexColor.isInitialized() ? fVertexColor : fInstanceColor;
518 }
519
520 MeshTestProcessor(bool instanced, bool hasVertexBuffer)
521 : INHERITED(kGrMeshTestProcessor_ClassID) {
522 if (instanced) {
523 fInstanceLocation = {"location", kFloat2_GrVertexAttribType, SkSLType::kHalf2};
524 fInstanceColor = {"color", kUByte4_norm_GrVertexAttribType, SkSLType::kHalf4};
525 this->setInstanceAttributesWithImplicitOffsets(&fInstanceLocation, 2);
526 if (hasVertexBuffer) {
527 fVertexPosition = {"vertex", kFloat2_GrVertexAttribType, SkSLType::kHalf2};
528 this->setVertexAttributesWithImplicitOffsets(&fVertexPosition, 1);
529 }
530 } else {
531 fVertexPosition = {"vertex", kFloat2_GrVertexAttribType, SkSLType::kHalf2};
532 fVertexColor = {"color", kUByte4_norm_GrVertexAttribType, SkSLType::kHalf4};
533 this->setVertexAttributesWithImplicitOffsets(&fVertexPosition, 2);
534 }
535 }
536
537 Attribute fVertexPosition;
538 Attribute fVertexColor;
539
540 Attribute fInstanceLocation;
541 Attribute fInstanceColor;
542
543 using INHERITED = GrGeometryProcessor;
544 };
545 } // anonymous namespace
546
547 std::unique_ptr<GrGeometryProcessor::ProgramImpl> MeshTestProcessor::makeProgramImpl(
548 const GrShaderCaps&) const {
549 class Impl : public ProgramImpl {
550 public:
551 void setData(const GrGLSLProgramDataManager&,
552 const GrShaderCaps&,
553 const GrGeometryProcessor&) final {}
554
555 private:
556 void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) final {
557 const MeshTestProcessor& mp = args.fGeomProc.cast<MeshTestProcessor>();
558 GrGLSLVertexBuilder* v = args.fVertBuilder;
559 GrGLSLFPFragmentBuilder* f = args.fFragBuilder;
560
561 GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
562 varyingHandler->emitAttributes(mp);
563 f->codeAppendf("half4 %s;", args.fOutputColor);
564 varyingHandler->addPassThroughAttribute(mp.inColor().asShaderVar(), args.fOutputColor);
565
566 if (!mp.fInstanceLocation.isInitialized()) {
567 v->codeAppendf("float2 vertex = %s;", mp.fVertexPosition.name());
568 } else {
569 if (mp.fVertexPosition.isInitialized()) {
570 v->codeAppendf("float2 offset = %s;", mp.fVertexPosition.name());
571 } else {
572 v->codeAppend("float2 offset = float2(sk_VertexID / 2, sk_VertexID % 2);");
573 }
574 v->codeAppendf("float2 vertex = %s + offset * %i;", mp.fInstanceLocation.name(),
575 kBoxSize);
576 }
577 gpArgs->fPositionVar.set(SkSLType::kFloat2, "vertex");
578
579 f->codeAppendf("const half4 %s = half4(1);", args.fOutputCoverage);
580 }
581 };
582
583 return std::make_unique<Impl>();
584 }
585
586 ////////////////////////////////////////////////////////////////////////////////////////////////////
587
588 sk_sp<const GrBuffer> DrawMeshHelper::makeIndexBuffer(const uint16_t indices[], int count) {
589 return fState->resourceProvider()->createBuffer(indices,
590 count*sizeof(uint16_t),
591 GrGpuBufferType::kIndex,
592 kDynamic_GrAccessPattern);
593 }
594
595 template<typename T>
596 sk_sp<const GrBuffer> DrawMeshHelper::makeVertexBuffer(const T* data, int count) {
597 return fState->resourceProvider()->createBuffer(data,
598 count*sizeof(T),
599 GrGpuBufferType::kVertex,
600 kDynamic_GrAccessPattern);
601 }
602
603 sk_sp<const GrBuffer> DrawMeshHelper::getIndexBuffer() {
604 SKGPU_DEFINE_STATIC_UNIQUE_KEY(gIndexBufferKey);
605 return fState->resourceProvider()->findOrCreatePatternedIndexBuffer(
606 kIndexPattern, 6, kIndexPatternRepeatCount, 4, gIndexBufferKey);
607 }
608
609 GrOpsRenderPass* DrawMeshHelper::bindPipeline(GrPrimitiveType primitiveType, bool isInstanced,
610 bool hasVertexBuffer) {
611 GrProcessorSet processorSet(SkBlendMode::kSrc);
612
613 // TODO: add a GrProcessorSet testing helper to make this easier
614 SkPMColor4f overrideColor;
615 processorSet.finalize(GrProcessorAnalysisColor(),
616 GrProcessorAnalysisCoverage::kNone,
617 fState->appliedClip(),
618 nullptr,
619 fState->caps(),
620 GrClampType::kAuto,
621 &overrideColor);
622
623 auto pipeline = GrSimpleMeshDrawOpHelper::CreatePipeline(fState,
624 std::move(processorSet),
625 GrPipeline::InputFlags::kNone);
626
627 GrGeometryProcessor* mtp = MeshTestProcessor::Make(fState->allocator(), isInstanced,
628 hasVertexBuffer);
629
630 GrProgramInfo programInfo(fState->caps(), fState->writeView(), fState->usesMSAASurface(),
631 pipeline, &GrUserStencilSettings::kUnused, mtp, primitiveType,
632 fState->renderPassBarriers(), fState->colorLoadOp());
633
634 fState->opsRenderPass()->bindPipeline(programInfo, SkRect::MakeIWH(kImageWidth, kImageHeight));
635 return fState->opsRenderPass();
636 }
637
638 static void run_test(GrDirectContext* dContext,
639 const char* testName,
640 skiatest::Reporter* reporter,
641 const std::unique_ptr<skgpu::ganesh::SurfaceDrawContext>& sdc,
642 const SkBitmap& gold,
643 std::function<void(DrawMeshHelper*)> prepareFn,
644 std::function<void(DrawMeshHelper*)> executeFn) {
645 const int w = gold.width(), h = gold.height();
646 const uint32_t* goldPx = reinterpret_cast<const uint32_t*>(gold.getPixels());
647 if (h != sdc->height() || w != sdc->width()) {
648 ERRORF(reporter, "[%s] expectation and rtc not compatible (?).", testName);
649 return;
650 }
651 if (sizeof(uint32_t) * kImageWidth != gold.rowBytes()) {
652 ERRORF(reporter, "[%s] unexpected row bytes in gold image", testName);
653 return;
654 }
655
656 GrPixmap resultPM = GrPixmap::Allocate(gold.info());
657 sdc->clear(SkPMColor4f::FromBytes_RGBA(0xbaaaaaad));
658 sdc->addDrawOp(MeshTestOp::Make(dContext, prepareFn, executeFn));
659
660 sdc->readPixels(dContext, resultPM, {0, 0});
661
662 #ifdef WRITE_PNG_CONTEXT_TYPE
663 #define STRINGIFY(X) #X
664 #define TOSTRING(X) STRINGIFY(X)
665 SkString filename;
666 filename.printf("GrMeshTest_%s_%s.png", TOSTRING(WRITE_PNG_CONTEXT_TYPE), testName);
667 SkDebugf("writing %s...\n", filename.c_str());
668 ToolUtils::EncodeImageToPngFile(filename.c_str(), resultPM);
669 #endif
670
671 for (int y = 0; y < h; ++y) {
672 for (int x = 0; x < w; ++x) {
673 uint32_t expected = goldPx[y * kImageWidth + x];
674 uint32_t actual = static_cast<uint32_t*>(resultPM.addr())[y * kImageWidth + x];
675 if (expected != actual) {
676 ERRORF(reporter, "[%s] pixel (%i,%i): got 0x%x expected 0x%x",
677 testName, x, y, actual, expected);
678 return;
679 }
680 }
681 }
682 }
683