GrMeshTest.cpp 16 KB

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