1 /* 2 * Copyright 2011 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 "GrAAHairLinePathRenderer.h" 9 #include "GrBuffer.h" 10 #include "GrCaps.h" 11 #include "GrClip.h" 12 #include "GrContext.h" 13 #include "GrDefaultGeoProcFactory.h" 14 #include "GrDrawOpTest.h" 15 #include "GrOpFlushState.h" 16 #include "GrPathUtils.h" 17 #include "GrProcessor.h" 18 #include "GrResourceProvider.h" 19 #include "GrSimpleMeshDrawOpHelper.h" 20 #include "SkGeometry.h" 21 #include "SkStroke.h" 22 #include "SkTemplates.h" 23 #include "effects/GrBezierEffect.h" 24 #include "ops/GrMeshDrawOp.h" 25 26 #define PREALLOC_PTARRAY(N) SkSTArray<(N),SkPoint, true> 27 28 // quadratics are rendered as 5-sided polys in order to bound the 29 // AA stroke around the center-curve. See comments in push_quad_index_buffer and 30 // bloat_quad. Quadratics and conics share an index buffer 31 32 // lines are rendered as: 33 // *______________* 34 // |\ -_______ /| 35 // | \ \ / | 36 // | *--------* | 37 // | / ______/ \ | 38 // */_-__________\* 39 // For: 6 vertices and 18 indices (for 6 triangles) 40 41 // Each quadratic is rendered as a five sided polygon. This poly bounds 42 // the quadratic's bounding triangle but has been expanded so that the 43 // 1-pixel wide area around the curve is inside the poly. 44 // If a,b,c are the original control points then the poly a0,b0,c0,c1,a1 45 // that is rendered would look like this: 46 // b0 47 // b 48 // 49 // a0 c0 50 // a c 51 // a1 c1 52 // Each is drawn as three triangles ((a0,a1,b0), (b0,c1,c0), (a1,c1,b0)) 53 // specified by these 9 indices: 54 static const uint16_t kQuadIdxBufPattern[] = { 55 0, 1, 2, 56 2, 4, 3, 57 1, 4, 2 58 }; 59 60 static const int kIdxsPerQuad = SK_ARRAY_COUNT(kQuadIdxBufPattern); 61 static const int kQuadNumVertices = 5; 62 static const int kQuadsNumInIdxBuffer = 256; 63 GR_DECLARE_STATIC_UNIQUE_KEY(gQuadsIndexBufferKey); 64 65 static const GrBuffer* ref_quads_index_buffer(GrResourceProvider* resourceProvider) { 66 GR_DEFINE_STATIC_UNIQUE_KEY(gQuadsIndexBufferKey); 67 return resourceProvider->findOrCreatePatternedIndexBuffer( 68 kQuadIdxBufPattern, kIdxsPerQuad, kQuadsNumInIdxBuffer, kQuadNumVertices, 69 gQuadsIndexBufferKey); 70 } 71 72 73 // Each line segment is rendered as two quads and two triangles. 74 // p0 and p1 have alpha = 1 while all other points have alpha = 0. 75 // The four external points are offset 1 pixel perpendicular to the 76 // line and half a pixel parallel to the line. 77 // 78 // p4 p5 79 // p0 p1 80 // p2 p3 81 // 82 // Each is drawn as six triangles specified by these 18 indices: 83 84 static const uint16_t kLineSegIdxBufPattern[] = { 85 0, 1, 3, 86 0, 3, 2, 87 0, 4, 5, 88 0, 5, 1, 89 0, 2, 4, 90 1, 5, 3 91 }; 92 93 static const int kIdxsPerLineSeg = SK_ARRAY_COUNT(kLineSegIdxBufPattern); 94 static const int kLineSegNumVertices = 6; 95 static const int kLineSegsNumInIdxBuffer = 256; 96 97 GR_DECLARE_STATIC_UNIQUE_KEY(gLinesIndexBufferKey); 98 99 static const GrBuffer* ref_lines_index_buffer(GrResourceProvider* resourceProvider) { 100 GR_DEFINE_STATIC_UNIQUE_KEY(gLinesIndexBufferKey); 101 return resourceProvider->findOrCreatePatternedIndexBuffer( 102 kLineSegIdxBufPattern, kIdxsPerLineSeg, kLineSegsNumInIdxBuffer, kLineSegNumVertices, 103 gLinesIndexBufferKey); 104 } 105 106 // Takes 178th time of logf on Z600 / VC2010 107 static int get_float_exp(float x) { 108 GR_STATIC_ASSERT(sizeof(int) == sizeof(float)); 109 #ifdef SK_DEBUG 110 static bool tested; 111 if (!tested) { 112 tested = true; 113 SkASSERT(get_float_exp(0.25f) == -2); 114 SkASSERT(get_float_exp(0.3f) == -2); 115 SkASSERT(get_float_exp(0.5f) == -1); 116 SkASSERT(get_float_exp(1.f) == 0); 117 SkASSERT(get_float_exp(2.f) == 1); 118 SkASSERT(get_float_exp(2.5f) == 1); 119 SkASSERT(get_float_exp(8.f) == 3); 120 SkASSERT(get_float_exp(100.f) == 6); 121 SkASSERT(get_float_exp(1000.f) == 9); 122 SkASSERT(get_float_exp(1024.f) == 10); 123 SkASSERT(get_float_exp(3000000.f) == 21); 124 } 125 #endif 126 const int* iptr = (const int*)&x; 127 return (((*iptr) & 0x7f800000) >> 23) - 127; 128 } 129 130 // Uses the max curvature function for quads to estimate 131 // where to chop the conic. If the max curvature is not 132 // found along the curve segment it will return 1 and 133 // dst[0] is the original conic. If it returns 2 the dst[0] 134 // and dst[1] are the two new conics. 135 static int split_conic(const SkPoint src[3], SkConic dst[2], const SkScalar weight) { 136 SkScalar t = SkFindQuadMaxCurvature(src); 137 if (t == 0) { 138 if (dst) { 139 dst[0].set(src, weight); 140 } 141 return 1; 142 } else { 143 if (dst) { 144 SkConic conic; 145 conic.set(src, weight); 146 if (!conic.chopAt(t, dst)) { 147 dst[0].set(src, weight); 148 return 1; 149 } 150 } 151 return 2; 152 } 153 } 154 155 // Calls split_conic on the entire conic and then once more on each subsection. 156 // Most cases will result in either 1 conic (chop point is not within t range) 157 // or 3 points (split once and then one subsection is split again). 158 static int chop_conic(const SkPoint src[3], SkConic dst[4], const SkScalar weight) { 159 SkConic dstTemp[2]; 160 int conicCnt = split_conic(src, dstTemp, weight); 161 if (2 == conicCnt) { 162 int conicCnt2 = split_conic(dstTemp[0].fPts, dst, dstTemp[0].fW); 163 conicCnt = conicCnt2 + split_conic(dstTemp[1].fPts, &dst[conicCnt2], dstTemp[1].fW); 164 } else { 165 dst[0] = dstTemp[0]; 166 } 167 return conicCnt; 168 } 169 170 // returns 0 if quad/conic is degen or close to it 171 // in this case approx the path with lines 172 // otherwise returns 1 173 static int is_degen_quad_or_conic(const SkPoint p[3], SkScalar* dsqd) { 174 static const SkScalar gDegenerateToLineTol = GrPathUtils::kDefaultTolerance; 175 static const SkScalar gDegenerateToLineTolSqd = 176 gDegenerateToLineTol * gDegenerateToLineTol; 177 178 if (p[0].distanceToSqd(p[1]) < gDegenerateToLineTolSqd || 179 p[1].distanceToSqd(p[2]) < gDegenerateToLineTolSqd) { 180 return 1; 181 } 182 183 *dsqd = p[1].distanceToLineBetweenSqd(p[0], p[2]); 184 if (*dsqd < gDegenerateToLineTolSqd) { 185 return 1; 186 } 187 188 if (p[2].distanceToLineBetweenSqd(p[1], p[0]) < gDegenerateToLineTolSqd) { 189 return 1; 190 } 191 return 0; 192 } 193 194 static int is_degen_quad_or_conic(const SkPoint p[3]) { 195 SkScalar dsqd; 196 return is_degen_quad_or_conic(p, &dsqd); 197 } 198 199 // we subdivide the quads to avoid huge overfill 200 // if it returns -1 then should be drawn as lines 201 static int num_quad_subdivs(const SkPoint p[3]) { 202 SkScalar dsqd; 203 if (is_degen_quad_or_conic(p, &dsqd)) { 204 return -1; 205 } 206 207 // tolerance of triangle height in pixels 208 // tuned on windows Quadro FX 380 / Z600 209 // trade off of fill vs cpu time on verts 210 // maybe different when do this using gpu (geo or tess shaders) 211 static const SkScalar gSubdivTol = 175 * SK_Scalar1; 212 213 if (dsqd <= gSubdivTol * gSubdivTol) { 214 return 0; 215 } else { 216 static const int kMaxSub = 4; 217 // subdividing the quad reduces d by 4. so we want x = log4(d/tol) 218 // = log4(d*d/tol*tol)/2 219 // = log2(d*d/tol*tol) 220 221 // +1 since we're ignoring the mantissa contribution. 222 int log = get_float_exp(dsqd/(gSubdivTol*gSubdivTol)) + 1; 223 log = SkTMin(SkTMax(0, log), kMaxSub); 224 return log; 225 } 226 } 227 228 /** 229 * Generates the lines and quads to be rendered. Lines are always recorded in 230 * device space. We will do a device space bloat to account for the 1pixel 231 * thickness. 232 * Quads are recorded in device space unless m contains 233 * perspective, then in they are in src space. We do this because we will 234 * subdivide large quads to reduce over-fill. This subdivision has to be 235 * performed before applying the perspective matrix. 236 */ 237 static int gather_lines_and_quads(const SkPath& path, 238 const SkMatrix& m, 239 const SkIRect& devClipBounds, 240 SkScalar capLength, 241 GrAAHairLinePathRenderer::PtArray* lines, 242 GrAAHairLinePathRenderer::PtArray* quads, 243 GrAAHairLinePathRenderer::PtArray* conics, 244 GrAAHairLinePathRenderer::IntArray* quadSubdivCnts, 245 GrAAHairLinePathRenderer::FloatArray* conicWeights) { 246 SkPath::Iter iter(path, false); 247 248 int totalQuadCount = 0; 249 SkRect bounds; 250 SkIRect ibounds; 251 252 bool persp = m.hasPerspective(); 253 254 // Whenever a degenerate, zero-length contour is encountered, this code will insert a 255 // 'capLength' x-aligned line segment. Since this is rendering hairlines it is hoped this will 256 // suffice for AA square & circle capping. 257 int verbsInContour = 0; // Does not count moves 258 bool seenZeroLengthVerb = false; 259 SkPoint zeroVerbPt; 260 261 for (;;) { 262 SkPoint pathPts[4]; 263 SkPoint devPts[4]; 264 SkPath::Verb verb = iter.next(pathPts, false); 265 switch (verb) { 266 case SkPath::kConic_Verb: { 267 SkConic dst[4]; 268 // We chop the conics to create tighter clipping to hide error 269 // that appears near max curvature of very thin conics. Thin 270 // hyperbolas with high weight still show error. 271 int conicCnt = chop_conic(pathPts, dst, iter.conicWeight()); 272 for (int i = 0; i < conicCnt; ++i) { 273 SkPoint* chopPnts = dst[i].fPts; 274 m.mapPoints(devPts, chopPnts, 3); 275 bounds.setBounds(devPts, 3); 276 bounds.outset(SK_Scalar1, SK_Scalar1); 277 bounds.roundOut(&ibounds); 278 if (SkIRect::Intersects(devClipBounds, ibounds)) { 279 if (is_degen_quad_or_conic(devPts)) { 280 SkPoint* pts = lines->push_back_n(4); 281 pts[0] = devPts[0]; 282 pts[1] = devPts[1]; 283 pts[2] = devPts[1]; 284 pts[3] = devPts[2]; 285 if (verbsInContour == 0 && i == 0 && 286 pts[0] == pts[1] && pts[2] == pts[3]) { 287 seenZeroLengthVerb = true; 288 zeroVerbPt = pts[0]; 289 } 290 } else { 291 // when in perspective keep conics in src space 292 SkPoint* cPts = persp ? chopPnts : devPts; 293 SkPoint* pts = conics->push_back_n(3); 294 pts[0] = cPts[0]; 295 pts[1] = cPts[1]; 296 pts[2] = cPts[2]; 297 conicWeights->push_back() = dst[i].fW; 298 } 299 } 300 } 301 verbsInContour++; 302 break; 303 } 304 case SkPath::kMove_Verb: 305 // New contour (and last one was unclosed). If it was just a zero length drawing 306 // operation, and we're supposed to draw caps, then add a tiny line. 307 if (seenZeroLengthVerb && verbsInContour == 1 && capLength > 0) { 308 SkPoint* pts = lines->push_back_n(2); 309 pts[0] = SkPoint::Make(zeroVerbPt.fX - capLength, zeroVerbPt.fY); 310 pts[1] = SkPoint::Make(zeroVerbPt.fX + capLength, zeroVerbPt.fY); 311 } 312 verbsInContour = 0; 313 seenZeroLengthVerb = false; 314 break; 315 case SkPath::kLine_Verb: 316 m.mapPoints(devPts, pathPts, 2); 317 bounds.setBounds(devPts, 2); 318 bounds.outset(SK_Scalar1, SK_Scalar1); 319 bounds.roundOut(&ibounds); 320 if (SkIRect::Intersects(devClipBounds, ibounds)) { 321 SkPoint* pts = lines->push_back_n(2); 322 pts[0] = devPts[0]; 323 pts[1] = devPts[1]; 324 if (verbsInContour == 0 && pts[0] == pts[1]) { 325 seenZeroLengthVerb = true; 326 zeroVerbPt = pts[0]; 327 } 328 } 329 verbsInContour++; 330 break; 331 case SkPath::kQuad_Verb: { 332 SkPoint choppedPts[5]; 333 // Chopping the quad helps when the quad is either degenerate or nearly degenerate. 334 // When it is degenerate it allows the approximation with lines to work since the 335 // chop point (if there is one) will be at the parabola's vertex. In the nearly 336 // degenerate the QuadUVMatrix computed for the points is almost singular which 337 // can cause rendering artifacts. 338 int n = SkChopQuadAtMaxCurvature(pathPts, choppedPts); 339 for (int i = 0; i < n; ++i) { 340 SkPoint* quadPts = choppedPts + i * 2; 341 m.mapPoints(devPts, quadPts, 3); 342 bounds.setBounds(devPts, 3); 343 bounds.outset(SK_Scalar1, SK_Scalar1); 344 bounds.roundOut(&ibounds); 345 346 if (SkIRect::Intersects(devClipBounds, ibounds)) { 347 int subdiv = num_quad_subdivs(devPts); 348 SkASSERT(subdiv >= -1); 349 if (-1 == subdiv) { 350 SkPoint* pts = lines->push_back_n(4); 351 pts[0] = devPts[0]; 352 pts[1] = devPts[1]; 353 pts[2] = devPts[1]; 354 pts[3] = devPts[2]; 355 if (verbsInContour == 0 && i == 0 && 356 pts[0] == pts[1] && pts[2] == pts[3]) { 357 seenZeroLengthVerb = true; 358 zeroVerbPt = pts[0]; 359 } 360 } else { 361 // when in perspective keep quads in src space 362 SkPoint* qPts = persp ? quadPts : devPts; 363 SkPoint* pts = quads->push_back_n(3); 364 pts[0] = qPts[0]; 365 pts[1] = qPts[1]; 366 pts[2] = qPts[2]; 367 quadSubdivCnts->push_back() = subdiv; 368 totalQuadCount += 1 << subdiv; 369 } 370 } 371 } 372 verbsInContour++; 373 break; 374 } 375 case SkPath::kCubic_Verb: 376 m.mapPoints(devPts, pathPts, 4); 377 bounds.setBounds(devPts, 4); 378 bounds.outset(SK_Scalar1, SK_Scalar1); 379 bounds.roundOut(&ibounds); 380 if (SkIRect::Intersects(devClipBounds, ibounds)) { 381 PREALLOC_PTARRAY(32) q; 382 // We convert cubics to quadratics (for now). 383 // In perspective have to do conversion in src space. 384 if (persp) { 385 SkScalar tolScale = 386 GrPathUtils::scaleToleranceToSrc(SK_Scalar1, m, path.getBounds()); 387 GrPathUtils::convertCubicToQuads(pathPts, tolScale, &q); 388 } else { 389 GrPathUtils::convertCubicToQuads(devPts, SK_Scalar1, &q); 390 } 391 for (int i = 0; i < q.count(); i += 3) { 392 SkPoint* qInDevSpace; 393 // bounds has to be calculated in device space, but q is 394 // in src space when there is perspective. 395 if (persp) { 396 m.mapPoints(devPts, &q[i], 3); 397 bounds.setBounds(devPts, 3); 398 qInDevSpace = devPts; 399 } else { 400 bounds.setBounds(&q[i], 3); 401 qInDevSpace = &q[i]; 402 } 403 bounds.outset(SK_Scalar1, SK_Scalar1); 404 bounds.roundOut(&ibounds); 405 if (SkIRect::Intersects(devClipBounds, ibounds)) { 406 int subdiv = num_quad_subdivs(qInDevSpace); 407 SkASSERT(subdiv >= -1); 408 if (-1 == subdiv) { 409 SkPoint* pts = lines->push_back_n(4); 410 // lines should always be in device coords 411 pts[0] = qInDevSpace[0]; 412 pts[1] = qInDevSpace[1]; 413 pts[2] = qInDevSpace[1]; 414 pts[3] = qInDevSpace[2]; 415 if (verbsInContour == 0 && i == 0 && 416 pts[0] == pts[1] && pts[2] == pts[3]) { 417 seenZeroLengthVerb = true; 418 zeroVerbPt = pts[0]; 419 } 420 } else { 421 SkPoint* pts = quads->push_back_n(3); 422 // q is already in src space when there is no 423 // perspective and dev coords otherwise. 424 pts[0] = q[0 + i]; 425 pts[1] = q[1 + i]; 426 pts[2] = q[2 + i]; 427 quadSubdivCnts->push_back() = subdiv; 428 totalQuadCount += 1 << subdiv; 429 } 430 } 431 } 432 } 433 verbsInContour++; 434 break; 435 case SkPath::kClose_Verb: 436 // Contour is closed, so we don't need to grow the starting line, unless it's 437 // *just* a zero length subpath. (SVG Spec 11.4, 'stroke'). 438 if (capLength > 0) { 439 if (seenZeroLengthVerb && verbsInContour == 1) { 440 SkPoint* pts = lines->push_back_n(2); 441 pts[0] = SkPoint::Make(zeroVerbPt.fX - capLength, zeroVerbPt.fY); 442 pts[1] = SkPoint::Make(zeroVerbPt.fX + capLength, zeroVerbPt.fY); 443 } else if (verbsInContour == 0) { 444 // Contour was (moveTo, close). Add a line. 445 m.mapPoints(devPts, pathPts, 1); 446 devPts[1] = devPts[0]; 447 bounds.setBounds(devPts, 2); 448 bounds.outset(SK_Scalar1, SK_Scalar1); 449 bounds.roundOut(&ibounds); 450 if (SkIRect::Intersects(devClipBounds, ibounds)) { 451 SkPoint* pts = lines->push_back_n(2); 452 pts[0] = SkPoint::Make(devPts[0].fX - capLength, devPts[0].fY); 453 pts[1] = SkPoint::Make(devPts[1].fX + capLength, devPts[1].fY); 454 } 455 } 456 } 457 break; 458 case SkPath::kDone_Verb: 459 if (seenZeroLengthVerb && verbsInContour == 1 && capLength > 0) { 460 // Path ended with a dangling (moveTo, line|quad|etc). If the final verb is 461 // degenerate, we need to draw a line. 462 SkPoint* pts = lines->push_back_n(2); 463 pts[0] = SkPoint::Make(zeroVerbPt.fX - capLength, zeroVerbPt.fY); 464 pts[1] = SkPoint::Make(zeroVerbPt.fX + capLength, zeroVerbPt.fY); 465 } 466 return totalQuadCount; 467 } 468 } 469 } 470 471 struct LineVertex { 472 SkPoint fPos; 473 float fCoverage; 474 }; 475 476 struct BezierVertex { 477 SkPoint fPos; 478 union { 479 struct { 480 SkScalar fKLM[3]; 481 } fConic; 482 SkVector fQuadCoord; 483 struct { 484 SkScalar fBogus[4]; 485 }; 486 }; 487 }; 488 489 GR_STATIC_ASSERT(sizeof(BezierVertex) == 3 * sizeof(SkPoint)); 490 491 static void intersect_lines(const SkPoint& ptA, const SkVector& normA, 492 const SkPoint& ptB, const SkVector& normB, 493 SkPoint* result) { 494 495 SkScalar lineAW = -normA.dot(ptA); 496 SkScalar lineBW = -normB.dot(ptB); 497 498 SkScalar wInv = normA.fX * normB.fY - normA.fY * normB.fX; 499 wInv = SkScalarInvert(wInv); 500 501 result->fX = normA.fY * lineBW - lineAW * normB.fY; 502 result->fX *= wInv; 503 504 result->fY = lineAW * normB.fX - normA.fX * lineBW; 505 result->fY *= wInv; 506 } 507 508 static void set_uv_quad(const SkPoint qpts[3], BezierVertex verts[kQuadNumVertices]) { 509 // this should be in the src space, not dev coords, when we have perspective 510 GrPathUtils::QuadUVMatrix DevToUV(qpts); 511 DevToUV.apply<kQuadNumVertices, sizeof(BezierVertex), sizeof(SkPoint)>(verts); 512 } 513 514 static void bloat_quad(const SkPoint qpts[3], const SkMatrix* toDevice, 515 const SkMatrix* toSrc, BezierVertex verts[kQuadNumVertices]) { 516 SkASSERT(!toDevice == !toSrc); 517 // original quad is specified by tri a,b,c 518 SkPoint a = qpts[0]; 519 SkPoint b = qpts[1]; 520 SkPoint c = qpts[2]; 521 522 if (toDevice) { 523 toDevice->mapPoints(&a, 1); 524 toDevice->mapPoints(&b, 1); 525 toDevice->mapPoints(&c, 1); 526 } 527 // make a new poly where we replace a and c by a 1-pixel wide edges orthog 528 // to edges ab and bc: 529 // 530 // before | after 531 // | b0 532 // b | 533 // | 534 // | a0 c0 535 // a c | a1 c1 536 // 537 // edges a0->b0 and b0->c0 are parallel to original edges a->b and b->c, 538 // respectively. 539 BezierVertex& a0 = verts[0]; 540 BezierVertex& a1 = verts[1]; 541 BezierVertex& b0 = verts[2]; 542 BezierVertex& c0 = verts[3]; 543 BezierVertex& c1 = verts[4]; 544 545 SkVector ab = b; 546 ab -= a; 547 SkVector ac = c; 548 ac -= a; 549 SkVector cb = b; 550 cb -= c; 551 552 // We should have already handled degenerates 553 SkASSERT(ab.length() > 0 && cb.length() > 0); 554 555 ab.normalize(); 556 SkVector abN; 557 abN.setOrthog(ab, SkVector::kLeft_Side); 558 if (abN.dot(ac) > 0) { 559 abN.negate(); 560 } 561 562 cb.normalize(); 563 SkVector cbN; 564 cbN.setOrthog(cb, SkVector::kLeft_Side); 565 if (cbN.dot(ac) < 0) { 566 cbN.negate(); 567 } 568 569 a0.fPos = a; 570 a0.fPos += abN; 571 a1.fPos = a; 572 a1.fPos -= abN; 573 574 c0.fPos = c; 575 c0.fPos += cbN; 576 c1.fPos = c; 577 c1.fPos -= cbN; 578 579 intersect_lines(a0.fPos, abN, c0.fPos, cbN, &b0.fPos); 580 581 if (toSrc) { 582 toSrc->mapPointsWithStride(&verts[0].fPos, sizeof(BezierVertex), kQuadNumVertices); 583 } 584 } 585 586 // Equations based off of Loop-Blinn Quadratic GPU Rendering 587 // Input Parametric: 588 // 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) 589 // Output Implicit: 590 // f(x, y, w) = f(P) = K^2 - LM 591 // K = dot(k, P), L = dot(l, P), M = dot(m, P) 592 // k, l, m are calculated in function GrPathUtils::getConicKLM 593 static void set_conic_coeffs(const SkPoint p[3], BezierVertex verts[kQuadNumVertices], 594 const SkScalar weight) { 595 SkMatrix klm; 596 597 GrPathUtils::getConicKLM(p, weight, &klm); 598 599 for (int i = 0; i < kQuadNumVertices; ++i) { 600 const SkScalar pt3[3] = {verts[i].fPos.x(), verts[i].fPos.y(), 1.f}; 601 klm.mapHomogeneousPoints(verts[i].fConic.fKLM, pt3, 1); 602 } 603 } 604 605 static void add_conics(const SkPoint p[3], 606 const SkScalar weight, 607 const SkMatrix* toDevice, 608 const SkMatrix* toSrc, 609 BezierVertex** vert) { 610 bloat_quad(p, toDevice, toSrc, *vert); 611 set_conic_coeffs(p, *vert, weight); 612 *vert += kQuadNumVertices; 613 } 614 615 static void add_quads(const SkPoint p[3], 616 int subdiv, 617 const SkMatrix* toDevice, 618 const SkMatrix* toSrc, 619 BezierVertex** vert) { 620 SkASSERT(subdiv >= 0); 621 if (subdiv) { 622 SkPoint newP[5]; 623 SkChopQuadAtHalf(p, newP); 624 add_quads(newP + 0, subdiv-1, toDevice, toSrc, vert); 625 add_quads(newP + 2, subdiv-1, toDevice, toSrc, vert); 626 } else { 627 bloat_quad(p, toDevice, toSrc, *vert); 628 set_uv_quad(p, *vert); 629 *vert += kQuadNumVertices; 630 } 631 } 632 633 static void add_line(const SkPoint p[2], 634 const SkMatrix* toSrc, 635 uint8_t coverage, 636 LineVertex** vert) { 637 const SkPoint& a = p[0]; 638 const SkPoint& b = p[1]; 639 640 SkVector ortho, vec = b; 641 vec -= a; 642 643 if (vec.setLength(SK_ScalarHalf)) { 644 // Create a vector orthogonal to 'vec' and of unit length 645 ortho.fX = 2.0f * vec.fY; 646 ortho.fY = -2.0f * vec.fX; 647 648 float floatCoverage = GrNormalizeByteToFloat(coverage); 649 650 (*vert)[0].fPos = a; 651 (*vert)[0].fCoverage = floatCoverage; 652 (*vert)[1].fPos = b; 653 (*vert)[1].fCoverage = floatCoverage; 654 (*vert)[2].fPos = a - vec + ortho; 655 (*vert)[2].fCoverage = 0; 656 (*vert)[3].fPos = b + vec + ortho; 657 (*vert)[3].fCoverage = 0; 658 (*vert)[4].fPos = a - vec - ortho; 659 (*vert)[4].fCoverage = 0; 660 (*vert)[5].fPos = b + vec - ortho; 661 (*vert)[5].fCoverage = 0; 662 663 if (toSrc) { 664 toSrc->mapPointsWithStride(&(*vert)->fPos, 665 sizeof(LineVertex), 666 kLineSegNumVertices); 667 } 668 } else { 669 // just make it degenerate and likely offscreen 670 for (int i = 0; i < kLineSegNumVertices; ++i) { 671 (*vert)[i].fPos.set(SK_ScalarMax, SK_ScalarMax); 672 } 673 } 674 675 *vert += kLineSegNumVertices; 676 } 677 678 /////////////////////////////////////////////////////////////////////////////// 679 680 bool GrAAHairLinePathRenderer::onCanDrawPath(const CanDrawPathArgs& args) const { 681 if (GrAAType::kCoverage != args.fAAType) { 682 return false; 683 } 684 685 if (!IsStrokeHairlineOrEquivalent(args.fShape->style(), *args.fViewMatrix, nullptr)) { 686 return false; 687 } 688 689 // We don't currently handle dashing in this class though perhaps we should. 690 if (args.fShape->style().pathEffect()) { 691 return false; 692 } 693 694 if (SkPath::kLine_SegmentMask == args.fShape->segmentMask() || 695 args.fCaps->shaderCaps()->shaderDerivativeSupport()) { 696 return true; 697 } 698 699 return false; 700 } 701 702 template <class VertexType> 703 bool check_bounds(const SkMatrix& viewMatrix, const SkRect& devBounds, void* vertices, int vCount) 704 { 705 SkRect tolDevBounds = devBounds; 706 // The bounds ought to be tight, but in perspective the below code runs the verts 707 // through the view matrix to get back to dev coords, which can introduce imprecision. 708 if (viewMatrix.hasPerspective()) { 709 tolDevBounds.outset(SK_Scalar1 / 1000, SK_Scalar1 / 1000); 710 } else { 711 // Non-persp matrices cause this path renderer to draw in device space. 712 SkASSERT(viewMatrix.isIdentity()); 713 } 714 SkRect actualBounds; 715 716 VertexType* verts = reinterpret_cast<VertexType*>(vertices); 717 bool first = true; 718 for (int i = 0; i < vCount; ++i) { 719 SkPoint pos = verts[i].fPos; 720 // This is a hack to workaround the fact that we move some degenerate segments offscreen. 721 if (SK_ScalarMax == pos.fX) { 722 continue; 723 } 724 viewMatrix.mapPoints(&pos, 1); 725 if (first) { 726 actualBounds.set(pos.fX, pos.fY, pos.fX, pos.fY); 727 first = false; 728 } else { 729 actualBounds.growToInclude(pos.fX, pos.fY); 730 } 731 } 732 if (!first) { 733 return tolDevBounds.contains(actualBounds); 734 } 735 736 return true; 737 } 738 739 namespace { 740 741 class AAHairlineOp final : public GrMeshDrawOp { 742 private: 743 using Helper = GrSimpleMeshDrawOpHelperWithStencil; 744 745 public: 746 DEFINE_OP_CLASS_ID 747 748 static std::unique_ptr<GrDrawOp> Make(GrPaint&& paint, 749 const SkMatrix& viewMatrix, 750 const SkPath& path, 751 const GrStyle& style, 752 const SkIRect& devClipBounds, 753 const GrUserStencilSettings* stencilSettings) { 754 SkScalar hairlineCoverage; 755 uint8_t newCoverage = 0xff; 756 if (GrPathRenderer::IsStrokeHairlineOrEquivalent(style, viewMatrix, &hairlineCoverage)) { 757 newCoverage = SkScalarRoundToInt(hairlineCoverage * 0xff); 758 } 759 760 const SkStrokeRec& stroke = style.strokeRec(); 761 SkScalar capLength = SkPaint::kButt_Cap != stroke.getCap() ? hairlineCoverage * 0.5f : 0.0f; 762 763 return Helper::FactoryHelper<AAHairlineOp>(std::move(paint), newCoverage, viewMatrix, path, 764 devClipBounds, capLength, stencilSettings); 765 } 766 767 AAHairlineOp(const Helper::MakeArgs& helperArgs, 768 GrColor color, 769 uint8_t coverage, 770 const SkMatrix& viewMatrix, 771 const SkPath& path, 772 SkIRect devClipBounds, 773 SkScalar capLength, 774 const GrUserStencilSettings* stencilSettings) 775 : INHERITED(ClassID()) 776 , fHelper(helperArgs, GrAAType::kCoverage, stencilSettings) 777 , fColor(color) 778 , fCoverage(coverage) { 779 fPaths.emplace_back(PathData{viewMatrix, path, devClipBounds, capLength}); 780 781 this->setTransformedBounds(path.getBounds(), viewMatrix, HasAABloat::kYes, 782 IsZeroArea::kYes); 783 } 784 785 const char* name() const override { return "AAHairlineOp"; } 786 787 SkString dumpInfo() const override { 788 SkString string; 789 string.appendf("Color: 0x%08x Coverage: 0x%02x, Count: %d\n", fColor, fCoverage, 790 fPaths.count()); 791 string += INHERITED::dumpInfo(); 792 string += fHelper.dumpInfo(); 793 return string; 794 } 795 796 FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); } 797 798 RequiresDstTexture finalize(const GrCaps& caps, const GrAppliedClip* clip) override { 799 return fHelper.xpRequiresDstTexture(caps, clip, GrProcessorAnalysisCoverage::kSingleChannel, 800 &fColor); 801 } 802 803 private: 804 void onPrepareDraws(Target*) const override; 805 806 typedef SkTArray<SkPoint, true> PtArray; 807 typedef SkTArray<int, true> IntArray; 808 typedef SkTArray<float, true> FloatArray; 809 810 bool onCombineIfPossible(GrOp* t, const GrCaps& caps) override { 811 AAHairlineOp* that = t->cast<AAHairlineOp>(); 812 813 if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) { 814 return false; 815 } 816 817 if (this->viewMatrix().hasPerspective() != that->viewMatrix().hasPerspective()) { 818 return false; 819 } 820 821 // We go to identity if we don't have perspective 822 if (this->viewMatrix().hasPerspective() && 823 !this->viewMatrix().cheapEqualTo(that->viewMatrix())) { 824 return false; 825 } 826 827 // TODO we can actually combine hairlines if they are the same color in a kind of bulk 828 // method but we haven't implemented this yet 829 // TODO investigate going to vertex color and coverage? 830 if (this->coverage() != that->coverage()) { 831 return false; 832 } 833 834 if (this->color() != that->color()) { 835 return false; 836 } 837 838 if (fHelper.usesLocalCoords() && !this->viewMatrix().cheapEqualTo(that->viewMatrix())) { 839 return false; 840 } 841 842 fPaths.push_back_n(that->fPaths.count(), that->fPaths.begin()); 843 this->joinBounds(*that); 844 return true; 845 } 846 847 GrColor color() const { return fColor; } 848 uint8_t coverage() const { return fCoverage; } 849 const SkMatrix& viewMatrix() const { return fPaths[0].fViewMatrix; } 850 851 struct PathData { 852 SkMatrix fViewMatrix; 853 SkPath fPath; 854 SkIRect fDevClipBounds; 855 SkScalar fCapLength; 856 }; 857 858 SkSTArray<1, PathData, true> fPaths; 859 Helper fHelper; 860 GrColor fColor; 861 uint8_t fCoverage; 862 863 typedef GrMeshDrawOp INHERITED; 864 }; 865 866 } // anonymous namespace 867 868 void AAHairlineOp::onPrepareDraws(Target* target) const { 869 // Setup the viewmatrix and localmatrix for the GrGeometryProcessor. 870 SkMatrix invert; 871 if (!this->viewMatrix().invert(&invert)) { 872 return; 873 } 874 875 // we will transform to identity space if the viewmatrix does not have perspective 876 bool hasPerspective = this->viewMatrix().hasPerspective(); 877 const SkMatrix* geometryProcessorViewM = &SkMatrix::I(); 878 const SkMatrix* geometryProcessorLocalM = &invert; 879 const SkMatrix* toDevice = nullptr; 880 const SkMatrix* toSrc = nullptr; 881 if (hasPerspective) { 882 geometryProcessorViewM = &this->viewMatrix(); 883 geometryProcessorLocalM = &SkMatrix::I(); 884 toDevice = &this->viewMatrix(); 885 toSrc = &invert; 886 } 887 888 // This is hand inlined for maximum performance. 889 PREALLOC_PTARRAY(128) lines; 890 PREALLOC_PTARRAY(128) quads; 891 PREALLOC_PTARRAY(128) conics; 892 IntArray qSubdivs; 893 FloatArray cWeights; 894 int quadCount = 0; 895 896 int instanceCount = fPaths.count(); 897 for (int i = 0; i < instanceCount; i++) { 898 const PathData& args = fPaths[i]; 899 quadCount += gather_lines_and_quads(args.fPath, args.fViewMatrix, args.fDevClipBounds, 900 args.fCapLength, &lines, &quads, &conics, &qSubdivs, 901 &cWeights); 902 } 903 904 int lineCount = lines.count() / 2; 905 int conicCount = conics.count() / 3; 906 907 const GrPipeline* pipeline = fHelper.makePipeline(target); 908 // do lines first 909 if (lineCount) { 910 sk_sp<GrGeometryProcessor> lineGP; 911 { 912 using namespace GrDefaultGeoProcFactory; 913 914 Color color(this->color()); 915 LocalCoords localCoords(fHelper.usesLocalCoords() ? LocalCoords::kUsePosition_Type 916 : LocalCoords::kUnused_Type); 917 localCoords.fMatrix = geometryProcessorLocalM; 918 lineGP = GrDefaultGeoProcFactory::Make(color, Coverage::kAttribute_Type, localCoords, 919 *geometryProcessorViewM); 920 } 921 922 sk_sp<const GrBuffer> linesIndexBuffer( 923 ref_lines_index_buffer(target->resourceProvider())); 924 925 const GrBuffer* vertexBuffer; 926 int firstVertex; 927 928 size_t vertexStride = lineGP->getVertexStride(); 929 int vertexCount = kLineSegNumVertices * lineCount; 930 LineVertex* verts = reinterpret_cast<LineVertex*>( 931 target->makeVertexSpace(vertexStride, vertexCount, &vertexBuffer, &firstVertex)); 932 933 if (!verts|| !linesIndexBuffer) { 934 SkDebugf("Could not allocate vertices\n"); 935 return; 936 } 937 938 SkASSERT(lineGP->getVertexStride() == sizeof(LineVertex)); 939 940 for (int i = 0; i < lineCount; ++i) { 941 add_line(&lines[2*i], toSrc, this->coverage(), &verts); 942 } 943 944 GrMesh mesh(GrPrimitiveType::kTriangles); 945 mesh.setIndexedPatterned(linesIndexBuffer.get(), kIdxsPerLineSeg, kLineSegNumVertices, 946 lineCount, kLineSegsNumInIdxBuffer); 947 mesh.setVertexData(vertexBuffer, firstVertex); 948 target->draw(lineGP.get(), pipeline, mesh); 949 } 950 951 if (quadCount || conicCount) { 952 sk_sp<GrGeometryProcessor> quadGP(GrQuadEffect::Make(this->color(), 953 *geometryProcessorViewM, 954 kHairlineAA_GrProcessorEdgeType, 955 target->caps(), 956 *geometryProcessorLocalM, 957 fHelper.usesLocalCoords(), 958 this->coverage())); 959 960 sk_sp<GrGeometryProcessor> conicGP(GrConicEffect::Make(this->color(), 961 *geometryProcessorViewM, 962 kHairlineAA_GrProcessorEdgeType, 963 target->caps(), 964 *geometryProcessorLocalM, 965 fHelper.usesLocalCoords(), 966 this->coverage())); 967 968 const GrBuffer* vertexBuffer; 969 int firstVertex; 970 971 sk_sp<const GrBuffer> quadsIndexBuffer( 972 ref_quads_index_buffer(target->resourceProvider())); 973 974 size_t vertexStride = sizeof(BezierVertex); 975 int vertexCount = kQuadNumVertices * quadCount + kQuadNumVertices * conicCount; 976 void *vertices = target->makeVertexSpace(vertexStride, vertexCount, 977 &vertexBuffer, &firstVertex); 978 979 if (!vertices || !quadsIndexBuffer) { 980 SkDebugf("Could not allocate vertices\n"); 981 return; 982 } 983 984 // Setup vertices 985 BezierVertex* bezVerts = reinterpret_cast<BezierVertex*>(vertices); 986 987 int unsubdivQuadCnt = quads.count() / 3; 988 for (int i = 0; i < unsubdivQuadCnt; ++i) { 989 SkASSERT(qSubdivs[i] >= 0); 990 add_quads(&quads[3*i], qSubdivs[i], toDevice, toSrc, &bezVerts); 991 } 992 993 // Start Conics 994 for (int i = 0; i < conicCount; ++i) { 995 add_conics(&conics[3*i], cWeights[i], toDevice, toSrc, &bezVerts); 996 } 997 998 if (quadCount > 0) { 999 GrMesh mesh(GrPrimitiveType::kTriangles); 1000 mesh.setIndexedPatterned(quadsIndexBuffer.get(), kIdxsPerQuad, kQuadNumVertices, 1001 quadCount, kQuadsNumInIdxBuffer); 1002 mesh.setVertexData(vertexBuffer, firstVertex); 1003 target->draw(quadGP.get(), pipeline, mesh); 1004 firstVertex += quadCount * kQuadNumVertices; 1005 } 1006 1007 if (conicCount > 0) { 1008 GrMesh mesh(GrPrimitiveType::kTriangles); 1009 mesh.setIndexedPatterned(quadsIndexBuffer.get(), kIdxsPerQuad, kQuadNumVertices, 1010 conicCount, kQuadsNumInIdxBuffer); 1011 mesh.setVertexData(vertexBuffer, firstVertex); 1012 target->draw(conicGP.get(), pipeline, mesh); 1013 } 1014 } 1015 } 1016 1017 bool GrAAHairLinePathRenderer::onDrawPath(const DrawPathArgs& args) { 1018 GR_AUDIT_TRAIL_AUTO_FRAME(args.fRenderTargetContext->auditTrail(), 1019 "GrAAHairlinePathRenderer::onDrawPath"); 1020 SkASSERT(GrFSAAType::kUnifiedMSAA != args.fRenderTargetContext->fsaaType()); 1021 1022 SkIRect devClipBounds; 1023 args.fClip->getConservativeBounds(args.fRenderTargetContext->width(), 1024 args.fRenderTargetContext->height(), 1025 &devClipBounds); 1026 SkPath path; 1027 args.fShape->asPath(&path); 1028 std::unique_ptr<GrDrawOp> op = 1029 AAHairlineOp::Make(std::move(args.fPaint), *args.fViewMatrix, path, 1030 args.fShape->style(), devClipBounds, args.fUserStencilSettings); 1031 args.fRenderTargetContext->addDrawOp(*args.fClip, std::move(op)); 1032 return true; 1033 } 1034 1035 /////////////////////////////////////////////////////////////////////////////////////////////////// 1036 1037 #if GR_TEST_UTILS 1038 1039 GR_DRAW_OP_TEST_DEFINE(AAHairlineOp) { 1040 SkMatrix viewMatrix = GrTest::TestMatrix(random); 1041 SkPath path = GrTest::TestPath(random); 1042 SkIRect devClipBounds; 1043 devClipBounds.setEmpty(); 1044 return AAHairlineOp::Make(std::move(paint), viewMatrix, path, GrStyle::SimpleHairline(), 1045 devClipBounds, GrGetRandomStencil(random, context)); 1046 } 1047 1048 #endif 1049