1 /*
2 * Copyright 2018 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 "GrCCDrawPathsOp.h"
9
10 #include "GrMemoryPool.h"
11 #include "GrOpFlushState.h"
12 #include "GrRecordingContext.h"
13 #include "GrRecordingContextPriv.h"
14 #include "ccpr/GrCCPathCache.h"
15 #include "ccpr/GrCCPerFlushResources.h"
16 #include "ccpr/GrCoverageCountingPathRenderer.h"
17
has_coord_transforms(const GrPaint & paint)18 static bool has_coord_transforms(const GrPaint& paint) {
19 GrFragmentProcessor::Iter iter(paint);
20 while (const GrFragmentProcessor* fp = iter.next()) {
21 if (!fp->coordTransforms().empty()) {
22 return true;
23 }
24 }
25 return false;
26 }
27
Make(GrRecordingContext * context,const SkIRect & clipIBounds,const SkMatrix & m,const GrShape & shape,GrPaint && paint)28 std::unique_ptr<GrCCDrawPathsOp> GrCCDrawPathsOp::Make(
29 GrRecordingContext* context, const SkIRect& clipIBounds, const SkMatrix& m,
30 const GrShape& shape, GrPaint&& paint) {
31 SkRect conservativeDevBounds;
32 m.mapRect(&conservativeDevBounds, shape.bounds());
33
34 const SkStrokeRec& stroke = shape.style().strokeRec();
35 float strokeDevWidth = 0;
36 float conservativeInflationRadius = 0;
37 if (!stroke.isFillStyle()) {
38 strokeDevWidth = GrCoverageCountingPathRenderer::GetStrokeDevWidth(
39 m, stroke, &conservativeInflationRadius);
40 conservativeDevBounds.outset(conservativeInflationRadius, conservativeInflationRadius);
41 }
42
43 std::unique_ptr<GrCCDrawPathsOp> op;
44 float conservativeSize = SkTMax(conservativeDevBounds.height(), conservativeDevBounds.width());
45 if (conservativeSize > GrCoverageCountingPathRenderer::kPathCropThreshold) {
46 // The path is too large. Crop it or analytic AA can run out of fp32 precision.
47 SkPath croppedDevPath;
48 shape.asPath(&croppedDevPath);
49 croppedDevPath.transform(m, &croppedDevPath);
50
51 SkIRect cropBox = clipIBounds;
52 GrShape croppedDevShape;
53 if (stroke.isFillStyle()) {
54 GrCoverageCountingPathRenderer::CropPath(croppedDevPath, cropBox, &croppedDevPath);
55 croppedDevShape = GrShape(croppedDevPath);
56 conservativeDevBounds = croppedDevShape.bounds();
57 } else {
58 int r = SkScalarCeilToInt(conservativeInflationRadius);
59 cropBox.outset(r, r);
60 GrCoverageCountingPathRenderer::CropPath(croppedDevPath, cropBox, &croppedDevPath);
61 SkStrokeRec devStroke = stroke;
62 devStroke.setStrokeStyle(strokeDevWidth);
63 croppedDevShape = GrShape(croppedDevPath, GrStyle(devStroke, nullptr));
64 conservativeDevBounds = croppedDevPath.getBounds();
65 conservativeDevBounds.outset(conservativeInflationRadius, conservativeInflationRadius);
66 }
67
68 // FIXME: This breaks local coords: http://skbug.com/8003
69 return InternalMake(context, clipIBounds, SkMatrix::I(), croppedDevShape, strokeDevWidth,
70 conservativeDevBounds, std::move(paint));
71 }
72
73 return InternalMake(context, clipIBounds, m, shape, strokeDevWidth, conservativeDevBounds,
74 std::move(paint));
75 }
76
InternalMake(GrRecordingContext * context,const SkIRect & clipIBounds,const SkMatrix & m,const GrShape & shape,float strokeDevWidth,const SkRect & conservativeDevBounds,GrPaint && paint)77 std::unique_ptr<GrCCDrawPathsOp> GrCCDrawPathsOp::InternalMake(
78 GrRecordingContext* context, const SkIRect& clipIBounds, const SkMatrix& m,
79 const GrShape& shape, float strokeDevWidth, const SkRect& conservativeDevBounds,
80 GrPaint&& paint) {
81 // The path itself should have been cropped if larger than kPathCropThreshold. If it had a
82 // stroke, that would have further inflated its draw bounds.
83 SkASSERT(SkTMax(conservativeDevBounds.height(), conservativeDevBounds.width()) <
84 GrCoverageCountingPathRenderer::kPathCropThreshold +
85 GrCoverageCountingPathRenderer::kMaxBoundsInflationFromStroke*2 + 1);
86
87 SkIRect shapeConservativeIBounds;
88 conservativeDevBounds.roundOut(&shapeConservativeIBounds);
89
90 SkIRect maskDevIBounds;
91 if (!maskDevIBounds.intersect(clipIBounds, shapeConservativeIBounds)) {
92 return nullptr;
93 }
94
95 GrOpMemoryPool* pool = context->priv().opMemoryPool();
96 return pool->allocate<GrCCDrawPathsOp>(m, shape, strokeDevWidth, shapeConservativeIBounds,
97 maskDevIBounds, conservativeDevBounds, std::move(paint));
98 }
99
GrCCDrawPathsOp(const SkMatrix & m,const GrShape & shape,float strokeDevWidth,const SkIRect & shapeConservativeIBounds,const SkIRect & maskDevIBounds,const SkRect & conservativeDevBounds,GrPaint && paint)100 GrCCDrawPathsOp::GrCCDrawPathsOp(const SkMatrix& m, const GrShape& shape, float strokeDevWidth,
101 const SkIRect& shapeConservativeIBounds,
102 const SkIRect& maskDevIBounds, const SkRect& conservativeDevBounds,
103 GrPaint&& paint)
104 : GrDrawOp(ClassID())
105 , fViewMatrixIfUsingLocalCoords(has_coord_transforms(paint) ? m : SkMatrix::I())
106 , fDraws(m, shape, strokeDevWidth, shapeConservativeIBounds, maskDevIBounds,
107 paint.getColor4f())
108 , fProcessors(std::move(paint)) { // Paint must be moved after fetching its color above.
109 SkDEBUGCODE(fBaseInstance = -1);
110 // FIXME: intersect with clip bounds to (hopefully) improve batching.
111 // (This is nontrivial due to assumptions in generating the octagon cover geometry.)
112 this->setBounds(conservativeDevBounds, GrOp::HasAABloat::kYes, GrOp::IsZeroArea::kNo);
113 }
114
~GrCCDrawPathsOp()115 GrCCDrawPathsOp::~GrCCDrawPathsOp() {
116 if (fOwningPerOpListPaths) {
117 // Remove the list's dangling pointer to this Op before deleting it.
118 fOwningPerOpListPaths->fDrawOps.remove(this);
119 }
120 }
121
SingleDraw(const SkMatrix & m,const GrShape & shape,float strokeDevWidth,const SkIRect & shapeConservativeIBounds,const SkIRect & maskDevIBounds,const SkPMColor4f & color)122 GrCCDrawPathsOp::SingleDraw::SingleDraw(const SkMatrix& m, const GrShape& shape,
123 float strokeDevWidth,
124 const SkIRect& shapeConservativeIBounds,
125 const SkIRect& maskDevIBounds, const SkPMColor4f& color)
126 : fMatrix(m)
127 , fShape(shape)
128 , fStrokeDevWidth(strokeDevWidth)
129 , fShapeConservativeIBounds(shapeConservativeIBounds)
130 , fMaskDevIBounds(maskDevIBounds)
131 , fColor(color) {
132 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
133 if (fShape.hasUnstyledKey()) {
134 // On AOSP we round view matrix translates to integer values for cachable paths. We do this
135 // to match HWUI's cache hit ratio, which doesn't consider the matrix when caching paths.
136 fMatrix.setTranslateX(SkScalarRoundToScalar(fMatrix.getTranslateX()));
137 fMatrix.setTranslateY(SkScalarRoundToScalar(fMatrix.getTranslateY()));
138 }
139 #endif
140 }
141
finalize(const GrCaps & caps,const GrAppliedClip * clip,GrFSAAType fsaaType,GrClampType clampType)142 GrProcessorSet::Analysis GrCCDrawPathsOp::finalize(const GrCaps& caps, const GrAppliedClip* clip,
143 GrFSAAType fsaaType, GrClampType clampType) {
144 SkASSERT(1 == fNumDraws); // There should only be one single path draw in this Op right now.
145 return fDraws.head().finalize(caps, clip, fsaaType, clampType, &fProcessors);
146 }
147
finalize(const GrCaps & caps,const GrAppliedClip * clip,GrFSAAType fsaaType,GrClampType clampType,GrProcessorSet * processors)148 GrProcessorSet::Analysis GrCCDrawPathsOp::SingleDraw::finalize(
149 const GrCaps& caps, const GrAppliedClip* clip, GrFSAAType fsaaType, GrClampType clampType,
150 GrProcessorSet* processors) {
151 const GrProcessorSet::Analysis& analysis = processors->finalize(
152 fColor, GrProcessorAnalysisCoverage::kSingleChannel, clip,
153 &GrUserStencilSettings::kUnused, fsaaType, caps, clampType, &fColor);
154
155 // Lines start looking jagged when they get thinner than 1px. For thin strokes it looks better
156 // if we can convert them to hairline (i.e., inflate the stroke width to 1px), and instead
157 // reduce the opacity to create the illusion of thin-ness. This strategy also helps reduce
158 // artifacts from coverage dilation when there are self intersections.
159 if (analysis.isCompatibleWithCoverageAsAlpha() &&
160 !fShape.style().strokeRec().isFillStyle() && fStrokeDevWidth < 1) {
161 // Modifying the shape affects its cache key. The draw can't have a cache entry yet or else
162 // our next step would invalidate it.
163 SkASSERT(!fCacheEntry);
164 SkASSERT(SkStrokeRec::kStroke_Style == fShape.style().strokeRec().getStyle());
165
166 SkPath path;
167 fShape.asPath(&path);
168
169 // Create a hairline version of our stroke.
170 SkStrokeRec hairlineStroke = fShape.style().strokeRec();
171 hairlineStroke.setStrokeStyle(0);
172
173 // How transparent does a 1px stroke have to be in order to appear as thin as the real one?
174 float coverage = fStrokeDevWidth;
175
176 fShape = GrShape(path, GrStyle(hairlineStroke, nullptr));
177 fStrokeDevWidth = 1;
178
179 // fShapeConservativeIBounds already accounted for this possibility of inflating the stroke.
180 fColor = fColor * coverage;
181 }
182
183 return analysis;
184 }
185
onCombineIfPossible(GrOp * op,const GrCaps &)186 GrOp::CombineResult GrCCDrawPathsOp::onCombineIfPossible(GrOp* op, const GrCaps&) {
187 GrCCDrawPathsOp* that = op->cast<GrCCDrawPathsOp>();
188 SkASSERT(fOwningPerOpListPaths);
189 SkASSERT(fNumDraws);
190 SkASSERT(!that->fOwningPerOpListPaths || that->fOwningPerOpListPaths == fOwningPerOpListPaths);
191 SkASSERT(that->fNumDraws);
192
193 if (fProcessors != that->fProcessors ||
194 fViewMatrixIfUsingLocalCoords != that->fViewMatrixIfUsingLocalCoords) {
195 return CombineResult::kCannotCombine;
196 }
197
198 fDraws.append(std::move(that->fDraws), &fOwningPerOpListPaths->fAllocator);
199
200 SkDEBUGCODE(fNumDraws += that->fNumDraws);
201 SkDEBUGCODE(that->fNumDraws = 0);
202 return CombineResult::kMerged;
203 }
204
addToOwningPerOpListPaths(sk_sp<GrCCPerOpListPaths> owningPerOpListPaths)205 void GrCCDrawPathsOp::addToOwningPerOpListPaths(sk_sp<GrCCPerOpListPaths> owningPerOpListPaths) {
206 SkASSERT(1 == fNumDraws);
207 SkASSERT(!fOwningPerOpListPaths);
208 fOwningPerOpListPaths = std::move(owningPerOpListPaths);
209 fOwningPerOpListPaths->fDrawOps.addToTail(this);
210 }
211
accountForOwnPaths(GrCCPathCache * pathCache,GrOnFlushResourceProvider * onFlushRP,GrCCPerFlushResourceSpecs * specs)212 void GrCCDrawPathsOp::accountForOwnPaths(GrCCPathCache* pathCache,
213 GrOnFlushResourceProvider* onFlushRP,
214 GrCCPerFlushResourceSpecs* specs) {
215 for (SingleDraw& draw : fDraws) {
216 draw.accountForOwnPath(pathCache, onFlushRP, specs);
217 }
218 }
219
accountForOwnPath(GrCCPathCache * pathCache,GrOnFlushResourceProvider * onFlushRP,GrCCPerFlushResourceSpecs * specs)220 void GrCCDrawPathsOp::SingleDraw::accountForOwnPath(
221 GrCCPathCache* pathCache, GrOnFlushResourceProvider* onFlushRP,
222 GrCCPerFlushResourceSpecs* specs) {
223 using CoverageType = GrCCAtlas::CoverageType;
224
225 SkPath path;
226 fShape.asPath(&path);
227
228 SkASSERT(!fCacheEntry);
229
230 if (pathCache) {
231 fCacheEntry =
232 pathCache->find(onFlushRP, fShape, fMaskDevIBounds, fMatrix, &fCachedMaskShift);
233 }
234
235 if (fCacheEntry) {
236 if (const GrCCCachedAtlas* cachedAtlas = fCacheEntry->cachedAtlas()) {
237 SkASSERT(cachedAtlas->getOnFlushProxy());
238 if (CoverageType::kA8_LiteralCoverage == cachedAtlas->coverageType()) {
239 ++specs->fNumCachedPaths;
240 } else {
241 // Suggest that this path be copied to a literal coverage atlas, to save memory.
242 // (The client may decline this copy via DoCopiesToA8Coverage::kNo.)
243 int idx = (fShape.style().strokeRec().isFillStyle())
244 ? GrCCPerFlushResourceSpecs::kFillIdx
245 : GrCCPerFlushResourceSpecs::kStrokeIdx;
246 ++specs->fNumCopiedPaths[idx];
247 specs->fCopyPathStats[idx].statPath(path);
248 specs->fCopyAtlasSpecs.accountForSpace(fCacheEntry->width(), fCacheEntry->height());
249 fDoCopyToA8Coverage = true;
250 }
251 return;
252 }
253
254 if (this->shouldCachePathMask(onFlushRP->caps()->maxRenderTargetSize())) {
255 fDoCachePathMask = true;
256 // We don't cache partial masks; ensure the bounds include the entire path.
257 fMaskDevIBounds = fShapeConservativeIBounds;
258 }
259 }
260
261 // Plan on rendering this path in a new atlas.
262 int idx = (fShape.style().strokeRec().isFillStyle())
263 ? GrCCPerFlushResourceSpecs::kFillIdx
264 : GrCCPerFlushResourceSpecs::kStrokeIdx;
265 ++specs->fNumRenderedPaths[idx];
266 specs->fRenderedPathStats[idx].statPath(path);
267 specs->fRenderedAtlasSpecs.accountForSpace(fMaskDevIBounds.width(), fMaskDevIBounds.height());
268 }
269
shouldCachePathMask(int maxRenderTargetSize) const270 bool GrCCDrawPathsOp::SingleDraw::shouldCachePathMask(int maxRenderTargetSize) const {
271 SkASSERT(fCacheEntry);
272 SkASSERT(!fCacheEntry->cachedAtlas());
273 if (fCacheEntry->hitCount() <= 1) {
274 return false; // Don't cache a path mask until at least its second hit.
275 }
276
277 int shapeMaxDimension = SkTMax(fShapeConservativeIBounds.height(),
278 fShapeConservativeIBounds.width());
279 if (shapeMaxDimension > maxRenderTargetSize) {
280 return false; // This path isn't cachable.
281 }
282
283 int64_t shapeArea = sk_64_mul(fShapeConservativeIBounds.height(),
284 fShapeConservativeIBounds.width());
285 if (shapeArea < 100*100) {
286 // If a path is small enough, we might as well try to render and cache the entire thing, no
287 // matter how much of it is actually visible.
288 return true;
289 }
290
291 // The hitRect should already be contained within the shape's bounds, but we still intersect it
292 // because it's possible for edges very near pixel boundaries (e.g., 0.999999), to round out
293 // inconsistently, depending on the integer translation values and fp32 precision.
294 SkIRect hitRect = fCacheEntry->hitRect().makeOffset(fCachedMaskShift.x(), fCachedMaskShift.y());
295 hitRect.intersect(fShapeConservativeIBounds);
296
297 // Render and cache the entire path mask if we see enough of it to justify rendering all the
298 // pixels. Our criteria for "enough" is that we must have seen at least 50% of the path in the
299 // past, and in this particular draw we must see at least 10% of it.
300 int64_t hitArea = sk_64_mul(hitRect.height(), hitRect.width());
301 int64_t drawArea = sk_64_mul(fMaskDevIBounds.height(), fMaskDevIBounds.width());
302 return hitArea*2 >= shapeArea && drawArea*10 >= shapeArea;
303 }
304
setupResources(GrCCPathCache * pathCache,GrOnFlushResourceProvider * onFlushRP,GrCCPerFlushResources * resources,DoCopiesToA8Coverage doCopies)305 void GrCCDrawPathsOp::setupResources(
306 GrCCPathCache* pathCache, GrOnFlushResourceProvider* onFlushRP,
307 GrCCPerFlushResources* resources, DoCopiesToA8Coverage doCopies) {
308 SkASSERT(fNumDraws > 0);
309 SkASSERT(-1 == fBaseInstance);
310 fBaseInstance = resources->nextPathInstanceIdx();
311
312 for (SingleDraw& draw : fDraws) {
313 draw.setupResources(pathCache, onFlushRP, resources, doCopies, this);
314 }
315
316 if (!fInstanceRanges.empty()) {
317 fInstanceRanges.back().fEndInstanceIdx = resources->nextPathInstanceIdx();
318 }
319 }
320
setupResources(GrCCPathCache * pathCache,GrOnFlushResourceProvider * onFlushRP,GrCCPerFlushResources * resources,DoCopiesToA8Coverage doCopies,GrCCDrawPathsOp * op)321 void GrCCDrawPathsOp::SingleDraw::setupResources(
322 GrCCPathCache* pathCache, GrOnFlushResourceProvider* onFlushRP,
323 GrCCPerFlushResources* resources, DoCopiesToA8Coverage doCopies, GrCCDrawPathsOp* op) {
324 using DoEvenOddFill = GrCCPathProcessor::DoEvenOddFill;
325
326 SkPath path;
327 fShape.asPath(&path);
328
329 auto doEvenOddFill = DoEvenOddFill(fShape.style().strokeRec().isFillStyle() &&
330 SkPath::kEvenOdd_FillType == path.getFillType());
331 SkASSERT(SkPath::kEvenOdd_FillType == path.getFillType() ||
332 SkPath::kWinding_FillType == path.getFillType());
333
334 if (fCacheEntry) {
335 // Does the path already exist in a cached atlas texture?
336 if (fCacheEntry->cachedAtlas()) {
337 SkASSERT(fCacheEntry->cachedAtlas()->getOnFlushProxy());
338 if (DoCopiesToA8Coverage::kYes == doCopies && fDoCopyToA8Coverage) {
339 resources->upgradeEntryToLiteralCoverageAtlas(pathCache, onFlushRP,
340 fCacheEntry.get(), doEvenOddFill);
341 SkASSERT(fCacheEntry->cachedAtlas());
342 SkASSERT(GrCCAtlas::CoverageType::kA8_LiteralCoverage
343 == fCacheEntry->cachedAtlas()->coverageType());
344 SkASSERT(fCacheEntry->cachedAtlas()->getOnFlushProxy());
345 }
346 #if 0
347 // Simple color manipulation to visualize cached paths.
348 fColor = (GrCCAtlas::CoverageType::kA8_LiteralCoverage
349 == fCacheEntry->cachedAtlas()->coverageType())
350 ? SkPMColor4f{0,0,.25,.25} : SkPMColor4f{0,.25,0,.25};
351 #endif
352 op->recordInstance(fCacheEntry->cachedAtlas()->getOnFlushProxy(),
353 resources->nextPathInstanceIdx());
354 resources->appendDrawPathInstance().set(*fCacheEntry, fCachedMaskShift,
355 SkPMColor4f_toFP16(fColor));
356 return;
357 }
358 }
359
360 // Render the raw path into a coverage count atlas. renderShapeInAtlas() gives us two tight
361 // bounding boxes: One in device space, as well as a second one rotated an additional 45
362 // degrees. The path vertex shader uses these two bounding boxes to generate an octagon that
363 // circumscribes the path.
364 SkRect devBounds, devBounds45;
365 SkIRect devIBounds;
366 SkIVector devToAtlasOffset;
367 if (auto atlas = resources->renderShapeInAtlas(
368 fMaskDevIBounds, fMatrix, fShape, fStrokeDevWidth, &devBounds, &devBounds45,
369 &devIBounds, &devToAtlasOffset)) {
370 op->recordInstance(atlas->textureProxy(), resources->nextPathInstanceIdx());
371 resources->appendDrawPathInstance().set(devBounds, devBounds45, devToAtlasOffset,
372 SkPMColor4f_toFP16(fColor), doEvenOddFill);
373
374 if (fDoCachePathMask) {
375 SkASSERT(fCacheEntry);
376 SkASSERT(!fCacheEntry->cachedAtlas());
377 SkASSERT(fShapeConservativeIBounds == fMaskDevIBounds);
378 fCacheEntry->setCoverageCountAtlas(onFlushRP, atlas, devToAtlasOffset, devBounds,
379 devBounds45, devIBounds, fCachedMaskShift);
380 }
381 }
382 }
383
recordInstance(GrTextureProxy * atlasProxy,int instanceIdx)384 inline void GrCCDrawPathsOp::recordInstance(GrTextureProxy* atlasProxy, int instanceIdx) {
385 if (fInstanceRanges.empty()) {
386 fInstanceRanges.push_back({atlasProxy, instanceIdx});
387 return;
388 }
389 if (fInstanceRanges.back().fAtlasProxy != atlasProxy) {
390 fInstanceRanges.back().fEndInstanceIdx = instanceIdx;
391 fInstanceRanges.push_back({atlasProxy, instanceIdx});
392 return;
393 }
394 }
395
onExecute(GrOpFlushState * flushState,const SkRect & chainBounds)396 void GrCCDrawPathsOp::onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) {
397 SkASSERT(fOwningPerOpListPaths);
398
399 const GrCCPerFlushResources* resources = fOwningPerOpListPaths->fFlushResources.get();
400 if (!resources) {
401 return; // Setup failed.
402 }
403
404 GrPipeline::InitArgs initArgs;
405 initArgs.fCaps = &flushState->caps();
406 initArgs.fResourceProvider = flushState->resourceProvider();
407 initArgs.fDstProxy = flushState->drawOpArgs().fDstProxy;
408 auto clip = flushState->detachAppliedClip();
409 GrPipeline::FixedDynamicState fixedDynamicState(clip.scissorState().rect());
410 GrPipeline pipeline(initArgs, std::move(fProcessors), std::move(clip));
411
412 int baseInstance = fBaseInstance;
413 SkASSERT(baseInstance >= 0); // Make sure setupResources() has been called.
414
415 for (const InstanceRange& range : fInstanceRanges) {
416 SkASSERT(range.fEndInstanceIdx > baseInstance);
417
418 GrCCPathProcessor pathProc(range.fAtlasProxy, fViewMatrixIfUsingLocalCoords);
419 GrTextureProxy* atlasProxy = range.fAtlasProxy;
420 fixedDynamicState.fPrimitiveProcessorTextures = &atlasProxy;
421 pathProc.drawPaths(flushState, pipeline, &fixedDynamicState, *resources, baseInstance,
422 range.fEndInstanceIdx, this->bounds());
423
424 baseInstance = range.fEndInstanceIdx;
425 }
426 }
427