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 "src/gpu/ops/AAHairLinePathRenderer.h" 9 10#include "include/core/SkPoint3.h" 11#include "include/private/SkTemplates.h" 12#include "src/core/SkGeometry.h" 13#include "src/core/SkMatrixPriv.h" 14#include "src/core/SkPointPriv.h" 15#include "src/core/SkRectPriv.h" 16#include "src/core/SkStroke.h" 17#include "src/gpu/GrAuditTrail.h" 18#include "src/gpu/GrBuffer.h" 19#include "src/gpu/GrCaps.h" 20#include "src/gpu/GrDefaultGeoProcFactory.h" 21#include "src/gpu/GrDrawOpTest.h" 22#include "src/gpu/GrOpFlushState.h" 23#include "src/gpu/GrProcessor.h" 24#include "src/gpu/GrProgramInfo.h" 25#include "src/gpu/GrResourceProvider.h" 26#include "src/gpu/GrStyle.h" 27#include "src/gpu/GrUtil.h" 28#include "src/gpu/effects/GrBezierEffect.h" 29#include "src/gpu/geometry/GrPathUtils.h" 30#include "src/gpu/geometry/GrStyledShape.h" 31#include "src/gpu/ops/GrMeshDrawOp.h" 32#include "src/gpu/ops/GrSimpleMeshDrawOpHelperWithStencil.h" 33#include "src/gpu/v1/SurfaceDrawContext_v1.h" 34 35#define PREALLOC_PTARRAY(N) SkSTArray<(N),SkPoint, true> 36 37using PtArray = SkTArray<SkPoint, true>; 38using IntArray = SkTArray<int, true>; 39using FloatArray = SkTArray<float, true>; 40 41namespace { 42 43// quadratics are rendered as 5-sided polys in order to bound the 44// AA stroke around the center-curve. See comments in push_quad_index_buffer and 45// bloat_quad. Quadratics and conics share an index buffer 46 47// lines are rendered as: 48// *______________* 49// |\ -_______ /| 50// | \ \ / | 51// | *--------* | 52// | / ______/ \ | 53// */_-__________\* 54// For: 6 vertices and 18 indices (for 6 triangles) 55 56// Each quadratic is rendered as a five sided polygon. This poly bounds 57// the quadratic's bounding triangle but has been expanded so that the 58// 1-pixel wide area around the curve is inside the poly. 59// If a,b,c are the original control points then the poly a0,b0,c0,c1,a1 60// that is rendered would look like this: 61// b0 62// b 63// 64// a0 c0 65// a c 66// a1 c1 67// Each is drawn as three triangles ((a0,a1,b0), (b0,c1,c0), (a1,c1,b0)) 68// specified by these 9 indices: 69static const uint16_t kQuadIdxBufPattern[] = { 70 0, 1, 2, 71 2, 4, 3, 72 1, 4, 2 73}; 74 75static const int kIdxsPerQuad = SK_ARRAY_COUNT(kQuadIdxBufPattern); 76static const int kQuadNumVertices = 5; 77static const int kQuadsNumInIdxBuffer = 256; 78GR_DECLARE_STATIC_UNIQUE_KEY(gQuadsIndexBufferKey); 79 80sk_sp<const GrBuffer> get_quads_index_buffer(GrResourceProvider* resourceProvider) { 81 GR_DEFINE_STATIC_UNIQUE_KEY(gQuadsIndexBufferKey); 82 return resourceProvider->findOrCreatePatternedIndexBuffer( 83 kQuadIdxBufPattern, kIdxsPerQuad, kQuadsNumInIdxBuffer, kQuadNumVertices, 84 gQuadsIndexBufferKey); 85} 86 87 88// Each line segment is rendered as two quads and two triangles. 89// p0 and p1 have alpha = 1 while all other points have alpha = 0. 90// The four external points are offset 1 pixel perpendicular to the 91// line and half a pixel parallel to the line. 92// 93// p4 p5 94// p0 p1 95// p2 p3 96// 97// Each is drawn as six triangles specified by these 18 indices: 98 99static const uint16_t kLineSegIdxBufPattern[] = { 100 0, 1, 3, 101 0, 3, 2, 102 0, 4, 5, 103 0, 5, 1, 104 0, 2, 4, 105 1, 5, 3 106}; 107 108static const int kIdxsPerLineSeg = SK_ARRAY_COUNT(kLineSegIdxBufPattern); 109static const int kLineSegNumVertices = 6; 110static const int kLineSegsNumInIdxBuffer = 256; 111 112GR_DECLARE_STATIC_UNIQUE_KEY(gLinesIndexBufferKey); 113 114sk_sp<const GrBuffer> get_lines_index_buffer(GrResourceProvider* resourceProvider) { 115 GR_DEFINE_STATIC_UNIQUE_KEY(gLinesIndexBufferKey); 116 return resourceProvider->findOrCreatePatternedIndexBuffer( 117 kLineSegIdxBufPattern, kIdxsPerLineSeg, kLineSegsNumInIdxBuffer, kLineSegNumVertices, 118 gLinesIndexBufferKey); 119} 120 121// Takes 178th time of logf on Z600 / VC2010 122int get_float_exp(float x) { 123 static_assert(sizeof(int) == sizeof(float)); 124#ifdef SK_DEBUG 125 static bool tested; 126 if (!tested) { 127 tested = true; 128 SkASSERT(get_float_exp(0.25f) == -2); 129 SkASSERT(get_float_exp(0.3f) == -2); 130 SkASSERT(get_float_exp(0.5f) == -1); 131 SkASSERT(get_float_exp(1.f) == 0); 132 SkASSERT(get_float_exp(2.f) == 1); 133 SkASSERT(get_float_exp(2.5f) == 1); 134 SkASSERT(get_float_exp(8.f) == 3); 135 SkASSERT(get_float_exp(100.f) == 6); 136 SkASSERT(get_float_exp(1000.f) == 9); 137 SkASSERT(get_float_exp(1024.f) == 10); 138 SkASSERT(get_float_exp(3000000.f) == 21); 139 } 140#endif 141 const int* iptr = (const int*)&x; 142 return (((*iptr) & 0x7f800000) >> 23) - 127; 143} 144 145// Uses the max curvature function for quads to estimate 146// where to chop the conic. If the max curvature is not 147// found along the curve segment it will return 1 and 148// dst[0] is the original conic. If it returns 2 the dst[0] 149// and dst[1] are the two new conics. 150int split_conic(const SkPoint src[3], SkConic dst[2], const SkScalar weight) { 151 SkScalar t = SkFindQuadMaxCurvature(src); 152 if (t == 0 || t == 1) { 153 if (dst) { 154 dst[0].set(src, weight); 155 } 156 return 1; 157 } else { 158 if (dst) { 159 SkConic conic; 160 conic.set(src, weight); 161 if (!conic.chopAt(t, dst)) { 162 dst[0].set(src, weight); 163 return 1; 164 } 165 } 166 return 2; 167 } 168} 169 170// Calls split_conic on the entire conic and then once more on each subsection. 171// Most cases will result in either 1 conic (chop point is not within t range) 172// or 3 points (split once and then one subsection is split again). 173int chop_conic(const SkPoint src[3], SkConic dst[4], const SkScalar weight) { 174 SkConic dstTemp[2]; 175 int conicCnt = split_conic(src, dstTemp, weight); 176 if (2 == conicCnt) { 177 int conicCnt2 = split_conic(dstTemp[0].fPts, dst, dstTemp[0].fW); 178 conicCnt = conicCnt2 + split_conic(dstTemp[1].fPts, &dst[conicCnt2], dstTemp[1].fW); 179 } else { 180 dst[0] = dstTemp[0]; 181 } 182 return conicCnt; 183} 184 185// returns 0 if quad/conic is degen or close to it 186// in this case approx the path with lines 187// otherwise returns 1 188int is_degen_quad_or_conic(const SkPoint p[3], SkScalar* dsqd) { 189 static const SkScalar gDegenerateToLineTol = GrPathUtils::kDefaultTolerance; 190 static const SkScalar gDegenerateToLineTolSqd = 191 gDegenerateToLineTol * gDegenerateToLineTol; 192 193 if (SkPointPriv::DistanceToSqd(p[0], p[1]) < gDegenerateToLineTolSqd || 194 SkPointPriv::DistanceToSqd(p[1], p[2]) < gDegenerateToLineTolSqd) { 195 return 1; 196 } 197 198 *dsqd = SkPointPriv::DistanceToLineBetweenSqd(p[1], p[0], p[2]); 199 if (*dsqd < gDegenerateToLineTolSqd) { 200 return 1; 201 } 202 203 if (SkPointPriv::DistanceToLineBetweenSqd(p[2], p[1], p[0]) < gDegenerateToLineTolSqd) { 204 return 1; 205 } 206 return 0; 207} 208 209int is_degen_quad_or_conic(const SkPoint p[3]) { 210 SkScalar dsqd; 211 return is_degen_quad_or_conic(p, &dsqd); 212} 213 214// we subdivide the quads to avoid huge overfill 215// if it returns -1 then should be drawn as lines 216int num_quad_subdivs(const SkPoint p[3]) { 217 SkScalar dsqd; 218 if (is_degen_quad_or_conic(p, &dsqd)) { 219 return -1; 220 } 221 222 // tolerance of triangle height in pixels 223 // tuned on windows Quadro FX 380 / Z600 224 // trade off of fill vs cpu time on verts 225 // maybe different when do this using gpu (geo or tess shaders) 226 static const SkScalar gSubdivTol = 175 * SK_Scalar1; 227 228 if (dsqd <= gSubdivTol * gSubdivTol) { 229 return 0; 230 } else { 231 static const int kMaxSub = 4; 232 // subdividing the quad reduces d by 4. so we want x = log4(d/tol) 233 // = log4(d*d/tol*tol)/2 234 // = log2(d*d/tol*tol) 235 236 // +1 since we're ignoring the mantissa contribution. 237 int log = get_float_exp(dsqd/(gSubdivTol*gSubdivTol)) + 1; 238 log = std::min(std::max(0, log), kMaxSub); 239 return log; 240 } 241} 242 243/** 244 * Generates the lines and quads to be rendered. Lines are always recorded in 245 * device space. We will do a device space bloat to account for the 1pixel 246 * thickness. 247 * Quads are recorded in device space unless m contains 248 * perspective, then in they are in src space. We do this because we will 249 * subdivide large quads to reduce over-fill. This subdivision has to be 250 * performed before applying the perspective matrix. 251 */ 252int gather_lines_and_quads(const SkPath& path, 253 const SkMatrix& m, 254 const SkIRect& devClipBounds, 255 SkScalar capLength, 256 bool convertConicsToQuads, 257 PtArray* lines, 258 PtArray* quads, 259 PtArray* conics, 260 IntArray* quadSubdivCnts, 261 FloatArray* conicWeights) { 262 SkPath::Iter iter(path, false); 263 264 int totalQuadCount = 0; 265 SkRect bounds; 266 SkIRect ibounds; 267 268 bool persp = m.hasPerspective(); 269 270 // Whenever a degenerate, zero-length contour is encountered, this code will insert a 271 // 'capLength' x-aligned line segment. Since this is rendering hairlines it is hoped this will 272 // suffice for AA square & circle capping. 273 int verbsInContour = 0; // Does not count moves 274 bool seenZeroLengthVerb = false; 275 SkPoint zeroVerbPt; 276 277 // Adds a quad that has already been chopped to the list and checks for quads that are close to 278 // lines. Also does a bounding box check. It takes points that are in src space and device 279 // space. The src points are only required if the view matrix has perspective. 280 auto addChoppedQuad = [&](const SkPoint srcPts[3], const SkPoint devPts[4], 281 bool isContourStart) { 282 SkRect bounds; 283 SkIRect ibounds; 284 bounds.setBounds(devPts, 3); 285 bounds.outset(SK_Scalar1, SK_Scalar1); 286 bounds.roundOut(&ibounds); 287 // We only need the src space space pts when not in perspective. 288 SkASSERT(srcPts || !persp); 289 if (SkIRect::Intersects(devClipBounds, ibounds)) { 290 int subdiv = num_quad_subdivs(devPts); 291 SkASSERT(subdiv >= -1); 292 if (-1 == subdiv) { 293 SkPoint* pts = lines->push_back_n(4); 294 pts[0] = devPts[0]; 295 pts[1] = devPts[1]; 296 pts[2] = devPts[1]; 297 pts[3] = devPts[2]; 298 if (isContourStart && pts[0] == pts[1] && pts[2] == pts[3]) { 299 seenZeroLengthVerb = true; 300 zeroVerbPt = pts[0]; 301 } 302 } else { 303 // when in perspective keep quads in src space 304 const SkPoint* qPts = persp ? srcPts : devPts; 305 SkPoint* pts = quads->push_back_n(3); 306 pts[0] = qPts[0]; 307 pts[1] = qPts[1]; 308 pts[2] = qPts[2]; 309 quadSubdivCnts->push_back() = subdiv; 310 totalQuadCount += 1 << subdiv; 311 } 312 } 313 }; 314 315 // Applies the view matrix to quad src points and calls the above helper. 316 auto addSrcChoppedQuad = [&](const SkPoint srcSpaceQuadPts[3], bool isContourStart) { 317 SkPoint devPts[3]; 318 m.mapPoints(devPts, srcSpaceQuadPts, 3); 319 addChoppedQuad(srcSpaceQuadPts, devPts, isContourStart); 320 }; 321 322 for (;;) { 323 SkPoint pathPts[4]; 324 SkPath::Verb verb = iter.next(pathPts); 325 switch (verb) { 326 case SkPath::kConic_Verb: 327 if (convertConicsToQuads) { 328 SkScalar weight = iter.conicWeight(); 329 SkAutoConicToQuads converter; 330 const SkPoint* quadPts = converter.computeQuads(pathPts, weight, 0.25f); 331 for (int i = 0; i < converter.countQuads(); ++i) { 332 addSrcChoppedQuad(quadPts + 2 * i, !verbsInContour && 0 == i); 333 } 334 } else { 335 SkConic dst[4]; 336 // We chop the conics to create tighter clipping to hide error 337 // that appears near max curvature of very thin conics. Thin 338 // hyperbolas with high weight still show error. 339 int conicCnt = chop_conic(pathPts, dst, iter.conicWeight()); 340 for (int i = 0; i < conicCnt; ++i) { 341 SkPoint devPts[4]; 342 SkPoint* chopPnts = dst[i].fPts; 343 m.mapPoints(devPts, chopPnts, 3); 344 bounds.setBounds(devPts, 3); 345 bounds.outset(SK_Scalar1, SK_Scalar1); 346 bounds.roundOut(&ibounds); 347 if (SkIRect::Intersects(devClipBounds, ibounds)) { 348 if (is_degen_quad_or_conic(devPts)) { 349 SkPoint* pts = lines->push_back_n(4); 350 pts[0] = devPts[0]; 351 pts[1] = devPts[1]; 352 pts[2] = devPts[1]; 353 pts[3] = devPts[2]; 354 if (verbsInContour == 0 && i == 0 && pts[0] == pts[1] && 355 pts[2] == pts[3]) { 356 seenZeroLengthVerb = true; 357 zeroVerbPt = pts[0]; 358 } 359 } else { 360 // when in perspective keep conics in src space 361 SkPoint* cPts = persp ? chopPnts : devPts; 362 SkPoint* pts = conics->push_back_n(3); 363 pts[0] = cPts[0]; 364 pts[1] = cPts[1]; 365 pts[2] = cPts[2]; 366 conicWeights->push_back() = dst[i].fW; 367 } 368 } 369 } 370 } 371 verbsInContour++; 372 break; 373 case SkPath::kMove_Verb: 374 // New contour (and last one was unclosed). If it was just a zero length drawing 375 // operation, and we're supposed to draw caps, then add a tiny line. 376 if (seenZeroLengthVerb && verbsInContour == 1 && capLength > 0) { 377 SkPoint* pts = lines->push_back_n(2); 378 pts[0] = SkPoint::Make(zeroVerbPt.fX - capLength, zeroVerbPt.fY); 379 pts[1] = SkPoint::Make(zeroVerbPt.fX + capLength, zeroVerbPt.fY); 380 } 381 verbsInContour = 0; 382 seenZeroLengthVerb = false; 383 break; 384 case SkPath::kLine_Verb: { 385 SkPoint devPts[2]; 386 m.mapPoints(devPts, pathPts, 2); 387 bounds.setBounds(devPts, 2); 388 bounds.outset(SK_Scalar1, SK_Scalar1); 389 bounds.roundOut(&ibounds); 390 if (SkIRect::Intersects(devClipBounds, ibounds)) { 391 SkPoint* pts = lines->push_back_n(2); 392 pts[0] = devPts[0]; 393 pts[1] = devPts[1]; 394 if (verbsInContour == 0 && pts[0] == pts[1]) { 395 seenZeroLengthVerb = true; 396 zeroVerbPt = pts[0]; 397 } 398 } 399 verbsInContour++; 400 break; 401 } 402 case SkPath::kQuad_Verb: { 403 SkPoint choppedPts[5]; 404 // Chopping the quad helps when the quad is either degenerate or nearly degenerate. 405 // When it is degenerate it allows the approximation with lines to work since the 406 // chop point (if there is one) will be at the parabola's vertex. In the nearly 407 // degenerate the QuadUVMatrix computed for the points is almost singular which 408 // can cause rendering artifacts. 409 int n = SkChopQuadAtMaxCurvature(pathPts, choppedPts); 410 for (int i = 0; i < n; ++i) { 411 addSrcChoppedQuad(choppedPts + i * 2, !verbsInContour && 0 == i); 412 } 413 verbsInContour++; 414 break; 415 } 416 case SkPath::kCubic_Verb: { 417 SkPoint devPts[4]; 418 m.mapPoints(devPts, pathPts, 4); 419 bounds.setBounds(devPts, 4); 420 bounds.outset(SK_Scalar1, SK_Scalar1); 421 bounds.roundOut(&ibounds); 422 if (SkIRect::Intersects(devClipBounds, ibounds)) { 423 PREALLOC_PTARRAY(32) q; 424 // We convert cubics to quadratics (for now). 425 // In perspective have to do conversion in src space. 426 if (persp) { 427 SkScalar tolScale = 428 GrPathUtils::scaleToleranceToSrc(SK_Scalar1, m, path.getBounds()); 429 GrPathUtils::convertCubicToQuads(pathPts, tolScale, &q); 430 } else { 431 GrPathUtils::convertCubicToQuads(devPts, SK_Scalar1, &q); 432 } 433 for (int i = 0; i < q.count(); i += 3) { 434 if (persp) { 435 addSrcChoppedQuad(&q[i], !verbsInContour && 0 == i); 436 } else { 437 addChoppedQuad(nullptr, &q[i], !verbsInContour && 0 == i); 438 } 439 } 440 } 441 verbsInContour++; 442 break; 443 } 444 case SkPath::kClose_Verb: 445 // Contour is closed, so we don't need to grow the starting line, unless it's 446 // *just* a zero length subpath. (SVG Spec 11.4, 'stroke'). 447 if (capLength > 0) { 448 if (seenZeroLengthVerb && verbsInContour == 1) { 449 SkPoint* pts = lines->push_back_n(2); 450 pts[0] = SkPoint::Make(zeroVerbPt.fX - capLength, zeroVerbPt.fY); 451 pts[1] = SkPoint::Make(zeroVerbPt.fX + capLength, zeroVerbPt.fY); 452 } else if (verbsInContour == 0) { 453 // Contour was (moveTo, close). Add a line. 454 SkPoint devPts[2]; 455 m.mapPoints(devPts, pathPts, 1); 456 devPts[1] = devPts[0]; 457 bounds.setBounds(devPts, 2); 458 bounds.outset(SK_Scalar1, SK_Scalar1); 459 bounds.roundOut(&ibounds); 460 if (SkIRect::Intersects(devClipBounds, ibounds)) { 461 SkPoint* pts = lines->push_back_n(2); 462 pts[0] = SkPoint::Make(devPts[0].fX - capLength, devPts[0].fY); 463 pts[1] = SkPoint::Make(devPts[1].fX + capLength, devPts[1].fY); 464 } 465 } 466 } 467 break; 468 case SkPath::kDone_Verb: 469 if (seenZeroLengthVerb && verbsInContour == 1 && capLength > 0) { 470 // Path ended with a dangling (moveTo, line|quad|etc). If the final verb is 471 // degenerate, we need to draw a line. 472 SkPoint* pts = lines->push_back_n(2); 473 pts[0] = SkPoint::Make(zeroVerbPt.fX - capLength, zeroVerbPt.fY); 474 pts[1] = SkPoint::Make(zeroVerbPt.fX + capLength, zeroVerbPt.fY); 475 } 476 return totalQuadCount; 477 } 478 } 479} 480 481struct LineVertex { 482 SkPoint fPos; 483 float fCoverage; 484}; 485 486struct BezierVertex { 487 SkPoint fPos; 488 union { 489 struct { 490 SkScalar fKLM[3]; 491 } fConic; 492 SkVector fQuadCoord; 493 struct { 494 SkScalar fBogus[4]; 495 }; 496 }; 497}; 498 499static_assert(sizeof(BezierVertex) == 3 * sizeof(SkPoint)); 500 501void intersect_lines(const SkPoint& ptA, const SkVector& normA, 502 const SkPoint& ptB, const SkVector& normB, 503 SkPoint* result) { 504 505 SkScalar lineAW = -normA.dot(ptA); 506 SkScalar lineBW = -normB.dot(ptB); 507 508 SkScalar wInv = normA.fX * normB.fY - normA.fY * normB.fX; 509 wInv = SkScalarInvert(wInv); 510 if (!SkScalarIsFinite(wInv)) { 511 // lines are parallel, pick the point in between 512 *result = (ptA + ptB)*SK_ScalarHalf; 513 *result += normA; 514 } else { 515 result->fX = normA.fY * lineBW - lineAW * normB.fY; 516 result->fX *= wInv; 517 518 result->fY = lineAW * normB.fX - normA.fX * lineBW; 519 result->fY *= wInv; 520 } 521} 522 523void set_uv_quad(const SkPoint qpts[3], BezierVertex verts[kQuadNumVertices]) { 524 // this should be in the src space, not dev coords, when we have perspective 525 GrPathUtils::QuadUVMatrix DevToUV(qpts); 526 DevToUV.apply(verts, kQuadNumVertices, sizeof(BezierVertex), sizeof(SkPoint)); 527} 528 529void bloat_quad(const SkPoint qpts[3], 530 const SkMatrix* toDevice, 531 const SkMatrix* toSrc, 532 BezierVertex verts[kQuadNumVertices]) { 533 SkASSERT(!toDevice == !toSrc); 534 // original quad is specified by tri a,b,c 535 SkPoint a = qpts[0]; 536 SkPoint b = qpts[1]; 537 SkPoint c = qpts[2]; 538 539 if (toDevice) { 540 toDevice->mapPoints(&a, 1); 541 toDevice->mapPoints(&b, 1); 542 toDevice->mapPoints(&c, 1); 543 } 544 // make a new poly where we replace a and c by a 1-pixel wide edges orthog 545 // to edges ab and bc: 546 // 547 // before | after 548 // | b0 549 // b | 550 // | 551 // | a0 c0 552 // a c | a1 c1 553 // 554 // edges a0->b0 and b0->c0 are parallel to original edges a->b and b->c, 555 // respectively. 556 BezierVertex& a0 = verts[0]; 557 BezierVertex& a1 = verts[1]; 558 BezierVertex& b0 = verts[2]; 559 BezierVertex& c0 = verts[3]; 560 BezierVertex& c1 = verts[4]; 561 562 SkVector ab = b; 563 ab -= a; 564 SkVector ac = c; 565 ac -= a; 566 SkVector cb = b; 567 cb -= c; 568 569 // After the transform (or due to floating point math) we might have a line, 570 // try to do something reasonable 571 if (SkPointPriv::LengthSqd(ab) <= SK_ScalarNearlyZero*SK_ScalarNearlyZero) { 572 ab = cb; 573 } 574 if (SkPointPriv::LengthSqd(cb) <= SK_ScalarNearlyZero*SK_ScalarNearlyZero) { 575 cb = ab; 576 } 577 578 // We should have already handled degenerates 579 SkASSERT(ab.length() > 0 && cb.length() > 0); 580 581 ab.normalize(); 582 SkVector abN = SkPointPriv::MakeOrthog(ab, SkPointPriv::kLeft_Side); 583 if (abN.dot(ac) > 0) { 584 abN.negate(); 585 } 586 587 cb.normalize(); 588 SkVector cbN = SkPointPriv::MakeOrthog(cb, SkPointPriv::kLeft_Side); 589 if (cbN.dot(ac) < 0) { 590 cbN.negate(); 591 } 592 593 a0.fPos = a; 594 a0.fPos += abN; 595 a1.fPos = a; 596 a1.fPos -= abN; 597 598 if (toDevice && SkPointPriv::LengthSqd(ac) <= SK_ScalarNearlyZero*SK_ScalarNearlyZero) { 599 c = b; 600 } 601 c0.fPos = c; 602 c0.fPos += cbN; 603 c1.fPos = c; 604 c1.fPos -= cbN; 605 606 intersect_lines(a0.fPos, abN, c0.fPos, cbN, &b0.fPos); 607 608 if (toSrc) { 609 SkMatrixPriv::MapPointsWithStride(*toSrc, &verts[0].fPos, sizeof(BezierVertex), 610 kQuadNumVertices); 611 } 612} 613 614// Equations based off of Loop-Blinn Quadratic GPU Rendering 615// Input Parametric: 616// 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) 617// Output Implicit: 618// f(x, y, w) = f(P) = K^2 - LM 619// K = dot(k, P), L = dot(l, P), M = dot(m, P) 620// k, l, m are calculated in function GrPathUtils::getConicKLM 621void set_conic_coeffs(const SkPoint p[3], 622 BezierVertex verts[kQuadNumVertices], 623 const SkScalar weight) { 624 SkMatrix klm; 625 626 GrPathUtils::getConicKLM(p, weight, &klm); 627 628 for (int i = 0; i < kQuadNumVertices; ++i) { 629 const SkPoint3 pt3 = {verts[i].fPos.x(), verts[i].fPos.y(), 1.f}; 630 klm.mapHomogeneousPoints((SkPoint3* ) verts[i].fConic.fKLM, &pt3, 1); 631 } 632} 633 634void add_conics(const SkPoint p[3], 635 const SkScalar weight, 636 const SkMatrix* toDevice, 637 const SkMatrix* toSrc, 638 BezierVertex** vert) { 639 bloat_quad(p, toDevice, toSrc, *vert); 640 set_conic_coeffs(p, *vert, weight); 641 *vert += kQuadNumVertices; 642} 643 644void add_quads(const SkPoint p[3], 645 int subdiv, 646 const SkMatrix* toDevice, 647 const SkMatrix* toSrc, 648 BezierVertex** vert) { 649 SkASSERT(subdiv >= 0); 650 // temporary vertex storage to avoid reading the vertex buffer 651 BezierVertex outVerts[kQuadNumVertices] = {}; 652 653 // storage for the chopped quad 654 // pts 0,1,2 are the first quad, and 2,3,4 the second quad 655 SkPoint choppedQuadPts[5]; 656 // start off with our original curve in the second quad slot 657 memcpy(&choppedQuadPts[2], p, 3*sizeof(SkPoint)); 658 659 int stepCount = 1 << subdiv; 660 while (stepCount > 1) { 661 // The general idea is: 662 // * chop the quad using pts 2,3,4 as the input 663 // * write out verts using pts 0,1,2 664 // * now 2,3,4 is the remainder of the curve, chop again until all subdivisions are done 665 SkScalar h = 1.f / stepCount; 666 SkChopQuadAt(&choppedQuadPts[2], choppedQuadPts, h); 667 668 bloat_quad(choppedQuadPts, toDevice, toSrc, outVerts); 669 set_uv_quad(choppedQuadPts, outVerts); 670 memcpy(*vert, outVerts, kQuadNumVertices*sizeof(BezierVertex)); 671 *vert += kQuadNumVertices; 672 --stepCount; 673 } 674 675 // finish up, write out the final quad 676 bloat_quad(&choppedQuadPts[2], toDevice, toSrc, outVerts); 677 set_uv_quad(&choppedQuadPts[2], outVerts); 678 memcpy(*vert, outVerts, kQuadNumVertices * sizeof(BezierVertex)); 679 *vert += kQuadNumVertices; 680} 681 682void add_line(const SkPoint p[2], 683 const SkMatrix* toSrc, 684 uint8_t coverage, 685 LineVertex** vert) { 686 const SkPoint& a = p[0]; 687 const SkPoint& b = p[1]; 688 689 SkVector ortho, vec = b; 690 vec -= a; 691 692 SkScalar lengthSqd = SkPointPriv::LengthSqd(vec); 693 694 if (vec.setLength(SK_ScalarHalf)) { 695 // Create a vector orthogonal to 'vec' and of unit length 696 ortho.fX = 2.0f * vec.fY; 697 ortho.fY = -2.0f * vec.fX; 698 699 float floatCoverage = GrNormalizeByteToFloat(coverage); 700 701 if (lengthSqd >= 1.0f) { 702 // Relative to points a and b: 703 // The inner vertices are inset half a pixel along the line a,b 704 (*vert)[0].fPos = a + vec; 705 (*vert)[0].fCoverage = floatCoverage; 706 (*vert)[1].fPos = b - vec; 707 (*vert)[1].fCoverage = floatCoverage; 708 } else { 709 // The inner vertices are inset a distance of length(a,b) from the outer edge of 710 // geometry. For the "a" inset this is the same as insetting from b by half a pixel. 711 // The coverage is then modulated by the length. This gives us the correct 712 // coverage for rects shorter than a pixel as they get translated subpixel amounts 713 // inside of a pixel. 714 SkScalar length = SkScalarSqrt(lengthSqd); 715 (*vert)[0].fPos = b - vec; 716 (*vert)[0].fCoverage = floatCoverage * length; 717 (*vert)[1].fPos = a + vec; 718 (*vert)[1].fCoverage = floatCoverage * length; 719 } 720 // Relative to points a and b: 721 // The outer vertices are outset half a pixel along the line a,b and then a whole pixel 722 // orthogonally. 723 (*vert)[2].fPos = a - vec + ortho; 724 (*vert)[2].fCoverage = 0; 725 (*vert)[3].fPos = b + vec + ortho; 726 (*vert)[3].fCoverage = 0; 727 (*vert)[4].fPos = a - vec - ortho; 728 (*vert)[4].fCoverage = 0; 729 (*vert)[5].fPos = b + vec - ortho; 730 (*vert)[5].fCoverage = 0; 731 732 if (toSrc) { 733 SkMatrixPriv::MapPointsWithStride(*toSrc, &(*vert)->fPos, sizeof(LineVertex), 734 kLineSegNumVertices); 735 } 736 } else { 737 // just make it degenerate and likely offscreen 738 for (int i = 0; i < kLineSegNumVertices; ++i) { 739 (*vert)[i].fPos.set(SK_ScalarMax, SK_ScalarMax); 740 } 741 } 742 743 *vert += kLineSegNumVertices; 744} 745 746/////////////////////////////////////////////////////////////////////////////// 747 748class AAHairlineOp final : public GrMeshDrawOp { 749private: 750 using Helper = GrSimpleMeshDrawOpHelperWithStencil; 751 752public: 753 DEFINE_OP_CLASS_ID 754 755 static GrOp::Owner Make(GrRecordingContext* context, 756 GrPaint&& paint, 757 const SkMatrix& viewMatrix, 758 const SkPath& path, 759 const GrStyle& style, 760 const SkIRect& devClipBounds, 761 const GrUserStencilSettings* stencilSettings) { 762 SkScalar hairlineCoverage; 763 uint8_t newCoverage = 0xff; 764 if (GrIsStrokeHairlineOrEquivalent(style, viewMatrix, &hairlineCoverage)) { 765 newCoverage = SkScalarRoundToInt(hairlineCoverage * 0xff); 766 } 767 768 const SkStrokeRec& stroke = style.strokeRec(); 769 SkScalar capLength = SkPaint::kButt_Cap != stroke.getCap() ? hairlineCoverage * 0.5f : 0.0f; 770 771 return Helper::FactoryHelper<AAHairlineOp>(context, std::move(paint), newCoverage, 772 viewMatrix, path, 773 devClipBounds, capLength, stencilSettings); 774 } 775 776 AAHairlineOp(GrProcessorSet* processorSet, 777 const SkPMColor4f& color, 778 uint8_t coverage, 779 const SkMatrix& viewMatrix, 780 const SkPath& path, 781 SkIRect devClipBounds, 782 SkScalar capLength, 783 const GrUserStencilSettings* stencilSettings) 784 : INHERITED(ClassID()) 785 , fHelper(processorSet, GrAAType::kCoverage, stencilSettings) 786 , fColor(color) 787 , fCoverage(coverage) { 788 fPaths.emplace_back(PathData{viewMatrix, path, devClipBounds, capLength}); 789 790 this->setTransformedBounds(path.getBounds(), viewMatrix, HasAABloat::kYes, 791 IsHairline::kYes); 792 } 793 794 const char* name() const override { return "AAHairlineOp"; } 795 796 void visitProxies(const GrVisitProxyFunc& func) const override { 797 798 bool visited = false; 799 for (int i = 0; i < 3; ++i) { 800 if (fProgramInfos[i]) { 801 fProgramInfos[i]->visitFPProxies(func); 802 visited = true; 803 } 804 } 805 806 if (!visited) { 807 fHelper.visitProxies(func); 808 } 809 } 810 811 FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); } 812 813 GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip, 814 GrClampType clampType) override { 815 // This Op uses uniform (not vertex) color, so doesn't need to track wide color. 816 return fHelper.finalizeProcessors(caps, clip, clampType, 817 GrProcessorAnalysisCoverage::kSingleChannel, &fColor, 818 nullptr); 819 } 820 821 enum class Program : uint8_t { 822 kNone = 0x0, 823 kLine = 0x1, 824 kQuad = 0x2, 825 kConic = 0x4, 826 }; 827 828private: 829 void makeLineProgramInfo(const GrCaps&, SkArenaAlloc*, const GrPipeline*, 830 const GrSurfaceProxyView& writeView, 831 bool usesMSAASurface, 832 const SkMatrix* geometryProcessorViewM, 833 const SkMatrix* geometryProcessorLocalM, 834 GrXferBarrierFlags renderPassXferBarriers, 835 GrLoadOp colorLoadOp); 836 void makeQuadProgramInfo(const GrCaps&, SkArenaAlloc*, const GrPipeline*, 837 const GrSurfaceProxyView& writeView, 838 bool usesMSAASurface, 839 const SkMatrix* geometryProcessorViewM, 840 const SkMatrix* geometryProcessorLocalM, 841 GrXferBarrierFlags renderPassXferBarriers, 842 GrLoadOp colorLoadOp); 843 void makeConicProgramInfo(const GrCaps&, SkArenaAlloc*, const GrPipeline*, 844 const GrSurfaceProxyView& writeView, 845 bool usesMSAASurface, 846 const SkMatrix* geometryProcessorViewM, 847 const SkMatrix* geometryProcessorLocalM, 848 GrXferBarrierFlags renderPassXferBarriers, 849 GrLoadOp colorLoadOp); 850 851 GrProgramInfo* programInfo() override { 852 // This Op has 3 programInfos and implements its own onPrePrepareDraws so this entry point 853 // should really never be called. 854 SkASSERT(0); 855 return nullptr; 856 } 857 858 Program predictPrograms(const GrCaps*) const; 859 860 void onCreateProgramInfo(const GrCaps*, 861 SkArenaAlloc*, 862 const GrSurfaceProxyView& writeView, 863 bool usesMSAASurface, 864 GrAppliedClip&&, 865 const GrDstProxyView&, 866 GrXferBarrierFlags renderPassXferBarriers, 867 GrLoadOp colorLoadOp) override; 868 869 void onPrePrepareDraws(GrRecordingContext*, 870 const GrSurfaceProxyView& writeView, 871 GrAppliedClip*, 872 const GrDstProxyView&, 873 GrXferBarrierFlags renderPassXferBarriers, 874 GrLoadOp colorLoadOp) override; 875 876 void onPrepareDraws(GrMeshDrawTarget*) override; 877 void onExecute(GrOpFlushState*, const SkRect& chainBounds) override; 878 879 CombineResult onCombineIfPossible(GrOp* t, SkArenaAlloc*, const GrCaps& caps) override { 880 AAHairlineOp* that = t->cast<AAHairlineOp>(); 881 882 if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) { 883 return CombineResult::kCannotCombine; 884 } 885 886 if (this->viewMatrix().hasPerspective() != that->viewMatrix().hasPerspective()) { 887 return CombineResult::kCannotCombine; 888 } 889 890 // We go to identity if we don't have perspective 891 if (this->viewMatrix().hasPerspective() && 892 !SkMatrixPriv::CheapEqual(this->viewMatrix(), that->viewMatrix())) { 893 return CombineResult::kCannotCombine; 894 } 895 896 // TODO we can actually combine hairlines if they are the same color in a kind of bulk 897 // method but we haven't implemented this yet 898 // TODO investigate going to vertex color and coverage? 899 if (this->coverage() != that->coverage()) { 900 return CombineResult::kCannotCombine; 901 } 902 903 if (this->color() != that->color()) { 904 return CombineResult::kCannotCombine; 905 } 906 907 if (fHelper.usesLocalCoords() && !SkMatrixPriv::CheapEqual(this->viewMatrix(), 908 that->viewMatrix())) { 909 return CombineResult::kCannotCombine; 910 } 911 912 fPaths.push_back_n(that->fPaths.count(), that->fPaths.begin()); 913 return CombineResult::kMerged; 914 } 915 916#if GR_TEST_UTILS 917 SkString onDumpInfo() const override { 918 return SkStringPrintf("Color: 0x%08x Coverage: 0x%02x, Count: %d\n%s", 919 fColor.toBytes_RGBA(), fCoverage, fPaths.count(), 920 fHelper.dumpInfo().c_str()); 921 } 922#endif 923 924 const SkPMColor4f& color() const { return fColor; } 925 uint8_t coverage() const { return fCoverage; } 926 const SkMatrix& viewMatrix() const { return fPaths[0].fViewMatrix; } 927 928 struct PathData { 929 SkMatrix fViewMatrix; 930 SkPath fPath; 931 SkIRect fDevClipBounds; 932 SkScalar fCapLength; 933 }; 934 935 SkSTArray<1, PathData, true> fPaths; 936 Helper fHelper; 937 SkPMColor4f fColor; 938 uint8_t fCoverage; 939 940 Program fCharacterization = Program::kNone; // holds a mask of required programs 941 GrSimpleMesh* fMeshes[3] = { nullptr }; 942 GrProgramInfo* fProgramInfos[3] = { nullptr }; 943 944 using INHERITED = GrMeshDrawOp; 945}; 946 947GR_MAKE_BITFIELD_CLASS_OPS(AAHairlineOp::Program) 948 949void AAHairlineOp::makeLineProgramInfo(const GrCaps& caps, SkArenaAlloc* arena, 950 const GrPipeline* pipeline, 951 const GrSurfaceProxyView& writeView, 952 bool usesMSAASurface, 953 const SkMatrix* geometryProcessorViewM, 954 const SkMatrix* geometryProcessorLocalM, 955 GrXferBarrierFlags renderPassXferBarriers, 956 GrLoadOp colorLoadOp) { 957 if (fProgramInfos[0]) { 958 return; 959 } 960 961 GrGeometryProcessor* lineGP; 962 { 963 using namespace GrDefaultGeoProcFactory; 964 965 Color color(this->color()); 966 LocalCoords localCoords(fHelper.usesLocalCoords() ? LocalCoords::kUsePosition_Type 967 : LocalCoords::kUnused_Type); 968 localCoords.fMatrix = geometryProcessorLocalM; 969 970 lineGP = GrDefaultGeoProcFactory::Make(arena, 971 color, 972 Coverage::kAttribute_Type, 973 localCoords, 974 *geometryProcessorViewM); 975 SkASSERT(sizeof(LineVertex) == lineGP->vertexStride()); 976 } 977 978 fProgramInfos[0] = GrSimpleMeshDrawOpHelper::CreateProgramInfo( 979 &caps, arena, pipeline, writeView, usesMSAASurface, lineGP, GrPrimitiveType::kTriangles, 980 renderPassXferBarriers, colorLoadOp, fHelper.stencilSettings()); 981} 982 983void AAHairlineOp::makeQuadProgramInfo(const GrCaps& caps, SkArenaAlloc* arena, 984 const GrPipeline* pipeline, 985 const GrSurfaceProxyView& writeView, 986 bool usesMSAASurface, 987 const SkMatrix* geometryProcessorViewM, 988 const SkMatrix* geometryProcessorLocalM, 989 GrXferBarrierFlags renderPassXferBarriers, 990 GrLoadOp colorLoadOp) { 991 if (fProgramInfos[1]) { 992 return; 993 } 994 995 GrGeometryProcessor* quadGP = GrQuadEffect::Make(arena, 996 this->color(), 997 *geometryProcessorViewM, 998 caps, 999 *geometryProcessorLocalM, 1000 fHelper.usesLocalCoords(), 1001 this->coverage()); 1002 SkASSERT(sizeof(BezierVertex) == quadGP->vertexStride()); 1003 1004 fProgramInfos[1] = GrSimpleMeshDrawOpHelper::CreateProgramInfo( 1005 &caps, arena, pipeline, writeView, usesMSAASurface, quadGP, GrPrimitiveType::kTriangles, 1006 renderPassXferBarriers, colorLoadOp, fHelper.stencilSettings()); 1007} 1008 1009void AAHairlineOp::makeConicProgramInfo(const GrCaps& caps, SkArenaAlloc* arena, 1010 const GrPipeline* pipeline, 1011 const GrSurfaceProxyView& writeView, 1012 bool usesMSAASurface, 1013 const SkMatrix* geometryProcessorViewM, 1014 const SkMatrix* geometryProcessorLocalM, 1015 GrXferBarrierFlags renderPassXferBarriers, 1016 GrLoadOp colorLoadOp) { 1017 if (fProgramInfos[2]) { 1018 return; 1019 } 1020 1021 GrGeometryProcessor* conicGP = GrConicEffect::Make(arena, 1022 this->color(), 1023 *geometryProcessorViewM, 1024 caps, 1025 *geometryProcessorLocalM, 1026 fHelper.usesLocalCoords(), 1027 this->coverage()); 1028 SkASSERT(sizeof(BezierVertex) == conicGP->vertexStride()); 1029 1030 fProgramInfos[2] = GrSimpleMeshDrawOpHelper::CreateProgramInfo( 1031 &caps, arena, pipeline, writeView, usesMSAASurface, conicGP, 1032 GrPrimitiveType::kTriangles, renderPassXferBarriers, colorLoadOp, 1033 fHelper.stencilSettings()); 1034} 1035 1036AAHairlineOp::Program AAHairlineOp::predictPrograms(const GrCaps* caps) const { 1037 bool convertConicsToQuads = !caps->shaderCaps()->floatIs32Bits(); 1038 1039 // When predicting the programs we always include the lineProgram bc it is used as a fallback 1040 // for quads and conics. In non-DDL mode there are cases where it sometimes isn't needed for a 1041 // given path. 1042 Program neededPrograms = Program::kLine; 1043 1044 for (int i = 0; i < fPaths.count(); i++) { 1045 uint32_t mask = fPaths[i].fPath.getSegmentMasks(); 1046 1047 if (mask & (SkPath::kQuad_SegmentMask | SkPath::kCubic_SegmentMask)) { 1048 neededPrograms |= Program::kQuad; 1049 } 1050 if (mask & SkPath::kConic_SegmentMask) { 1051 if (convertConicsToQuads) { 1052 neededPrograms |= Program::kQuad; 1053 } else { 1054 neededPrograms |= Program::kConic; 1055 } 1056 } 1057 } 1058 1059 return neededPrograms; 1060} 1061 1062void AAHairlineOp::onCreateProgramInfo(const GrCaps* caps, 1063 SkArenaAlloc* arena, 1064 const GrSurfaceProxyView& writeView, 1065 bool usesMSAASurface, 1066 GrAppliedClip&& appliedClip, 1067 const GrDstProxyView& dstProxyView, 1068 GrXferBarrierFlags renderPassXferBarriers, 1069 GrLoadOp colorLoadOp) { 1070 // Setup the viewmatrix and localmatrix for the GrGeometryProcessor. 1071 SkMatrix invert; 1072 if (!this->viewMatrix().invert(&invert)) { 1073 return; 1074 } 1075 1076 // we will transform to identity space if the viewmatrix does not have perspective 1077 bool hasPerspective = this->viewMatrix().hasPerspective(); 1078 const SkMatrix* geometryProcessorViewM = &SkMatrix::I(); 1079 const SkMatrix* geometryProcessorLocalM = &invert; 1080 if (hasPerspective) { 1081 geometryProcessorViewM = &this->viewMatrix(); 1082 geometryProcessorLocalM = &SkMatrix::I(); 1083 } 1084 1085 auto pipeline = fHelper.createPipeline(caps, arena, writeView.swizzle(), 1086 std::move(appliedClip), dstProxyView); 1087 1088 if (fCharacterization & Program::kLine) { 1089 this->makeLineProgramInfo(*caps, arena, pipeline, writeView, usesMSAASurface, 1090 geometryProcessorViewM, geometryProcessorLocalM, 1091 renderPassXferBarriers, colorLoadOp); 1092 } 1093 if (fCharacterization & Program::kQuad) { 1094 this->makeQuadProgramInfo(*caps, arena, pipeline, writeView, usesMSAASurface, 1095 geometryProcessorViewM, geometryProcessorLocalM, 1096 renderPassXferBarriers, colorLoadOp); 1097 } 1098 if (fCharacterization & Program::kConic) { 1099 this->makeConicProgramInfo(*caps, arena, pipeline, writeView, usesMSAASurface, 1100 geometryProcessorViewM, geometryProcessorLocalM, 1101 renderPassXferBarriers, colorLoadOp); 1102 1103 } 1104} 1105 1106void AAHairlineOp::onPrePrepareDraws(GrRecordingContext* context, 1107 const GrSurfaceProxyView& writeView, 1108 GrAppliedClip* clip, 1109 const GrDstProxyView& dstProxyView, 1110 GrXferBarrierFlags renderPassXferBarriers, 1111 GrLoadOp colorLoadOp) { 1112 SkArenaAlloc* arena = context->priv().recordTimeAllocator(); 1113 const GrCaps* caps = context->priv().caps(); 1114 1115 // http://skbug.com/12201 -- DDL does not yet support DMSAA. 1116 bool usesMSAASurface = writeView.asRenderTargetProxy()->numSamples() > 1; 1117 1118 // This is equivalent to a GrOpFlushState::detachAppliedClip 1119 GrAppliedClip appliedClip = clip ? std::move(*clip) : GrAppliedClip::Disabled(); 1120 1121 // Conservatively predict which programs will be required 1122 fCharacterization = this->predictPrograms(caps); 1123 1124 this->createProgramInfo(caps, arena, writeView, usesMSAASurface, std::move(appliedClip), 1125 dstProxyView, renderPassXferBarriers, colorLoadOp); 1126 1127 context->priv().recordProgramInfo(fProgramInfos[0]); 1128 context->priv().recordProgramInfo(fProgramInfos[1]); 1129 context->priv().recordProgramInfo(fProgramInfos[2]); 1130} 1131 1132void AAHairlineOp::onPrepareDraws(GrMeshDrawTarget* target) { 1133 // Setup the viewmatrix and localmatrix for the GrGeometryProcessor. 1134 SkMatrix invert; 1135 if (!this->viewMatrix().invert(&invert)) { 1136 return; 1137 } 1138 1139 // we will transform to identity space if the viewmatrix does not have perspective 1140 const SkMatrix* toDevice = nullptr; 1141 const SkMatrix* toSrc = nullptr; 1142 if (this->viewMatrix().hasPerspective()) { 1143 toDevice = &this->viewMatrix(); 1144 toSrc = &invert; 1145 } 1146 1147 SkDEBUGCODE(Program predictedPrograms = this->predictPrograms(&target->caps())); 1148 Program actualPrograms = Program::kNone; 1149 1150 // This is hand inlined for maximum performance. 1151 PREALLOC_PTARRAY(128) lines; 1152 PREALLOC_PTARRAY(128) quads; 1153 PREALLOC_PTARRAY(128) conics; 1154 IntArray qSubdivs; 1155 FloatArray cWeights; 1156 int quadCount = 0; 1157 1158 int instanceCount = fPaths.count(); 1159 bool convertConicsToQuads = !target->caps().shaderCaps()->floatIs32Bits(); 1160 for (int i = 0; i < instanceCount; i++) { 1161 const PathData& args = fPaths[i]; 1162 quadCount += gather_lines_and_quads(args.fPath, args.fViewMatrix, args.fDevClipBounds, 1163 args.fCapLength, convertConicsToQuads, &lines, &quads, 1164 &conics, &qSubdivs, &cWeights); 1165 } 1166 1167 int lineCount = lines.count() / 2; 1168 int conicCount = conics.count() / 3; 1169 int quadAndConicCount = conicCount + quadCount; 1170 1171 static constexpr int kMaxLines = SK_MaxS32 / kLineSegNumVertices; 1172 static constexpr int kMaxQuadsAndConics = SK_MaxS32 / kQuadNumVertices; 1173 if (lineCount > kMaxLines || quadAndConicCount > kMaxQuadsAndConics) { 1174 return; 1175 } 1176 1177 // do lines first 1178 if (lineCount) { 1179 SkASSERT(predictedPrograms & Program::kLine); 1180 actualPrograms |= Program::kLine; 1181 1182 sk_sp<const GrBuffer> linesIndexBuffer = get_lines_index_buffer(target->resourceProvider()); 1183 1184 GrMeshDrawOp::PatternHelper helper(target, GrPrimitiveType::kTriangles, sizeof(LineVertex), 1185 std::move(linesIndexBuffer), kLineSegNumVertices, 1186 kIdxsPerLineSeg, lineCount, kLineSegsNumInIdxBuffer); 1187 1188 LineVertex* verts = reinterpret_cast<LineVertex*>(helper.vertices()); 1189 if (!verts) { 1190 SkDebugf("Could not allocate vertices\n"); 1191 return; 1192 } 1193 1194 for (int i = 0; i < lineCount; ++i) { 1195 add_line(&lines[2*i], toSrc, this->coverage(), &verts); 1196 } 1197 1198 fMeshes[0] = helper.mesh(); 1199 } 1200 1201 if (quadCount || conicCount) { 1202 sk_sp<const GrBuffer> vertexBuffer; 1203 int firstVertex; 1204 1205 sk_sp<const GrBuffer> quadsIndexBuffer = get_quads_index_buffer(target->resourceProvider()); 1206 1207 int vertexCount = kQuadNumVertices * quadAndConicCount; 1208 void* vertices = target->makeVertexSpace(sizeof(BezierVertex), vertexCount, &vertexBuffer, 1209 &firstVertex); 1210 1211 if (!vertices || !quadsIndexBuffer) { 1212 SkDebugf("Could not allocate vertices\n"); 1213 return; 1214 } 1215 1216 // Setup vertices 1217 BezierVertex* bezVerts = reinterpret_cast<BezierVertex*>(vertices); 1218 1219 int unsubdivQuadCnt = quads.count() / 3; 1220 for (int i = 0; i < unsubdivQuadCnt; ++i) { 1221 SkASSERT(qSubdivs[i] >= 0); 1222 if (!quads[3*i].isFinite() || !quads[3*i+1].isFinite() || !quads[3*i+2].isFinite()) { 1223 return; 1224 } 1225 add_quads(&quads[3*i], qSubdivs[i], toDevice, toSrc, &bezVerts); 1226 } 1227 1228 // Start Conics 1229 for (int i = 0; i < conicCount; ++i) { 1230 add_conics(&conics[3*i], cWeights[i], toDevice, toSrc, &bezVerts); 1231 } 1232 1233 if (quadCount > 0) { 1234 SkASSERT(predictedPrograms & Program::kQuad); 1235 actualPrograms |= Program::kQuad; 1236 1237 fMeshes[1] = target->allocMesh(); 1238 fMeshes[1]->setIndexedPatterned(quadsIndexBuffer, kIdxsPerQuad, quadCount, 1239 kQuadsNumInIdxBuffer, vertexBuffer, kQuadNumVertices, 1240 firstVertex); 1241 firstVertex += quadCount * kQuadNumVertices; 1242 } 1243 1244 if (conicCount > 0) { 1245 SkASSERT(predictedPrograms & Program::kConic); 1246 actualPrograms |= Program::kConic; 1247 1248 fMeshes[2] = target->allocMesh(); 1249 fMeshes[2]->setIndexedPatterned(std::move(quadsIndexBuffer), kIdxsPerQuad, conicCount, 1250 kQuadsNumInIdxBuffer, std::move(vertexBuffer), 1251 kQuadNumVertices, firstVertex); 1252 } 1253 } 1254 1255 // In DDL mode this will replace the predicted program requirements with the actual ones. 1256 // However, we will already have surfaced the predicted programs to the DDL. 1257 fCharacterization = actualPrograms; 1258} 1259 1260void AAHairlineOp::onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) { 1261 this->createProgramInfo(flushState); 1262 1263 for (int i = 0; i < 3; ++i) { 1264 if (fProgramInfos[i] && fMeshes[i]) { 1265 flushState->bindPipelineAndScissorClip(*fProgramInfos[i], chainBounds); 1266 flushState->bindTextures(fProgramInfos[i]->geomProc(), nullptr, 1267 fProgramInfos[i]->pipeline()); 1268 flushState->drawMesh(*fMeshes[i]); 1269 } 1270 } 1271} 1272 1273} // anonymous namespace 1274 1275/////////////////////////////////////////////////////////////////////////////////////////////////// 1276 1277#if GR_TEST_UTILS 1278 1279GR_DRAW_OP_TEST_DEFINE(AAHairlineOp) { 1280 SkMatrix viewMatrix = GrTest::TestMatrix(random); 1281 const SkPath& path = GrTest::TestPath(random); 1282 SkIRect devClipBounds; 1283 devClipBounds.setEmpty(); 1284 return AAHairlineOp::Make(context, std::move(paint), viewMatrix, path, 1285 GrStyle::SimpleHairline(), devClipBounds, 1286 GrGetRandomStencil(random, context)); 1287} 1288 1289#endif 1290 1291/////////////////////////////////////////////////////////////////////////////////////////////////// 1292 1293namespace skgpu::v1 { 1294 1295PathRenderer::CanDrawPath AAHairLinePathRenderer::onCanDrawPath(const CanDrawPathArgs& args) const { 1296 if (GrAAType::kCoverage != args.fAAType) { 1297 return CanDrawPath::kNo; 1298 } 1299 1300 if (!GrIsStrokeHairlineOrEquivalent(args.fShape->style(), *args.fViewMatrix, nullptr)) { 1301 return CanDrawPath::kNo; 1302 } 1303 1304 // We don't currently handle dashing in this class though perhaps we should. 1305 if (args.fShape->style().pathEffect()) { 1306 return CanDrawPath::kNo; 1307 } 1308 1309 if (SkPath::kLine_SegmentMask == args.fShape->segmentMask() || 1310 args.fCaps->shaderCaps()->shaderDerivativeSupport()) { 1311 return CanDrawPath::kYes; 1312 } 1313 1314 return CanDrawPath::kNo; 1315} 1316 1317 1318bool AAHairLinePathRenderer::onDrawPath(const DrawPathArgs& args) { 1319 GR_AUDIT_TRAIL_AUTO_FRAME(args.fContext->priv().auditTrail(), 1320 "AAHairlinePathRenderer::onDrawPath"); 1321 SkASSERT(args.fSurfaceDrawContext->numSamples() <= 1); 1322 1323 SkPath path; 1324 args.fShape->asPath(&path); 1325 GrOp::Owner op = 1326 AAHairlineOp::Make(args.fContext, std::move(args.fPaint), *args.fViewMatrix, path, 1327 args.fShape->style(), *args.fClipConservativeBounds, 1328 args.fUserStencilSettings); 1329 args.fSurfaceDrawContext->addDrawOp(args.fClip, std::move(op)); 1330 return true; 1331} 1332 1333} // namespace skgpu::v1 1334 1335