blob: 6c2daab2648ca5ba42b28b9f0492c3f12bb9a7d6 [file] [log] [blame]
Michael Ludwig0f809022019-06-04 09:14:37 -04001/*
2 * Copyright 2019 Google LLC
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/geometry/GrQuadUtils.h"
9
Michael Ludwig61328202019-06-19 14:48:58 +000010#include "include/core/SkRect.h"
Michael Ludwig0f809022019-06-04 09:14:37 -040011#include "include/private/GrTypesPriv.h"
Michael Ludwig61328202019-06-19 14:48:58 +000012#include "include/private/SkVx.h"
Michael Ludwig0f809022019-06-04 09:14:37 -040013#include "src/gpu/geometry/GrQuad.h"
14
Michael Ludwig61328202019-06-19 14:48:58 +000015using V4f = skvx::Vec<4, float>;
16using M4f = skvx::Vec<4, int32_t>;
17
Michael Ludwigfb7ba522019-10-29 15:33:34 -040018#define AI SK_ALWAYS_INLINE
19
20static constexpr float kTolerance = 1e-2f;
21// True/false bit masks for initializing an M4f
22static constexpr int32_t kTrue = ~0;
23static constexpr int32_t kFalse = 0;
24
25// These rotate the points/edge values either clockwise or counterclockwise assuming tri strip
26// order.
27static AI V4f next_cw(const V4f& v) {
28 return skvx::shuffle<2, 0, 3, 1>(v);
29}
30
31static AI V4f next_ccw(const V4f& v) {
32 return skvx::shuffle<1, 3, 0, 2>(v);
33}
34
35// Replaces zero-length 'bad' edge vectors with the reversed opposite edge vector.
36// e3 may be null if only 2D edges need to be corrected for.
37static AI void correct_bad_edges(const M4f& bad, V4f* e1, V4f* e2, V4f* e3) {
38 if (any(bad)) {
39 // Want opposite edges, L B T R -> R T B L but with flipped sign to preserve winding
40 *e1 = if_then_else(bad, -skvx::shuffle<3, 2, 1, 0>(*e1), *e1);
41 *e2 = if_then_else(bad, -skvx::shuffle<3, 2, 1, 0>(*e2), *e2);
42 if (e3) {
43 *e3 = if_then_else(bad, -skvx::shuffle<3, 2, 1, 0>(*e3), *e3);
44 }
45 }
46}
47
48// Replace 'bad' coordinates by rotating CCW to get the next point. c3 may be null for 2D points.
49static AI void correct_bad_coords(const M4f& bad, V4f* c1, V4f* c2, V4f* c3) {
50 if (any(bad)) {
51 *c1 = if_then_else(bad, next_ccw(*c1), *c1);
52 *c2 = if_then_else(bad, next_ccw(*c2), *c2);
53 if (c3) {
54 *c3 = if_then_else(bad, next_ccw(*c3), *c3);
55 }
56 }
57}
58
Michael Ludwig61328202019-06-19 14:48:58 +000059// Since the local quad may not be type kRect, this uses the opposites for each vertex when
60// interpolating, and calculates new ws in addition to new xs, ys.
61static void interpolate_local(float alpha, int v0, int v1, int v2, int v3,
62 float lx[4], float ly[4], float lw[4]) {
63 SkASSERT(v0 >= 0 && v0 < 4);
64 SkASSERT(v1 >= 0 && v1 < 4);
65 SkASSERT(v2 >= 0 && v2 < 4);
66 SkASSERT(v3 >= 0 && v3 < 4);
67
68 float beta = 1.f - alpha;
69 lx[v0] = alpha * lx[v0] + beta * lx[v2];
70 ly[v0] = alpha * ly[v0] + beta * ly[v2];
71 lw[v0] = alpha * lw[v0] + beta * lw[v2];
72
73 lx[v1] = alpha * lx[v1] + beta * lx[v3];
74 ly[v1] = alpha * ly[v1] + beta * ly[v3];
75 lw[v1] = alpha * lw[v1] + beta * lw[v3];
76}
77
78// Crops v0 to v1 based on the clipDevRect. v2 is opposite of v0, v3 is opposite of v1.
79// It is written to not modify coordinates if there's no intersection along the edge.
80// Ideally this would have been detected earlier and the entire draw is skipped.
81static bool crop_rect_edge(const SkRect& clipDevRect, int v0, int v1, int v2, int v3,
82 float x[4], float y[4], float lx[4], float ly[4], float lw[4]) {
83 SkASSERT(v0 >= 0 && v0 < 4);
84 SkASSERT(v1 >= 0 && v1 < 4);
85 SkASSERT(v2 >= 0 && v2 < 4);
86 SkASSERT(v3 >= 0 && v3 < 4);
87
88 if (SkScalarNearlyEqual(x[v0], x[v1])) {
89 // A vertical edge
90 if (x[v0] < clipDevRect.fLeft && x[v2] >= clipDevRect.fLeft) {
91 // Overlapping with left edge of clipDevRect
92 if (lx) {
93 float alpha = (x[v2] - clipDevRect.fLeft) / (x[v2] - x[v0]);
94 interpolate_local(alpha, v0, v1, v2, v3, lx, ly, lw);
95 }
96 x[v0] = clipDevRect.fLeft;
97 x[v1] = clipDevRect.fLeft;
98 return true;
99 } else if (x[v0] > clipDevRect.fRight && x[v2] <= clipDevRect.fRight) {
100 // Overlapping with right edge of clipDevRect
101 if (lx) {
102 float alpha = (clipDevRect.fRight - x[v2]) / (x[v0] - x[v2]);
103 interpolate_local(alpha, v0, v1, v2, v3, lx, ly, lw);
104 }
105 x[v0] = clipDevRect.fRight;
106 x[v1] = clipDevRect.fRight;
107 return true;
108 }
109 } else {
110 // A horizontal edge
111 SkASSERT(SkScalarNearlyEqual(y[v0], y[v1]));
112 if (y[v0] < clipDevRect.fTop && y[v2] >= clipDevRect.fTop) {
113 // Overlapping with top edge of clipDevRect
114 if (lx) {
115 float alpha = (y[v2] - clipDevRect.fTop) / (y[v2] - y[v0]);
116 interpolate_local(alpha, v0, v1, v2, v3, lx, ly, lw);
117 }
118 y[v0] = clipDevRect.fTop;
119 y[v1] = clipDevRect.fTop;
120 return true;
121 } else if (y[v0] > clipDevRect.fBottom && y[v2] <= clipDevRect.fBottom) {
122 // Overlapping with bottom edge of clipDevRect
123 if (lx) {
124 float alpha = (clipDevRect.fBottom - y[v2]) / (y[v0] - y[v2]);
125 interpolate_local(alpha, v0, v1, v2, v3, lx, ly, lw);
126 }
127 y[v0] = clipDevRect.fBottom;
128 y[v1] = clipDevRect.fBottom;
129 return true;
130 }
131 }
132
133 // No overlap so don't crop it
134 return false;
135}
136
Michael Ludwig0a7cab02019-07-09 17:20:08 +0000137// Updates x and y to intersect with clipDevRect. lx, ly, and lw are updated appropriately and may
138// be null to skip calculations. Returns bit mask of edges that were clipped.
139static GrQuadAAFlags crop_rect(const SkRect& clipDevRect, float x[4], float y[4],
140 float lx[4], float ly[4], float lw[4]) {
Michael Ludwig61328202019-06-19 14:48:58 +0000141 GrQuadAAFlags clipEdgeFlags = GrQuadAAFlags::kNone;
142
Michael Ludwig0a7cab02019-07-09 17:20:08 +0000143 // The quad's left edge may not align with the SkRect notion of left due to 90 degree rotations
144 // or mirrors. So, this processes the logical edges of the quad and clamps it to the 4 sides of
145 // clipDevRect.
Michael Ludwig61328202019-06-19 14:48:58 +0000146
147 // Quad's left is v0 to v1 (op. v2 and v3)
148 if (crop_rect_edge(clipDevRect, 0, 1, 2, 3, x, y, lx, ly, lw)) {
149 clipEdgeFlags |= GrQuadAAFlags::kLeft;
150 }
151 // Quad's top edge is v0 to v2 (op. v1 and v3)
152 if (crop_rect_edge(clipDevRect, 0, 2, 1, 3, x, y, lx, ly, lw)) {
153 clipEdgeFlags |= GrQuadAAFlags::kTop;
154 }
155 // Quad's right edge is v2 to v3 (op. v0 and v1)
156 if (crop_rect_edge(clipDevRect, 2, 3, 0, 1, x, y, lx, ly, lw)) {
157 clipEdgeFlags |= GrQuadAAFlags::kRight;
158 }
159 // Quad's bottom edge is v1 to v3 (op. v0 and v2)
160 if (crop_rect_edge(clipDevRect, 1, 3, 0, 2, x, y, lx, ly, lw)) {
161 clipEdgeFlags |= GrQuadAAFlags::kBottom;
162 }
163
Michael Ludwig0a7cab02019-07-09 17:20:08 +0000164 return clipEdgeFlags;
165}
166
167// Similar to crop_rect, but assumes that both the device coordinates and optional local coordinates
168// geometrically match the TL, BL, TR, BR vertex ordering, i.e. axis-aligned but not flipped, etc.
169static GrQuadAAFlags crop_simple_rect(const SkRect& clipDevRect, float x[4], float y[4],
170 float lx[4], float ly[4]) {
171 GrQuadAAFlags clipEdgeFlags = GrQuadAAFlags::kNone;
172
173 // Update local coordinates proportionately to how much the device rect edge was clipped
174 const SkScalar dx = lx ? (lx[2] - lx[0]) / (x[2] - x[0]) : 0.f;
175 const SkScalar dy = ly ? (ly[1] - ly[0]) / (y[1] - y[0]) : 0.f;
176 if (clipDevRect.fLeft > x[0]) {
177 if (lx) {
178 lx[0] += (clipDevRect.fLeft - x[0]) * dx;
179 lx[1] = lx[0];
180 }
181 x[0] = clipDevRect.fLeft;
182 x[1] = clipDevRect.fLeft;
183 clipEdgeFlags |= GrQuadAAFlags::kLeft;
Michael Ludwig61328202019-06-19 14:48:58 +0000184 }
Michael Ludwig0a7cab02019-07-09 17:20:08 +0000185 if (clipDevRect.fTop > y[0]) {
186 if (ly) {
187 ly[0] += (clipDevRect.fTop - y[0]) * dy;
188 ly[2] = ly[0];
189 }
190 y[0] = clipDevRect.fTop;
191 y[2] = clipDevRect.fTop;
192 clipEdgeFlags |= GrQuadAAFlags::kTop;
193 }
194 if (clipDevRect.fRight < x[2]) {
195 if (lx) {
196 lx[2] -= (x[2] - clipDevRect.fRight) * dx;
197 lx[3] = lx[2];
198 }
199 x[2] = clipDevRect.fRight;
200 x[3] = clipDevRect.fRight;
201 clipEdgeFlags |= GrQuadAAFlags::kRight;
202 }
203 if (clipDevRect.fBottom < y[1]) {
204 if (ly) {
205 ly[1] -= (y[1] - clipDevRect.fBottom) * dy;
206 ly[3] = ly[1];
207 }
208 y[1] = clipDevRect.fBottom;
209 y[3] = clipDevRect.fBottom;
210 clipEdgeFlags |= GrQuadAAFlags::kBottom;
211 }
212
213 return clipEdgeFlags;
214}
215// Consistent with GrQuad::asRect()'s return value but requires fewer operations since we don't need
216// to calculate the bounds of the quad.
217static bool is_simple_rect(const GrQuad& quad) {
218 if (quad.quadType() != GrQuad::Type::kAxisAligned) {
219 return false;
220 }
221 // v0 at the geometric top-left is unique, so we only need to compare x[0] < x[2] for left
222 // and y[0] < y[1] for top, but add a little padding to protect against numerical precision
223 // on R90 and R270 transforms tricking this check.
224 return ((quad.x(0) + SK_ScalarNearlyZero) < quad.x(2)) &&
225 ((quad.y(0) + SK_ScalarNearlyZero) < quad.y(1));
Michael Ludwig61328202019-06-19 14:48:58 +0000226}
227
228// Calculates barycentric coordinates for each point in (testX, testY) in the triangle formed by
229// (x0,y0) - (x1,y1) - (x2, y2) and stores them in u, v, w.
230static void barycentric_coords(float x0, float y0, float x1, float y1, float x2, float y2,
231 const V4f& testX, const V4f& testY,
232 V4f* u, V4f* v, V4f* w) {
233 // Modeled after SkPathOpsQuad::pointInTriangle() but uses float instead of double, is
234 // vectorized and outputs normalized barycentric coordinates instead of inside/outside test
235 float v0x = x2 - x0;
236 float v0y = y2 - y0;
237 float v1x = x1 - x0;
238 float v1y = y1 - y0;
239 V4f v2x = testX - x0;
240 V4f v2y = testY - y0;
241
242 float dot00 = v0x * v0x + v0y * v0y;
243 float dot01 = v0x * v1x + v0y * v1y;
244 V4f dot02 = v0x * v2x + v0y * v2y;
245 float dot11 = v1x * v1x + v1y * v1y;
246 V4f dot12 = v1x * v2x + v1y * v2y;
247 float invDenom = sk_ieee_float_divide(1.f, dot00 * dot11 - dot01 * dot01);
248 *u = (dot11 * dot02 - dot01 * dot12) * invDenom;
249 *v = (dot00 * dot12 - dot01 * dot02) * invDenom;
250 *w = 1.f - *u - *v;
251}
252
253static M4f inside_triangle(const V4f& u, const V4f& v, const V4f& w) {
254 return ((u >= 0.f) & (u <= 1.f)) & ((v >= 0.f) & (v <= 1.f)) & ((w >= 0.f) & (w <= 1.f));
255}
256
Michael Ludwig0f809022019-06-04 09:14:37 -0400257namespace GrQuadUtils {
258
259void ResolveAAType(GrAAType requestedAAType, GrQuadAAFlags requestedEdgeFlags, const GrQuad& quad,
260 GrAAType* outAAType, GrQuadAAFlags* outEdgeFlags) {
261 // Most cases will keep the requested types unchanged
262 *outAAType = requestedAAType;
263 *outEdgeFlags = requestedEdgeFlags;
264
265 switch (requestedAAType) {
266 // When aa type is coverage, disable AA if the edge configuration doesn't actually need it
267 case GrAAType::kCoverage:
268 if (requestedEdgeFlags == GrQuadAAFlags::kNone) {
269 // Turn off anti-aliasing
270 *outAAType = GrAAType::kNone;
271 } else {
272 // For coverage AA, if the quad is a rect and it lines up with pixel boundaries
273 // then overall aa and per-edge aa can be completely disabled
274 if (quad.quadType() == GrQuad::Type::kAxisAligned && !quad.aaHasEffectOnRect()) {
275 *outAAType = GrAAType::kNone;
276 *outEdgeFlags = GrQuadAAFlags::kNone;
277 }
278 }
279 break;
280 // For no or msaa anti aliasing, override the edge flags since edge flags only make sense
281 // when coverage aa is being used.
282 case GrAAType::kNone:
283 *outEdgeFlags = GrQuadAAFlags::kNone;
284 break;
285 case GrAAType::kMSAA:
286 *outEdgeFlags = GrQuadAAFlags::kAll;
287 break;
Michael Ludwig0f809022019-06-04 09:14:37 -0400288 }
Michael Ludwig61328202019-06-19 14:48:58 +0000289}
290
291bool CropToRect(const SkRect& cropRect, GrAA cropAA, GrQuadAAFlags* edgeFlags, GrQuad* quad,
292 GrQuad* local) {
Michael Ludwiged71b7e2019-06-21 13:47:02 -0400293 SkASSERT(quad->isFinite());
294
Michael Ludwig61328202019-06-19 14:48:58 +0000295 if (quad->quadType() == GrQuad::Type::kAxisAligned) {
Michael Ludwig0a7cab02019-07-09 17:20:08 +0000296 // crop_rect and crop_rect_simple keep the rectangles as rectangles, so the intersection
297 // of the crop and quad can be calculated exactly. Some care must be taken if the quad
298 // is axis-aligned but does not satisfy asRect() due to flips, etc.
299 GrQuadAAFlags clippedEdges;
Michael Ludwig61328202019-06-19 14:48:58 +0000300 if (local) {
Michael Ludwig0a7cab02019-07-09 17:20:08 +0000301 if (is_simple_rect(*quad) && is_simple_rect(*local)) {
302 clippedEdges = crop_simple_rect(cropRect, quad->xs(), quad->ys(),
303 local->xs(), local->ys());
304 } else {
305 clippedEdges = crop_rect(cropRect, quad->xs(), quad->ys(),
306 local->xs(), local->ys(), local->ws());
307 }
Michael Ludwig61328202019-06-19 14:48:58 +0000308 } else {
Michael Ludwig0a7cab02019-07-09 17:20:08 +0000309 if (is_simple_rect(*quad)) {
310 clippedEdges = crop_simple_rect(cropRect, quad->xs(), quad->ys(), nullptr, nullptr);
311 } else {
312 clippedEdges = crop_rect(cropRect, quad->xs(), quad->ys(),
313 nullptr, nullptr, nullptr);
314 }
315 }
316
317 // Apply the clipped edge updates to the original edge flags
318 if (cropAA == GrAA::kYes) {
319 // Turn on all edges that were clipped
320 *edgeFlags |= clippedEdges;
321 } else {
322 // Turn off all edges that were clipped
323 *edgeFlags &= ~clippedEdges;
Michael Ludwig61328202019-06-19 14:48:58 +0000324 }
325 return true;
326 }
327
328 if (local) {
329 // FIXME (michaelludwig) Calculate cropped local coordinates when not kAxisAligned
330 return false;
331 }
332
333 V4f devX = quad->x4f();
334 V4f devY = quad->y4f();
335 V4f devIW = quad->iw4f();
336 // Project the 3D coordinates to 2D
337 if (quad->quadType() == GrQuad::Type::kPerspective) {
338 devX *= devIW;
339 devY *= devIW;
340 }
341
342 V4f clipX = {cropRect.fLeft, cropRect.fLeft, cropRect.fRight, cropRect.fRight};
343 V4f clipY = {cropRect.fTop, cropRect.fBottom, cropRect.fTop, cropRect.fBottom};
344
345 // Calculate barycentric coordinates for the 4 rect corners in the 2 triangles that the quad
346 // is tessellated into when drawn.
347 V4f u1, v1, w1;
348 barycentric_coords(devX[0], devY[0], devX[1], devY[1], devX[2], devY[2], clipX, clipY,
349 &u1, &v1, &w1);
350 V4f u2, v2, w2;
351 barycentric_coords(devX[1], devY[1], devX[3], devY[3], devX[2], devY[2], clipX, clipY,
352 &u2, &v2, &w2);
353
354 // clipDevRect is completely inside this quad if each corner is in at least one of two triangles
355 M4f inTri1 = inside_triangle(u1, v1, w1);
356 M4f inTri2 = inside_triangle(u2, v2, w2);
357 if (all(inTri1 | inTri2)) {
358 // We can crop to exactly the clipDevRect.
359 // FIXME (michaelludwig) - there are other ways to have determined quad covering the clip
360 // rect, but the barycentric coords will be useful to derive local coordinates in the future
361
362 // Since we are cropped to exactly clipDevRect, we have discarded any perspective and the
363 // type becomes kRect. If updated locals were requested, they will incorporate perspective.
364 // FIXME (michaelludwig) - once we have local coordinates handled, it may be desirable to
365 // keep the draw as perspective so that the hardware does perspective interpolation instead
366 // of pushing it into a local coord w and having the shader do an extra divide.
367 clipX.store(quad->xs());
368 clipY.store(quad->ys());
369 quad->ws()[0] = 1.f;
370 quad->ws()[1] = 1.f;
371 quad->ws()[2] = 1.f;
372 quad->ws()[3] = 1.f;
373 quad->setQuadType(GrQuad::Type::kAxisAligned);
374
375 // Update the edge flags to match the clip setting since all 4 edges have been clipped
376 *edgeFlags = cropAA == GrAA::kYes ? GrQuadAAFlags::kAll : GrQuadAAFlags::kNone;
377
378 return true;
379 }
380
381 // FIXME (michaelludwig) - use the GrQuadPerEdgeAA tessellation inset/outset math to move
382 // edges to the closest clip corner they are outside of
383
384 return false;
385}
Michael Ludwig0f809022019-06-04 09:14:37 -0400386
Michael Ludwigfb7ba522019-10-29 15:33:34 -0400387///////////////////////////////////////////////////////////////////////////////////////////////////
388// TessellationHelper implementation
389///////////////////////////////////////////////////////////////////////////////////////////////////
390
391TessellationHelper::QuadMetadata TessellationHelper::getMetadata(const Vertices& vertices,
392 GrQuadAAFlags aaFlags) {
393 V4f dx = next_ccw(vertices.fX) - vertices.fX;
394 V4f dy = next_ccw(vertices.fY) - vertices.fY;
395 V4f invLengths = rsqrt(mad(dx, dx, dy * dy));
396
397 V4f mask = aaFlags == GrQuadAAFlags::kAll ? V4f(1.f) :
398 V4f{(GrQuadAAFlags::kLeft & aaFlags) ? 1.f : 0.f,
399 (GrQuadAAFlags::kBottom & aaFlags) ? 1.f : 0.f,
400 (GrQuadAAFlags::kTop & aaFlags) ? 1.f : 0.f,
401 (GrQuadAAFlags::kRight & aaFlags) ? 1.f : 0.f};
402 return { dx * invLengths, dy * invLengths, invLengths, mask };
403}
404
405TessellationHelper::Edges TessellationHelper::getEdgeEquations(const QuadMetadata& metadata,
406 const Vertices& vertices) {
407 V4f dx = metadata.fDX;
408 V4f dy = metadata.fDY;
409 // Correct for bad edges by copying adjacent edge information into the bad component
410 correct_bad_edges(metadata.fInvLengths >= 1.f / kTolerance, &dx, &dy, nullptr);
411
412 V4f c = mad(dx, vertices.fY, -dy * vertices.fX);
413 // Make sure normals point into the shape
414 V4f test = mad(dy, next_cw(vertices.fX), mad(-dx, next_cw(vertices.fY), c));
415 if (any(test < -kTolerance)) {
416 return {-dy, dx, -c, true};
417 } else {
418 return {dy, -dx, c, false};
419 }
420}
421
422bool TessellationHelper::getOptimizedOutset(const QuadMetadata& metadata,
423 bool rectilinear,
424 V4f* outset) {
425 if (rectilinear) {
426 *outset = 0.5f;
427 // Stay in the fast path as long as all edges are at least a pixel long (so 1/len <= 1)
428 return all(metadata.fInvLengths <= 1.f);
429 }
430
431 if (any(metadata.fInvLengths >= 1.f / kTolerance)) {
432 // Have an empty edge from a degenerate quad, so there's no hope
433 return false;
434 }
435
436 // The distance the point needs to move is 1/2sin(theta), where theta is the angle between the
437 // two edges at that point. cos(theta) is equal to dot(dxy, next_cw(dxy))
438 V4f cosTheta = mad(metadata.fDX, next_cw(metadata.fDX), metadata.fDY * next_cw(metadata.fDY));
439 // If the angle is too shallow between edges, go through the degenerate path, otherwise adding
440 // and subtracting very large vectors in almost opposite directions leads to float errors
441 if (any(abs(cosTheta) >= 0.9f)) {
442 return false;
443 }
444 *outset = 0.5f * rsqrt(1.f - cosTheta * cosTheta); // 1/2sin(theta)
445
446 // When outsetting or insetting, the current edge's AA adds to the length:
447 // cos(pi - theta)/2sin(theta) + cos(pi-ccw(theta))/2sin(ccw(theta))
448 // Moving an adjacent edge updates the length by 1/2sin(theta|ccw(theta))
449 V4f halfTanTheta = -cosTheta * (*outset); // cos(pi - theta) = -cos(theta)
450 V4f edgeAdjust = metadata.fMask * (halfTanTheta + next_ccw(halfTanTheta)) +
451 next_ccw(metadata.fMask) * next_ccw(*outset) +
452 next_cw(metadata.fMask) * (*outset);
453 // If either outsetting (plus edgeAdjust) or insetting (minus edgeAdjust) make edgeLen negative
454 // then use the slow path
455 V4f threshold = 0.1f - (1.f / metadata.fInvLengths);
456 return all(edgeAdjust > threshold) && all(edgeAdjust < -threshold);
457}
458
459void TessellationHelper::outsetVertices(const V4f& outset,
460 const QuadMetadata& metadata,
461 Vertices* quad) {
462 // The mask is rotated compared to the outsets and edge vectors, since if the edge is "on"
463 // both its points need to be moved along their other edge vectors.
464 auto maskedOutset = -outset * next_cw(metadata.fMask);
465 auto maskedOutsetCW = outset * metadata.fMask;
466 // x = x + outset * mask * next_cw(xdiff) - outset * next_cw(mask) * xdiff
467 quad->fX += mad(maskedOutsetCW, next_cw(metadata.fDX), maskedOutset * metadata.fDX);
468 quad->fY += mad(maskedOutsetCW, next_cw(metadata.fDY), maskedOutset * metadata.fDY);
469 if (quad->fUVRCount > 0) {
470 // We want to extend the texture coords by the same proportion as the positions.
471 maskedOutset *= metadata.fInvLengths;
472 maskedOutsetCW *= next_cw(metadata.fInvLengths);
473 V4f du = next_ccw(quad->fU) - quad->fU;
474 V4f dv = next_ccw(quad->fV) - quad->fV;
475 quad->fU += mad(maskedOutsetCW, next_cw(du), maskedOutset * du);
476 quad->fV += mad(maskedOutsetCW, next_cw(dv), maskedOutset * dv);
477 if (quad->fUVRCount == 3) {
478 V4f dr = next_ccw(quad->fR) - quad->fR;
479 quad->fR += mad(maskedOutsetCW, next_cw(dr), maskedOutset * dr);
480 }
481 }
482}
483
484void TessellationHelper::outsetProjectedVertices(const V4f& x2d, const V4f& y2d,
485 GrQuadAAFlags aaFlags, Vertices* quad) {
486 // Left to right, in device space, for each point
487 V4f e1x = skvx::shuffle<2, 3, 2, 3>(quad->fX) - skvx::shuffle<0, 1, 0, 1>(quad->fX);
488 V4f e1y = skvx::shuffle<2, 3, 2, 3>(quad->fY) - skvx::shuffle<0, 1, 0, 1>(quad->fY);
489 V4f e1w = skvx::shuffle<2, 3, 2, 3>(quad->fW) - skvx::shuffle<0, 1, 0, 1>(quad->fW);
490 correct_bad_edges(mad(e1x, e1x, e1y * e1y) < kTolerance * kTolerance, &e1x, &e1y, &e1w);
491
492 // // Top to bottom, in device space, for each point
493 V4f e2x = skvx::shuffle<1, 1, 3, 3>(quad->fX) - skvx::shuffle<0, 0, 2, 2>(quad->fX);
494 V4f e2y = skvx::shuffle<1, 1, 3, 3>(quad->fY) - skvx::shuffle<0, 0, 2, 2>(quad->fY);
495 V4f e2w = skvx::shuffle<1, 1, 3, 3>(quad->fW) - skvx::shuffle<0, 0, 2, 2>(quad->fW);
496 correct_bad_edges(mad(e2x, e2x, e2y * e2y) < kTolerance * kTolerance, &e2x, &e2y, &e2w);
497
498 // Can only move along e1 and e2 to reach the new 2D point, so we have
499 // x2d = (x + a*e1x + b*e2x) / (w + a*e1w + b*e2w) and
500 // y2d = (y + a*e1y + b*e2y) / (w + a*e1w + b*e2w) for some a, b
501 // This can be rewritten to a*c1x + b*c2x + c3x = 0; a * c1y + b*c2y + c3y = 0, where
502 // the cNx and cNy coefficients are:
503 V4f c1x = e1w * x2d - e1x;
504 V4f c1y = e1w * y2d - e1y;
505 V4f c2x = e2w * x2d - e2x;
506 V4f c2y = e2w * y2d - e2y;
507 V4f c3x = quad->fW * x2d - quad->fX;
508 V4f c3y = quad->fW * y2d - quad->fY;
509
510 // Solve for a and b
511 V4f a, b, denom;
512 if (aaFlags == GrQuadAAFlags::kAll) {
513 // When every edge is outset/inset, each corner can use both edge vectors
514 denom = c1x * c2y - c2x * c1y;
515 a = (c2x * c3y - c3x * c2y) / denom;
516 b = (c3x * c1y - c1x * c3y) / denom;
517 } else {
518 // Force a or b to be 0 if that edge cannot be used due to non-AA
519 M4f aMask = M4f{(aaFlags & GrQuadAAFlags::kLeft) ? kTrue : kFalse,
520 (aaFlags & GrQuadAAFlags::kLeft) ? kTrue : kFalse,
521 (aaFlags & GrQuadAAFlags::kRight) ? kTrue : kFalse,
522 (aaFlags & GrQuadAAFlags::kRight) ? kTrue : kFalse};
523 M4f bMask = M4f{(aaFlags & GrQuadAAFlags::kTop) ? kTrue : kFalse,
524 (aaFlags & GrQuadAAFlags::kBottom) ? kTrue : kFalse,
525 (aaFlags & GrQuadAAFlags::kTop) ? kTrue : kFalse,
526 (aaFlags & GrQuadAAFlags::kBottom) ? kTrue : kFalse};
527
528 // When aMask[i]&bMask[i], then a[i], b[i], denom[i] match the kAll case.
529 // When aMask[i]&!bMask[i], then b[i] = 0, a[i] = -c3x/c1x or -c3y/c1y, using better denom
530 // When !aMask[i]&bMask[i], then a[i] = 0, b[i] = -c3x/c2x or -c3y/c2y, ""
531 // When !aMask[i]&!bMask[i], then both a[i] = 0 and b[i] = 0
532 M4f useC1x = abs(c1x) > abs(c1y);
533 M4f useC2x = abs(c2x) > abs(c2y);
534
535 denom = if_then_else(aMask,
536 if_then_else(bMask,
537 c1x * c2y - c2x * c1y, /* A & B */
538 if_then_else(useC1x, c1x, c1y)), /* A & !B */
539 if_then_else(bMask,
540 if_then_else(useC2x, c2x, c2y), /* !A & B */
541 V4f(1.f))); /* !A & !B */
542
543 a = if_then_else(aMask,
544 if_then_else(bMask,
545 c2x * c3y - c3x * c2y, /* A & B */
546 if_then_else(useC1x, -c3x, -c3y)), /* A & !B */
547 V4f(0.f)) / denom; /* !A */
548 b = if_then_else(bMask,
549 if_then_else(aMask,
550 c3x * c1y - c1x * c3y, /* A & B */
551 if_then_else(useC2x, -c3x, -c3y)), /* !A & B */
552 V4f(0.f)) / denom; /* !B */
553 }
554
555 V4f newW = quad->fW + a * e1w + b * e2w;
556 // If newW < 0, scale a and b such that the point reaches the infinity plane instead of crossing
557 // This breaks orthogonality of inset/outsets, but GPUs don't handle negative Ws well so this
558 // is far less visually disturbing (likely not noticeable since it's at extreme perspective).
559 // The alternative correction (multiply xyw by -1) has the disadvantage of changing how local
560 // coordinates would be interpolated.
561 static const float kMinW = 1e-6f;
562 if (any(newW < 0.f)) {
563 V4f scale = if_then_else(newW < kMinW, (kMinW - quad->fW) / (newW - quad->fW), V4f(1.f));
564 a *= scale;
565 b *= scale;
566 }
567
568 quad->fX += a * e1x + b * e2x;
569 quad->fY += a * e1y + b * e2y;
570 quad->fW += a * e1w + b * e2w;
571 correct_bad_coords(abs(denom) < kTolerance, &quad->fX, &quad->fY, &quad->fW);
572
573 if (quad->fUVRCount > 0) {
574 // Calculate R here so it can be corrected with U and V in case it's needed later
575 V4f e1u = skvx::shuffle<2, 3, 2, 3>(quad->fU) - skvx::shuffle<0, 1, 0, 1>(quad->fU);
576 V4f e1v = skvx::shuffle<2, 3, 2, 3>(quad->fV) - skvx::shuffle<0, 1, 0, 1>(quad->fV);
577 V4f e1r = skvx::shuffle<2, 3, 2, 3>(quad->fR) - skvx::shuffle<0, 1, 0, 1>(quad->fR);
578 correct_bad_edges(mad(e1u, e1u, e1v * e1v) < kTolerance * kTolerance, &e1u, &e1v, &e1r);
579
580 V4f e2u = skvx::shuffle<1, 1, 3, 3>(quad->fU) - skvx::shuffle<0, 0, 2, 2>(quad->fU);
581 V4f e2v = skvx::shuffle<1, 1, 3, 3>(quad->fV) - skvx::shuffle<0, 0, 2, 2>(quad->fV);
582 V4f e2r = skvx::shuffle<1, 1, 3, 3>(quad->fR) - skvx::shuffle<0, 0, 2, 2>(quad->fR);
583 correct_bad_edges(mad(e2u, e2u, e2v * e2v) < kTolerance * kTolerance, &e2u, &e2v, &e2r);
584
585 quad->fU += a * e1u + b * e2u;
586 quad->fV += a * e1v + b * e2v;
587 if (quad->fUVRCount == 3) {
588 quad->fR += a * e1r + b * e2r;
589 correct_bad_coords(abs(denom) < kTolerance, &quad->fU, &quad->fV, &quad->fR);
590 } else {
591 correct_bad_coords(abs(denom) < kTolerance, &quad->fU, &quad->fV, nullptr);
592 }
593 }
594}
595
596V4f TessellationHelper::getDegenerateCoverage(const V4f& px, const V4f& py, const Edges& edges) {
597 // Calculate distance of the 4 inset points (px, py) to the 4 edges
598 V4f d0 = mad(edges.fA[0], px, mad(edges.fB[0], py, edges.fC[0]));
599 V4f d1 = mad(edges.fA[1], px, mad(edges.fB[1], py, edges.fC[1]));
600 V4f d2 = mad(edges.fA[2], px, mad(edges.fB[2], py, edges.fC[2]));
601 V4f d3 = mad(edges.fA[3], px, mad(edges.fB[3], py, edges.fC[3]));
602
603 // For each point, pretend that there's a rectangle that touches e0 and e3 on the horizontal
604 // axis, so its width is "approximately" d0 + d3, and it touches e1 and e2 on the vertical axis
605 // so its height is d1 + d2. Pin each of these dimensions to [0, 1] and approximate the coverage
606 // at each point as clamp(d0+d3, 0, 1) x clamp(d1+d2, 0, 1). For rectilinear quads this is an
607 // accurate calculation of its area clipped to an aligned pixel. For arbitrary quads it is not
608 // mathematically accurate but qualitatively provides a stable value proportional to the size of
609 // the shape.
610 V4f w = max(0.f, min(1.f, d0 + d3));
611 V4f h = max(0.f, min(1.f, d1 + d2));
612 return w * h;
613}
614
615V4f TessellationHelper::computeDegenerateQuad(GrQuadAAFlags aaFlags, const V4f& mask,
616 const Edges& edges, bool outset, Vertices* quad) {
617 // Move the edge 1/2 pixel in or out depending on 'outset'.
618 V4f oc = edges.fC + mask * (outset ? 0.5f : -0.5f);
619
620 // There are 6 points that we care about to determine the final shape of the polygon, which
621 // are the intersections between (e0,e2), (e1,e0), (e2,e3), (e3,e1) (corresponding to the
622 // 4 corners), and (e1, e2), (e0, e3) (representing the intersections of opposite edges).
623 V4f denom = edges.fA * next_cw(edges.fB) - edges.fB * next_cw(edges.fA);
624 V4f px = (edges.fB * next_cw(oc) - oc * next_cw(edges.fB)) / denom;
625 V4f py = (oc * next_cw(edges.fA) - edges.fA * next_cw(oc)) / denom;
626 correct_bad_coords(abs(denom) < kTolerance, &px, &py, nullptr);
627
628 // Calculate the signed distances from these 4 corners to the other two edges that did not
629 // define the intersection. So p(0) is compared to e3,e1, p(1) to e3,e2 , p(2) to e0,e1, and
630 // p(3) to e0,e2
631 V4f dists1 = px * skvx::shuffle<3, 3, 0, 0>(edges.fA) +
632 py * skvx::shuffle<3, 3, 0, 0>(edges.fB) +
633 skvx::shuffle<3, 3, 0, 0>(oc);
634 V4f dists2 = px * skvx::shuffle<1, 2, 1, 2>(edges.fA) +
635 py * skvx::shuffle<1, 2, 1, 2>(edges.fB) +
636 skvx::shuffle<1, 2, 1, 2>(oc);
637
638 // If all the distances are >= 0, the 4 corners form a valid quadrilateral, so use them as
639 // the 4 points. If any point is on the wrong side of both edges, the interior has collapsed
640 // and we need to use a central point to represent it. If all four points are only on the
641 // wrong side of 1 edge, one edge has crossed over another and we use a line to represent it.
642 // Otherwise, use a triangle that replaces the bad points with the intersections of
643 // (e1, e2) or (e0, e3) as needed.
644 M4f d1v0 = dists1 < kTolerance;
645 M4f d2v0 = dists2 < kTolerance;
646 M4f d1And2 = d1v0 & d2v0;
647 M4f d1Or2 = d1v0 | d2v0;
648
649 V4f coverage;
650 if (!any(d1Or2)) {
651 // Every dists1 and dists2 >= kTolerance so it's not degenerate, use all 4 corners as-is
652 // and use full coverage
653 coverage = 1.f;
654 } else if (any(d1And2)) {
655 // A point failed against two edges, so reduce the shape to a single point, which we take as
656 // the center of the original quad to ensure it is contained in the intended geometry. Since
657 // it has collapsed, we know the shape cannot cover a pixel so update the coverage.
658 SkPoint center = {0.25f * (quad->fX[0] + quad->fX[1] + quad->fX[2] + quad->fX[3]),
659 0.25f * (quad->fY[0] + quad->fY[1] + quad->fY[2] + quad->fY[3])};
660 px = center.fX;
661 py = center.fY;
662 coverage = getDegenerateCoverage(px, py, edges);
663 } else if (all(d1Or2)) {
664 // Degenerates to a line. Compare p[2] and p[3] to edge 0. If they are on the wrong side,
665 // that means edge 0 and 3 crossed, and otherwise edge 1 and 2 crossed.
666 if (dists1[2] < kTolerance && dists1[3] < kTolerance) {
667 // Edges 0 and 3 have crossed over, so make the line from average of (p0,p2) and (p1,p3)
668 px = 0.5f * (skvx::shuffle<0, 1, 0, 1>(px) + skvx::shuffle<2, 3, 2, 3>(px));
669 py = 0.5f * (skvx::shuffle<0, 1, 0, 1>(py) + skvx::shuffle<2, 3, 2, 3>(py));
670 } else {
671 // Edges 1 and 2 have crossed over, so make the line from average of (p0,p1) and (p2,p3)
672 px = 0.5f * (skvx::shuffle<0, 0, 2, 2>(px) + skvx::shuffle<1, 1, 3, 3>(px));
673 py = 0.5f * (skvx::shuffle<0, 0, 2, 2>(py) + skvx::shuffle<1, 1, 3, 3>(py));
674 }
675 coverage = getDegenerateCoverage(px, py, edges);
676 } else {
677 // This turns into a triangle. Replace corners as needed with the intersections between
678 // (e0,e3) and (e1,e2), which must now be calculated
679 using V2f = skvx::Vec<2, float>;
680 V2f eDenom = skvx::shuffle<0, 1>(edges.fA) * skvx::shuffle<3, 2>(edges.fB) -
681 skvx::shuffle<0, 1>(edges.fB) * skvx::shuffle<3, 2>(edges.fA);
682 V2f ex = (skvx::shuffle<0, 1>(edges.fB) * skvx::shuffle<3, 2>(oc) -
683 skvx::shuffle<0, 1>(oc) * skvx::shuffle<3, 2>(edges.fB)) / eDenom;
684 V2f ey = (skvx::shuffle<0, 1>(oc) * skvx::shuffle<3, 2>(edges.fA) -
685 skvx::shuffle<0, 1>(edges.fA) * skvx::shuffle<3, 2>(oc)) / eDenom;
686
687 if (SkScalarAbs(eDenom[0]) > kTolerance) {
688 px = if_then_else(d1v0, V4f(ex[0]), px);
689 py = if_then_else(d1v0, V4f(ey[0]), py);
690 }
691 if (SkScalarAbs(eDenom[1]) > kTolerance) {
692 px = if_then_else(d2v0, V4f(ex[1]), px);
693 py = if_then_else(d2v0, V4f(ey[1]), py);
694 }
695
696 coverage = 1.f;
697 }
698
699 outsetProjectedVertices(px, py, aaFlags, quad);
700 return coverage;
701}
702
703V4f TessellationHelper::computeNestedQuadVertices(GrQuadAAFlags aaFlags, bool rectilinear,
704 Vertices* inner, Vertices* outer) {
705 SkASSERT(inner->fUVRCount == 0 || inner->fUVRCount == 2 || inner->fUVRCount == 3);
706 SkASSERT(outer->fUVRCount == inner->fUVRCount);
707
708 QuadMetadata metadata = getMetadata(*inner, aaFlags);
709
710 // When outsetting, we want the new edge to be .5px away from the old line, which means the
711 // corners may need to be adjusted by more than .5px if the matrix had sheer. This adjustment
712 // is only computed if there are no empty edges, and it may signal going through the slow path.
713 V4f outset = 0.5f;
714 if (getOptimizedOutset(metadata, rectilinear, &outset)) {
715 // Since it's not subpixel, outsetting and insetting are trivial vector additions.
716 outsetVertices(outset, metadata, outer);
717 outsetVertices(-outset, metadata, inner);
718 return 1.f;
719 }
720
721 // Only compute edge equations once since they are the same for inner and outer quads
722 Edges edges = getEdgeEquations(metadata, *inner);
723
724 // Calculate both outset and inset, returning the coverage reported for the inset, since the
725 // outset will always have 0.0f.
726 computeDegenerateQuad(aaFlags, metadata.fMask, edges, true, outer);
727 return computeDegenerateQuad(aaFlags, metadata.fMask, edges, false, inner);
728}
729
730V4f TessellationHelper::computeNestedPerspQuadVertices(const GrQuadAAFlags aaFlags,
731 Vertices* inner,
732 Vertices* outer) {
733 SkASSERT(inner->fUVRCount == 0 || inner->fUVRCount == 2 || inner->fUVRCount == 3);
734 SkASSERT(outer->fUVRCount == inner->fUVRCount);
735
736 // Calculate the projected 2D quad and use it to form projeccted inner/outer quads
737 V4f iw = 1.0f / inner->fW;
738 V4f x2d = inner->fX * iw;
739 V4f y2d = inner->fY * iw;
740
741 Vertices inner2D = { x2d, y2d, /*w*/ 1.f, 0.f, 0.f, 0.f, 0 }; // No uvr outsetting in 2D
742 Vertices outer2D = inner2D;
743
744 V4f coverage = computeNestedQuadVertices(aaFlags, /* rect */ false, &inner2D, &outer2D);
745
746 // Now map from the 2D inset/outset back to 3D and update the local coordinates as well
747 outsetProjectedVertices(inner2D.fX, inner2D.fY, aaFlags, inner);
748 outsetProjectedVertices(outer2D.fX, outer2D.fY, aaFlags, outer);
749
750 return coverage;
751}
752
753TessellationHelper::TessellationHelper(const GrQuad& deviceQuad, const GrQuad* localQuad)
754 : fAAFlags(GrQuadAAFlags::kNone)
755 , fCoverage(1.f)
756 , fDeviceType(deviceQuad.quadType())
757 , fLocalType(localQuad ? localQuad->quadType() : GrQuad::Type::kAxisAligned) {
758 fOriginal.fX = deviceQuad.x4f();
759 fOriginal.fY = deviceQuad.y4f();
760 fOriginal.fW = deviceQuad.w4f();
761
762 if (localQuad) {
763 fOriginal.fU = localQuad->x4f();
764 fOriginal.fV = localQuad->y4f();
765 fOriginal.fR = localQuad->w4f();
766 fOriginal.fUVRCount = fLocalType == GrQuad::Type::kPerspective ? 3 : 2;
767 } else {
768 fOriginal.fUVRCount = 0;
769 }
770}
771
772V4f TessellationHelper::pixelCoverage() {
773 // When there are no AA edges, insetting and outsetting is skipped since the original geometry
774 // can just be reported directly (in which case fCoverage may be stale).
775 return fAAFlags == GrQuadAAFlags::kNone ? 1.f : fCoverage;
776}
777
778void TessellationHelper::inset(GrQuadAAFlags aaFlags, GrQuad* deviceInset, GrQuad* localInset) {
779 if (aaFlags != fAAFlags) {
780 fAAFlags = aaFlags;
781 if (aaFlags != GrQuadAAFlags::kNone) {
782 this->recomputeInsetAndOutset();
783 }
784 }
785 if (fAAFlags == GrQuadAAFlags::kNone) {
786 this->setQuads(fOriginal, deviceInset, localInset);
787 } else {
788 this->setQuads(fInset, deviceInset, localInset);
789 }
790}
791
792void TessellationHelper::outset(GrQuadAAFlags aaFlags, GrQuad* deviceOutset, GrQuad* localOutset) {
793 if (aaFlags != fAAFlags) {
794 fAAFlags = aaFlags;
795 if (aaFlags != GrQuadAAFlags::kNone) {
796 this->recomputeInsetAndOutset();
797 }
798 }
799 if (fAAFlags == GrQuadAAFlags::kNone) {
800 this->setQuads(fOriginal, deviceOutset, localOutset);
801 } else {
802 this->setQuads(fOutset, deviceOutset, localOutset);
803 }
804}
805
806void TessellationHelper::recomputeInsetAndOutset() {
807 // Start from the original geometry
808 fInset = fOriginal;
809 fOutset = fOriginal;
810
811 if (fDeviceType == GrQuad::Type::kPerspective) {
812 fCoverage = computeNestedPerspQuadVertices(fAAFlags, &fInset, &fOutset);
813 } else {
814 fCoverage = computeNestedQuadVertices(fAAFlags, fDeviceType <= GrQuad::Type::kRectilinear,
815 &fInset, &fOutset);
816 }
817}
818
819void TessellationHelper::setQuads(const Vertices& vertices,
820 GrQuad* deviceOut, GrQuad* localOut) const {
821 SkASSERT(deviceOut);
822 SkASSERT(vertices.fUVRCount == 0 || localOut);
823
824 vertices.fX.store(deviceOut->xs());
825 vertices.fY.store(deviceOut->ys());
826 if (fDeviceType == GrQuad::Type::kPerspective) {
827 vertices.fW.store(deviceOut->ws());
828 }
829 deviceOut->setQuadType(fDeviceType); // This sets ws == 1 when device type != perspective
830
831 if (vertices.fUVRCount > 0) {
832 vertices.fU.store(localOut->xs());
833 vertices.fV.store(localOut->ys());
834 if (vertices.fUVRCount == 3) {
835 vertices.fR.store(localOut->ws());
836 }
837 localOut->setQuadType(fLocalType);
838 }
839}
840
Michael Ludwig0f809022019-06-04 09:14:37 -0400841}; // namespace GrQuadUtils