SampleCCPRGeometry.cpp 18 KB

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