Home | History | Annotate | Download | only in ccpr
      1 /*
      2  * Copyright 2017 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 "GrCCCoverageProcessor.h"
      9 
     10 #include "GrGpuCommandBuffer.h"
     11 #include "GrOpFlushState.h"
     12 #include "SkMakeUnique.h"
     13 #include "ccpr/GrCCConicShader.h"
     14 #include "ccpr/GrCCCubicShader.h"
     15 #include "ccpr/GrCCQuadraticShader.h"
     16 #include "glsl/GrGLSLVertexGeoBuilder.h"
     17 #include "glsl/GrGLSLFragmentShaderBuilder.h"
     18 #include "glsl/GrGLSLVertexGeoBuilder.h"
     19 
     20 class GrCCCoverageProcessor::TriangleShader : public GrCCCoverageProcessor::Shader {
     21     void onEmitVaryings(GrGLSLVaryingHandler* varyingHandler, GrGLSLVarying::Scope scope,
     22                         SkString* code, const char* position, const char* coverage,
     23                         const char* cornerCoverage) override {
     24         if (!cornerCoverage) {
     25             fCoverages.reset(kHalf_GrSLType, scope);
     26             varyingHandler->addVarying("coverage", &fCoverages);
     27             code->appendf("%s = %s;", OutName(fCoverages), coverage);
     28         } else {
     29             fCoverages.reset(kHalf3_GrSLType, scope);
     30             varyingHandler->addVarying("coverages", &fCoverages);
     31             code->appendf("%s = half3(%s, %s);", OutName(fCoverages), coverage, cornerCoverage);
     32         }
     33     }
     34 
     35     void onEmitFragmentCode(GrGLSLFPFragmentBuilder* f, const char* outputCoverage) const override {
     36         if (kHalf_GrSLType == fCoverages.type()) {
     37             f->codeAppendf("%s = %s;", outputCoverage, fCoverages.fsIn());
     38         } else {
     39             f->codeAppendf("%s = %s.z * %s.y + %s.x;",
     40                            outputCoverage, fCoverages.fsIn(), fCoverages.fsIn(), fCoverages.fsIn());
     41         }
     42     }
     43 
     44     GrGLSLVarying fCoverages;
     45 };
     46 
     47 void GrCCCoverageProcessor::Shader::CalcWind(const GrCCCoverageProcessor& proc,
     48                                              GrGLSLVertexGeoBuilder* s, const char* pts,
     49                                              const char* outputWind) {
     50     if (3 == proc.numInputPoints()) {
     51         s->codeAppendf("float2 a = %s[0] - %s[1], "
     52                               "b = %s[0] - %s[2];", pts, pts, pts, pts);
     53     } else {
     54         // All inputs are convex, so it's sufficient to just average the middle two input points.
     55         SkASSERT(4 == proc.numInputPoints());
     56         s->codeAppendf("float2 p12 = (%s[1] + %s[2]) * .5;", pts, pts);
     57         s->codeAppendf("float2 a = %s[0] - p12, "
     58                               "b = %s[0] - %s[3];", pts, pts, pts);
     59     }
     60 
     61     s->codeAppend ("float area_x2 = determinant(float2x2(a, b));");
     62     if (proc.isTriangles()) {
     63         // We cull extremely thin triangles by zeroing wind. When a triangle gets too thin it's
     64         // possible for FP round-off error to actually give us the wrong winding direction, causing
     65         // rendering artifacts. The criteria we choose is "height <~ 1/1024". So we drop a triangle
     66         // if the max effect it can have on any single pixel is <~ 1/1024, or 1/4 of a bit in 8888.
     67         s->codeAppend ("float2 bbox_size = max(abs(a), abs(b));");
     68         s->codeAppend ("float basewidth = max(bbox_size.x + bbox_size.y, 1);");
     69         s->codeAppendf("%s = (abs(area_x2 * 1024) > basewidth) ? sign(half(area_x2)) : 0;",
     70                        outputWind);
     71     } else {
     72         // We already converted nearly-flat curves to lines on the CPU, so no need to worry about
     73         // thin curve hulls at this point.
     74         s->codeAppendf("%s = sign(half(area_x2));", outputWind);
     75     }
     76 }
     77 
     78 void GrCCCoverageProcessor::Shader::EmitEdgeDistanceEquation(GrGLSLVertexGeoBuilder* s,
     79                                                              const char* leftPt,
     80                                                              const char* rightPt,
     81                                                              const char* outputDistanceEquation) {
     82     s->codeAppendf("float2 n = float2(%s.y - %s.y, %s.x - %s.x);",
     83                    rightPt, leftPt, leftPt, rightPt);
     84     s->codeAppend ("float nwidth = (abs(n.x) + abs(n.y)) * (bloat * 2);");
     85     // When nwidth=0, wind must also be 0 (and coverage * wind = 0). So it doesn't matter what we
     86     // come up with here as long as it isn't NaN or Inf.
     87     s->codeAppend ("n /= (0 != nwidth) ? nwidth : 1;");
     88     s->codeAppendf("%s = float3(-n, dot(n, %s) - .5);", outputDistanceEquation, leftPt);
     89 }
     90 
     91 void GrCCCoverageProcessor::Shader::CalcEdgeCoverageAtBloatVertex(GrGLSLVertexGeoBuilder* s,
     92                                                                   const char* leftPt,
     93                                                                   const char* rightPt,
     94                                                                   const char* rasterVertexDir,
     95                                                                   const char* outputCoverage) {
     96     // Here we find an edge's coverage at one corner of a conservative raster bloat box whose center
     97     // falls on the edge in question. (A bloat box is axis-aligned and the size of one pixel.) We
     98     // always set up coverage so it is -1 at the outermost corner, 0 at the innermost, and -.5 at
     99     // the center. Interpolated, these coverage values convert jagged conservative raster edges into
    100     // smooth antialiased edges.
    101     //
    102     // d1 == (P + sign(n) * bloat) dot n                   (Distance at the bloat box vertex whose
    103     //    == P dot n + (abs(n.x) + abs(n.y)) * bloatSize    coverage=-1, where the bloat box is
    104     //                                                      centered on P.)
    105     //
    106     // d0 == (P - sign(n) * bloat) dot n                   (Distance at the bloat box vertex whose
    107     //    == P dot n - (abs(n.x) + abs(n.y)) * bloatSize    coverage=0, where the bloat box is
    108     //                                                      centered on P.)
    109     //
    110     // d == (P + rasterVertexDir * bloatSize) dot n        (Distance at the bloat box vertex whose
    111     //   == P dot n + (rasterVertexDir dot n) * bloatSize   coverage we wish to calculate.)
    112     //
    113     // coverage == -(d - d0) / (d1 - d0)                   (coverage=-1 at d=d1; coverage=0 at d=d0)
    114     //
    115     //          == (rasterVertexDir dot n) / (abs(n.x) + abs(n.y)) * -.5 - .5
    116     //
    117     s->codeAppendf("float2 n = float2(%s.y - %s.y, %s.x - %s.x);",
    118                    rightPt, leftPt, leftPt, rightPt);
    119     s->codeAppend ("float nwidth = abs(n.x) + abs(n.y);");
    120     s->codeAppendf("float t = dot(%s, n);", rasterVertexDir);
    121     // The below conditional guarantees we get exactly 1 on the divide when nwidth=t (in case the
    122     // GPU divides by multiplying by the reciprocal?) It also guards against NaN when nwidth=0.
    123     s->codeAppendf("%s = half(abs(t) != nwidth ? t / nwidth : sign(t)) * -.5 - .5;",
    124                    outputCoverage);
    125 }
    126 
    127 void GrCCCoverageProcessor::Shader::CalcEdgeCoveragesAtBloatVertices(GrGLSLVertexGeoBuilder* s,
    128                                                                      const char* leftPt,
    129                                                                      const char* rightPt,
    130                                                                      const char* bloatDir1,
    131                                                                      const char* bloatDir2,
    132                                                                      const char* outputCoverages) {
    133     // See comments in CalcEdgeCoverageAtBloatVertex.
    134     s->codeAppendf("float2 n = float2(%s.y - %s.y, %s.x - %s.x);",
    135                    rightPt, leftPt, leftPt, rightPt);
    136     s->codeAppend ("float nwidth = abs(n.x) + abs(n.y);");
    137     s->codeAppendf("float2 t = n * float2x2(%s, %s);", bloatDir1, bloatDir2);
    138     s->codeAppendf("for (int i = 0; i < 2; ++i) {");
    139     s->codeAppendf(    "%s[i] = half(abs(t[i]) != nwidth ? t[i] / nwidth : sign(t[i])) * -.5 - .5;",
    140                        outputCoverages);
    141     s->codeAppendf("}");
    142 }
    143 
    144 void GrCCCoverageProcessor::Shader::CalcCornerAttenuation(GrGLSLVertexGeoBuilder* s,
    145                                                           const char* leftDir, const char* rightDir,
    146                                                           const char* outputAttenuation) {
    147     // obtuseness = cos(corner_angle)  if corner_angle > 90 degrees
    148     //                              0  if corner_angle <= 90 degrees
    149     //
    150     // NOTE: leftDir and rightDir are normalized and point in the same direction the path was
    151     // defined with, i.e., leftDir points into the corner and rightDir points away from the corner.
    152     s->codeAppendf("half obtuseness = max(half(dot(%s, %s)), 0);", leftDir, rightDir);
    153 
    154     // axis_alignedness = 1 - tan(angle_to_nearest_axis_from_corner_bisector)
    155     //                    (i.e.,  1  when the corner bisector is aligned with the x- or y-axis
    156     //                            0  when the corner bisector falls on a 45 degree angle
    157     //                         0..1  when the corner bisector falls somewhere in between
    158     s->codeAppendf("half2 abs_bisect_maybe_transpose = abs((0 == obtuseness) ? half2(%s - %s) : "
    159                                                                               "half2(%s + %s));",
    160                    leftDir, rightDir, leftDir, rightDir);
    161     s->codeAppend ("half axis_alignedness = "
    162                            "1 - min(abs_bisect_maybe_transpose.y, abs_bisect_maybe_transpose.x) / "
    163                                "max(abs_bisect_maybe_transpose.x, abs_bisect_maybe_transpose.y);");
    164 
    165     // ninety_degreesness = sin^2(corner_angle)
    166     // sin^2 just because... it's always positive and the results looked better than plain sine... ?
    167     s->codeAppendf("half ninety_degreesness = determinant(half2x2(%s, %s));", leftDir, rightDir);
    168     s->codeAppend ("ninety_degreesness = ninety_degreesness * ninety_degreesness;");
    169 
    170     // The below formula is not smart. It was just arrived at by considering the following
    171     // observations:
    172     //
    173     // 1. 90-degree, axis-aligned corners have full attenuation along the bisector.
    174     //    (i.e. coverage = 1 - distance_to_corner^2)
    175     //    (i.e. outputAttenuation = 0)
    176     //
    177     // 2. 180-degree corners always have zero attenuation.
    178     //    (i.e. coverage = 1 - distance_to_corner)
    179     //    (i.e. outputAttenuation = 1)
    180     //
    181     // 3. 90-degree corners whose bisector falls on a 45 degree angle also do not attenuate.
    182     //    (i.e. outputAttenuation = 1)
    183     s->codeAppendf("%s = max(obtuseness, axis_alignedness * ninety_degreesness);",
    184                    outputAttenuation);
    185 }
    186 
    187 void GrCCCoverageProcessor::getGLSLProcessorKey(const GrShaderCaps&,
    188                                                 GrProcessorKeyBuilder* b) const {
    189     int key = (int)fPrimitiveType << 2;
    190     if (GSSubpass::kCorners == fGSSubpass) {
    191         key |= 2;
    192     }
    193     if (Impl::kVertexShader == fImpl) {
    194         key |= 1;
    195     }
    196 #ifdef SK_DEBUG
    197     uint32_t bloatBits;
    198     memcpy(&bloatBits, &fDebugBloat, 4);
    199     b->add32(bloatBits);
    200 #endif
    201     b->add32(key);
    202 }
    203 
    204 GrGLSLPrimitiveProcessor* GrCCCoverageProcessor::createGLSLInstance(const GrShaderCaps&) const {
    205     std::unique_ptr<Shader> shader;
    206     switch (fPrimitiveType) {
    207         case PrimitiveType::kTriangles:
    208         case PrimitiveType::kWeightedTriangles:
    209             shader = skstd::make_unique<TriangleShader>();
    210             break;
    211         case PrimitiveType::kQuadratics:
    212             shader = skstd::make_unique<GrCCQuadraticShader>();
    213             break;
    214         case PrimitiveType::kCubics:
    215             shader = skstd::make_unique<GrCCCubicShader>();
    216             break;
    217         case PrimitiveType::kConics:
    218             shader = skstd::make_unique<GrCCConicShader>();
    219             break;
    220     }
    221     return Impl::kGeometryShader == fImpl ? this->createGSImpl(std::move(shader))
    222                                           : this->createVSImpl(std::move(shader));
    223 }
    224 
    225 void GrCCCoverageProcessor::Shader::emitFragmentCode(const GrCCCoverageProcessor& proc,
    226                                                      GrGLSLFPFragmentBuilder* f,
    227                                                      const char* skOutputColor,
    228                                                      const char* skOutputCoverage) const {
    229     f->codeAppendf("half coverage = 0;");
    230     this->onEmitFragmentCode(f, "coverage");
    231     f->codeAppendf("%s.a = coverage;", skOutputColor);
    232     f->codeAppendf("%s = half4(1);", skOutputCoverage);
    233 }
    234 
    235 void GrCCCoverageProcessor::draw(GrOpFlushState* flushState, const GrPipeline& pipeline,
    236                                  const SkIRect scissorRects[], const GrMesh meshes[], int meshCount,
    237                                  const SkRect& drawBounds) const {
    238     GrPipeline::DynamicStateArrays dynamicStateArrays;
    239     dynamicStateArrays.fScissorRects = scissorRects;
    240     GrGpuRTCommandBuffer* cmdBuff = flushState->rtCommandBuffer();
    241     cmdBuff->draw(*this, pipeline, nullptr, &dynamicStateArrays, meshes, meshCount, drawBounds);
    242 
    243     // Geometry shader backend draws primitives in two subpasses.
    244     if (Impl::kGeometryShader == fImpl) {
    245         SkASSERT(GSSubpass::kHulls == fGSSubpass);
    246         GrCCCoverageProcessor cornerProc(*this, GSSubpass::kCorners);
    247         cmdBuff->draw(cornerProc, pipeline, nullptr, &dynamicStateArrays, meshes, meshCount,
    248                       drawBounds);
    249     }
    250 }
    251