2 * Copyright 2011 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 "GrAAHairLinePathRenderer.h"
11 #include "GrBatchTarget.h"
12 #include "GrBufferAllocPool.h"
13 #include "GrContext.h"
14 #include "GrDefaultGeoProcFactory.h"
15 #include "GrDrawTargetCaps.h"
17 #include "GrIndexBuffer.h"
18 #include "GrPathUtils.h"
19 #include "GrPipelineBuilder.h"
20 #include "GrProcessor.h"
21 #include "SkGeometry.h"
23 #include "SkTemplates.h"
25 #include "effects/GrBezierEffect.h"
27 // quadratics are rendered as 5-sided polys in order to bound the
28 // AA stroke around the center-curve. See comments in push_quad_index_buffer and
29 // bloat_quad. Quadratics and conics share an index buffer
31 // lines are rendered as:
38 // For: 6 vertices and 18 indices (for 6 triangles)
40 // Each quadratic is rendered as a five sided polygon. This poly bounds
41 // the quadratic's bounding triangle but has been expanded so that the
42 // 1-pixel wide area around the curve is inside the poly.
43 // If a,b,c are the original control points then the poly a0,b0,c0,c1,a1
44 // that is rendered would look like this:
51 // Each is drawn as three triangles ((a0,a1,b0), (b0,c1,c0), (a1,c1,b0))
52 // specified by these 9 indices:
53 static const uint16_t kQuadIdxBufPattern[] = {
59 static const int kIdxsPerQuad = SK_ARRAY_COUNT(kQuadIdxBufPattern);
60 static const int kQuadNumVertices = 5;
61 static const int kQuadsNumInIdxBuffer = 256;
64 // Each line segment is rendered as two quads and two triangles.
65 // p0 and p1 have alpha = 1 while all other points have alpha = 0.
66 // The four external points are offset 1 pixel perpendicular to the
67 // line and half a pixel parallel to the line.
73 // Each is drawn as six triangles specified by these 18 indices:
75 static const uint16_t kLineSegIdxBufPattern[] = {
84 static const int kIdxsPerLineSeg = SK_ARRAY_COUNT(kLineSegIdxBufPattern);
85 static const int kLineSegNumVertices = 6;
86 static const int kLineSegsNumInIdxBuffer = 256;
88 GrPathRenderer* GrAAHairLinePathRenderer::Create(GrContext* context) {
89 GrGpu* gpu = context->getGpu();
90 GrIndexBuffer* qIdxBuf = gpu->createInstancedIndexBuffer(kQuadIdxBufPattern,
94 SkAutoTUnref<GrIndexBuffer> qIdxBuffer(qIdxBuf);
95 GrIndexBuffer* lIdxBuf = gpu->createInstancedIndexBuffer(kLineSegIdxBufPattern,
97 kLineSegsNumInIdxBuffer,
99 SkAutoTUnref<GrIndexBuffer> lIdxBuffer(lIdxBuf);
100 return SkNEW_ARGS(GrAAHairLinePathRenderer,
101 (context, lIdxBuf, qIdxBuf));
104 GrAAHairLinePathRenderer::GrAAHairLinePathRenderer(
105 const GrContext* context,
106 const GrIndexBuffer* linesIndexBuffer,
107 const GrIndexBuffer* quadsIndexBuffer) {
108 fLinesIndexBuffer = linesIndexBuffer;
109 linesIndexBuffer->ref();
110 fQuadsIndexBuffer = quadsIndexBuffer;
111 quadsIndexBuffer->ref();
114 GrAAHairLinePathRenderer::~GrAAHairLinePathRenderer() {
115 fLinesIndexBuffer->unref();
116 fQuadsIndexBuffer->unref();
121 #define PREALLOC_PTARRAY(N) SkSTArray<(N),SkPoint, true>
123 // Takes 178th time of logf on Z600 / VC2010
124 int get_float_exp(float x) {
125 GR_STATIC_ASSERT(sizeof(int) == sizeof(float));
130 SkASSERT(get_float_exp(0.25f) == -2);
131 SkASSERT(get_float_exp(0.3f) == -2);
132 SkASSERT(get_float_exp(0.5f) == -1);
133 SkASSERT(get_float_exp(1.f) == 0);
134 SkASSERT(get_float_exp(2.f) == 1);
135 SkASSERT(get_float_exp(2.5f) == 1);
136 SkASSERT(get_float_exp(8.f) == 3);
137 SkASSERT(get_float_exp(100.f) == 6);
138 SkASSERT(get_float_exp(1000.f) == 9);
139 SkASSERT(get_float_exp(1024.f) == 10);
140 SkASSERT(get_float_exp(3000000.f) == 21);
143 const int* iptr = (const int*)&x;
144 return (((*iptr) & 0x7f800000) >> 23) - 127;
147 // Uses the max curvature function for quads to estimate
148 // where to chop the conic. If the max curvature is not
149 // found along the curve segment it will return 1 and
150 // dst[0] is the original conic. If it returns 2 the dst[0]
151 // and dst[1] are the two new conics.
152 int split_conic(const SkPoint src[3], SkConic dst[2], const SkScalar weight) {
153 SkScalar t = SkFindQuadMaxCurvature(src);
156 dst[0].set(src, weight);
162 conic.set(src, weight);
163 conic.chopAt(t, dst);
169 // Calls split_conic on the entire conic and then once more on each subsection.
170 // Most cases will result in either 1 conic (chop point is not within t range)
171 // or 3 points (split once and then one subsection is split again).
172 int chop_conic(const SkPoint src[3], SkConic dst[4], const SkScalar weight) {
174 int conicCnt = split_conic(src, dstTemp, weight);
176 int conicCnt2 = split_conic(dstTemp[0].fPts, dst, dstTemp[0].fW);
177 conicCnt = conicCnt2 + split_conic(dstTemp[1].fPts, &dst[conicCnt2], dstTemp[1].fW);
184 // returns 0 if quad/conic is degen or close to it
185 // in this case approx the path with lines
186 // otherwise returns 1
187 int is_degen_quad_or_conic(const SkPoint p[3], SkScalar* dsqd) {
188 static const SkScalar gDegenerateToLineTol = SK_Scalar1;
189 static const SkScalar gDegenerateToLineTolSqd =
190 SkScalarMul(gDegenerateToLineTol, gDegenerateToLineTol);
192 if (p[0].distanceToSqd(p[1]) < gDegenerateToLineTolSqd ||
193 p[1].distanceToSqd(p[2]) < gDegenerateToLineTolSqd) {
197 *dsqd = p[1].distanceToLineBetweenSqd(p[0], p[2]);
198 if (*dsqd < gDegenerateToLineTolSqd) {
202 if (p[2].distanceToLineBetweenSqd(p[1], p[0]) < gDegenerateToLineTolSqd) {
208 int is_degen_quad_or_conic(const SkPoint p[3]) {
210 return is_degen_quad_or_conic(p, &dsqd);
213 // we subdivide the quads to avoid huge overfill
214 // if it returns -1 then should be drawn as lines
215 int num_quad_subdivs(const SkPoint p[3]) {
217 if (is_degen_quad_or_conic(p, &dsqd)) {
221 // tolerance of triangle height in pixels
222 // tuned on windows Quadro FX 380 / Z600
223 // trade off of fill vs cpu time on verts
224 // maybe different when do this using gpu (geo or tess shaders)
225 static const SkScalar gSubdivTol = 175 * SK_Scalar1;
227 if (dsqd <= SkScalarMul(gSubdivTol, gSubdivTol)) {
230 static const int kMaxSub = 4;
231 // subdividing the quad reduces d by 4. so we want x = log4(d/tol)
232 // = log4(d*d/tol*tol)/2
233 // = log2(d*d/tol*tol)
235 // +1 since we're ignoring the mantissa contribution.
236 int log = get_float_exp(dsqd/(gSubdivTol*gSubdivTol)) + 1;
237 log = SkTMin(SkTMax(0, log), kMaxSub);
243 * Generates the lines and quads to be rendered. Lines are always recorded in
244 * device space. We will do a device space bloat to account for the 1pixel
246 * Quads are recorded in device space unless m contains
247 * perspective, then in they are in src space. We do this because we will
248 * subdivide large quads to reduce over-fill. This subdivision has to be
249 * performed before applying the perspective matrix.
251 int gather_lines_and_quads(const SkPath& path,
253 const SkIRect& devClipBounds,
254 GrAAHairLinePathRenderer::PtArray* lines,
255 GrAAHairLinePathRenderer::PtArray* quads,
256 GrAAHairLinePathRenderer::PtArray* conics,
257 GrAAHairLinePathRenderer::IntArray* quadSubdivCnts,
258 GrAAHairLinePathRenderer::FloatArray* conicWeights) {
259 SkPath::Iter iter(path, false);
261 int totalQuadCount = 0;
265 bool persp = m.hasPerspective();
270 SkPath::Verb verb = iter.next(pathPts);
272 case SkPath::kConic_Verb: {
274 // We chop the conics to create tighter clipping to hide error
275 // that appears near max curvature of very thin conics. Thin
276 // hyperbolas with high weight still show error.
277 int conicCnt = chop_conic(pathPts, dst, iter.conicWeight());
278 for (int i = 0; i < conicCnt; ++i) {
279 SkPoint* chopPnts = dst[i].fPts;
280 m.mapPoints(devPts, chopPnts, 3);
281 bounds.setBounds(devPts, 3);
282 bounds.outset(SK_Scalar1, SK_Scalar1);
283 bounds.roundOut(&ibounds);
284 if (SkIRect::Intersects(devClipBounds, ibounds)) {
285 if (is_degen_quad_or_conic(devPts)) {
286 SkPoint* pts = lines->push_back_n(4);
292 // when in perspective keep conics in src space
293 SkPoint* cPts = persp ? chopPnts : devPts;
294 SkPoint* pts = conics->push_back_n(3);
298 conicWeights->push_back() = dst[i].fW;
304 case SkPath::kMove_Verb:
306 case SkPath::kLine_Verb:
307 m.mapPoints(devPts, pathPts, 2);
308 bounds.setBounds(devPts, 2);
309 bounds.outset(SK_Scalar1, SK_Scalar1);
310 bounds.roundOut(&ibounds);
311 if (SkIRect::Intersects(devClipBounds, ibounds)) {
312 SkPoint* pts = lines->push_back_n(2);
317 case SkPath::kQuad_Verb: {
318 SkPoint choppedPts[5];
319 // Chopping the quad helps when the quad is either degenerate or nearly degenerate.
320 // When it is degenerate it allows the approximation with lines to work since the
321 // chop point (if there is one) will be at the parabola's vertex. In the nearly
322 // degenerate the QuadUVMatrix computed for the points is almost singular which
323 // can cause rendering artifacts.
324 int n = SkChopQuadAtMaxCurvature(pathPts, choppedPts);
325 for (int i = 0; i < n; ++i) {
326 SkPoint* quadPts = choppedPts + i * 2;
327 m.mapPoints(devPts, quadPts, 3);
328 bounds.setBounds(devPts, 3);
329 bounds.outset(SK_Scalar1, SK_Scalar1);
330 bounds.roundOut(&ibounds);
332 if (SkIRect::Intersects(devClipBounds, ibounds)) {
333 int subdiv = num_quad_subdivs(devPts);
334 SkASSERT(subdiv >= -1);
336 SkPoint* pts = lines->push_back_n(4);
342 // when in perspective keep quads in src space
343 SkPoint* qPts = persp ? quadPts : devPts;
344 SkPoint* pts = quads->push_back_n(3);
348 quadSubdivCnts->push_back() = subdiv;
349 totalQuadCount += 1 << subdiv;
355 case SkPath::kCubic_Verb:
356 m.mapPoints(devPts, pathPts, 4);
357 bounds.setBounds(devPts, 4);
358 bounds.outset(SK_Scalar1, SK_Scalar1);
359 bounds.roundOut(&ibounds);
360 if (SkIRect::Intersects(devClipBounds, ibounds)) {
361 PREALLOC_PTARRAY(32) q;
362 // we don't need a direction if we aren't constraining the subdivision
363 static const SkPath::Direction kDummyDir = SkPath::kCCW_Direction;
364 // We convert cubics to quadratics (for now).
365 // In perspective have to do conversion in src space.
368 GrPathUtils::scaleToleranceToSrc(SK_Scalar1, m,
370 GrPathUtils::convertCubicToQuads(pathPts, tolScale, false, kDummyDir, &q);
372 GrPathUtils::convertCubicToQuads(devPts, SK_Scalar1, false, kDummyDir, &q);
374 for (int i = 0; i < q.count(); i += 3) {
375 SkPoint* qInDevSpace;
376 // bounds has to be calculated in device space, but q is
377 // in src space when there is perspective.
379 m.mapPoints(devPts, &q[i], 3);
380 bounds.setBounds(devPts, 3);
381 qInDevSpace = devPts;
383 bounds.setBounds(&q[i], 3);
386 bounds.outset(SK_Scalar1, SK_Scalar1);
387 bounds.roundOut(&ibounds);
388 if (SkIRect::Intersects(devClipBounds, ibounds)) {
389 int subdiv = num_quad_subdivs(qInDevSpace);
390 SkASSERT(subdiv >= -1);
392 SkPoint* pts = lines->push_back_n(4);
393 // lines should always be in device coords
394 pts[0] = qInDevSpace[0];
395 pts[1] = qInDevSpace[1];
396 pts[2] = qInDevSpace[1];
397 pts[3] = qInDevSpace[2];
399 SkPoint* pts = quads->push_back_n(3);
400 // q is already in src space when there is no
401 // perspective and dev coords otherwise.
405 quadSubdivCnts->push_back() = subdiv;
406 totalQuadCount += 1 << subdiv;
412 case SkPath::kClose_Verb:
414 case SkPath::kDone_Verb:
415 return totalQuadCount;
425 struct BezierVertex {
440 GR_STATIC_ASSERT(sizeof(BezierVertex) == 3 * sizeof(SkPoint));
442 void intersect_lines(const SkPoint& ptA, const SkVector& normA,
443 const SkPoint& ptB, const SkVector& normB,
446 SkScalar lineAW = -normA.dot(ptA);
447 SkScalar lineBW = -normB.dot(ptB);
449 SkScalar wInv = SkScalarMul(normA.fX, normB.fY) -
450 SkScalarMul(normA.fY, normB.fX);
451 wInv = SkScalarInvert(wInv);
453 result->fX = SkScalarMul(normA.fY, lineBW) - SkScalarMul(lineAW, normB.fY);
454 result->fX = SkScalarMul(result->fX, wInv);
456 result->fY = SkScalarMul(lineAW, normB.fX) - SkScalarMul(normA.fX, lineBW);
457 result->fY = SkScalarMul(result->fY, wInv);
460 void set_uv_quad(const SkPoint qpts[3], BezierVertex verts[kQuadNumVertices]) {
461 // this should be in the src space, not dev coords, when we have perspective
462 GrPathUtils::QuadUVMatrix DevToUV(qpts);
463 DevToUV.apply<kQuadNumVertices, sizeof(BezierVertex), sizeof(SkPoint)>(verts);
466 void bloat_quad(const SkPoint qpts[3], const SkMatrix* toDevice,
467 const SkMatrix* toSrc, BezierVertex verts[kQuadNumVertices]) {
468 SkASSERT(!toDevice == !toSrc);
469 // original quad is specified by tri a,b,c
475 toDevice->mapPoints(&a, 1);
476 toDevice->mapPoints(&b, 1);
477 toDevice->mapPoints(&c, 1);
479 // make a new poly where we replace a and c by a 1-pixel wide edges orthog
480 // to edges ab and bc:
489 // edges a0->b0 and b0->c0 are parallel to original edges a->b and b->c,
491 BezierVertex& a0 = verts[0];
492 BezierVertex& a1 = verts[1];
493 BezierVertex& b0 = verts[2];
494 BezierVertex& c0 = verts[3];
495 BezierVertex& c1 = verts[4];
504 // We should have already handled degenerates
505 SkASSERT(ab.length() > 0 && cb.length() > 0);
509 abN.setOrthog(ab, SkVector::kLeft_Side);
510 if (abN.dot(ac) > 0) {
516 cbN.setOrthog(cb, SkVector::kLeft_Side);
517 if (cbN.dot(ac) < 0) {
531 intersect_lines(a0.fPos, abN, c0.fPos, cbN, &b0.fPos);
534 toSrc->mapPointsWithStride(&verts[0].fPos, sizeof(BezierVertex), kQuadNumVertices);
538 // Equations based off of Loop-Blinn Quadratic GPU Rendering
540 // P(t) = (P0*(1-t)^2 + 2*w*P1*t*(1-t) + P2*t^2) / (1-t)^2 + 2*w*t*(1-t) + t^2)
542 // f(x, y, w) = f(P) = K^2 - LM
543 // K = dot(k, P), L = dot(l, P), M = dot(m, P)
544 // k, l, m are calculated in function GrPathUtils::getConicKLM
545 void set_conic_coeffs(const SkPoint p[3], BezierVertex verts[kQuadNumVertices],
546 const SkScalar weight) {
549 GrPathUtils::getConicKLM(p, weight, klm);
551 for (int i = 0; i < kQuadNumVertices; ++i) {
552 const SkPoint pnt = verts[i].fPos;
553 verts[i].fConic.fK = pnt.fX * klm[0] + pnt.fY * klm[1] + klm[2];
554 verts[i].fConic.fL = pnt.fX * klm[3] + pnt.fY * klm[4] + klm[5];
555 verts[i].fConic.fM = pnt.fX * klm[6] + pnt.fY * klm[7] + klm[8];
559 void add_conics(const SkPoint p[3],
560 const SkScalar weight,
561 const SkMatrix* toDevice,
562 const SkMatrix* toSrc,
563 BezierVertex** vert) {
564 bloat_quad(p, toDevice, toSrc, *vert);
565 set_conic_coeffs(p, *vert, weight);
566 *vert += kQuadNumVertices;
569 void add_quads(const SkPoint p[3],
571 const SkMatrix* toDevice,
572 const SkMatrix* toSrc,
573 BezierVertex** vert) {
574 SkASSERT(subdiv >= 0);
577 SkChopQuadAtHalf(p, newP);
578 add_quads(newP + 0, subdiv-1, toDevice, toSrc, vert);
579 add_quads(newP + 2, subdiv-1, toDevice, toSrc, vert);
581 bloat_quad(p, toDevice, toSrc, *vert);
582 set_uv_quad(p, *vert);
583 *vert += kQuadNumVertices;
587 void add_line(const SkPoint p[2],
588 const SkMatrix* toSrc,
591 const SkPoint& a = p[0];
592 const SkPoint& b = p[1];
594 SkVector ortho, vec = b;
597 if (vec.setLength(SK_ScalarHalf)) {
598 // Create a vector orthogonal to 'vec' and of unit length
599 ortho.fX = 2.0f * vec.fY;
600 ortho.fY = -2.0f * vec.fX;
602 float floatCoverage = GrNormalizeByteToFloat(coverage);
605 (*vert)[0].fCoverage = floatCoverage;
607 (*vert)[1].fCoverage = floatCoverage;
608 (*vert)[2].fPos = a - vec + ortho;
609 (*vert)[2].fCoverage = 0;
610 (*vert)[3].fPos = b + vec + ortho;
611 (*vert)[3].fCoverage = 0;
612 (*vert)[4].fPos = a - vec - ortho;
613 (*vert)[4].fCoverage = 0;
614 (*vert)[5].fPos = b + vec - ortho;
615 (*vert)[5].fCoverage = 0;
618 toSrc->mapPointsWithStride(&(*vert)->fPos,
620 kLineSegNumVertices);
623 // just make it degenerate and likely offscreen
624 for (int i = 0; i < kLineSegNumVertices; ++i) {
625 (*vert)[i].fPos.set(SK_ScalarMax, SK_ScalarMax);
629 *vert += kLineSegNumVertices;
634 ///////////////////////////////////////////////////////////////////////////////
636 bool GrAAHairLinePathRenderer::canDrawPath(const GrDrawTarget* target,
637 const GrPipelineBuilder* pipelineBuilder,
638 const SkMatrix& viewMatrix,
640 const SkStrokeRec& stroke,
641 bool antiAlias) const {
646 if (!IsStrokeHairlineOrEquivalent(stroke, viewMatrix, NULL)) {
650 if (SkPath::kLine_SegmentMask == path.getSegmentMasks() ||
651 target->caps()->shaderDerivativeSupport()) {
657 template <class VertexType>
658 bool check_bounds(const SkMatrix& viewMatrix, const SkRect& devBounds, void* vertices, int vCount)
660 SkRect tolDevBounds = devBounds;
661 // The bounds ought to be tight, but in perspective the below code runs the verts
662 // through the view matrix to get back to dev coords, which can introduce imprecision.
663 if (viewMatrix.hasPerspective()) {
664 tolDevBounds.outset(SK_Scalar1 / 1000, SK_Scalar1 / 1000);
666 // Non-persp matrices cause this path renderer to draw in device space.
667 SkASSERT(viewMatrix.isIdentity());
671 VertexType* verts = reinterpret_cast<VertexType*>(vertices);
673 for (int i = 0; i < vCount; ++i) {
674 SkPoint pos = verts[i].fPos;
675 // This is a hack to workaround the fact that we move some degenerate segments offscreen.
676 if (SK_ScalarMax == pos.fX) {
679 viewMatrix.mapPoints(&pos, 1);
681 actualBounds.set(pos.fX, pos.fY, pos.fX, pos.fY);
684 actualBounds.growToInclude(pos.fX, pos.fY);
688 return tolDevBounds.contains(actualBounds);
694 class AAHairlineBatch : public GrBatch {
699 SkMatrix fViewMatrix;
701 SkDEBUGCODE(SkRect fDevBounds;)
702 SkIRect fDevClipBounds;
705 // TODO Batch itself should not hold on to index buffers. Instead, these should live in the
707 static GrBatch* Create(const Geometry& geometry, const GrIndexBuffer* linesIndexBuffer,
708 const GrIndexBuffer* quadsIndexBuffer) {
709 return SkNEW_ARGS(AAHairlineBatch, (geometry, linesIndexBuffer, quadsIndexBuffer));
712 const char* name() const override { return "AAHairlineBatch"; }
714 void getInvariantOutputColor(GrInitInvariantOutput* out) const override {
715 // When this is called on a batch, there is only one geometry bundle
716 out->setKnownFourComponents(fGeoData[0].fColor);
718 void getInvariantOutputCoverage(GrInitInvariantOutput* out) const override {
719 out->setUnknownSingleComponent();
722 void initBatchTracker(const GrPipelineInfo& init) override {
723 // Handle any color overrides
724 if (init.fColorIgnored) {
725 fGeoData[0].fColor = GrColor_ILLEGAL;
726 } else if (GrColor_ILLEGAL != init.fOverrideColor) {
727 fGeoData[0].fColor = init.fOverrideColor;
730 // setup batch properties
731 fBatch.fColorIgnored = init.fColorIgnored;
732 fBatch.fColor = fGeoData[0].fColor;
733 fBatch.fUsesLocalCoords = init.fUsesLocalCoords;
734 fBatch.fCoverageIgnored = init.fCoverageIgnored;
735 fBatch.fCoverage = fGeoData[0].fCoverage;
736 SkDEBUGCODE(fBatch.fDevBounds = fGeoData[0].fDevBounds;)
739 void generateGeometry(GrBatchTarget* batchTarget, const GrPipeline* pipeline) override;
741 SkSTArray<1, Geometry, true>* geoData() { return &fGeoData; }
744 typedef SkTArray<SkPoint, true> PtArray;
745 typedef SkTArray<int, true> IntArray;
746 typedef SkTArray<float, true> FloatArray;
748 AAHairlineBatch(const Geometry& geometry, const GrIndexBuffer* linesIndexBuffer,
749 const GrIndexBuffer* quadsIndexBuffer)
750 : fLinesIndexBuffer(linesIndexBuffer)
751 , fQuadsIndexBuffer(quadsIndexBuffer) {
752 SkASSERT(linesIndexBuffer && quadsIndexBuffer);
753 this->initClassID<AAHairlineBatch>();
754 fGeoData.push_back(geometry);
757 bool onCombineIfPossible(GrBatch* t) override {
758 AAHairlineBatch* that = t->cast<AAHairlineBatch>();
760 if (this->viewMatrix().hasPerspective() != that->viewMatrix().hasPerspective()) {
764 // We go to identity if we don't have perspective
765 if (this->viewMatrix().hasPerspective() &&
766 !this->viewMatrix().cheapEqualTo(that->viewMatrix())) {
770 // TODO we can actually batch hairlines if they are the same color in a kind of bulk method
771 // but we haven't implemented this yet
772 // TODO investigate going to vertex color and coverage?
773 if (this->coverage() != that->coverage()) {
777 if (this->color() != that->color()) {
781 SkASSERT(this->usesLocalCoords() == that->usesLocalCoords());
782 if (this->usesLocalCoords() && !this->viewMatrix().cheapEqualTo(that->viewMatrix())) {
786 fGeoData.push_back_n(that->geoData()->count(), that->geoData()->begin());
790 GrColor color() const { return fBatch.fColor; }
791 uint8_t coverage() const { return fBatch.fCoverage; }
792 bool usesLocalCoords() const { return fBatch.fUsesLocalCoords; }
793 const SkMatrix& viewMatrix() const { return fGeoData[0].fViewMatrix; }
795 struct BatchTracker {
799 bool fUsesLocalCoords;
801 bool fCoverageIgnored;
805 SkSTArray<1, Geometry, true> fGeoData;
806 const GrIndexBuffer* fLinesIndexBuffer;
807 const GrIndexBuffer* fQuadsIndexBuffer;
810 void AAHairlineBatch::generateGeometry(GrBatchTarget* batchTarget, const GrPipeline* pipeline) {
811 // Setup the viewmatrix and localmatrix for the GrGeometryProcessor.
813 if (!this->viewMatrix().invert(&invert)) {
817 // we will transform to identity space if the viewmatrix does not have perspective
818 bool hasPerspective = this->viewMatrix().hasPerspective();
819 const SkMatrix* geometryProcessorViewM = &SkMatrix::I();
820 const SkMatrix* geometryProcessorLocalM = &invert;
821 const SkMatrix* toDevice = NULL;
822 const SkMatrix* toSrc = NULL;
823 if (hasPerspective) {
824 geometryProcessorViewM = &this->viewMatrix();
825 geometryProcessorLocalM = &SkMatrix::I();
826 toDevice = &this->viewMatrix();
830 // Setup geometry processors for worst case
831 uint32_t gpFlags = GrDefaultGeoProcFactory::kPosition_GPType |
832 GrDefaultGeoProcFactory::kCoverage_GPType;
834 SkAutoTUnref<const GrGeometryProcessor> lineGP(
835 GrDefaultGeoProcFactory::Create(gpFlags,
837 *geometryProcessorViewM,
838 *geometryProcessorLocalM,
842 SkAutoTUnref<const GrGeometryProcessor> quadGP(
843 GrQuadEffect::Create(this->color(),
844 *geometryProcessorViewM,
845 kHairlineAA_GrProcessorEdgeType,
847 *geometryProcessorLocalM,
850 SkAutoTUnref<const GrGeometryProcessor> conicGP(
851 GrConicEffect::Create(this->color(),
852 *geometryProcessorViewM,
853 kHairlineAA_GrProcessorEdgeType,
855 *geometryProcessorLocalM,
858 // This is hand inlined for maximum performance.
859 PREALLOC_PTARRAY(128) lines;
860 PREALLOC_PTARRAY(128) quads;
861 PREALLOC_PTARRAY(128) conics;
866 int instanceCount = fGeoData.count();
867 for (int i = 0; i < instanceCount; i++) {
868 const Geometry& args = fGeoData[i];
869 quadCount += gather_lines_and_quads(args.fPath, args.fViewMatrix, args.fDevClipBounds,
870 &lines, &quads, &conics, &qSubdivs, &cWeights);
873 int lineCount = lines.count() / 2;
874 int conicCount = conics.count() / 3;
878 batchTarget->initDraw(lineGP, pipeline);
880 // TODO remove this when batch is everywhere
882 init.fColorIgnored = fBatch.fColorIgnored;
883 init.fOverrideColor = GrColor_ILLEGAL;
884 init.fCoverageIgnored = fBatch.fCoverageIgnored;
885 init.fUsesLocalCoords = this->usesLocalCoords();
886 lineGP->initBatchTracker(batchTarget->currentBatchTracker(), init);
888 const GrVertexBuffer* vertexBuffer;
891 size_t vertexStride = lineGP->getVertexStride();
892 int vertexCount = kLineSegNumVertices * lineCount;
893 void *vertices = batchTarget->vertexPool()->makeSpace(vertexStride,
899 SkDebugf("Could not allocate vertices\n");
903 SkASSERT(lineGP->getVertexStride() == sizeof(LineVertex));
905 LineVertex* verts = reinterpret_cast<LineVertex*>(vertices);
906 for (int i = 0; i < lineCount; ++i) {
907 add_line(&lines[2*i], toSrc, this->coverage(), &verts);
911 GrDrawTarget::DrawInfo info;
912 info.setVertexBuffer(vertexBuffer);
913 info.setIndexBuffer(fLinesIndexBuffer);
914 info.setPrimitiveType(kTriangles_GrPrimitiveType);
915 info.setStartIndex(0);
918 while (lines < lineCount) {
919 int n = SkTMin(lineCount - lines, kLineSegsNumInIdxBuffer);
921 info.setStartVertex(kLineSegNumVertices*lines + firstVertex);
922 info.setVertexCount(kLineSegNumVertices*n);
923 info.setIndexCount(kIdxsPerLineSeg*n);
924 batchTarget->draw(info);
931 if (quadCount || conicCount) {
932 const GrVertexBuffer* vertexBuffer;
935 size_t vertexStride = sizeof(BezierVertex);
936 int vertexCount = kQuadNumVertices * quadCount + kQuadNumVertices * conicCount;
937 void *vertices = batchTarget->vertexPool()->makeSpace(vertexStride,
943 SkDebugf("Could not allocate vertices\n");
948 BezierVertex* verts = reinterpret_cast<BezierVertex*>(vertices);
950 int unsubdivQuadCnt = quads.count() / 3;
951 for (int i = 0; i < unsubdivQuadCnt; ++i) {
952 SkASSERT(qSubdivs[i] >= 0);
953 add_quads(&quads[3*i], qSubdivs[i], toDevice, toSrc, &verts);
957 for (int i = 0; i < conicCount; ++i) {
958 add_conics(&conics[3*i], cWeights[i], toDevice, toSrc, &verts);
962 batchTarget->initDraw(quadGP, pipeline);
964 // TODO remove this when batch is everywhere
966 init.fColorIgnored = fBatch.fColorIgnored;
967 init.fOverrideColor = GrColor_ILLEGAL;
968 init.fCoverageIgnored = fBatch.fCoverageIgnored;
969 init.fUsesLocalCoords = this->usesLocalCoords();
970 quadGP->initBatchTracker(batchTarget->currentBatchTracker(), init);
973 GrDrawTarget::DrawInfo info;
974 info.setVertexBuffer(vertexBuffer);
975 info.setIndexBuffer(fQuadsIndexBuffer);
976 info.setPrimitiveType(kTriangles_GrPrimitiveType);
977 info.setStartIndex(0);
980 while (quads < quadCount) {
981 int n = SkTMin(quadCount - quads, kQuadsNumInIdxBuffer);
983 info.setStartVertex(kQuadNumVertices*quads + firstVertex);
984 info.setVertexCount(kQuadNumVertices*n);
985 info.setIndexCount(kIdxsPerQuad*n);
986 batchTarget->draw(info);
993 if (conicCount > 0) {
994 batchTarget->initDraw(conicGP, pipeline);
996 // TODO remove this when batch is everywhere
998 init.fColorIgnored = fBatch.fColorIgnored;
999 init.fOverrideColor = GrColor_ILLEGAL;
1000 init.fCoverageIgnored = fBatch.fCoverageIgnored;
1001 init.fUsesLocalCoords = this->usesLocalCoords();
1002 conicGP->initBatchTracker(batchTarget->currentBatchTracker(), init);
1005 GrDrawTarget::DrawInfo info;
1006 info.setVertexBuffer(vertexBuffer);
1007 info.setIndexBuffer(fQuadsIndexBuffer);
1008 info.setPrimitiveType(kTriangles_GrPrimitiveType);
1009 info.setStartIndex(0);
1012 while (conics < conicCount) {
1013 int n = SkTMin(conicCount - conics, kQuadsNumInIdxBuffer);
1015 info.setStartVertex(kQuadNumVertices*(quadCount + conics) + firstVertex);
1016 info.setVertexCount(kQuadNumVertices*n);
1017 info.setIndexCount(kIdxsPerQuad*n);
1018 batchTarget->draw(info);
1027 bool GrAAHairLinePathRenderer::onDrawPath(GrDrawTarget* target,
1028 GrPipelineBuilder* pipelineBuilder,
1030 const SkMatrix& viewMatrix,
1032 const SkStrokeRec& stroke,
1034 if (!fLinesIndexBuffer || !fQuadsIndexBuffer) {
1035 SkDebugf("unable to allocate indices\n");
1039 SkScalar hairlineCoverage;
1040 uint8_t newCoverage = 0xff;
1041 if (IsStrokeHairlineOrEquivalent(stroke, viewMatrix, &hairlineCoverage)) {
1042 newCoverage = SkScalarRoundToInt(hairlineCoverage * 0xff);
1045 SkIRect devClipBounds;
1046 pipelineBuilder->clip().getConservativeBounds(pipelineBuilder->getRenderTarget(),
1049 // This outset was determined experimentally by running skps and gms. It probably could be a
1051 SkRect devRect = path.getBounds();
1052 viewMatrix.mapRect(&devRect);
1053 devRect.outset(2, 2);
1055 AAHairlineBatch::Geometry geometry;
1056 geometry.fColor = color;
1057 geometry.fCoverage = newCoverage;
1058 geometry.fViewMatrix = viewMatrix;
1059 geometry.fPath = path;
1060 SkDEBUGCODE(geometry.fDevBounds = devRect;)
1061 geometry.fDevClipBounds = devClipBounds;
1063 SkAutoTUnref<GrBatch> batch(AAHairlineBatch::Create(geometry, fLinesIndexBuffer,
1064 fQuadsIndexBuffer));
1065 target->drawBatch(pipelineBuilder, batch, &devRect);