1 /*
2 * Copyright 2017 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "include/core/SkTypes.h"
9
10 #if SK_SUPPORT_GPU
11
12 #include "include/core/SkCanvas.h"
13 #include "include/core/SkPaint.h"
14 #include "include/core/SkPath.h"
15 #include "samplecode/Sample.h"
16 #include "src/core/SkMakeUnique.h"
17 #include "src/core/SkRectPriv.h"
18 #include "src/gpu/GrClip.h"
19 #include "src/gpu/GrContextPriv.h"
20 #include "src/gpu/GrMemoryPool.h"
21 #include "src/gpu/GrRenderTargetContext.h"
22 #include "src/gpu/GrRenderTargetContextPriv.h"
23 #include "src/gpu/GrResourceProvider.h"
24 #include "src/gpu/ccpr/GrCCCoverageProcessor.h"
25 #include "src/gpu/ccpr/GrCCFillGeometry.h"
26 #include "src/gpu/ccpr/GrCCStroker.h"
27 #include "src/gpu/ccpr/GrGSCoverageProcessor.h"
28 #include "src/gpu/ccpr/GrVSCoverageProcessor.h"
29 #include "src/gpu/geometry/GrPathUtils.h"
30 #include "src/gpu/gl/GrGLGpu.h"
31 #include "src/gpu/glsl/GrGLSLFragmentProcessor.h"
32 #include "src/gpu/ops/GrDrawOp.h"
33
34 using TriPointInstance = GrCCCoverageProcessor::TriPointInstance;
35 using QuadPointInstance = GrCCCoverageProcessor::QuadPointInstance;
36 using PrimitiveType = GrCCCoverageProcessor::PrimitiveType;
37
38 static constexpr float kDebugBloat = 40;
39
40 /**
41 * This sample visualizes the AA bloat geometry generated by the ccpr geometry shaders. It
42 * increases the AA bloat by 50x and outputs color instead of coverage (coverage=+1 -> green,
43 * coverage=0 -> black, coverage=-1 -> red). Use the keys 1-7 to cycle through the different
44 * geometry processors.
45 */
46 class CCPRGeometryView : public Sample {
onOnceBeforeDraw()47 void onOnceBeforeDraw() override { this->updateGpuData(); }
48 void onDrawContent(SkCanvas*) override;
49
50 Sample::Click* onFindClickHandler(SkScalar x, SkScalar y, ModifierKey) override;
51 bool onClick(Sample::Click*) override;
52 bool onChar(SkUnichar) override;
name()53 SkString name() override { return SkString("CCPRGeometry"); }
54
55 class Click;
56 class DrawCoverageCountOp;
57 class VisualizeCoverageCountFP;
58
updateAndInval()59 void updateAndInval() { this->updateGpuData(); }
60
61 void updateGpuData();
62
63 PrimitiveType fPrimitiveType = PrimitiveType::kTriangles;
64 SkCubicType fCubicType;
65 SkMatrix fCubicKLM;
66
67 SkPoint fPoints[4] = {
68 {100.05f, 100.05f}, {400.75f, 100.05f}, {400.75f, 300.95f}, {100.05f, 300.95f}};
69
70 float fConicWeight = .5;
71 float fStrokeWidth = 40;
72 bool fDoStroke = false;
73
74 SkTArray<TriPointInstance> fTriPointInstances;
75 SkTArray<QuadPointInstance> fQuadPointInstances;
76 SkPath fPath;
77 };
78
79 class CCPRGeometryView::DrawCoverageCountOp : public GrDrawOp {
80 DEFINE_OP_CLASS_ID
81
82 public:
DrawCoverageCountOp(CCPRGeometryView * view)83 DrawCoverageCountOp(CCPRGeometryView* view) : INHERITED(ClassID()), fView(view) {
84 this->setBounds(SkRect::MakeIWH(fView->width(), fView->height()), GrOp::HasAABloat::kNo,
85 GrOp::IsZeroArea::kNo);
86 }
87
name() const88 const char* name() const override {
89 return "[Testing/Sample code] CCPRGeometryView::DrawCoverageCountOp";
90 }
91
92 private:
fixedFunctionFlags() const93 FixedFunctionFlags fixedFunctionFlags() const override { return FixedFunctionFlags::kNone; }
finalize(const GrCaps &,const GrAppliedClip *,bool hasMixedSampledCoverage,GrClampType)94 GrProcessorSet::Analysis finalize(const GrCaps&, const GrAppliedClip*,
95 bool hasMixedSampledCoverage, GrClampType) override {
96 return GrProcessorSet::EmptySetAnalysis();
97 }
onPrepare(GrOpFlushState *)98 void onPrepare(GrOpFlushState*) override {}
99 void onExecute(GrOpFlushState*, const SkRect& chainBounds) override;
100
101 CCPRGeometryView* fView;
102
103 typedef GrDrawOp INHERITED;
104 };
105
106 class CCPRGeometryView::VisualizeCoverageCountFP : public GrFragmentProcessor {
107 public:
VisualizeCoverageCountFP()108 VisualizeCoverageCountFP() : GrFragmentProcessor(kTestFP_ClassID, kNone_OptimizationFlags) {}
109
110 private:
name() const111 const char* name() const override {
112 return "[Testing/Sample code] CCPRGeometryView::VisualizeCoverageCountFP";
113 }
clone() const114 std::unique_ptr<GrFragmentProcessor> clone() const override {
115 return skstd::make_unique<VisualizeCoverageCountFP>();
116 }
onGetGLSLProcessorKey(const GrShaderCaps &,GrProcessorKeyBuilder *) const117 void onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const override {}
onIsEqual(const GrFragmentProcessor &) const118 bool onIsEqual(const GrFragmentProcessor&) const override { return true; }
119
120 class Impl : public GrGLSLFragmentProcessor {
emitCode(EmitArgs & args)121 void emitCode(EmitArgs& args) override {
122 GrGLSLFPFragmentBuilder* f = args.fFragBuilder;
123 f->codeAppendf("half count = %s.a;", args.fInputColor);
124 f->codeAppendf("%s = half4(clamp(-count, 0, 1), clamp(+count, 0, 1), 0, abs(count));",
125 args.fOutputColor);
126 }
127 };
128
onCreateGLSLInstance() const129 GrGLSLFragmentProcessor* onCreateGLSLInstance() const override { return new Impl; }
130 };
131
draw_klm_line(int w,int h,SkCanvas * canvas,const SkScalar line[3],SkColor color)132 static void draw_klm_line(int w, int h, SkCanvas* canvas, const SkScalar line[3], SkColor color) {
133 SkPoint p1, p2;
134 if (SkScalarAbs(line[1]) > SkScalarAbs(line[0])) {
135 // Draw from vertical edge to vertical edge.
136 p1 = {0, -line[2] / line[1]};
137 p2 = {(SkScalar)w, (-line[2] - w * line[0]) / line[1]};
138 } else {
139 // Draw from horizontal edge to horizontal edge.
140 p1 = {-line[2] / line[0], 0};
141 p2 = {(-line[2] - h * line[1]) / line[0], (SkScalar)h};
142 }
143
144 SkPaint linePaint;
145 linePaint.setColor(color);
146 linePaint.setAlpha(128);
147 linePaint.setStyle(SkPaint::kStroke_Style);
148 linePaint.setStrokeWidth(0);
149 linePaint.setAntiAlias(true);
150 canvas->drawLine(p1, p2, linePaint);
151 }
152
onDrawContent(SkCanvas * canvas)153 void CCPRGeometryView::onDrawContent(SkCanvas* canvas) {
154 canvas->clear(SK_ColorBLACK);
155
156 if (!fDoStroke) {
157 SkPaint outlinePaint;
158 outlinePaint.setColor(0x80ffffff);
159 outlinePaint.setStyle(SkPaint::kStroke_Style);
160 outlinePaint.setStrokeWidth(0);
161 outlinePaint.setAntiAlias(true);
162 canvas->drawPath(fPath, outlinePaint);
163 }
164
165 #if 0
166 SkPaint gridPaint;
167 gridPaint.setColor(0x10000000);
168 gridPaint.setStyle(SkPaint::kStroke_Style);
169 gridPaint.setStrokeWidth(0);
170 gridPaint.setAntiAlias(true);
171 for (int y = 0; y < this->height(); y += kDebugBloat) {
172 canvas->drawLine(0, y, this->width(), y, gridPaint);
173 }
174 for (int x = 0; x < this->width(); x += kDebugBloat) {
175 canvas->drawLine(x, 0, x, this->height(), outlinePaint);
176 }
177 #endif
178
179 SkString caption;
180 if (GrRenderTargetContext* rtc = canvas->internal_private_accessTopLayerRenderTargetContext()) {
181 // Render coverage count.
182 GrContext* ctx = canvas->getGrContext();
183 SkASSERT(ctx);
184
185 GrOpMemoryPool* pool = ctx->priv().opMemoryPool();
186
187 sk_sp<GrRenderTargetContext> ccbuff = ctx->priv().makeDeferredRenderTargetContext(
188 SkBackingFit::kApprox, this->width(), this->height(), GrColorType::kAlpha_F16,
189 nullptr);
190 SkASSERT(ccbuff);
191 ccbuff->clear(nullptr, SK_PMColor4fTRANSPARENT,
192 GrRenderTargetContext::CanClearFullscreen::kYes);
193 ccbuff->priv().testingOnly_addDrawOp(pool->allocate<DrawCoverageCountOp>(this));
194
195 // Visualize coverage count in main canvas.
196 GrPaint paint;
197 paint.addColorFragmentProcessor(
198 GrSimpleTextureEffect::Make(sk_ref_sp(ccbuff->asTextureProxy()), SkMatrix::I()));
199 paint.addColorFragmentProcessor(
200 skstd::make_unique<VisualizeCoverageCountFP>());
201 paint.setPorterDuffXPFactory(SkBlendMode::kSrcOver);
202 rtc->drawRect(GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(),
203 SkRect::MakeIWH(this->width(), this->height()));
204
205 // Add label.
206 caption.appendf("PrimitiveType_%s",
207 GrCCCoverageProcessor::PrimitiveTypeName(fPrimitiveType));
208 if (PrimitiveType::kCubics == fPrimitiveType) {
209 caption.appendf(" (%s)", SkCubicTypeName(fCubicType));
210 } else if (PrimitiveType::kConics == fPrimitiveType) {
211 caption.appendf(" (w=%f)", fConicWeight);
212 }
213 if (fDoStroke) {
214 caption.appendf(" (stroke_width=%f)", fStrokeWidth);
215 }
216 } else {
217 caption = "Use GPU backend to visualize geometry.";
218 }
219
220 SkPaint pointsPaint;
221 pointsPaint.setColor(SK_ColorBLUE);
222 pointsPaint.setStrokeWidth(8);
223 pointsPaint.setAntiAlias(true);
224
225 if (PrimitiveType::kCubics == fPrimitiveType) {
226 canvas->drawPoints(SkCanvas::kPoints_PointMode, 4, fPoints, pointsPaint);
227 if (!fDoStroke) {
228 int w = this->width(), h = this->height();
229 draw_klm_line(w, h, canvas, &fCubicKLM[0], SK_ColorYELLOW);
230 draw_klm_line(w, h, canvas, &fCubicKLM[3], SK_ColorBLUE);
231 draw_klm_line(w, h, canvas, &fCubicKLM[6], SK_ColorRED);
232 }
233 } else {
234 canvas->drawPoints(SkCanvas::kPoints_PointMode, 2, fPoints, pointsPaint);
235 canvas->drawPoints(SkCanvas::kPoints_PointMode, 1, fPoints + 3, pointsPaint);
236 }
237
238 SkFont font(nullptr, 20);
239 SkPaint captionPaint;
240 captionPaint.setColor(SK_ColorWHITE);
241 canvas->drawString(caption, 10, 30, font, captionPaint);
242 }
243
updateGpuData()244 void CCPRGeometryView::updateGpuData() {
245 using Verb = GrCCFillGeometry::Verb;
246 fTriPointInstances.reset();
247 fQuadPointInstances.reset();
248
249 fPath.reset();
250 fPath.moveTo(fPoints[0]);
251
252 if (PrimitiveType::kCubics == fPrimitiveType) {
253 double t[2], s[2];
254 fCubicType = GrPathUtils::getCubicKLM(fPoints, &fCubicKLM, t, s);
255 GrCCFillGeometry geometry;
256 geometry.beginContour(fPoints[0]);
257 geometry.cubicTo(fPoints, kDebugBloat / 2, kDebugBloat / 2);
258 geometry.endContour();
259 int ptsIdx = 0;
260 for (Verb verb : geometry.verbs()) {
261 switch (verb) {
262 case Verb::kLineTo:
263 ++ptsIdx;
264 continue;
265 case Verb::kMonotonicQuadraticTo:
266 ptsIdx += 2;
267 continue;
268 case Verb::kMonotonicCubicTo:
269 fQuadPointInstances.push_back().set(&geometry.points()[ptsIdx], 0, 0);
270 ptsIdx += 3;
271 continue;
272 default:
273 continue;
274 }
275 }
276 fPath.cubicTo(fPoints[1], fPoints[2], fPoints[3]);
277 } else if (PrimitiveType::kTriangles != fPrimitiveType) {
278 SkPoint P3[3] = {fPoints[0], fPoints[1], fPoints[3]};
279 GrCCFillGeometry geometry;
280 geometry.beginContour(P3[0]);
281 if (PrimitiveType::kQuadratics == fPrimitiveType) {
282 geometry.quadraticTo(P3);
283 fPath.quadTo(fPoints[1], fPoints[3]);
284 } else {
285 SkASSERT(PrimitiveType::kConics == fPrimitiveType);
286 geometry.conicTo(P3, fConicWeight);
287 fPath.conicTo(fPoints[1], fPoints[3], fConicWeight);
288 }
289 geometry.endContour();
290 int ptsIdx = 0, conicWeightIdx = 0;
291 for (Verb verb : geometry.verbs()) {
292 if (Verb::kBeginContour == verb ||
293 Verb::kEndOpenContour == verb ||
294 Verb::kEndClosedContour == verb) {
295 continue;
296 }
297 if (Verb::kLineTo == verb) {
298 ++ptsIdx;
299 continue;
300 }
301 SkASSERT(Verb::kMonotonicQuadraticTo == verb || Verb::kMonotonicConicTo == verb);
302 if (PrimitiveType::kQuadratics == fPrimitiveType &&
303 Verb::kMonotonicQuadraticTo == verb) {
304 fTriPointInstances.push_back().set(
305 &geometry.points()[ptsIdx], Sk2f(0, 0),
306 TriPointInstance::Ordering::kXYTransposed);
307 } else if (PrimitiveType::kConics == fPrimitiveType &&
308 Verb::kMonotonicConicTo == verb) {
309 fQuadPointInstances.push_back().setW(&geometry.points()[ptsIdx], Sk2f(0, 0),
310 geometry.getConicWeight(conicWeightIdx++));
311 }
312 ptsIdx += 2;
313 }
314 } else {
315 fTriPointInstances.push_back().set(
316 fPoints[0], fPoints[1], fPoints[3], Sk2f(0, 0),
317 TriPointInstance::Ordering::kXYTransposed);
318 fPath.lineTo(fPoints[1]);
319 fPath.lineTo(fPoints[3]);
320 fPath.close();
321 }
322 }
323
onExecute(GrOpFlushState * state,const SkRect & chainBounds)324 void CCPRGeometryView::DrawCoverageCountOp::onExecute(GrOpFlushState* state,
325 const SkRect& chainBounds) {
326 GrResourceProvider* rp = state->resourceProvider();
327 GrContext* context = state->gpu()->getContext();
328 GrGLGpu* glGpu = GrBackendApi::kOpenGL == context->backend()
329 ? static_cast<GrGLGpu*>(state->gpu())
330 : nullptr;
331 if (glGpu) {
332 glGpu->handleDirtyContext();
333 // GR_GL_CALL(glGpu->glInterface(), PolygonMode(GR_GL_FRONT_AND_BACK, GR_GL_LINE));
334 GR_GL_CALL(glGpu->glInterface(), Enable(GR_GL_LINE_SMOOTH));
335 }
336
337 GrPipeline pipeline(GrScissorTest::kDisabled, SkBlendMode::kPlus,
338 state->drawOpArgs().fOutputSwizzle);
339
340 std::unique_ptr<GrCCCoverageProcessor> proc;
341 if (state->caps().shaderCaps()->geometryShaderSupport()) {
342 proc = skstd::make_unique<GrGSCoverageProcessor>();
343 } else {
344 proc = skstd::make_unique<GrVSCoverageProcessor>();
345 }
346
347 if (!fView->fDoStroke) {
348 proc->reset(fView->fPrimitiveType, rp);
349 SkDEBUGCODE(proc->enableDebugBloat(kDebugBloat));
350
351 SkSTArray<1, GrMesh> mesh;
352 if (PrimitiveType::kCubics == fView->fPrimitiveType ||
353 PrimitiveType::kConics == fView->fPrimitiveType) {
354 sk_sp<GrGpuBuffer> instBuff(
355 rp->createBuffer(fView->fQuadPointInstances.count() * sizeof(QuadPointInstance),
356 GrGpuBufferType::kVertex, kDynamic_GrAccessPattern,
357 fView->fQuadPointInstances.begin()));
358 if (!fView->fQuadPointInstances.empty() && instBuff) {
359 proc->appendMesh(std::move(instBuff), fView->fQuadPointInstances.count(), 0, &mesh);
360 }
361 } else {
362 sk_sp<GrGpuBuffer> instBuff(
363 rp->createBuffer(fView->fTriPointInstances.count() * sizeof(TriPointInstance),
364 GrGpuBufferType::kVertex, kDynamic_GrAccessPattern,
365 fView->fTriPointInstances.begin()));
366 if (!fView->fTriPointInstances.empty() && instBuff) {
367 proc->appendMesh(std::move(instBuff), fView->fTriPointInstances.count(), 0, &mesh);
368 }
369 }
370
371 if (!mesh.empty()) {
372 SkASSERT(1 == mesh.count());
373 proc->draw(state, pipeline, nullptr, mesh.begin(), 1, this->bounds());
374 }
375 } else if (PrimitiveType::kConics != fView->fPrimitiveType) { // No conic stroke support yet.
376 GrCCStroker stroker(0,0,0);
377
378 SkPaint p;
379 p.setStyle(SkPaint::kStroke_Style);
380 p.setStrokeWidth(fView->fStrokeWidth);
381 p.setStrokeJoin(SkPaint::kMiter_Join);
382 p.setStrokeMiter(4);
383 // p.setStrokeCap(SkPaint::kRound_Cap);
384 stroker.parseDeviceSpaceStroke(fView->fPath, SkPathPriv::PointData(fView->fPath),
385 SkStrokeRec(p), p.getStrokeWidth(), GrScissorTest::kDisabled,
386 SkIRect::MakeWH(fView->width(), fView->height()), {0, 0});
387 GrCCStroker::BatchID batchID = stroker.closeCurrentBatch();
388
389 GrOnFlushResourceProvider onFlushRP(context->priv().drawingManager());
390 stroker.prepareToDraw(&onFlushRP);
391
392 SkIRect ibounds;
393 this->bounds().roundOut(&ibounds);
394 stroker.drawStrokes(state, proc.get(), batchID, ibounds);
395 }
396
397 if (glGpu) {
398 context->resetContext(kMisc_GrGLBackendState);
399 }
400 }
401
402 class CCPRGeometryView::Click : public Sample::Click {
403 public:
Click(int ptIdx)404 Click(int ptIdx) : fPtIdx(ptIdx) {}
405
doClick(SkPoint points[])406 void doClick(SkPoint points[]) {
407 if (fPtIdx >= 0) {
408 points[fPtIdx] += fCurr - fPrev;
409 } else {
410 for (int i = 0; i < 4; ++i) {
411 points[i] += fCurr - fPrev;
412 }
413 }
414 }
415
416 private:
417 int fPtIdx;
418 };
419
onFindClickHandler(SkScalar x,SkScalar y,ModifierKey)420 Sample::Click* CCPRGeometryView::onFindClickHandler(SkScalar x, SkScalar y, ModifierKey) {
421 for (int i = 0; i < 4; ++i) {
422 if (PrimitiveType::kCubics != fPrimitiveType && 2 == i) {
423 continue;
424 }
425 if (fabs(x - fPoints[i].x()) < 20 && fabsf(y - fPoints[i].y()) < 20) {
426 return new Click(i);
427 }
428 }
429 return new Click(-1);
430 }
431
onClick(Sample::Click * click)432 bool CCPRGeometryView::onClick(Sample::Click* click) {
433 Click* myClick = (Click*)click;
434 myClick->doClick(fPoints);
435 this->updateAndInval();
436 return true;
437 }
438
onChar(SkUnichar unichar)439 bool CCPRGeometryView::onChar(SkUnichar unichar) {
440 if (unichar >= '1' && unichar <= '4') {
441 fPrimitiveType = PrimitiveType(unichar - '1');
442 if (fPrimitiveType >= PrimitiveType::kWeightedTriangles) {
443 fPrimitiveType = (PrimitiveType) ((int)fPrimitiveType + 1);
444 }
445 this->updateAndInval();
446 return true;
447 }
448 float* valueToScale = nullptr;
449 if (fDoStroke) {
450 valueToScale = &fStrokeWidth;
451 } else if (PrimitiveType::kConics == fPrimitiveType) {
452 valueToScale = &fConicWeight;
453 }
454 if (valueToScale) {
455 if (unichar == '+') {
456 *valueToScale *= 2;
457 this->updateAndInval();
458 return true;
459 }
460 if (unichar == '+' || unichar == '=') {
461 *valueToScale *= 5/4.f;
462 this->updateAndInval();
463 return true;
464 }
465 if (unichar == '-') {
466 *valueToScale *= 4/5.f;
467 this->updateAndInval();
468 return true;
469 }
470 if (unichar == '_') {
471 *valueToScale *= .5f;
472 this->updateAndInval();
473 return true;
474 }
475 }
476 if (unichar == 'D') {
477 SkDebugf(" SkPoint fPoints[4] = {\n");
478 SkDebugf(" {%ff, %ff},\n", fPoints[0].x(), fPoints[0].y());
479 SkDebugf(" {%ff, %ff},\n", fPoints[1].x(), fPoints[1].y());
480 SkDebugf(" {%ff, %ff},\n", fPoints[2].x(), fPoints[2].y());
481 SkDebugf(" {%ff, %ff}\n", fPoints[3].x(), fPoints[3].y());
482 SkDebugf(" };\n");
483 return true;
484 }
485 if (unichar == 'S') {
486 fDoStroke = !fDoStroke;
487 this->updateAndInval();
488 }
489 return false;
490 }
491
492 DEF_SAMPLE(return new CCPRGeometryView;)
493
494 #endif // SK_SUPPORT_GPU
495