GrCCPathProcessor.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. #include "src/gpu/ccpr/GrCCPathProcessor.h"
  8. #include "include/gpu/GrTexture.h"
  9. #include "src/gpu/GrGpuCommandBuffer.h"
  10. #include "src/gpu/GrOnFlushResourceProvider.h"
  11. #include "src/gpu/GrTexturePriv.h"
  12. #include "src/gpu/ccpr/GrCCPerFlushResources.h"
  13. #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
  14. #include "src/gpu/glsl/GrGLSLGeometryProcessor.h"
  15. #include "src/gpu/glsl/GrGLSLProgramBuilder.h"
  16. #include "src/gpu/glsl/GrGLSLVarying.h"
  17. // Paths are drawn as octagons. Each point on the octagon is the intersection of two lines: one edge
  18. // from the path's bounding box and one edge from its 45-degree bounding box. The selectors
  19. // below indicate one corner from the bounding box, paired with a corner from the 45-degree bounding
  20. // box. The octagon vertex is the point that lies between these two corners, found by intersecting
  21. // their edges.
  22. static constexpr float kOctoEdgeNorms[8*4] = {
  23. // bbox // bbox45
  24. 0,0, 0,0,
  25. 0,0, 1,0,
  26. 1,0, 1,0,
  27. 1,0, 1,1,
  28. 1,1, 1,1,
  29. 1,1, 0,1,
  30. 0,1, 0,1,
  31. 0,1, 0,0,
  32. };
  33. GR_DECLARE_STATIC_UNIQUE_KEY(gVertexBufferKey);
  34. sk_sp<const GrGpuBuffer> GrCCPathProcessor::FindVertexBuffer(GrOnFlushResourceProvider* onFlushRP) {
  35. GR_DEFINE_STATIC_UNIQUE_KEY(gVertexBufferKey);
  36. return onFlushRP->findOrMakeStaticBuffer(GrGpuBufferType::kVertex, sizeof(kOctoEdgeNorms),
  37. kOctoEdgeNorms, gVertexBufferKey);
  38. }
  39. static constexpr uint16_t kRestartStrip = 0xffff;
  40. static constexpr uint16_t kOctoIndicesAsStrips[] = {
  41. 3, 4, 2, 0, 1, kRestartStrip, // First half.
  42. 7, 0, 6, 4, 5 // Second half.
  43. };
  44. static constexpr uint16_t kOctoIndicesAsTris[] = {
  45. // First half.
  46. 3, 4, 2,
  47. 4, 0, 2,
  48. 2, 0, 1,
  49. // Second half.
  50. 7, 0, 6,
  51. 0, 4, 6,
  52. 6, 4, 5,
  53. };
  54. GR_DECLARE_STATIC_UNIQUE_KEY(gIndexBufferKey);
  55. constexpr GrPrimitiveProcessor::Attribute GrCCPathProcessor::kInstanceAttribs[];
  56. constexpr GrPrimitiveProcessor::Attribute GrCCPathProcessor::kCornersAttrib;
  57. sk_sp<const GrGpuBuffer> GrCCPathProcessor::FindIndexBuffer(GrOnFlushResourceProvider* onFlushRP) {
  58. GR_DEFINE_STATIC_UNIQUE_KEY(gIndexBufferKey);
  59. if (onFlushRP->caps()->usePrimitiveRestart()) {
  60. return onFlushRP->findOrMakeStaticBuffer(GrGpuBufferType::kIndex,
  61. sizeof(kOctoIndicesAsStrips), kOctoIndicesAsStrips,
  62. gIndexBufferKey);
  63. } else {
  64. return onFlushRP->findOrMakeStaticBuffer(GrGpuBufferType::kIndex,
  65. sizeof(kOctoIndicesAsTris), kOctoIndicesAsTris,
  66. gIndexBufferKey);
  67. }
  68. }
  69. GrCCPathProcessor::GrCCPathProcessor(CoverageMode coverageMode, const GrTexture* atlasTexture,
  70. const GrSwizzle& swizzle, GrSurfaceOrigin atlasOrigin,
  71. const SkMatrix& viewMatrixIfUsingLocalCoords)
  72. : INHERITED(kGrCCPathProcessor_ClassID)
  73. , fCoverageMode(coverageMode)
  74. , fAtlasAccess(atlasTexture->texturePriv().textureType(), atlasTexture->config(),
  75. GrSamplerState::Filter::kNearest, GrSamplerState::WrapMode::kClamp, swizzle)
  76. , fAtlasSize(SkISize::Make(atlasTexture->width(), atlasTexture->height()))
  77. , fAtlasOrigin(atlasOrigin) {
  78. // TODO: Can we just assert that atlas has GrCCAtlas::kTextureOrigin and remove fAtlasOrigin?
  79. this->setInstanceAttributes(kInstanceAttribs, SK_ARRAY_COUNT(kInstanceAttribs));
  80. SkASSERT(this->instanceStride() == sizeof(Instance));
  81. this->setVertexAttributes(&kCornersAttrib, 1);
  82. this->setTextureSamplerCnt(1);
  83. if (!viewMatrixIfUsingLocalCoords.invert(&fLocalMatrix)) {
  84. fLocalMatrix.setIdentity();
  85. }
  86. }
  87. class GrCCPathProcessor::Impl : public GrGLSLGeometryProcessor {
  88. public:
  89. void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override;
  90. private:
  91. void setData(const GrGLSLProgramDataManager& pdman, const GrPrimitiveProcessor& primProc,
  92. FPCoordTransformIter&& transformIter) override {
  93. const auto& proc = primProc.cast<GrCCPathProcessor>();
  94. pdman.set2f(
  95. fAtlasAdjustUniform, 1.0f / proc.fAtlasSize.fWidth, 1.0f / proc.fAtlasSize.fHeight);
  96. this->setTransformDataHelper(proc.fLocalMatrix, pdman, &transformIter);
  97. }
  98. GrGLSLUniformHandler::UniformHandle fAtlasAdjustUniform;
  99. typedef GrGLSLGeometryProcessor INHERITED;
  100. };
  101. GrGLSLPrimitiveProcessor* GrCCPathProcessor::createGLSLInstance(const GrShaderCaps&) const {
  102. return new Impl();
  103. }
  104. void GrCCPathProcessor::drawPaths(GrOpFlushState* flushState, const GrPipeline& pipeline,
  105. const GrPipeline::FixedDynamicState* fixedDynamicState,
  106. const GrCCPerFlushResources& resources, int baseInstance,
  107. int endInstance, const SkRect& bounds) const {
  108. const GrCaps& caps = flushState->caps();
  109. GrPrimitiveType primitiveType = caps.usePrimitiveRestart()
  110. ? GrPrimitiveType::kTriangleStrip
  111. : GrPrimitiveType::kTriangles;
  112. int numIndicesPerInstance = caps.usePrimitiveRestart()
  113. ? SK_ARRAY_COUNT(kOctoIndicesAsStrips)
  114. : SK_ARRAY_COUNT(kOctoIndicesAsTris);
  115. GrMesh mesh(primitiveType);
  116. auto enablePrimitiveRestart = GrPrimitiveRestart(flushState->caps().usePrimitiveRestart());
  117. mesh.setIndexedInstanced(resources.refIndexBuffer(), numIndicesPerInstance,
  118. resources.refInstanceBuffer(), endInstance - baseInstance,
  119. baseInstance, enablePrimitiveRestart);
  120. mesh.setVertexData(resources.refVertexBuffer());
  121. flushState->rtCommandBuffer()->draw(*this, pipeline, fixedDynamicState, nullptr, &mesh, 1,
  122. bounds);
  123. }
  124. void GrCCPathProcessor::Impl::onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) {
  125. using Interpolation = GrGLSLVaryingHandler::Interpolation;
  126. const GrCCPathProcessor& proc = args.fGP.cast<GrCCPathProcessor>();
  127. GrGLSLUniformHandler* uniHandler = args.fUniformHandler;
  128. GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
  129. bool isCoverageCount = (CoverageMode::kCoverageCount == proc.fCoverageMode);
  130. const char* atlasAdjust;
  131. fAtlasAdjustUniform = uniHandler->addUniform(
  132. kVertex_GrShaderFlag, kFloat2_GrSLType, "atlas_adjust", &atlasAdjust);
  133. varyingHandler->emitAttributes(proc);
  134. GrGLSLVarying texcoord((isCoverageCount) ? kFloat3_GrSLType : kFloat2_GrSLType);
  135. varyingHandler->addVarying("texcoord", &texcoord);
  136. GrGLSLVarying color(kHalf4_GrSLType);
  137. varyingHandler->addPassThroughAttribute(
  138. kInstanceAttribs[kColorAttribIdx], args.fOutputColor, Interpolation::kCanBeFlat);
  139. // The vertex shader bloats and intersects the devBounds and devBounds45 rectangles, in order to
  140. // find an octagon that circumscribes the (bloated) path.
  141. GrGLSLVertexBuilder* v = args.fVertBuilder;
  142. // Are we clockwise? (Positive wind => nonzero fill rule.)
  143. // Or counter-clockwise? (negative wind => even/odd fill rule.)
  144. v->codeAppendf("float wind = sign(devbounds.z - devbounds.x);");
  145. // Find our reference corner from the device-space bounding box.
  146. v->codeAppendf("float2 refpt = mix(devbounds.xy, devbounds.zw, corners.xy);");
  147. // Find our reference corner from the 45-degree bounding box.
  148. v->codeAppendf("float2 refpt45 = mix(devbounds45.xy, devbounds45.zw, corners.zw);");
  149. // Transform back to device space.
  150. v->codeAppendf("refpt45 *= float2x2(+1, +1, -wind, +wind) * .5;");
  151. // Find the normals to each edge, then intersect them to find our octagon vertex.
  152. v->codeAppendf("float2x2 N = float2x2("
  153. "corners.z + corners.w - 1, corners.w - corners.z, "
  154. "corners.xy*2 - 1);");
  155. v->codeAppendf("N = float2x2(wind, 0, 0, 1) * N;");
  156. v->codeAppendf("float2 K = float2(dot(N[0], refpt), dot(N[1], refpt45));");
  157. v->codeAppendf("float2 octocoord = K * inverse(N);");
  158. // Round the octagon out to ensure we rasterize every pixel the path might touch. (Positive
  159. // bloatdir means we should take the "ceil" and negative means to take the "floor".)
  160. //
  161. // NOTE: If we were just drawing a rect, ceil/floor would be enough. But since there are also
  162. // diagonals in the octagon that cross through pixel centers, we need to outset by another
  163. // quarter px to ensure those pixels get rasterized.
  164. v->codeAppendf("float2 bloatdir = (0 != N[0].x) "
  165. "? float2(N[0].x, N[1].y)"
  166. ": float2(N[1].x, N[0].y);");
  167. v->codeAppendf("octocoord = (ceil(octocoord * bloatdir - 1e-4) + 0.25) * bloatdir;");
  168. v->codeAppendf("float2 atlascoord = octocoord + float2(dev_to_atlas_offset);");
  169. // Convert to atlas coordinates in order to do our texture lookup.
  170. if (kTopLeft_GrSurfaceOrigin == proc.fAtlasOrigin) {
  171. v->codeAppendf("%s.xy = atlascoord * %s;", texcoord.vsOut(), atlasAdjust);
  172. } else {
  173. SkASSERT(kBottomLeft_GrSurfaceOrigin == proc.fAtlasOrigin);
  174. v->codeAppendf("%s.xy = float2(atlascoord.x * %s.x, 1 - atlascoord.y * %s.y);",
  175. texcoord.vsOut(), atlasAdjust, atlasAdjust);
  176. }
  177. if (isCoverageCount) {
  178. v->codeAppendf("%s.z = wind * .5;", texcoord.vsOut());
  179. }
  180. gpArgs->fPositionVar.set(kFloat2_GrSLType, "octocoord");
  181. this->emitTransforms(v, varyingHandler, uniHandler, gpArgs->fPositionVar, proc.fLocalMatrix,
  182. args.fFPCoordTransformHandler);
  183. // Fragment shader.
  184. GrGLSLFPFragmentBuilder* f = args.fFragBuilder;
  185. // Look up coverage in the atlas.
  186. f->codeAppendf("half coverage = ");
  187. f->appendTextureLookup(args.fTexSamplers[0], SkStringPrintf("%s.xy", texcoord.fsIn()).c_str(),
  188. kFloat2_GrSLType);
  189. f->codeAppendf(".a;");
  190. if (isCoverageCount) {
  191. f->codeAppendf("coverage = abs(coverage);");
  192. // Scale coverage count by .5. Make it negative for even-odd paths and positive for
  193. // winding ones. Clamp winding coverage counts at 1.0 (i.e. min(coverage/2, .5)).
  194. f->codeAppendf("coverage = min(abs(coverage) * half(%s.z), .5);", texcoord.fsIn());
  195. // For negative values, this finishes the even-odd sawtooth function. Since positive
  196. // (winding) values were clamped at "coverage/2 = .5", this only undoes the previous
  197. // multiply by .5.
  198. f->codeAppend ("coverage = 1 - abs(fract(coverage) * 2 - 1);");
  199. }
  200. f->codeAppendf("%s = half4(coverage);", args.fOutputCoverage);
  201. }