Consolidate quad optimizations into single internal function.

Routes all non-textured quad draws through single internal function

Change-Id: Ief66864a0ad2d598982c5bf500c8a84ecbf84387
Reviewed-on: https://skia-review.googlesource.com/c/skia/+/215455
Commit-Queue: Michael Ludwig <michaelludwig@google.com>
Reviewed-by: Robert Phillips <robertphillips@google.com>
diff --git a/src/gpu/geometry/GrQuadUtils.cpp b/src/gpu/geometry/GrQuadUtils.cpp
index ba109cf..fce38d2 100644
--- a/src/gpu/geometry/GrQuadUtils.cpp
+++ b/src/gpu/geometry/GrQuadUtils.cpp
@@ -7,9 +7,158 @@
 
 #include "src/gpu/geometry/GrQuadUtils.h"
 
+#include "include/core/SkRect.h"
 #include "include/private/GrTypesPriv.h"
+#include "include/private/SkVx.h"
 #include "src/gpu/geometry/GrQuad.h"
 
+using V4f = skvx::Vec<4, float>;
+using M4f = skvx::Vec<4, int32_t>;
+
+// Since the local quad may not be type kRect, this uses the opposites for each vertex when
+// interpolating, and calculates new ws in addition to new xs, ys.
+static void interpolate_local(float alpha, int v0, int v1, int v2, int v3,
+                              float lx[4], float ly[4], float lw[4]) {
+    SkASSERT(v0 >= 0 && v0 < 4);
+    SkASSERT(v1 >= 0 && v1 < 4);
+    SkASSERT(v2 >= 0 && v2 < 4);
+    SkASSERT(v3 >= 0 && v3 < 4);
+
+    float beta = 1.f - alpha;
+    lx[v0] = alpha * lx[v0] + beta * lx[v2];
+    ly[v0] = alpha * ly[v0] + beta * ly[v2];
+    lw[v0] = alpha * lw[v0] + beta * lw[v2];
+
+    lx[v1] = alpha * lx[v1] + beta * lx[v3];
+    ly[v1] = alpha * ly[v1] + beta * ly[v3];
+    lw[v1] = alpha * lw[v1] + beta * lw[v3];
+}
+
+// Crops v0 to v1 based on the clipDevRect. v2 is opposite of v0, v3 is opposite of v1.
+// It is written to not modify coordinates if there's no intersection along the edge.
+// Ideally this would have been detected earlier and the entire draw is skipped.
+static bool crop_rect_edge(const SkRect& clipDevRect, int v0, int v1, int v2, int v3,
+                           float x[4], float y[4], float lx[4], float ly[4], float lw[4]) {
+    SkASSERT(v0 >= 0 && v0 < 4);
+    SkASSERT(v1 >= 0 && v1 < 4);
+    SkASSERT(v2 >= 0 && v2 < 4);
+    SkASSERT(v3 >= 0 && v3 < 4);
+
+    if (SkScalarNearlyEqual(x[v0], x[v1])) {
+        // A vertical edge
+        if (x[v0] < clipDevRect.fLeft && x[v2] >= clipDevRect.fLeft) {
+            // Overlapping with left edge of clipDevRect
+            if (lx) {
+                float alpha = (x[v2] - clipDevRect.fLeft) / (x[v2] - x[v0]);
+                interpolate_local(alpha, v0, v1, v2, v3, lx, ly, lw);
+            }
+            x[v0] = clipDevRect.fLeft;
+            x[v1] = clipDevRect.fLeft;
+            return true;
+        } else if (x[v0] > clipDevRect.fRight && x[v2] <= clipDevRect.fRight) {
+            // Overlapping with right edge of clipDevRect
+            if (lx) {
+                float alpha = (clipDevRect.fRight - x[v2]) / (x[v0] - x[v2]);
+                interpolate_local(alpha, v0, v1, v2, v3, lx, ly, lw);
+            }
+            x[v0] = clipDevRect.fRight;
+            x[v1] = clipDevRect.fRight;
+            return true;
+        }
+    } else {
+        // A horizontal edge
+        SkASSERT(SkScalarNearlyEqual(y[v0], y[v1]));
+        if (y[v0] < clipDevRect.fTop && y[v2] >= clipDevRect.fTop) {
+            // Overlapping with top edge of clipDevRect
+            if (lx) {
+                float alpha = (y[v2] - clipDevRect.fTop) / (y[v2] - y[v0]);
+                interpolate_local(alpha, v0, v1, v2, v3, lx, ly, lw);
+            }
+            y[v0] = clipDevRect.fTop;
+            y[v1] = clipDevRect.fTop;
+            return true;
+        } else if (y[v0] > clipDevRect.fBottom && y[v2] <= clipDevRect.fBottom) {
+            // Overlapping with bottom edge of clipDevRect
+            if (lx) {
+                float alpha = (clipDevRect.fBottom - y[v2]) / (y[v0] - y[v2]);
+                interpolate_local(alpha, v0, v1, v2, v3, lx, ly, lw);
+            }
+            y[v0] = clipDevRect.fBottom;
+            y[v1] = clipDevRect.fBottom;
+            return true;
+        }
+    }
+
+    // No overlap so don't crop it
+    return false;
+}
+
+// Updates x and y to intersect with clipDevRect, and applies clipAA policy to edgeFlags for each
+// intersected edge. lx, ly, and lw are updated appropriately and may be null to skip calculations.
+static void crop_rect(const SkRect& clipDevRect, GrAA clipAA, GrQuadAAFlags* edgeFlags,
+                      float x[4], float y[4], float lx[4], float ly[4], float lw[4]) {
+    // Filled in as if clipAA were true, will be inverted at the end if needed.
+    GrQuadAAFlags clipEdgeFlags = GrQuadAAFlags::kNone;
+
+    // However, the quad's left edge may not align with the SkRect notion of left due to 90 degree
+    // rotations or mirrors. So, this processes the logical edges of the quad and clamps it to the 4
+    // sides of clipDevRect.
+
+    // Quad's left is v0 to v1 (op. v2 and v3)
+    if (crop_rect_edge(clipDevRect, 0, 1, 2, 3, x, y, lx, ly, lw)) {
+        clipEdgeFlags |= GrQuadAAFlags::kLeft;
+    }
+    // Quad's top edge is v0 to v2 (op. v1 and v3)
+    if (crop_rect_edge(clipDevRect, 0, 2, 1, 3, x, y, lx, ly, lw)) {
+        clipEdgeFlags |= GrQuadAAFlags::kTop;
+    }
+    // Quad's right edge is v2 to v3 (op. v0 and v1)
+    if (crop_rect_edge(clipDevRect, 2, 3, 0, 1, x, y, lx, ly, lw)) {
+        clipEdgeFlags |= GrQuadAAFlags::kRight;
+    }
+    // Quad's bottom edge is v1 to v3 (op. v0 and v2)
+    if (crop_rect_edge(clipDevRect, 1, 3, 0, 2, x, y, lx, ly, lw)) {
+        clipEdgeFlags |= GrQuadAAFlags::kBottom;
+    }
+
+    if (clipAA == GrAA::kYes) {
+        // Turn on all edges that were clipped
+        *edgeFlags |= clipEdgeFlags;
+    } else {
+        // Turn off all edges that were clipped
+        *edgeFlags &= ~clipEdgeFlags;
+    }
+}
+
+// Calculates barycentric coordinates for each point in (testX, testY) in the triangle formed by
+// (x0,y0) - (x1,y1) - (x2, y2) and stores them in u, v, w.
+static void barycentric_coords(float x0, float y0, float x1, float y1, float x2, float y2,
+                               const V4f& testX, const V4f& testY,
+                               V4f* u, V4f* v, V4f* w) {
+    // Modeled after SkPathOpsQuad::pointInTriangle() but uses float instead of double, is
+    // vectorized and outputs normalized barycentric coordinates instead of inside/outside test
+    float v0x = x2 - x0;
+    float v0y = y2 - y0;
+    float v1x = x1 - x0;
+    float v1y = y1 - y0;
+    V4f v2x = testX - x0;
+    V4f v2y = testY - y0;
+
+    float dot00 = v0x * v0x + v0y * v0y;
+    float dot01 = v0x * v1x + v0y * v1y;
+    V4f   dot02 = v0x * v2x + v0y * v2y;
+    float dot11 = v1x * v1x + v1y * v1y;
+    V4f   dot12 = v1x * v2x + v1y * v2y;
+    float invDenom = sk_ieee_float_divide(1.f, dot00 * dot11 - dot01 * dot01);
+    *u = (dot11 * dot02 - dot01 * dot12) * invDenom;
+    *v = (dot00 * dot12 - dot01 * dot02) * invDenom;
+    *w = 1.f - *u - *v;
+}
+
+static M4f inside_triangle(const V4f& u, const V4f& v, const V4f& w) {
+    return ((u >= 0.f) & (u <= 1.f)) & ((v >= 0.f) & (v <= 1.f)) & ((w >= 0.f) & (w <= 1.f));
+}
+
 namespace GrQuadUtils {
 
 void ResolveAAType(GrAAType requestedAAType, GrQuadAAFlags requestedEdgeFlags, const GrQuad& quad,
@@ -45,6 +194,79 @@
             SK_ABORT("Should not use mixed sample AA with edge AA flags");
             break;
     }
-};
+}
+
+bool CropToRect(const SkRect& cropRect, GrAA cropAA, GrQuadAAFlags* edgeFlags, GrQuad* quad,
+                GrQuad* local) {
+    if (quad->quadType() == GrQuad::Type::kAxisAligned) {
+        // crop_rect keeps the rectangles as rectangles, so there's no need to modify types
+        if (local) {
+            crop_rect(cropRect, cropAA, edgeFlags, quad->xs(), quad->ys(),
+                      local->xs(), local->ys(), local->ws());
+        } else {
+            crop_rect(cropRect, cropAA, edgeFlags, quad->xs(), quad->ys(),
+                      nullptr, nullptr, nullptr);
+        }
+        return true;
+    }
+
+    if (local) {
+        // FIXME (michaelludwig) Calculate cropped local coordinates when not kAxisAligned
+        return false;
+    }
+
+    V4f devX = quad->x4f();
+    V4f devY = quad->y4f();
+    V4f devIW = quad->iw4f();
+    // Project the 3D coordinates to 2D
+    if (quad->quadType() == GrQuad::Type::kPerspective) {
+        devX *= devIW;
+        devY *= devIW;
+    }
+
+    V4f clipX = {cropRect.fLeft, cropRect.fLeft, cropRect.fRight, cropRect.fRight};
+    V4f clipY = {cropRect.fTop, cropRect.fBottom, cropRect.fTop, cropRect.fBottom};
+
+    // Calculate barycentric coordinates for the 4 rect corners in the 2 triangles that the quad
+    // is tessellated into when drawn.
+    V4f u1, v1, w1;
+    barycentric_coords(devX[0], devY[0], devX[1], devY[1], devX[2], devY[2], clipX, clipY,
+                       &u1, &v1, &w1);
+    V4f u2, v2, w2;
+    barycentric_coords(devX[1], devY[1], devX[3], devY[3], devX[2], devY[2], clipX, clipY,
+                       &u2, &v2, &w2);
+
+    // clipDevRect is completely inside this quad if each corner is in at least one of two triangles
+    M4f inTri1 = inside_triangle(u1, v1, w1);
+    M4f inTri2 = inside_triangle(u2, v2, w2);
+    if (all(inTri1 | inTri2)) {
+        // We can crop to exactly the clipDevRect.
+        // FIXME (michaelludwig) - there are other ways to have determined quad covering the clip
+        // rect, but the barycentric coords will be useful to derive local coordinates in the future
+
+        // Since we are cropped to exactly clipDevRect, we have discarded any perspective and the
+        // type becomes kRect. If updated locals were requested, they will incorporate perspective.
+        // FIXME (michaelludwig) - once we have local coordinates handled, it may be desirable to
+        // keep the draw as perspective so that the hardware does perspective interpolation instead
+        // of pushing it into a local coord w and having the shader do an extra divide.
+        clipX.store(quad->xs());
+        clipY.store(quad->ys());
+        quad->ws()[0] = 1.f;
+        quad->ws()[1] = 1.f;
+        quad->ws()[2] = 1.f;
+        quad->ws()[3] = 1.f;
+        quad->setQuadType(GrQuad::Type::kAxisAligned);
+
+        // Update the edge flags to match the clip setting since all 4 edges have been clipped
+        *edgeFlags = cropAA == GrAA::kYes ? GrQuadAAFlags::kAll : GrQuadAAFlags::kNone;
+
+        return true;
+    }
+
+    // FIXME (michaelludwig) - use the GrQuadPerEdgeAA tessellation inset/outset math to move
+    // edges to the closest clip corner they are outside of
+
+    return false;
+}
 
 }; // namespace GrQuadUtils