Debian Codegraph @

gm/mesh.cpp

raw
1 /*
2 * Copyright 2021 Google LLC
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 "gm/gm.h"
9 #include "include/core/SkBlender.h"
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkColor.h"
12 #include "include/core/SkColorSpace.h"
13 #include "include/core/SkData.h"
14 #include "include/core/SkMesh.h"
15 #include "include/core/SkPicture.h"
16 #include "include/core/SkPictureRecorder.h"
17 #include "include/core/SkPoint.h"
18 #include "include/core/SkString.h"
19 #include "include/core/SkSurface.h"
20 #include "include/effects/SkGradient.h"
21 #include "include/gpu/ganesh/GrDirectContext.h"
22 #include "include/gpu/ganesh/SkMeshGanesh.h"
23 #include "include/private/base/SkAssert.h"
24 #include "src/base/SkRandom.h"
25 #include "src/core/SkCanvasPriv.h"
26 #include "tools/DecodeUtils.h"
27 #include "tools/timer/TimeUtils.h"
28
29 using namespace skia_private;
30
31 namespace skiagm {
32
33 class MeshGM : public skiagm::GM {
34 public:
35 MeshGM() {}
36
37 protected:
38 using Attribute = SkMeshSpecification::Attribute;
39 using Varying = SkMeshSpecification::Varying;
40
41 SkISize getISize() override { return {435, 1180}; }
42
43 void onOnceBeforeDraw() override {
44 {
45 static const Attribute kAttributes[]{
46 {Attribute::Type::kFloat4, 8, SkString{"xuyv"}},
47 {Attribute::Type::kUByte4_unorm, 4, SkString{"brag"}},
48 };
49 static const Varying kVaryings[]{
50 {Varying::Type::kHalf4, SkString{"color"}},
51 {Varying::Type::kFloat2, SkString{"uv"} },
52 };
53 static constexpr char kVS[] = R"(
54 half4 unswizzle_color(half4 color) { return color.garb; }
55
56 Varyings main(const in Attributes attributes) {
57 Varyings varyings;
58 varyings.color = unswizzle_color(attributes.brag);
59 varyings.uv = attributes.xuyv.yw;
60 varyings.position = attributes.xuyv.xz;
61 return varyings;
62 }
63 )";
64 static constexpr char kFS[] = R"(
65 uniform colorFilter filter;
66
67 float2 main(const in Varyings varyings, out float4 color) {
68 color = filter.eval(varyings.color);
69 return varyings.uv;
70 }
71 )";
72 auto [spec, error] = SkMeshSpecification::Make(kAttributes,
73 sizeof(ColorVertex),
74 kVaryings,
75 SkString(kVS),
76 SkString(kFS));
77 if (!spec) {
78 SkDebugf("%s\n", error.c_str());
79 }
80 fSpecWithColor = std::move(spec);
81 }
82 {
83 static const Attribute kAttributes[]{
84 {Attribute::Type::kFloat4, 0, SkString{"xuyv"}},
85 };
86 static const Varying kVaryings[]{
87 {Varying::Type::kFloat2, SkString{"vux2"}},
88 };
89 static constexpr char kVS[] = R"(
90 Varyings main(const in Attributes a) {
91 Varyings v;
92 v.vux2 = 2*a.xuyv.wy;
93 v.position = a.xuyv.xz;
94 return v;
95 }
96 )";
97 static constexpr char kFS[] = R"(
98 float2 helper(in float2 vux2) { return vux2.yx/2; }
99 float2 main(const in Varyings varyings) {
100 return helper(varyings.vux2);
101 }
102 )";
103 auto [spec, error] = SkMeshSpecification::Make(kAttributes,
104 sizeof(NoColorVertex),
105 kVaryings,
106 SkString(kVS),
107 SkString(kFS));
108 if (!spec) {
109 SkDebugf("%s\n", error.c_str());
110 }
111 fSpecWithNoColor = std::move(spec);
112 }
113
114 static constexpr SkColor4f kColors[] = {SkColors::kTransparent, SkColors::kWhite};
115 fShader = SkShaders::RadialGradient({10, 10}, 3, {{kColors, {}, SkTileMode::kMirror}, {}});
116 }
117
118 DrawResult onGpuSetup(SkCanvas* canvas, SkString* string, GraphiteTestContext*) override {
119 auto dc = GrAsDirectContext(canvas->recordingContext());
120 this->ensureBuffers();
121 if (!dc || dc->abandoned()) {
122 return DrawResult::kOk;
123 }
124
125 fColorVB = SkMeshes::CopyVertexBuffer(dc, fColorVB);
126 fColorIndexedVB = SkMeshes::CopyVertexBuffer(dc, fColorIndexedVB);
127 fIB[1] = SkMeshes::CopyIndexBuffer (dc, fIB[0]);
128 if (!fColorVB || !fColorIndexedVB || !fIB[1]) {
129 return DrawResult::kFail;
130 }
131 return DrawResult::kOk;
132 }
133
134 void onGpuTeardown() override {
135 // Destroy the GPU buffers and recreate on CPU
136 fColorVB = nullptr;
137 fColorIndexedVB = nullptr;
138 fIB[1] = nullptr;
139 this->ensureBuffers();
140 }
141
142 SkString getName() const override { return SkString("custommesh"); }
143
144 DrawResult onDraw(SkCanvas* canvas, SkString*) override {
145 SkRuntimeEffect::ChildPtr nullChild[1] = {};
146 int i = 0;
147 for (const sk_sp<SkBlender>& blender : {SkBlender::Mode(SkBlendMode::kDst),
148 SkBlender::Mode(SkBlendMode::kSrc),
149 SkBlender::Mode(SkBlendMode::kSaturation)}) {
150 canvas->save();
151 for (uint8_t alpha : {0xFF , 0x40})
152 for (bool colors : {false, true})
153 for (bool shader : {false, true}) {
154 SkMesh::Result result;
155 // Rather than pile onto the combinatorics we draw every other test case indexed.
156 if ((i & 1) == 0) {
157 if (colors) {
158 result = SkMesh::Make(fSpecWithColor,
159 SkMesh::Mode::kTriangleStrip,
160 fColorVB,
161 /*vertexCount=*/4,
162 /*vertexOffset=*/0,
163 /*uniforms=*/nullptr,
164 /*children=*/nullChild,
165 kRect);
166 } else {
167 result = SkMesh::Make(fSpecWithNoColor,
168 SkMesh::Mode::kTriangleStrip,
169 fNoColorVB,
170 /*vertexCount=*/4,
171 kNoColorOffset,
172 /*uniforms=*/nullptr,
173 /*children=*/{},
174 kRect);
175 }
176 } else {
177 // Alternate between CPU and GPU-backend index buffers.
178 auto ib = (i % 4 == 0) ? fIB[0] : fIB[1];
179 if (colors) {
180 result = SkMesh::MakeIndexed(fSpecWithColor,
181 SkMesh::Mode::kTriangles,
182 fColorIndexedVB,
183 /*vertexCount=*/6,
184 kColorIndexedOffset,
185 std::move(ib),
186 /*indexCount=*/6,
187 kIndexOffset,
188 /*uniforms=*/nullptr,
189 /*children=*/nullChild,
190 kRect);
191 } else {
192 result = SkMesh::MakeIndexed(fSpecWithNoColor,
193 SkMesh::Mode::kTriangles,
194 fNoColorIndexedVB,
195 /*vertexCount=*/6,
196 /*vertexOffset=*/0,
197 std::move(ib),
198 /*indexCount=*/6,
199 kIndexOffset,
200 /*uniforms=*/nullptr,
201 /*children=*/{},
202 kRect);
203 }
204 }
205 if (!result.mesh.isValid()) {
206 SkDebugf("Mesh creation failed: %s\n", result.error.c_str());
207 return DrawResult::kFail;
208 }
209
210 SkPaint paint;
211 paint.setColor(SK_ColorGREEN);
212 paint.setShader(shader ? fShader : nullptr);
213 paint.setAlpha(alpha);
214
215 canvas->drawMesh(result.mesh, blender, paint);
216
217 canvas->translate(0, 150);
218 ++i;
219 }
220 canvas->restore();
221 canvas->translate(150, 0);
222 }
223 return DrawResult::kOk;
224 }
225
226 private:
227 void ensureBuffers() {
228 if (!fColorVB) {
229 fColorVB = SkMeshes::MakeVertexBuffer(kColorQuad, sizeof(kColorQuad));
230 }
231
232 if (!fNoColorVB) {
233 // Make this one such that the data is offset into the buffer.
234 auto data = SkData::MakeUninitialized(sizeof(kNoColorQuad) + kNoColorOffset);
235 std::memcpy(SkTAddOffset<void>(data->writable_data(), kNoColorOffset),
236 kNoColorQuad,
237 sizeof(kNoColorQuad));
238 fNoColorVB = SkMeshes::MakeVertexBuffer(data->data(), data->size());
239 }
240
241 if (!fColorIndexedVB) {
242 // This buffer also has an offset.
243 auto data = SkData::MakeUninitialized(sizeof(kColorIndexedQuad) + kColorIndexedOffset);
244 std::memcpy(SkTAddOffset<void>(data->writable_data(), kColorIndexedOffset),
245 kColorIndexedQuad,
246 sizeof(kColorIndexedQuad));
247 fColorIndexedVB = SkMeshes::MakeVertexBuffer(data->data(), data->size());
248 }
249
250 if (!fNoColorIndexedVB) {
251 fNoColorIndexedVB =
252 SkMeshes::MakeVertexBuffer(kNoColorIndexedQuad, sizeof(kNoColorIndexedQuad));
253 }
254
255 if (!fIB[0]) {
256 // The index buffer has an offset.
257 auto data = SkData::MakeUninitialized(sizeof(kIndices) + kIndexOffset);
258 std::memcpy(SkTAddOffset<void>(data->writable_data(), kIndexOffset),
259 kIndices,
260 sizeof(kIndices));
261 fIB[0] = SkMeshes::MakeIndexBuffer(data->data(), data->size());
262 }
263
264 if (!fIB[1]) {
265 // On CPU we always use the same CPU-backed index buffer.
266 fIB[1] = fIB[0];
267 }
268 }
269
270 struct ColorVertex {
271 uint32_t pad;
272 uint32_t brag;
273 float xuyv[4];
274 };
275
276 struct NoColorVertex {
277 float xuyv[4];
278 };
279
280 static constexpr auto kRect = SkRect::MakeLTRB(20, 20, 120, 120);
281 static constexpr auto kUV = SkRect::MakeLTRB( 0, 0, 20, 20);
282
283 static constexpr ColorVertex kColorQuad[] {
284 {0, 0x00FFFF00, {kRect.left(), kUV.left(), kRect.top(), kUV.top() }},
285 {0, 0x00FFFFFF, {kRect.right(), kUV.right(), kRect.top(), kUV.top() }},
286 {0, 0xFFFF00FF, {kRect.left(), kUV.left(), kRect.bottom(), kUV.bottom()}},
287 {0, 0xFFFFFF00, {kRect.right(), kUV.right(), kRect.bottom(), kUV.bottom()}},
288 };
289
290 static constexpr NoColorVertex kNoColorQuad[]{
291 {{kRect.left(), kUV.left(), kRect.top(), kUV.top() }},
292 {{kRect.right(), kUV.right(), kRect.top(), kUV.top() }},
293 {{kRect.left(), kUV.left(), kRect.bottom(), kUV.bottom()}},
294 {{kRect.right(), kUV.right(), kRect.bottom(), kUV.bottom()}},
295 };
296
297 // The indexed quads draw the same as the non-indexed. They just have unused vertices that the
298 // index buffer skips over draw with triangles instead of a triangle strip.
299 static constexpr ColorVertex kColorIndexedQuad[] {
300 {0, 0x00FFFF00, {kRect.left(), kUV.left(), kRect.top(), kUV.top() }},
301 {0, 0x00000000, { 100.f, 0.f, 100.f, 5.f }}, // unused
302 {0, 0x00FFFFFF, {kRect.right(), kUV.right(), kRect.top(), kUV.top() }},
303 {0, 0x00000000, { 200.f, 10.f, 200.f, 10.f }}, // unused
304 {0, 0xFFFF00FF, {kRect.left(), kUV.left(), kRect.bottom(), kUV.bottom()}},
305 {0, 0xFFFFFF00, {kRect.right(), kUV.right(), kRect.bottom(), kUV.bottom()}},
306 };
307
308 static constexpr NoColorVertex kNoColorIndexedQuad[]{
309 {{kRect.left(), kUV.left(), kRect.top(), kUV.top() }},
310 {{ 100.f, 0.f, 100.f, 5.f }}, // unused
311 {{kRect.right(), kUV.right(), kRect.top(), kUV.top() }},
312 {{ 200.f, 10.f, 200.f, 10.f }}, // unused
313 {{kRect.left(), kUV.left(), kRect.bottom(), kUV.bottom()}},
314 {{kRect.right(), kUV.right(), kRect.bottom(), kUV.bottom()}},
315 };
316
317 static constexpr uint16_t kIndices[]{0, 2, 4, 2, 5, 4};
318
319 // For some buffers we add an offset to ensure we're exercising drawing from mid-buffer.
320 static constexpr size_t kNoColorOffset = sizeof(NoColorVertex);
321 static constexpr size_t kColorIndexedOffset = 2*sizeof(ColorVertex);
322 static constexpr size_t kIndexOffset = 6;
323
324 sk_sp<SkShader> fShader;
325
326 sk_sp<SkMeshSpecification> fSpecWithColor;
327 sk_sp<SkMeshSpecification> fSpecWithNoColor;
328
329 // On GPU the first IB is a CPU buffer and the second is a GPU buffer.
330 sk_sp<SkMesh::IndexBuffer> fIB[2];
331
332 sk_sp<SkMesh::VertexBuffer> fColorVB;
333 sk_sp<SkMesh::VertexBuffer> fNoColorVB;
334 sk_sp<SkMesh::VertexBuffer> fColorIndexedVB;
335 sk_sp<SkMesh::VertexBuffer> fNoColorIndexedVB;
336 };
337
338 DEF_GM(return new MeshGM;)
339
340 class MeshColorSpaceGM : public skiagm::GM {
341 public:
342 MeshColorSpaceGM() {}
343
344 protected:
345 using Attribute = SkMeshSpecification::Attribute;
346 using Varying = SkMeshSpecification::Varying;
347
348 SkISize getISize() override { return {468, 258}; }
349
350 void onOnceBeforeDraw() override {
351 static const Attribute kAttributes[]{
352 {Attribute::Type::kFloat2, 0, SkString{"pos"} },
353 {Attribute::Type::kFloat4, 8, SkString{"color"}},
354 };
355 static const Varying kVaryings[]{
356 {Varying::Type::kHalf4, SkString{"color"}},
357 };
358 static constexpr char kPremulVS[] = R"(
359 Varyings main(const in Attributes attributes) {
360 Varyings varyings;
361 varyings.color = half4(attributes.color.a*attributes.color.rgb,
362 attributes.color.a);
363 varyings.position = attributes.pos;
364 return varyings;
365 }
366 )";
367 static constexpr char kUnpremulVS[] = R"(
368 Varyings main(const in Attributes attributes) {
369 Varyings varyings;
370 varyings.color = attributes.color;
371 varyings.position = attributes.pos;
372 return varyings;
373 }
374 )";
375 static constexpr char kFS[] = R"(
376 float2 main(in const Varyings varyings, out half4 color) {
377 color = varyings.color;
378 return varyings.position;
379 }
380 )";
381 for (bool unpremul : {false, true}) {
382 auto at = unpremul ? kUnpremul_SkAlphaType : kPremul_SkAlphaType;
383 auto vs = unpremul ? kUnpremulVS : kPremulVS;
384 for (bool spin : {false, true}) {
385 auto cs = SkColorSpace::MakeSRGB();
386 if (spin) {
387 cs = cs->makeColorSpin();
388 }
389
390 auto [spec, error] = SkMeshSpecification::Make(
391 kAttributes,
392 sizeof(Vertex),
393 kVaryings,
394 SkString(vs),
395 SkString(kFS),
396 std::move(cs),
397 at);
398 if (!spec) {
399 SkDebugf("%s\n", error.c_str());
400 }
401 fSpecs[SpecIndex(unpremul, spin)] = std::move(spec);
402 }
403 }
404 SkPoint pts[] = {{kRect.fLeft, 0}, {kRect.centerX(), 0}};
405 const SkColor4f colors[] = {SkColors::kWhite, SkColors::kTransparent};
406 fShader = SkShaders::LinearGradient(pts, {{colors, {}, SkTileMode::kMirror}, {}});
407
408 fVB = SkMeshes::MakeVertexBuffer(kQuad, sizeof(kQuad));
409 }
410
411 SkString getName() const override { return SkString("custommesh_cs"); }
412
413 DrawResult onDraw(SkCanvas* canvas, SkString* error) override {
414 // Force an intermediate surface if the canvas is in "legacy" mode
415 SkCanvas* c = canvas;
416 sk_sp<SkSurface> surface;
417 if (!c->imageInfo().colorSpace()) {
418 SkImageInfo info = canvas->imageInfo().makeColorSpace(SkColorSpace::MakeSRGB());
419 surface = canvas->makeSurface(info);
420 if (!surface) {
421 // This GM won't work on configs that use a recording canvas.
422 return DrawResult::kSkip;
423 }
424 c = surface->getCanvas();
425 c->clear(SK_ColorWHITE);
426 }
427 for (bool useShader : {false, true})
428 for (bool unpremul : {false, true}) {
429 c->save();
430 for (bool spin : {false, true}) {
431 auto result = SkMesh::Make(fSpecs[SpecIndex(unpremul, spin)],
432 SkMesh::Mode::kTriangleStrip,
433 fVB,
434 /*vertexCount=*/4,
435 /*vertexOffset=*/0,
436 /*uniforms=*/nullptr,
437 /*children=*/{},
438 kRect);
439 if (!result.mesh.isValid()) {
440 SkDebugf("Mesh creation failed: %s\n", result.error.c_str());
441 return DrawResult::kFail;
442 }
443
444 SkPaint paint;
445 paint.setShader(useShader ? fShader : nullptr);
446 SkBlendMode mode = useShader ? SkBlendMode::kModulate : SkBlendMode::kDst;
447 canvas->drawMesh(result.mesh, SkBlender::Mode(mode), paint);
448
449 c->translate(0, kRect.height() + 10);
450 }
451 c->restore();
452 c->translate(kRect.width() + 10, 0);
453 c->save();
454 }
455 if (surface) {
456 surface->draw(canvas, 0, 0);
457 }
458 return DrawResult::kOk;
459 }
460
461 private:
462 struct Vertex {
463 SkPoint pos;
464 SkColor4f color;
465 };
466
467 static int SpecIndex(bool spin, bool unpremul) {
468 return static_cast<int>(spin) + 2*static_cast<int>(unpremul);
469 }
470
471 static constexpr auto kRect = SkRect::MakeLTRB(20, 20, 120, 120);
472
473 static constexpr Vertex kQuad[] {
474 {{kRect.left() , kRect.top() }, {1, 0, 0, 1}},
475 {{kRect.right(), kRect.top() }, {0, 1, 0, 0}},
476 {{kRect.left() , kRect.bottom()}, {1, 1, 0, 0}},
477 {{kRect.right(), kRect.bottom()}, {0, 0, 1, 1}},
478 };
479
480 sk_sp<SkMesh::VertexBuffer> fVB;
481
482 sk_sp<SkMeshSpecification> fSpecs[4];
483
484 sk_sp<SkShader> fShader;
485 };
486
487 // helpers for cases when ctx could be nullptr
488 static sk_sp<SkMesh::VertexBuffer> make_vertex_buffer(GrDirectContext* ctx,
489 const void* data,
490 size_t size) {
491 if (ctx) {
492 return SkMeshes::MakeVertexBuffer(ctx, data, size);
493 }
494 return SkMeshes::MakeVertexBuffer(data, size);
495 }
496
497 static sk_sp<SkMesh::IndexBuffer> make_index_buffer(GrDirectContext* ctx,
498 const void* data,
499 size_t size) {
500 if (ctx) {
501 return SkMeshes::MakeIndexBuffer(ctx, data, size);
502 }
503 return SkMeshes::MakeIndexBuffer(data, size);
504 }
505
506 DEF_GM(return new MeshColorSpaceGM;)
507
508 class MeshUniformsGM : public skiagm::GM {
509 public:
510 MeshUniformsGM() { this->onAnimate(0); }
511
512 protected:
513 using Attribute = SkMeshSpecification::Attribute;
514 using Varying = SkMeshSpecification::Varying;
515
516 SkISize getISize() override { return {140, 250}; }
517
518 void onOnceBeforeDraw() override {
519 static const Attribute kAttributes[]{
520 {Attribute::Type::kFloat2, 0, SkString{"pos"} },
521 {Attribute::Type::kFloat2, 8, SkString{"coords"}},
522 };
523 static const Varying kVaryings[]{
524 {Varying::Type::kFloat2, SkString{"coords"}},
525 };
526 // To exercise shared VS/FS uniforms we have a matrix that is applied twice, once in each
527 // stage.
528 static constexpr char kVS[] = R"(
529 uniform float t[2];
530 uniform half3x3 m;
531 Varyings main(in const Attributes attributes) {
532 Varyings varyings;
533 varyings.coords = (m*float3(attributes.coords + float2(t[0], t[1]), 1)).xy;
534 varyings.position = attributes.pos;
535 return varyings;
536 }
537 )";
538 static constexpr char kFS[] = R"(
539 uniform half3x3 m;
540 layout(color) uniform half4 color;
541 float2 main(const Varyings varyings, out half4 c) {
542 c = color;
543 return (m*float3(varyings.coords, 1)).xy;
544 }
545 )";
546 auto [spec, error] =
547 SkMeshSpecification::Make(kAttributes,
548 sizeof(Vertex),
549 kVaryings,
550 SkString(kVS),
551 SkString(kFS),
552 SkColorSpace::MakeSRGB(),
553 kPremul_SkAlphaType);
554 if (!spec) {
555 SkDebugf("%s\n", error.c_str());
556 }
557 fSpec = std::move(spec);
558
559 const SkColor4f colors[] = {SkColors::kWhite, SkColors::kBlack};
560 fShader = SkShaders::RadialGradient(kGradCenter, .4f,
561 {{colors, {}, SkTileMode::kMirror}, {}});
562
563 fVB = SkMeshes::MakeVertexBuffer(kQuad, sizeof(kQuad));
564 }
565
566 SkString getName() const override { return SkString("custommesh_uniforms"); }
567
568 DrawResult onDraw(SkCanvas* canvas, SkString* error) override {
569 SkMatrix matrices[] {
570 SkMatrix::MakeAll(-1, 0, 0, // self inverse so no effect.
571 0, -1, 0,
572 0, 0, 1),
573 SkMatrix::RotateDeg(fDegrees/2.f, {0.5f, 0.5f}),
574 };
575 for (const auto& m : matrices) {
576 auto unis = SkData::MakeUninitialized(fSpec->uniformSize());
577
578 SkPoint trans = -kCoordTrans;
579 static_assert(sizeof(SkPoint) == 2*sizeof(float));
580
581 const SkMeshSpecification::Uniform* u = fSpec->findUniform("t");
582 SkASSERT(u);
583 std::memcpy(SkTAddOffset<void>(unis->writable_data(), u->offset),
584 (void*)&trans,
585 2*sizeof(float));
586
587 u = fSpec->findUniform("m");
588 SkASSERT(u);
589 for (size_t offset = u->offset, col = 0; col < 3; ++col) {
590 for (size_t row = 0; row < 3; ++row, offset += sizeof(float)) {
591 *SkTAddOffset<float>(unis->writable_data(), offset) = m.rc(row, col);
592 }
593 }
594
595 u = fSpec->findUniform("color");
596 SkASSERT(u);
597 std::memcpy(SkTAddOffset<void>(unis->writable_data(), u->offset),
598 fColor.vec(),
599 4*sizeof(float));
600
601 auto result = SkMesh::Make(fSpec,
602 SkMesh::Mode::kTriangleStrip,
603 fVB,
604 /*vertexCount=*/4,
605 /*vertexOffset=*/0,
606 /*uniforms=*/std::move(unis),
607 /*children=*/{},
608 kRect);
609
610 if (!result.mesh.isValid()) {
611 SkDebugf("Mesh creation failed: %s\n", result.error.c_str());
612 return DrawResult::kFail;
613 }
614
615 SkPaint paint;
616 paint.setShader(fShader);
617 canvas->drawMesh(result.mesh, SkBlender::Mode(SkBlendMode::kModulate), paint);
618
619 canvas->translate(0, kRect.height() + 10);
620 }
621 return DrawResult::kOk;
622 }
623
624 bool onAnimate(double nanos) override {
625 fDegrees = TimeUtils::NanosToSeconds(nanos) * 360.f/10.f + 45.f;
626 // prime number periods, like locusts.
627 fColor.fR = TimeUtils::SineWave(nanos, 13.f, 0.f, 0.f, 1.f);
628 fColor.fG = TimeUtils::SineWave(nanos, 23.f, 5.f, 0.f, 1.f);
629 fColor.fB = TimeUtils::SineWave(nanos, 11.f, 0.f, 0.f, 1.f);
630 fColor.fA = 1.f;
631 return true;
632 }
633
634 private:
635 struct Vertex {
636 SkPoint pos;
637 SkPoint tex;
638 };
639
640 static constexpr auto kRect = SkRect::MakeLTRB(20, 20, 120, 120);
641
642 // Our logical tex coords are [0..1] but we insert an arbitrary translation that gets undone
643 // with a uniform.
644 static constexpr SkPoint kCoordTrans = {75, -37};
645 static constexpr auto kCoordRect = SkRect::MakeXYWH(kCoordTrans.x(), kCoordTrans.y(), 1, 1);
646
647 static constexpr SkPoint kGradCenter = {0.3f, 0.2f};
648
649 static constexpr Vertex kQuad[] {
650 {{kRect.left() , kRect.top() }, {kCoordRect.left() , kCoordRect.top()} },
651 {{kRect.right(), kRect.top() }, {kCoordRect.right(), kCoordRect.top()} },
652 {{kRect.left() , kRect.bottom()}, {kCoordRect.left() , kCoordRect.bottom()}},
653 {{kRect.right(), kRect.bottom()}, {kCoordRect.right(), kCoordRect.bottom()}},
654 };
655
656 float fDegrees;
657
658 SkColor4f fColor;
659
660 sk_sp<SkMesh::VertexBuffer> fVB;
661
662 sk_sp<SkMeshSpecification> fSpec;
663
664 sk_sp<SkShader> fShader;
665 };
666
667 DEF_GM(return new MeshUniformsGM())
668
669 class MeshUpdateGM : public skiagm::GM {
670 public:
671 MeshUpdateGM() = default;
672
673 protected:
674 using Attribute = SkMeshSpecification::Attribute;
675 using Varying = SkMeshSpecification::Varying;
676
677 static constexpr int kWidth = 270;
678 static constexpr int kHeight = 490;
679 static constexpr int kVerticalPadding = 10;
680
681 SkISize getISize() override { return {kWidth, kHeight}; }
682
683 void onOnceBeforeDraw() override {
684 static const Attribute kAttributes[]{
685 {Attribute::Type::kFloat2, 0, SkString{"pos"}},
686 {Attribute::Type::kFloat2, 8, SkString{"coords"}},
687 };
688 static const Varying kVaryings[]{
689 {Varying::Type::kFloat2, SkString{"coords"}},
690 };
691 static constexpr char kVS[] = R"(
692 Varyings main(const in Attributes attributes) {
693 Varyings varyings;
694 varyings.coords = attributes.coords;
695 varyings.position = attributes.pos;
696 return varyings;
697 }
698 )";
699 static constexpr char kFS[] = R"(
700 float2 main(const Varyings varyings) { return varyings.coords; }
701 )";
702 auto [spec, error] = SkMeshSpecification::Make(kAttributes,
703 sizeof(Vertex),
704 kVaryings,
705 SkString(kVS),
706 SkString(kFS),
707 SkColorSpace::MakeSRGB(),
708 kPremul_SkAlphaType);
709 if (!spec) {
710 SkDebugf("%s\n", error.c_str());
711 }
712 fSpec = std::move(spec);
713
714 uint32_t colors[] = {SK_ColorYELLOW, SK_ColorMAGENTA, SK_ColorCYAN, SK_ColorWHITE};
715 SkPixmap pixmap(SkImageInfo::Make({2, 2}, kBGRA_8888_SkColorType, kPremul_SkAlphaType),
716 colors,
717 /*rowBytes=*/8);
718 fShader = SkImages::RasterFromPixmapCopy(pixmap)->makeShader(
719 SkTileMode::kClamp, SkTileMode::kClamp, SkFilterMode::kLinear);
720 }
721
722 SkString getName() const override { return SkString("mesh_updates"); }
723
724 // The top 4 rows are CPU buffers - the bottom 4 rows are GPU buffers
725 // Within each set of 4, the top 3 rows are vertex updates while the 4th row is an index update.
726 DrawResult onDraw(SkCanvas* canvas, SkString* error) override {
727 canvas->clear(SK_ColorBLACK);
728
729 GrRecordingContext* rc = canvas->recordingContext();
730 GrDirectContext* dc = GrAsDirectContext(rc);
731 if (rc && !dc) {
732 // On GPU this relies on using the DC to update the GPU backed vertex/index buffers.
733 return DrawResult::kSkip;
734 }
735
736 if (dc && dc->abandoned()) {
737 return DrawResult::kSkip;
738 }
739
740 SkPaint paint;
741 paint.setShader(fShader);
742
743 const SkRect r = SkRect::MakeXYWH(10.f, 10.f, 50.f, 50.f);
744
745 // We test updating CPU and GPU buffers.
746 for (bool gpuBuffer : {false, true}) {
747 auto ctx = gpuBuffer ? dc : nullptr;
748
749 // How many rects worth of storage is in the vertex buffer?
750 static constexpr int kVBRects = 2;
751
752 // How many times do we update the vertex buffer? Wraps to start of buffer if
753 // > kVBRects.
754 static constexpr int kUpdatesRects = 3;
755
756 auto vb = make_vertex_buffer(ctx, /*data=*/nullptr, kVBRects * 6 * sizeof(Vertex));
757 SkASSERT(vb);
758
759 SkRect bounds;
760 for (int i = 0; i < kUpdatesRects; ++i) {
761 auto p = r.makeOffset(100.f*i, 0.f);
762 if (i) {
763 bounds.join(p);
764 } else {
765 bounds = p;
766 }
767
768 std::array<SkPoint, 4> t = SkRect::MakeWH(2.f, 2.f).toQuad();
769 SkMatrix::RotateDeg(90.f*i, {1.f, 1.f}).mapPoints(t);
770
771 Vertex vertices[6];
772 vertices[0] = {{p.left(), p.top()}, t[0]};
773 vertices[1] = {{p.left(), p.bottom()}, t[3]};
774 vertices[2] = {{p.right(), p.top()}, t[1]};
775 vertices[3] = vertices[2];
776 vertices[4] = vertices[1];
777 vertices[5] = {{p.right(), p.bottom()}, t[2]};
778
779 size_t offset = 6*(i % kVBRects)*sizeof(Vertex);
780 SkAssertResult(vb->update(ctx, vertices, offset, 6*sizeof(Vertex)));
781 // Make there aren't accidentally deferred reads of the client data.
782 std::memset(vertices, 0, sizeof(vertices));
783
784 int rectCount = std::min(i + 1, kVBRects);
785 auto result = SkMesh::Make(fSpec,
786 SkMesh::Mode::kTriangles,
787 vb,
788 /*vertexCount=*/6 * rectCount,
789 /*vertexOffset=*/0,
790 /*uniforms=*/nullptr,
791 /*children=*/{},
792 bounds);
793
794 if (!result.mesh.isValid()) {
795 SkDebugf("Mesh creation failed: %s\n", result.error.c_str());
796 return DrawResult::kFail;
797 }
798
799 canvas->drawMesh(result.mesh, SkBlender::Mode(SkBlendMode::kDst), paint);
800
801 canvas->translate(0, r.height() + kVerticalPadding);
802 }
803
804 // Now test updating an IB.
805
806 // How many rects worth of storage is in the index buffer?
807 static constexpr int kIBRects = 2;
808
809 // How many times do we update the index buffer? Wraps to start of buffer if > kIBRects.
810 static constexpr int kNumIBUpdates = 3;
811
812 // Make the vertex buffer large enough to hold all the rects and populate.
813 vb = make_vertex_buffer(ctx, /*data=*/nullptr, kNumIBUpdates * 4 * sizeof(Vertex));
814 SkASSERT(vb);
815 for (int i = 0; i < kNumIBUpdates; ++i) {
816 auto rect = r.makeOffset(100*i, 0);
817 const std::array<SkPoint, 4> p = rect.toQuad();
818 if (i) {
819 bounds.join(rect);
820 } else {
821 bounds = rect;
822 }
823
824 std::array<SkPoint, 4> t = SkRect::MakeWH(2.f, 2.f).toQuad();
825 SkMatrix::RotateDeg(90.f*i, {1.f, 1.f}).mapPoints(t);
826 Vertex vertices[4]{{p[0], t[0]}, {p[1], t[1]}, {p[2], t[2]}, {p[3], t[3]}};
827 SkAssertResult(
828 vb->update(ctx, vertices, i*4*sizeof(Vertex), 4*sizeof(Vertex)));
829 }
830
831 auto ib = make_index_buffer(
832 ctx, /*data=*/nullptr, kIBRects * 6 * sizeof(uint16_t));
833 SkASSERT(ib);
834 for (int i = 0; i < kNumIBUpdates; ++i) {
835 uint16_t indices[6] = {SkToU16(0 + 4*i),
836 SkToU16(3 + 4*i),
837 SkToU16(1 + 4*i),
838 SkToU16(1 + 4*i),
839 SkToU16(3 + 4*i),
840 SkToU16(2 + 4*i)};
841 size_t offset = 6*(i % kIBRects)*sizeof(uint16_t);
842 SkAssertResult(ib->update(ctx, indices, offset, 6*sizeof(uint16_t)));
843 std::memset(indices, 0, 6*sizeof(uint16_t));
844
845 auto result = SkMesh::MakeIndexed(fSpec,
846 SkMesh::Mode::kTriangles,
847 vb,
848 /*vertexCount=*/4 * kNumIBUpdates,
849 /*vertexOffset=*/0,
850 ib,
851 /*indexCount=*/6,
852 /*indexOffset=*/offset,
853 /*uniforms=*/nullptr,
854 /*children=*/{},
855 bounds);
856
857 if (!result.mesh.isValid()) {
858 SkDebugf("Mesh creation failed: %s\n", result.error.c_str());
859 return DrawResult::kFail;
860 }
861
862 canvas->drawMesh(result.mesh, SkBlender::Mode(SkBlendMode::kDst), paint);
863 }
864 canvas->translate(0, r.height() + kVerticalPadding);
865 }
866
867 return DrawResult::kOk;
868 }
869
870 private:
871 struct Vertex {
872 SkPoint pos;
873 SkPoint tex;
874 };
875
876 sk_sp<SkMeshSpecification> fSpec;
877
878 sk_sp<SkShader> fShader;
879 };
880
881 DEF_GM(return new MeshUpdateGM())
882
883 class MeshZeroInitGM : public skiagm::GM {
884 public:
885 MeshZeroInitGM() = default;
886
887 protected:
888 using Attribute = SkMeshSpecification::Attribute;
889 using Varying = SkMeshSpecification::Varying;
890
891 SkISize getISize() override { return {90, 30}; }
892
893 void onOnceBeforeDraw() override {
894 static const Attribute kAttributes1[]{
895 {Attribute::Type::kUByte4_unorm, 0, SkString{"color"}},
896 {Attribute::Type::kFloat2, 4, SkString{"pos" }},
897 };
898 static const Attribute kAttributes2[]{
899 {Attribute::Type::kFloat2, 0, SkString{"pos" }},
900 {Attribute::Type::kUByte4_unorm, 8, SkString{"color"}},
901 };
902 static const Varying kVaryings[]{{Varying::Type::kHalf4, SkString{"color"}}};
903 static constexpr char kVS[] = R"(
904 Varyings main(const in Attributes attributes) {
905 Varyings varyings;
906 varyings.color = attributes.color;
907 varyings.position = attributes.pos;
908 return varyings;
909 }
910 )";
911 static constexpr char kFS[] = R"(
912 float2 main(const Varyings varyings, out half4 color) {
913 color = varyings.color;
914 return varyings.position;
915 }
916 )";
917 auto result = SkMeshSpecification::Make(kAttributes1,
918 /*vertexStride==*/12,
919 kVaryings,
920 SkString(kVS),
921 SkString(kFS),
922 SkColorSpace::MakeSRGB(),
923 kPremul_SkAlphaType);
924 if (!result.specification) {
925 SkDebugf("%s\n", result.error.c_str());
926 }
927 fSpec[0] = std::move(result.specification);
928
929 result = SkMeshSpecification::Make(kAttributes1,
930 /*vertexStride=*/12,
931 kVaryings,
932 SkString(kVS),
933 SkString(kFS),
934 SkColorSpace::MakeSRGB(),
935 kPremul_SkAlphaType);
936 if (!result.specification) {
937 SkDebugf("%s\n", result.error.c_str());
938 }
939 fSpec[1] = std::move(result.specification);
940 }
941
942 SkString getName() const override { return SkString("mesh_zero_init"); }
943
944 DrawResult onDraw(SkCanvas* canvas, SkString* error) override {
945 GrRecordingContext* rc = canvas->recordingContext();
946 GrDirectContext* dc = GrAsDirectContext(rc);
947 if (rc && !dc) {
948 // On GPU this relies on using the DC to update the GPU backed vertex/index buffers.
949 return DrawResult::kSkip;
950 }
951
952 if (dc && dc->abandoned()) {
953 return DrawResult::kSkip;
954 }
955
956 static constexpr SkPoint kTri[]{{10, 10}, {20, 10}, {10, 20}};
957 // The zero will come from the uninit part of the buffer.
958 static constexpr uint16_t kTiIndices[]{1, 2};
959
960 // We test updating CPU and GPU buffers.
961 for (bool gpuBuffer : {false, true}) {
962 auto ctx = gpuBuffer ? dc : nullptr;
963 for (int i = 0; i < 2; ++i) {
964 const auto& spec = fSpec[i];
965
966 size_t posOffset = spec->findAttribute("pos")->offset;
967 auto vb = make_vertex_buffer(ctx, nullptr, spec->stride() * std::size(kTri));
968 SkASSERT(vb);
969 for (size_t j = 0; j < std::size(kTri); ++j) {
970 SkAssertResult(vb->update(ctx,
971 &kTri[j],
972 spec->stride()*j + posOffset,
973 sizeof(kTri[j])));
974 }
975
976 // The first time we make the indices be 0,1,2 using the zero'ed buffer for the
977 // first. However, because uploads must be 4 byte aligned it's actually 0,0,1,2.
978 // The second time we upload 1,2 to beginning of the buffer to form 1,2,0.
979 size_t indexUploadOffset = i == 0 ? 4 : 0;
980 size_t indexMeshOffset = i == 0 ? 2 : 0;
981
982 auto ib = make_index_buffer(ctx, nullptr, sizeof(uint16_t) * 4);
983 SkASSERT(ib);
984 SkAssertResult(ib->update(ctx, kTiIndices, indexUploadOffset, sizeof(kTiIndices)));
985
986 const auto bounds = SkRect::BoundsOrEmpty(kTri);
987 auto result = SkMesh::MakeIndexed(spec,
988 SkMesh::Mode::kTriangles,
989 std::move(vb),
990 /*vertexCount=*/std::size(kTri),
991 /*vertexOffset=*/0,
992 std::move(ib),
993 /*indexCount=*/std::size(kTiIndices) + 1,
994 indexMeshOffset,
995 /*uniforms=*/nullptr,
996 /*children=*/{},
997 bounds);
998 if (!result.mesh.isValid()) {
999 SkDebugf("Mesh creation failed: %s\n", result.error.c_str());
1000 return DrawResult::kFail;
1001 }
1002
1003 SkPaint paint;
1004 // The color will be transparent black. Set the blender to kDstOver so when combined
1005 // with the paint's opaque black we get opaque black.
1006 canvas->drawMesh(result.mesh, SkBlender::Mode(SkBlendMode::kDstOver), paint);
1007 canvas->translate(bounds.width() + 10, 0);
1008 if (ctx) {
1009 // Free up the buffers for recycling in the cache. This helps test that
1010 // a recycled buffer gets zero'ed.
1011 result.mesh = {};
1012 SkASSERT(!ib); // NOLINT - bugprone-use-after-move. We're asserting it's moved.
1013 SkASSERT(!vb); // NOLINT
1014 ctx->flushAndSubmit(GrSyncCpu::kYes);
1015 }
1016 }
1017 }
1018
1019 return DrawResult::kOk;
1020 }
1021
1022 private:
1023 sk_sp<SkMeshSpecification> fSpec[2];
1024 };
1025
1026 DEF_GM(return new MeshZeroInitGM())
1027
1028 // We have a special GM for testing SkMesh through SkPicture because all of SkPicture GM testing
1029 // uses the CPU backend and SkMesh only works on GPU.
1030 class PictureMesh : public skiagm::GM {
1031 public:
1032 PictureMesh() = default;
1033
1034 protected:
1035 using Attribute = SkMeshSpecification::Attribute;
1036 using Varying = SkMeshSpecification::Varying;
1037
1038 SkISize getISize() override { return {390, 90}; }
1039
1040 void onOnceBeforeDraw() override {
1041 static const Attribute kAttributes[]{
1042 {Attribute::Type::kFloat2, 0, SkString{"pos"}},
1043 };
1044 static const Varying kVaryings[]{
1045 {Varying::Type::kFloat2, SkString{"coords"}},
1046 };
1047 static constexpr char kVS[] = R"(
1048 Varyings main(in const Attributes attributes) {
1049 Varyings varyings;
1050 varyings.position = attributes.pos;
1051 return varyings;
1052 }
1053 )";
1054 static const SkString kFS = SkStringPrintf(R"(
1055 uniform float2 offset;
1056 float2 main(const Varyings varyings, out float4 color) {
1057 float2 tl = float2(%f, %f);
1058 float2 wh = float2(%f, %f);
1059 float2 c = tl + wh/2;
1060 float r = length(wh)/4;
1061 color.rba = float3(1);
1062 color.g = min(1, length(varyings.position - c + offset) / r);
1063 return varyings.position;
1064 }
1065 )", kRect.x(), kRect.y(), kRect.width(), kRect.height());
1066 auto [spec, error] =
1067 SkMeshSpecification::Make(kAttributes,
1068 sizeof(Vertex),
1069 kVaryings,
1070 SkString(kVS),
1071 kFS,
1072 SkColorSpace::MakeSRGB()->makeColorSpin(),
1073 kPremul_SkAlphaType);
1074 if (!spec) {
1075 SkDebugf("%s\n", error.c_str());
1076 }
1077 fSpec = std::move(spec);
1078
1079 fVB = SkMeshes::MakeVertexBuffer(kQuad, sizeof(kQuad));
1080 fIB = SkMeshes::MakeIndexBuffer(kIndices, sizeof(kIndices));
1081
1082 SkRandom random;
1083 SkColor4f colors[6];
1084 for (size_t i = 0; i < std::size(colors) - 1; ++i) {
1085 colors[i] = {random.nextF(), random.nextF(), random.nextF(), 1.f};
1086 }
1087 colors[std::size(colors) - 1] = colors[0];
1088 SkPaint paint;
1089 SkGradient::Interpolation interpolation;
1090 interpolation.fColorSpace = SkGradient::Interpolation::ColorSpace::kHSL;
1091 fShader = SkShaders::SweepGradient(kRect.center(), 0, 360,
1092 {{colors, {}, SkTileMode::kRepeat, SkColorSpace::MakeSRGB()},
1093 interpolation});
1094 }
1095
1096 SkString getName() const override { return SkString("picture_mesh"); }
1097
1098 DrawResult onDraw(SkCanvas* canvas, SkString* error) override {
1099 SkPaint paint;
1100 paint.setShader(fShader);
1101
1102 auto dc = GrAsDirectContext(canvas->recordingContext());
1103 for (bool picture : {false, true}) {
1104 canvas->save();
1105 for (bool gpu : {false, true}) {
1106 auto vb = gpu ? SkMeshes::CopyVertexBuffer(dc, fVB) : fVB;
1107 auto ib = gpu ? SkMeshes::CopyIndexBuffer (dc, fIB) : fIB;
1108
1109 float offset[2] = {8, 8};
1110 for (size_t i = 0; i < 4; ++i) {
1111 auto uniforms = SkData::MakeWithCopy(&offset, sizeof(offset));
1112 SkMesh::Result r;
1113 switch (i) {
1114 case 0:
1115 r = SkMesh::Make(fSpec,
1116 SkMesh::Mode::kTriangles,
1117 fVB,
1118 6,
1119 1 * sizeof(Vertex),
1120 std::move(uniforms),
1121 /*children=*/{},
1122 kRect);
1123 break;
1124 case 1:
1125 r = SkMesh::Make(fSpec,
1126 SkMesh::Mode::kTriangleStrip,
1127 fVB,
1128 4,
1129 1 * sizeof(Vertex),
1130 std::move(uniforms),
1131 /*children=*/{},
1132 kRect);
1133 break;
1134 case 2:
1135 r = SkMesh::MakeIndexed(fSpec,
1136 SkMesh::Mode::kTriangles,
1137 fVB,
1138 std::size(kQuad),
1139 0,
1140 fIB,
1141 6,
1142 2 * (sizeof(uint16_t)),
1143 std::move(uniforms),
1144 /*children=*/{},
1145 kRect);
1146 break;
1147 case 3:
1148 r = SkMesh::MakeIndexed(fSpec,
1149 SkMesh::Mode::kTriangleStrip,
1150 fVB,
1151 std::size(kQuad),
1152 0,
1153 fIB,
1154 6,
1155 2 * sizeof(uint16_t),
1156 std::move(uniforms),
1157 /*children=*/{},
1158 kRect);
1159 break;
1160 }
1161
1162 if (!r.mesh.isValid()) {
1163 *error = r.error;
1164 return DrawResult::kFail;
1165 }
1166
1167 auto draw = [&](SkCanvas* c) {
1168 c->drawMesh(r.mesh, SkBlender::Mode(SkBlendMode::kDifference), paint);
1169 };
1170 if (picture) {
1171 SkPictureRecorder recorder;
1172 draw(recorder.beginRecording(SkRect::Make(this->getISize()),
1173 /*bbhFactory=*/nullptr));
1174 canvas->drawPicture(recorder.finishRecordingAsPicture());
1175 } else {
1176 draw(canvas);
1177 }
1178 offset[i%2] *= -1;
1179 canvas->translate(kRect.width() + 10, 0);
1180 }
1181 }
1182 canvas->restore();
1183 canvas->translate(0, kRect.height() + 10);
1184 }
1185 return DrawResult::kOk;
1186 }
1187
1188 private:
1189 struct Vertex {
1190 SkPoint pos;
1191 };
1192
1193 static constexpr auto kRect = SkRect::MakeWH(40, 40);
1194
1195 static constexpr Vertex kQuad[] {
1196 {1000, 1000}, // skip
1197 {{kRect.left() , kRect.top() }},
1198 {{kRect.right(), kRect.top() }},
1199 {{kRect.left() , kRect.bottom()}},
1200 {{kRect.right(), kRect.bottom()}},
1201 {{kRect.left() , kRect.bottom()}},
1202 {{kRect.right(), kRect.top() }},
1203 };
1204
1205 static constexpr uint16_t kIndices[] = {1000, 2000, 1, 2, 3, 4, 5, 6};
1206
1207 sk_sp<SkMesh::VertexBuffer> fVB;
1208
1209 sk_sp<SkMesh::IndexBuffer> fIB;
1210
1211 sk_sp<SkMeshSpecification> fSpec;
1212
1213 sk_sp<SkShader> fShader;
1214 };
1215
1216 DEF_GM(return new PictureMesh())
1217
1218 class MeshWithShadersGM : public skiagm::GM {
1219 public:
1220 enum class Type {
1221 kMeshWithImage,
1222 kMeshWithPaintColor,
1223 kMeshWithPaintImage,
1224 kMeshWithEffects,
1225 };
1226
1227 MeshWithShadersGM(Type type) : fType(type) {
1228 // Create a grid of evenly spaced points for our mesh
1229 this->onAnimate(0.0);
1230
1231 // Create an index buffer of triangles over our point mesh.
1232 for (int y = 0; y < kMeshSize - 1; ++y) {
1233 for (int x = 0; x < kMeshSize - 1; ++x) {
1234 SkASSERT(((y + 1) * kMeshSize + x + 1) < fVerts.size());
1235
1236 uint16_t TL = y * kMeshSize + x;
1237 uint16_t TR = y * kMeshSize + x + 1;
1238 uint16_t BL = (y + 1) * kMeshSize + x;
1239 uint16_t BR = (y + 1) * kMeshSize + x + 1;
1240
1241 fIndices.push_back(TL);
1242 fIndices.push_back(TR);
1243 fIndices.push_back(BL);
1244
1245 fIndices.push_back(BR);
1246 fIndices.push_back(BL);
1247 fIndices.push_back(TR);
1248 }
1249 }
1250 }
1251
1252 protected:
1253 using Attribute = SkMeshSpecification::Attribute;
1254 using Varying = SkMeshSpecification::Varying;
1255
1256 SkISize getISize() override { return {320, 320}; }
1257
1258 void onOnceBeforeDraw() override {
1259 {
1260 static const Attribute kAttributes[] = {
1261 {Attribute::Type::kFloat2, 0, SkString{"position"}},
1262 {Attribute::Type::kFloat2, 8, SkString{"uv"}},
1263 };
1264 static const Varying kVaryings[] = {
1265 {Varying::Type::kFloat2, SkString{"uv"}},
1266 };
1267 static constexpr char kVS[] = R"(
1268 Varyings main(const in Attributes attributes) {
1269 Varyings varyings;
1270 varyings.uv = attributes.uv;
1271 varyings.position = attributes.position;
1272 return varyings;
1273 }
1274 )";
1275 static constexpr char kFS[] = R"(
1276 uniform shader myShader1;
1277 uniform shader myShader2;
1278 uniform colorFilter myColorFilter;
1279 uniform blender myBlend;
1280
1281 float2 main(const in Varyings varyings, out half4 color) {
1282 half4 color1 = myShader1.eval(varyings.uv);
1283 half4 color2 = myShader2.eval(varyings.uv);
1284
1285 // Apply a inverse color filter to the first image.
1286 color1 = myColorFilter.eval(color1);
1287
1288 // Fade in the second image horizontally, leveraging the UVs.
1289 color2 *= varyings.uv.x / 128.0;
1290
1291 // Combine the two images by using a blender (set to dst-over).
1292 color = myBlend.eval(color1, color2);
1293
1294 return varyings.uv;
1295 }
1296 )";
1297 auto [spec, error] = SkMeshSpecification::Make(kAttributes,
1298 sizeof(Vertex),
1299 kVaryings,
1300 SkString(kVS),
1301 SkString(kFS));
1302 if (!spec) {
1303 SkDebugf("%s\n", error.c_str());
1304 }
1305 fSpec = std::move(spec);
1306 }
1307
1308
1309 switch (fType) {
1310 case Type::kMeshWithImage: {
1311 fShader1 = ToolUtils::GetResourceAsImage("images/mandrill_128.png")
1312 ->makeShader(SkSamplingOptions(SkFilterMode::kLinear));
1313 fShader2 = nullptr;
1314 fColorFilter = nullptr;
1315 fBlender = nullptr;
1316 fPaintShader = nullptr;
1317 break;
1318 }
1319 case Type::kMeshWithEffects: {
1320 uint8_t inverseTable[256];
1321 for (int index = 0; index < 256; ++index) {
1322 inverseTable[index] = 255 - index;
1323 }
1324
1325 fShader1 = ToolUtils::GetResourceAsImage("images/mandrill_128.png")
1326 ->makeShader(SkSamplingOptions(SkFilterMode::kLinear));
1327 fShader2 = ToolUtils::GetResourceAsImage("images/color_wheel.png")
1328 ->makeShader(SkSamplingOptions(SkFilterMode::kLinear));
1329 fColorFilter = SkColorFilters::TableARGB(/*tableA=*/nullptr,
1330 inverseTable,
1331 inverseTable,
1332 inverseTable);
1333 fBlender = SkBlender::Mode(SkBlendMode::kDstOver);
1334 fPaintShader = nullptr;
1335 break;
1336 }
1337 case Type::kMeshWithPaintColor: {
1338 fShader1 = nullptr;
1339 fShader2 = ToolUtils::GetResourceAsImage("images/mandrill_128.png")
1340 ->makeShader(SkSamplingOptions(SkFilterMode::kLinear));
1341 fColorFilter = nullptr;
1342 fBlender = SkBlender::Mode(SkBlendMode::kDst);
1343 fPaintShader = SkShaders::Color(SK_ColorGREEN);
1344 break;
1345 }
1346 case Type::kMeshWithPaintImage: {
1347 fShader1 = ToolUtils::GetResourceAsImage("images/color_wheel.png")
1348 ->makeShader(SkSamplingOptions(SkFilterMode::kLinear));
1349 fShader2 = nullptr;
1350 fColorFilter = nullptr;
1351 fBlender = nullptr;
1352 fPaintShader = ToolUtils::GetResourceAsImage("images/mandrill_128.png")
1353 ->makeShader(SkSamplingOptions(SkFilterMode::kLinear));
1354 break;
1355 }
1356 default:
1357 SkUNREACHABLE;
1358 }
1359 }
1360
1361 DrawResult onGpuSetup(SkCanvas* canvas, SkString* string, GraphiteTestContext*) override {
1362 auto dc = GrAsDirectContext(canvas->recordingContext());
1363 this->ensureBuffers();
1364 if (!dc || dc->abandoned()) {
1365 return DrawResult::kOk;
1366 }
1367
1368 fVB = SkMeshes::CopyVertexBuffer(dc, fVB);
1369 fIB = SkMeshes::CopyIndexBuffer (dc, fIB);
1370 return (!fVB || !fIB) ? DrawResult::kFail
1371 : DrawResult::kOk;
1372 }
1373
1374 void onGpuTeardown() override {
1375 // Destroy the GPU buffers and recreate on CPU
1376 fVB = nullptr;
1377 fIB = nullptr;
1378 this->ensureBuffers();
1379 }
1380
1381 SkString getName() const override {
1382 switch (fType) {
1383 case Type::kMeshWithImage: return SkString("mesh_with_image");
1384 case Type::kMeshWithEffects: return SkString("mesh_with_effects");
1385 case Type::kMeshWithPaintColor: return SkString("mesh_with_paint_color");
1386 case Type::kMeshWithPaintImage: return SkString("mesh_with_paint_image");
1387 default: SkUNREACHABLE;
1388 }
1389 }
1390
1391 bool onAnimate(double nanos) override {
1392 // `periodic` goes from zero to 2π every four seconds, then wraps around.
1393 double periodic = nanos / 4'000'000'000.;
1394 periodic -= std::floor(periodic);
1395 periodic *= 2 * SK_DoublePI;
1396
1397 double xOff[kMeshSize], yOff[kMeshSize];
1398 for (int index = 0; index < kMeshSize; ++index) {
1399 xOff[index] = std::sin(periodic) * kRippleSize;
1400 yOff[index] = std::sin(periodic + 10.0) * kRippleSize;
1401 periodic += 0.8;
1402 }
1403
1404 fVerts.clear();
1405 for (int y = 0; y < kMeshSize; ++y) {
1406 float yf = (float)y / (kMeshSize - 1); // yf = 0 .. 1
1407 for (int x = 0; x < kMeshSize; ++x) {
1408 float xf = (float)x / (kMeshSize - 1); // xf = 0 .. 1
1409
1410 Vertex* vert = &fVerts.push_back();
1411 vert->pos[0] = kRect.left() + xf * kRect.width() + xOff[y];
1412 vert->pos[1] = kRect.top() + yf * kRect.height() + yOff[x];
1413 vert->uv[0] = kUV.left() + xf * kUV.width();
1414 vert->uv[1] = kUV.top() + yf * kUV.height();
1415 }
1416 }
1417
1418 return true;
1419 }
1420
1421 DrawResult onDraw(SkCanvas* canvas, SkString*) override {
1422 SkRuntimeEffect::ChildPtr child[4] = {fShader1, fShader2, fColorFilter, fBlender};
1423
1424 GrRecordingContext* rc = canvas->recordingContext();
1425 GrDirectContext* dc = GrAsDirectContext(rc);
1426 fVB->update(dc, fVerts.data(), /*offset=*/0, fVerts.size_bytes());
1427
1428 SkMesh::Result result = SkMesh::MakeIndexed(fSpec,
1429 SkMesh::Mode::kTriangles,
1430 fVB,
1431 fVerts.size(),
1432 /*vertexOffset=*/0,
1433 fIB,
1434 fIndices.size(),
1435 /*indexOffset=*/0,
1436 /*uniforms=*/nullptr,
1437 /*children=*/child,
1438 kRect.makeOutset(kRippleSize, kRippleSize));
1439 if (!result.mesh.isValid()) {
1440 SkDebugf("Mesh creation failed: %s\n", result.error.c_str());
1441 return DrawResult::kFail;
1442 }
1443
1444 SkPaint paint;
1445 paint.setShader(fPaintShader);
1446 canvas->drawMesh(result.mesh, SkBlender::Mode(SkBlendMode::kDstOver), paint);
1447
1448 return DrawResult::kOk;
1449 }
1450
1451 private:
1452 void ensureBuffers() {
1453 if (!fVB) {
1454 fVB = SkMeshes::MakeVertexBuffer(fVerts.data(), fVerts.size_bytes());
1455 }
1456 if (!fIB) {
1457 fIB = SkMeshes::MakeIndexBuffer(fIndices.data(), fIndices.size_bytes());
1458 }
1459 }
1460
1461 struct Vertex {
1462 float pos[2];
1463 float uv[2];
1464 };
1465
1466 static constexpr auto kRect = SkRect::MakeLTRB(20, 20, 300, 300);
1467 static constexpr auto kUV = SkRect::MakeLTRB( 0, 0, 128, 128);
1468 static constexpr int kMeshSize = 16;
1469 static constexpr float kRippleSize = 6.0f;
1470
1471 Type fType;
1472
1473 TArray<Vertex> fVerts;
1474 TArray<uint16_t> fIndices;
1475
1476 sk_sp<SkShader> fShader1, fShader2, fPaintShader;
1477 sk_sp<SkColorFilter> fColorFilter;
1478 sk_sp<SkBlender> fBlender;
1479
1480 sk_sp<SkMeshSpecification> fSpec;
1481
1482 sk_sp<SkMesh::VertexBuffer> fVB;
1483 sk_sp<SkMesh::IndexBuffer> fIB;
1484 };
1485
1486 DEF_GM(return new MeshWithShadersGM(MeshWithShadersGM::Type::kMeshWithImage))
1487 DEF_GM(return new MeshWithShadersGM(MeshWithShadersGM::Type::kMeshWithPaintColor))
1488 DEF_GM(return new MeshWithShadersGM(MeshWithShadersGM::Type::kMeshWithPaintImage))
1489 DEF_GM(return new MeshWithShadersGM(MeshWithShadersGM::Type::kMeshWithEffects))
1490
1491 DEF_SIMPLE_GM_CAN_FAIL(custommesh_cs_uniforms, canvas, errorMsg, 200, 900) {
1492 if (!canvas->recordingContext() && !canvas->recorder()) {
1493 *errorMsg = GM::kErrorMsg_DrawSkippedGpuOnly;
1494 return DrawResult::kSkip;
1495 }
1496
1497 // Shared data
1498 static constexpr SkRect kRect = SkRect::MakeLTRB(20, 20, 80, 80);
1499 static constexpr SkPoint kQuad[]{
1500 {kRect.left(), kRect.top()},
1501 {kRect.right(), kRect.top()},
1502 {kRect.left(), kRect.bottom()},
1503 {kRect.right(), kRect.bottom()},
1504 };
1505 sk_sp<SkMesh::VertexBuffer> vb = SkMeshes::MakeVertexBuffer(kQuad, sizeof(kQuad));
1506 sk_sp<SkData> unis = SkData::MakeWithCopy(&SkColors::kRed, sizeof(SkColor4f));
1507
1508 // Surface helper
1509 auto makeSurface = [=](sk_sp<SkColorSpace> cs) {
1510 SkImageInfo ii = SkImageInfo::MakeN32Premul(200, 100, cs);
1511 sk_sp<SkSurface> surface = canvas->makeSurface(ii);
1512 return surface ? surface : SkSurfaces::Raster(ii);
1513 };
1514
1515 // Mesh helper
1516 enum class Managed : bool { kNo, kYes };
1517 auto makeMesh = [&](Managed managed, sk_sp<SkColorSpace> workingCS) {
1518 static const SkMeshSpecification::Attribute kAttributes[]{
1519 {SkMeshSpecification::Attribute::Type::kFloat2, 0, SkString{"pos"}},
1520 };
1521
1522 static constexpr char kVS[] = R"(
1523 Varyings main(in const Attributes attributes) {
1524 Varyings varyings;
1525 varyings.position = attributes.pos;
1526 return varyings;
1527 }
1528 )";
1529 static constexpr char kManagedFS[] = R"(
1530 layout(color) uniform half4 color;
1531 float2 main(const Varyings varyings, out half4 c) {
1532 c = color;
1533 return varyings.position;
1534 }
1535 )";
1536 static constexpr char kRawFS[] = R"(
1537 uniform half4 color;
1538 float2 main(const Varyings varyings, out half4 c) {
1539 c = color;
1540 return varyings.position;
1541 }
1542 )";
1543
1544 auto [spec, error] = SkMeshSpecification::Make(
1545 kAttributes,
1546 sizeof(SkPoint),
1547 /*varyings=*/{},
1548 SkString(kVS),
1549 SkString(managed == Managed::kYes ? kManagedFS : kRawFS),
1550 std::move(workingCS),
1551 kPremul_SkAlphaType);
1552 SkASSERT(spec);
1553
1554 SkMesh::Result result = SkMesh::Make(std::move(spec),
1555 SkMesh::Mode::kTriangleStrip,
1556 vb,
1557 /*vertexCount=*/4,
1558 /*vertexOffset=*/0,
1559 /*uniforms=*/unis,
1560 /*children=*/{},
1561 kRect);
1562 SkASSERT(result.mesh.isValid());
1563 return result.mesh;
1564 };
1565
1566 sk_sp<SkColorSpace> null = nullptr,
1567 srgb = SkColorSpace::MakeSRGB(),
1568 spin = SkColorSpace::MakeSRGB()->makeColorSpin(),
1569 wide = SkColorSpace::MakeRGB(SkNamedTransferFn::k2Dot2,
1570 SkNamedGamut::kRec2020);
1571
1572 struct Config {
1573 sk_sp<SkColorSpace> fMeshCS;
1574 sk_sp<SkColorSpace> fSurfaceCS;
1575 Managed fManaged;
1576 SkColor fExpectedColor = SK_ColorRED;
1577 };
1578 static const Config kConfigs[] = {
1579 // Uniforms should remain in sRGB mode, then get converted to destination after mesh FS
1580 // Before b/316594914 was fixed, these would get double-converted:
1581 {srgb, null, Managed::kYes},
1582 {srgb, srgb, Managed::kYes},
1583 {srgb, spin, Managed::kYes},
1584 {srgb, wide, Managed::kYes},
1585
1586 // Uniforms should be converted to working space (spun), then converted to destination
1587 {spin, srgb, Managed::kYes},
1588 {spin, spin, Managed::kYes},
1589 {spin, wide, Managed::kYes},
1590
1591 // Non-managed uniforms serve as a control group. The red uniforms are not converted to
1592 // the working space. The mesh FS returns "red" {1, 0, 0, 1}, but that's actually green,
1593 // because the working space of the mesh is `spin`. That output is converted to dest,
1594 // rendering as green. Therefore, we manually change the control color's box to green.
1595 {spin, srgb, Managed::kNo, SK_ColorGREEN},
1596 {spin, wide, Managed::kNo, SK_ColorGREEN},
1597 };
1598
1599 for (const Config& config : kConfigs) {
1600 SkMesh mesh = makeMesh(config.fManaged, config.fMeshCS);
1601
1602 sk_sp<SkSurface> offscreen = makeSurface(config.fSurfaceCS);
1603 SkCanvas* offscreenCanvas = offscreen->getCanvas();
1604
1605 SkPaint paint;
1606 offscreenCanvas->drawMesh(mesh, SkBlender::Mode(SkBlendMode::kDst), paint);
1607 offscreenCanvas->translate(100, 0);
1608 paint.setColor(config.fExpectedColor);
1609 offscreenCanvas->drawRect(kRect, paint);
1610
1611 offscreen->draw(canvas, 0, 0);
1612 canvas->translate(0, 100);
1613 }
1614
1615 return DrawResult::kOk;
1616 }
1617
1618 } // namespace skiagm