2 * Copyright 2015 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "src/gpu/ganesh/ops/AALinearizingConvexPathRenderer.h"
10 #include "include/core/SkString.h"
11 #include "src/core/SkGeometry.h"
12 #include "src/core/SkPathPriv.h"
13 #include "src/core/SkTraceEvent.h"
14 #include "src/gpu/BufferWriter.h"
15 #include "src/gpu/ganesh/GrAuditTrail.h"
16 #include "src/gpu/ganesh/GrCaps.h"
17 #include "src/gpu/ganesh/GrDefaultGeoProcFactory.h"
18 #include "src/gpu/ganesh/GrDrawOpTest.h"
19 #include "src/gpu/ganesh/GrGeometryProcessor.h"
20 #include "src/gpu/ganesh/GrOpFlushState.h"
21 #include "src/gpu/ganesh/GrProcessor.h"
22 #include "src/gpu/ganesh/GrProgramInfo.h"
23 #include "src/gpu/ganesh/GrStyle.h"
24 #include "src/gpu/ganesh/geometry/GrAAConvexTessellator.h"
25 #include "src/gpu/ganesh/geometry/GrPathUtils.h"
26 #include "src/gpu/ganesh/geometry/GrStyledShape.h"
27 #include "src/gpu/ganesh/ops/GrMeshDrawOp.h"
28 #include "src/gpu/ganesh/ops/GrSimpleMeshDrawOpHelperWithStencil.h"
29 #include "src/gpu/ganesh/v1/SurfaceDrawContext_v1.h"
31 ///////////////////////////////////////////////////////////////////////////////
36 static const int DEFAULT_BUFFER_SIZE = 100;
38 // The thicker the stroke, the harder it is to produce high-quality results using tessellation. For
39 // the time being, we simply drop back to software rendering above this stroke width.
40 static const SkScalar kMaxStrokeWidth = 20.0;
42 // extract the result vertices and indices from the GrAAConvexTessellator
43 void extract_verts(const GrAAConvexTessellator& tess,
44 const SkMatrix* localCoordsMatrix,
46 const VertexColor& color,
49 VertexWriter verts{vertData};
50 for (int i = 0; i < tess.numPts(); ++i) {
52 if (localCoordsMatrix) {
53 localCoordsMatrix->mapPoints(&lc, &tess.point(i), 1);
55 verts << tess.point(i) << color << VertexWriter::If(localCoordsMatrix, lc)
59 for (int i = 0; i < tess.numIndices(); ++i) {
60 idxs[i] = tess.index(i) + firstIndex;
64 GrGeometryProcessor* create_lines_only_gp(SkArenaAlloc* arena,
65 bool tweakAlphaForCoverage,
68 using namespace GrDefaultGeoProcFactory;
70 Coverage::Type coverageType =
71 tweakAlphaForCoverage ? Coverage::kAttributeTweakAlpha_Type : Coverage::kAttribute_Type;
72 LocalCoords::Type localCoordsType =
73 usesLocalCoords ? LocalCoords::kHasExplicit_Type : LocalCoords::kUnused_Type;
74 Color::Type colorType =
75 wideColor ? Color::kPremulWideColorAttribute_Type : Color::kPremulGrColorAttribute_Type;
77 return Make(arena, colorType, coverageType, localCoordsType, SkMatrix::I());
80 class AAFlatteningConvexPathOp final : public GrMeshDrawOp {
82 using Helper = GrSimpleMeshDrawOpHelperWithStencil;
87 static GrOp::Owner Make(GrRecordingContext* context,
89 const SkMatrix& viewMatrix,
92 SkStrokeRec::Style style,
95 const GrUserStencilSettings* stencilSettings) {
96 return Helper::FactoryHelper<AAFlatteningConvexPathOp>(context, std::move(paint),
98 strokeWidth, style, join, miterLimit,
102 AAFlatteningConvexPathOp(GrProcessorSet* processorSet,
103 const SkPMColor4f& color,
104 const SkMatrix& viewMatrix,
106 SkScalar strokeWidth,
107 SkStrokeRec::Style style,
110 const GrUserStencilSettings* stencilSettings)
111 : INHERITED(ClassID()), fHelper(processorSet, GrAAType::kCoverage, stencilSettings) {
113 PathData{viewMatrix, path, color, strokeWidth, miterLimit, style, join});
116 SkRect bounds = path.getBounds();
117 SkScalar w = strokeWidth;
120 SkScalar maxScale = viewMatrix.getMaxScale();
121 // We should not have a perspective matrix, thus we should have a valid scale.
122 SkASSERT(maxScale != -1);
123 if (SkPaint::kMiter_Join == join && w * maxScale > 1.f) {
128 this->setTransformedBounds(bounds, viewMatrix, HasAABloat::kYes, IsHairline::kNo);
131 const char* name() const override { return "AAFlatteningConvexPathOp"; }
133 void visitProxies(const GrVisitProxyFunc& func) const override {
135 fProgramInfo->visitFPProxies(func);
137 fHelper.visitProxies(func);
141 FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
143 GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip,
144 GrClampType clampType) override {
145 return fHelper.finalizeProcessors(caps, clip, clampType,
146 GrProcessorAnalysisCoverage::kSingleChannel,
147 &fPaths.back().fColor, &fWideColor);
151 GrProgramInfo* programInfo() override { return fProgramInfo; }
153 void onCreateProgramInfo(const GrCaps* caps,
155 const GrSurfaceProxyView& writeView,
156 bool usesMSAASurface,
157 GrAppliedClip&& appliedClip,
158 const GrDstProxyView& dstProxyView,
159 GrXferBarrierFlags renderPassXferBarriers,
160 GrLoadOp colorLoadOp) override {
161 GrGeometryProcessor* gp = create_lines_only_gp(arena,
162 fHelper.compatibleWithCoverageAsAlpha(),
163 fHelper.usesLocalCoords(),
166 SkDebugf("Couldn't create a GrGeometryProcessor\n");
170 fProgramInfo = fHelper.createProgramInfoWithStencil(caps, arena, writeView, usesMSAASurface,
171 std::move(appliedClip), dstProxyView,
172 gp, GrPrimitiveType::kTriangles,
173 renderPassXferBarriers, colorLoadOp);
176 void recordDraw(GrMeshDrawTarget* target,
177 int vertexCount, size_t vertexStride, void* vertices,
178 int indexCount, uint16_t* indices) {
179 if (vertexCount == 0 || indexCount == 0) {
182 sk_sp<const GrBuffer> vertexBuffer;
184 void* verts = target->makeVertexSpace(vertexStride, vertexCount, &vertexBuffer,
187 SkDebugf("Could not allocate vertices\n");
190 memcpy(verts, vertices, vertexCount * vertexStride);
192 sk_sp<const GrBuffer> indexBuffer;
194 uint16_t* idxs = target->makeIndexSpace(indexCount, &indexBuffer, &firstIndex);
196 SkDebugf("Could not allocate indices\n");
199 memcpy(idxs, indices, indexCount * sizeof(uint16_t));
200 GrSimpleMesh* mesh = target->allocMesh();
201 mesh->setIndexed(std::move(indexBuffer), indexCount, firstIndex, 0, vertexCount - 1,
202 GrPrimitiveRestart::kNo, std::move(vertexBuffer), firstVertex);
203 fMeshes.push_back(mesh);
206 void onPrepareDraws(GrMeshDrawTarget* target) override {
208 this->createProgramInfo(target);
214 size_t vertexStride = fProgramInfo->geomProc().vertexStride();
215 int instanceCount = fPaths.count();
217 int64_t vertexCount = 0;
218 int64_t indexCount = 0;
219 int64_t maxVertices = DEFAULT_BUFFER_SIZE;
220 int64_t maxIndices = DEFAULT_BUFFER_SIZE;
221 uint8_t* vertices = (uint8_t*) sk_malloc_throw(maxVertices * vertexStride);
222 uint16_t* indices = (uint16_t*) sk_malloc_throw(maxIndices * sizeof(uint16_t));
223 for (int i = 0; i < instanceCount; i++) {
224 const PathData& args = fPaths[i];
225 GrAAConvexTessellator tess(args.fStyle, args.fStrokeWidth,
226 args.fJoin, args.fMiterLimit);
228 if (!tess.tessellate(args.fViewMatrix, args.fPath)) {
232 int currentVertices = tess.numPts();
233 if (vertexCount + currentVertices > static_cast<int>(UINT16_MAX)) {
234 // if we added the current instance, we would overflow the indices we can store in a
235 // uint16_t. Draw what we've got so far and reset.
236 this->recordDraw(target, vertexCount, vertexStride, vertices, indexCount, indices);
240 if (vertexCount + currentVertices > maxVertices) {
241 maxVertices = std::max(vertexCount + currentVertices, maxVertices * 2);
242 if (maxVertices * vertexStride > SK_MaxS32) {
247 vertices = (uint8_t*) sk_realloc_throw(vertices, maxVertices * vertexStride);
249 int currentIndices = tess.numIndices();
250 if (indexCount + currentIndices > maxIndices) {
251 maxIndices = std::max(indexCount + currentIndices, maxIndices * 2);
252 if (maxIndices * sizeof(uint16_t) > SK_MaxS32) {
257 indices = (uint16_t*) sk_realloc_throw(indices, maxIndices * sizeof(uint16_t));
260 const SkMatrix* localCoordsMatrix = nullptr;
262 if (fHelper.usesLocalCoords()) {
263 if (!args.fViewMatrix.invert(&ivm)) {
266 localCoordsMatrix = &ivm;
269 extract_verts(tess, localCoordsMatrix, vertices + vertexStride * vertexCount,
270 VertexColor(args.fColor, fWideColor), vertexCount, indices + indexCount);
271 vertexCount += currentVertices;
272 indexCount += currentIndices;
274 if (vertexCount <= SK_MaxS32 && indexCount <= SK_MaxS32) {
275 this->recordDraw(target, vertexCount, vertexStride, vertices, indexCount, indices);
281 void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) override {
282 if (!fProgramInfo || fMeshes.isEmpty()) {
286 flushState->bindPipelineAndScissorClip(*fProgramInfo, chainBounds);
287 flushState->bindTextures(fProgramInfo->geomProc(), nullptr, fProgramInfo->pipeline());
288 for (int i = 0; i < fMeshes.count(); ++i) {
289 flushState->drawMesh(*fMeshes[i]);
293 CombineResult onCombineIfPossible(GrOp* t, SkArenaAlloc*, const GrCaps& caps) override {
294 AAFlatteningConvexPathOp* that = t->cast<AAFlatteningConvexPathOp>();
295 if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
296 return CombineResult::kCannotCombine;
299 fPaths.push_back_n(that->fPaths.count(), that->fPaths.begin());
300 fWideColor |= that->fWideColor;
301 return CombineResult::kMerged;
305 SkString onDumpInfo() const override {
307 for (const auto& path : fPaths) {
309 "Color: 0x%08x, StrokeWidth: %.2f, Style: %d, Join: %d, "
310 "MiterLimit: %.2f\n",
311 path.fColor.toBytes_RGBA(), path.fStrokeWidth, path.fStyle, path.fJoin,
314 string += fHelper.dumpInfo();
320 SkMatrix fViewMatrix;
323 SkScalar fStrokeWidth;
324 SkScalar fMiterLimit;
325 SkStrokeRec::Style fStyle;
329 SkSTArray<1, PathData, true> fPaths;
333 SkTDArray<GrSimpleMesh*> fMeshes;
334 GrProgramInfo* fProgramInfo = nullptr;
336 using INHERITED = GrMeshDrawOp;
339 } // anonymous namespace
341 ///////////////////////////////////////////////////////////////////////////////////////////////////
343 PathRenderer::CanDrawPath
344 AALinearizingConvexPathRenderer::onCanDrawPath(const CanDrawPathArgs& args) const {
345 if (GrAAType::kCoverage != args.fAAType) {
346 return CanDrawPath::kNo;
348 if (!args.fShape->knownToBeConvex()) {
349 return CanDrawPath::kNo;
351 if (args.fShape->style().pathEffect()) {
352 return CanDrawPath::kNo;
354 if (args.fShape->inverseFilled()) {
355 return CanDrawPath::kNo;
357 if (args.fShape->bounds().width() <= 0 && args.fShape->bounds().height() <= 0) {
358 // Stroked zero length lines should draw, but this PR doesn't handle that case
359 return CanDrawPath::kNo;
361 const SkStrokeRec& stroke = args.fShape->style().strokeRec();
363 if (stroke.getStyle() == SkStrokeRec::kStroke_Style ||
364 stroke.getStyle() == SkStrokeRec::kStrokeAndFill_Style) {
365 if (!args.fViewMatrix->isSimilarity()) {
366 return CanDrawPath::kNo;
368 SkScalar strokeWidth = args.fViewMatrix->getMaxScale() * stroke.getWidth();
369 if (strokeWidth < 1.0f && stroke.getStyle() == SkStrokeRec::kStroke_Style) {
370 return CanDrawPath::kNo;
372 if (strokeWidth > kMaxStrokeWidth ||
373 !args.fShape->knownToBeClosed() ||
374 stroke.getJoin() == SkPaint::Join::kRound_Join) {
375 return CanDrawPath::kNo;
377 return CanDrawPath::kYes;
379 if (stroke.getStyle() != SkStrokeRec::kFill_Style) {
380 return CanDrawPath::kNo;
382 // This can almost handle perspective. It would need to use 3 component explicit local coords
383 // when there are FPs that require them. This is difficult to test because AAConvexPathRenderer
384 // takes almost all filled paths that could get here. So just avoid perspective fills.
385 if (args.fViewMatrix->hasPerspective()) {
386 return CanDrawPath::kNo;
388 return CanDrawPath::kYes;
391 bool AALinearizingConvexPathRenderer::onDrawPath(const DrawPathArgs& args) {
392 GR_AUDIT_TRAIL_AUTO_FRAME(args.fContext->priv().auditTrail(),
393 "AALinearizingConvexPathRenderer::onDrawPath");
394 SkASSERT(args.fSurfaceDrawContext->numSamples() <= 1);
395 SkASSERT(!args.fShape->isEmpty());
396 SkASSERT(!args.fShape->style().pathEffect());
399 args.fShape->asPath(&path);
400 bool fill = args.fShape->style().isSimpleFill();
401 const SkStrokeRec& stroke = args.fShape->style().strokeRec();
402 SkScalar strokeWidth = fill ? -1.0f : stroke.getWidth();
403 SkPaint::Join join = fill ? SkPaint::Join::kMiter_Join : stroke.getJoin();
404 SkScalar miterLimit = stroke.getMiter();
406 GrOp::Owner op = AAFlatteningConvexPathOp::Make(
407 args.fContext, std::move(args.fPaint), *args.fViewMatrix, path, strokeWidth,
408 stroke.getStyle(), join, miterLimit, args.fUserStencilSettings);
409 args.fSurfaceDrawContext->addDrawOp(args.fClip, std::move(op));
413 } // namespace skgpu::v1
417 GR_DRAW_OP_TEST_DEFINE(AAFlatteningConvexPathOp) {
418 SkMatrix viewMatrix = GrTest::TestMatrixPreservesRightAngles(random);
419 const SkPath& path = GrTest::TestPathConvex(random);
421 SkStrokeRec::Style styles[3] = { SkStrokeRec::kFill_Style,
422 SkStrokeRec::kStroke_Style,
423 SkStrokeRec::kStrokeAndFill_Style };
425 SkStrokeRec::Style style = styles[random->nextU() % 3];
427 SkScalar strokeWidth = -1.f;
428 SkPaint::Join join = SkPaint::kMiter_Join;
429 SkScalar miterLimit = 0.5f;
431 if (SkStrokeRec::kFill_Style != style) {
432 strokeWidth = random->nextRangeF(1.0f, 10.0f);
433 if (random->nextBool()) {
434 join = SkPaint::kMiter_Join;
436 join = SkPaint::kBevel_Join;
438 miterLimit = random->nextRangeF(0.5f, 2.0f);
440 const GrUserStencilSettings* stencilSettings = GrGetRandomStencil(random, context);
441 return skgpu::v1::AAFlatteningConvexPathOp::Make(context, std::move(paint), viewMatrix, path,
442 strokeWidth, style, join, miterLimit,