Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
GrPathTessellationShader.cpp
Go to the documentation of this file.
1/*
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
9
10#include "src/base/SkMathPriv.h"
11#include "src/gpu/KeyBuilder.h"
19
20using namespace skia_private;
21
22namespace {
23
24using namespace skgpu::tess;
25
26// Draws a simple array of triangles.
27class SimpleTriangleShader : public GrPathTessellationShader {
28public:
29 SimpleTriangleShader(const SkMatrix& viewMatrix, SkPMColor4f color)
30 : GrPathTessellationShader(kTessellate_SimpleTriangleShader_ClassID,
32 viewMatrix,
33 color,
35 constexpr static Attribute kInputPointAttrib{"inputPoint", kFloat2_GrVertexAttribType,
37 this->setVertexAttributesWithImplicitOffsets(&kInputPointAttrib, 1);
38 }
39
40private:
41 const char* name() const final { return "tessellate_SimpleTriangleShader"; }
42 void addToKey(const GrShaderCaps&, skgpu::KeyBuilder*) const final {}
43 std::unique_ptr<ProgramImpl> makeProgramImpl(const GrShaderCaps&) const final;
44};
45
46std::unique_ptr<GrGeometryProcessor::ProgramImpl> SimpleTriangleShader::makeProgramImpl(
47 const GrShaderCaps&) const {
48 class Impl : public GrPathTessellationShader::Impl {
49 void emitVertexCode(const GrShaderCaps&,
53 GrGPArgs* gpArgs) override {
54 v->codeAppend(
55 "float2 localcoord = inputPoint;"
56 "float2 vertexpos = AFFINE_MATRIX * localcoord + TRANSLATE;");
57 gpArgs->fLocalCoordVar.set(SkSLType::kFloat2, "localcoord");
58 gpArgs->fPositionVar.set(SkSLType::kFloat2, "vertexpos");
59 }
60 };
61 return std::make_unique<Impl>();
62}
63
64
65// Uses instanced draws to triangulate standalone closed curves with a "middle-out" topology.
66// Middle-out draws a triangle with vertices at T=[0, 1/2, 1] and then recurses breadth first:
67//
68// depth=0: T=[0, 1/2, 1]
69// depth=1: T=[0, 1/4, 2/4], T=[2/4, 3/4, 1]
70// depth=2: T=[0, 1/8, 2/8], T=[2/8, 3/8, 4/8], T=[4/8, 5/8, 6/8], T=[6/8, 7/8, 1]
71// ...
72//
73// The shader determines how many segments are required to render each individual curve smoothly,
74// and emits empty triangles at any vertices whose sk_VertexIDs are higher than necessary. It is the
75// caller's responsibility to draw enough vertices per instance for the most complex curve in the
76// batch to render smoothly (i.e., NumTrianglesAtResolveLevel() * 3).
77class MiddleOutShader : public GrPathTessellationShader {
78public:
79 MiddleOutShader(const GrShaderCaps& shaderCaps, const SkMatrix& viewMatrix,
80 const SkPMColor4f& color, PatchAttribs attribs)
81 : GrPathTessellationShader(kTessellate_MiddleOutShader_ClassID,
82 GrPrimitiveType::kTriangles, viewMatrix, color, attribs) {
83 fInstanceAttribs.emplace_back("p01", kFloat4_GrVertexAttribType, SkSLType::kFloat4);
84 fInstanceAttribs.emplace_back("p23", kFloat4_GrVertexAttribType, SkSLType::kFloat4);
85 if (fAttribs & PatchAttribs::kFanPoint) {
86 fInstanceAttribs.emplace_back("fanPointAttrib",
89 }
90 if (fAttribs & PatchAttribs::kColor) {
91 fInstanceAttribs.emplace_back("colorAttrib",
92 (fAttribs & PatchAttribs::kWideColorIfEnabled)
96 }
97 if (fAttribs & PatchAttribs::kExplicitCurveType) {
98 // A conic curve is written out with p3=[w,Infinity], but GPUs that don't support
99 // infinity can't detect this. On these platforms we also write out an extra float with
100 // each patch that explicitly tells the shader what type of curve it is.
101 fInstanceAttribs.emplace_back("curveType", kFloat_GrVertexAttribType, SkSLType::kFloat);
102 }
103 this->setInstanceAttributesWithImplicitOffsets(fInstanceAttribs.data(),
104 fInstanceAttribs.size());
105 SkASSERT(fInstanceAttribs.size() <= kMaxInstanceAttribCount);
106 SkASSERT(this->instanceStride() ==
107 sizeof(SkPoint) * 4 + PatchAttribsStride(fAttribs));
108
109 constexpr static Attribute kVertexAttrib("resolveLevel_and_idx", kFloat2_GrVertexAttribType,
111 this->setVertexAttributesWithImplicitOffsets(&kVertexAttrib, 1);
112 }
113
114private:
115 const char* name() const final { return "tessellate_MiddleOutShader"; }
116 void addToKey(const GrShaderCaps&, skgpu::KeyBuilder* b) const final {
117 // When color is in a uniform, it's always wide so we need to ignore kWideColorIfEnabled.
118 // When color is in an attrib, its wideness is accounted for as part of the attrib key in
119 // GrGeometryProcessor::getAttributeKey().
120 // Either way, we get the correct key by ignoring .
121 b->add32((uint32_t)(fAttribs & ~PatchAttribs::kWideColorIfEnabled));
122 }
123 std::unique_ptr<ProgramImpl> makeProgramImpl(const GrShaderCaps&) const final;
124
125 constexpr static int kMaxInstanceAttribCount = 5;
127};
128
129std::unique_ptr<GrGeometryProcessor::ProgramImpl> MiddleOutShader::makeProgramImpl(
130 const GrShaderCaps&) const {
131 class Impl : public GrPathTessellationShader::Impl {
132 void emitVertexCode(const GrShaderCaps& shaderCaps,
133 const GrPathTessellationShader& shader,
135 GrGLSLVaryingHandler* varyingHandler,
136 GrGPArgs* gpArgs) override {
137 const MiddleOutShader& middleOutShader = shader.cast<MiddleOutShader>();
139 v->defineConstant("MAX_FIXED_RESOLVE_LEVEL",
141 v->defineConstant("MAX_FIXED_SEGMENTS",
144 if (middleOutShader.fAttribs & PatchAttribs::kExplicitCurveType) {
146 "bool is_conic_curve() {"
147 "return curveType != %g;"
150 "bool is_triangular_conic_curve() {"
151 "return curveType == %g;"
153 } else {
154 SkASSERT(shaderCaps.fInfinitySupport);
156 "bool is_conic_curve() { return isinf(p23.w); }"
157 "bool is_triangular_conic_curve() { return isinf(p23.z); }");
158 }
159 if (shaderCaps.fBitManipulationSupport) {
161 "float ldexp_portable(float x, float p) {"
162 "return ldexp(x, int(p));"
163 "}");
164 } else {
166 "float ldexp_portable(float x, float p) {"
167 "return x * exp2(p);"
168 "}");
169 }
170 v->codeAppend(
171 "float resolveLevel = resolveLevel_and_idx.x;"
172 "float idxInResolveLevel = resolveLevel_and_idx.y;"
173 "float2 localcoord;");
174 if (middleOutShader.fAttribs & PatchAttribs::kFanPoint) {
175 v->codeAppend(
176 // A negative resolve level means this is the fan point.
177 "if (resolveLevel < 0) {"
178 "localcoord = fanPointAttrib;"
179 "} else "); // Fall through to next if (). Trailing space is important.
180 }
181 v->codeAppend(
182 "if (is_triangular_conic_curve()) {"
183 // This patch is an exact triangle.
184 "localcoord = (resolveLevel != 0) ? p01.zw"
185 ": (idxInResolveLevel != 0) ? p23.xy"
186 ": p01.xy;"
187 "} else {"
188 "float2 p0=p01.xy, p1=p01.zw, p2=p23.xy, p3=p23.zw;"
189 "float w = -1;" // w < 0 tells us to treat the instance as an integral cubic.
190 "float maxResolveLevel;"
191 "if (is_conic_curve()) {"
192 // Conics are 3 points, with the weight in p3.
193 "w = p3.x;"
194 "maxResolveLevel = wangs_formula_conic_log2(PRECISION, AFFINE_MATRIX * p0,"
195 "AFFINE_MATRIX * p1,"
196 "AFFINE_MATRIX * p2, w);"
197 "p1 *= w;" // Unproject p1.
198 "p3 = p2;" // Duplicate the endpoint for shared code that also runs on cubics.
199 "} else {"
200 // The patch is an integral cubic.
201 "maxResolveLevel = wangs_formula_cubic_log2(PRECISION, p0, p1, p2, p3,"
202 "AFFINE_MATRIX);"
203 "}"
204 "if (resolveLevel > maxResolveLevel) {"
205 // This vertex is at a higher resolve level than we need. Demote to a lower
206 // resolveLevel, which will produce a degenerate triangle.
207 "idxInResolveLevel = floor(ldexp_portable(idxInResolveLevel,"
208 "maxResolveLevel - resolveLevel));"
209 "resolveLevel = maxResolveLevel;"
210 "}"
211 // Promote our location to a discrete position in the maximum fixed resolve level.
212 // This is extra paranoia to ensure we get the exact same fp32 coordinates for
213 // colocated points from different resolve levels (e.g., the vertices T=3/4 and
214 // T=6/8 should be exactly colocated).
215 "float fixedVertexID = floor(.5 + ldexp_portable("
216 "idxInResolveLevel, MAX_FIXED_RESOLVE_LEVEL - resolveLevel));"
217 "if (0 < fixedVertexID && fixedVertexID < MAX_FIXED_SEGMENTS) {"
218 "float T = fixedVertexID * (1 / MAX_FIXED_SEGMENTS);"
219
220 // Evaluate at T. Use De Casteljau's for its accuracy and stability.
221 "float2 ab = mix(p0, p1, T);"
222 "float2 bc = mix(p1, p2, T);"
223 "float2 cd = mix(p2, p3, T);"
224 "float2 abc = mix(ab, bc, T);"
225 "float2 bcd = mix(bc, cd, T);"
226 "float2 abcd = mix(abc, bcd, T);"
227
228 // Evaluate the conic weight at T.
229 "float u = mix(1.0, w, T);"
230 "float v = w + 1 - u;" // == mix(w, 1, T)
231 "float uv = mix(u, v, T);"
232
233 "localcoord = (w < 0) ?" /*cubic*/ "abcd:" /*conic*/ "abc/uv;"
234 "} else {"
235 "localcoord = (fixedVertexID == 0) ? p0.xy : p3.xy;"
236 "}"
237 "}"
238 "float2 vertexpos = AFFINE_MATRIX * localcoord + TRANSLATE;");
239 gpArgs->fLocalCoordVar.set(SkSLType::kFloat2, "localcoord");
240 gpArgs->fPositionVar.set(SkSLType::kFloat2, "vertexpos");
241 if (middleOutShader.fAttribs & PatchAttribs::kColor) {
242 GrGLSLVarying colorVarying(SkSLType::kHalf4);
243 varyingHandler->addVarying("color",
244 &colorVarying,
246 v->codeAppendf("%s = colorAttrib;", colorVarying.vsOut());
247 fVaryingColorName = colorVarying.fsIn();
248 }
249 }
250 };
251 return std::make_unique<Impl>();
252}
253
254} // namespace
255
257 SkArenaAlloc* arena,
258 const SkMatrix& viewMatrix,
259 const SkPMColor4f& color,
260 PatchAttribs attribs) {
261 // We should use explicit curve type when, and only when, there isn't infinity support.
262 // Otherwise the GPU can infer curve type based on infinity.
263 SkASSERT(shaderCaps.fInfinitySupport != (attribs & PatchAttribs::kExplicitCurveType));
264 return arena->make<MiddleOutShader>(shaderCaps, viewMatrix, color, attribs);
265}
266
268 SkArenaAlloc* arena, const SkMatrix& viewMatrix, const SkPMColor4f& color) {
269 return arena->make<SimpleTriangleShader>(viewMatrix, color);
270}
271
273 const ProgramArgs& args,
274 GrAAType aaType,
275 const GrAppliedHardClip& hardClip,
276 GrPipeline::InputFlags pipelineFlags) {
277 GrPipeline::InitArgs pipelineArgs;
278 pipelineArgs.fInputFlags = pipelineFlags;
279 pipelineArgs.fCaps = args.fCaps;
280 return args.fArena->make<GrPipeline>(pipelineArgs,
282 hardClip);
283}
284
285// Evaluate our point of interest using numerically stable linear interpolations. We add our own
286// "safe_mix" method to guarantee we get exactly "b" when T=1. The builtin mix() function seems
287// spec'd to behave this way, but empirical results results have shown it does not always.
289"float3 safe_mix(float3 a, float3 b, float T, float one_minus_T) {"
290 "return a*one_minus_T + b*T;"
291"}"
292"float2 eval_rational_cubic(float4x3 P, float T) {"
293 "float one_minus_T = 1.0 - T;"
294 "float3 ab = safe_mix(P[0], P[1], T, one_minus_T);"
295 "float3 bc = safe_mix(P[1], P[2], T, one_minus_T);"
296 "float3 cd = safe_mix(P[2], P[3], T, one_minus_T);"
297 "float3 abc = safe_mix(ab, bc, T, one_minus_T);"
298 "float3 bcd = safe_mix(bc, cd, T, one_minus_T);"
299 "float3 abcd = safe_mix(abc, bcd, T, one_minus_T);"
300 "return abcd.xy / abcd.z;"
301"}";
302
304 const auto& shader = args.fGeomProc.cast<GrPathTessellationShader>();
305 args.fVaryingHandler->emitAttributes(shader);
306
307 // Vertex shader.
308 const char* affineMatrix, *translate;
309 fAffineMatrixUniform = args.fUniformHandler->addUniform(nullptr, kVertex_GrShaderFlag,
310 SkSLType::kFloat4, "affineMatrix",
311 &affineMatrix);
312 fTranslateUniform = args.fUniformHandler->addUniform(nullptr, kVertex_GrShaderFlag,
313 SkSLType::kFloat2, "translate", &translate);
314 args.fVertBuilder->codeAppendf("float2x2 AFFINE_MATRIX = float2x2(%s.xy, %s.zw);",
315 affineMatrix, affineMatrix);
316 args.fVertBuilder->codeAppendf("float2 TRANSLATE = %s;", translate);
317 this->emitVertexCode(*args.fShaderCaps,
318 shader,
319 args.fVertBuilder,
320 args.fVaryingHandler,
321 gpArgs);
322
323 // Fragment shader.
324 if (!(shader.fAttribs & PatchAttribs::kColor)) {
325 const char* color;
326 fColorUniform = args.fUniformHandler->addUniform(nullptr, kFragment_GrShaderFlag,
327 SkSLType::kHalf4, "color", &color);
328 args.fFragBuilder->codeAppendf("half4 %s = %s;", args.fOutputColor, color);
329 } else {
330 args.fFragBuilder->codeAppendf("half4 %s = %s;",
331 args.fOutputColor, fVaryingColorName.c_str());
332 }
333 args.fFragBuilder->codeAppendf("const half4 %s = half4(1);", args.fOutputCoverage);
334}
335
337 GrShaderCaps&, const GrGeometryProcessor& geomProc) {
338 const auto& shader = geomProc.cast<GrPathTessellationShader>();
339 const SkMatrix& m = shader.viewMatrix();
340 pdman.set4f(fAffineMatrixUniform, m.getScaleX(), m.getSkewY(), m.getSkewX(), m.getScaleY());
341 pdman.set2f(fTranslateUniform, m.getTranslateX(), m.getTranslateY());
342
343 if (!(shader.fAttribs & PatchAttribs::kColor)) {
344 const SkPMColor4f& color = shader.color();
345 pdman.set4f(fColorUniform, color.fR, color.fG, color.fB, color.fA);
346 }
347}
@ kVertex_GrShaderFlag
@ kFragment_GrShaderFlag
GrPrimitiveType
Definition GrTypesPriv.h:42
GrAAType
@ kFloat2_GrVertexAttribType
@ kUByte4_norm_GrVertexAttribType
@ kFloat_GrVertexAttribType
@ kFloat4_GrVertexAttribType
SkColor4f color
#define SkASSERT(cond)
Definition SkAssert.h:116
SkSLType
SK_API SkString static SkString SkStringPrintf()
Definition SkString.h:287
static sk_sp< const GrXferProcessor > MakeXferProcessor()
virtual void set2f(UniformHandle, float, float) const =0
virtual void set4f(UniformHandle, float, float, float, float) const =0
void defineConstant(const char *type, const char *name, const char *value)
void codeAppend(const char *str)
void codeAppendf(const char format[],...) SK_PRINTF_LIKE(2
void addVarying(const char *name, GrGLSLVarying *varying, Interpolation=Interpolation::kInterpolated)
void insertFunction(const char *functionDefinition)
void setInstanceAttributesWithImplicitOffsets(const Attribute *attrs, int attrCount)
virtual std::unique_ptr< ProgramImpl > makeProgramImpl(const GrShaderCaps &) const =0
virtual void addToKey(const GrShaderCaps &, skgpu::KeyBuilder *) const =0
size_t instanceStride() const
void setVertexAttributesWithImplicitOffsets(const Attribute *attrs, int attrCount)
GrGLSLUniformHandler::UniformHandle fTranslateUniform
void setData(const GrGLSLProgramDataManager &, const GrShaderCaps &, const GrGeometryProcessor &) override
GrGLSLUniformHandler::UniformHandle fAffineMatrixUniform
virtual void emitVertexCode(const GrShaderCaps &, const GrPathTessellationShader &, GrGLSLVertexBuilder *, GrGLSLVaryingHandler *, GrGPArgs *)=0
void onEmitCode(EmitArgs &, GrGPArgs *) final
GrGLSLUniformHandler::UniformHandle fColorUniform
static GrPathTessellationShader * MakeSimpleTriangleShader(SkArenaAlloc *, const SkMatrix &viewMatrix, const SkPMColor4f &)
static const GrPipeline * MakeStencilOnlyPipeline(const ProgramArgs &, GrAAType, const GrAppliedHardClip &, GrPipeline::InputFlags=GrPipeline::InputFlags::kNone)
static GrPathTessellationShader * Make(const GrShaderCaps &, SkArenaAlloc *, const SkMatrix &viewMatrix, const SkPMColor4f &, PatchAttribs)
const T & cast() const
virtual const char * name() const =0
static const char * WangsFormulaSkSL()
const SkPMColor4f & color() const
const SkMatrix & viewMatrix() const
auto make(Ctor &&ctor) -> decltype(ctor(nullptr))
const char * c_str() const
Definition SkString.h:133
static bool b
G_BEGIN_DECLS G_MODULE_EXPORT FlValue * args
static constexpr float kTriangularConicCurveType
static constexpr int kMaxResolveLevel
constexpr size_t PatchAttribsStride(PatchAttribs attribs)
static constexpr float kPrecision
static constexpr float kCubicCurveType
static constexpr int kMaxParametricSegments
InputFlags fInputFlags
Definition GrPipeline.h:63
const GrCaps * fCaps
Definition GrPipeline.h:64
bool fBitManipulationSupport
float fB
blue component
Definition SkColor.h:265
float fR
red component
Definition SkColor.h:263
float fG
green component
Definition SkColor.h:264
float fA
alpha component
Definition SkColor.h:266
bool fInfinitySupport
Definition SkSLUtil.h:103