Debian Codegraph @

src/gpu/graphite/ShaderCodeDictionary.cpp

raw
1 /*
2 * Copyright 2022 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/graphite/ShaderCodeDictionary.h"
9
10 #include "include/core/SkTileMode.h"
11 #include "include/effects/SkRuntimeEffect.h"
12 #include "src/core/SkColorSpaceXformSteps.h"
13 #include "src/core/SkRuntimeEffectPriv.h"
14 #include "src/gpu/BlendFormula.h"
15 #include "src/gpu/graphite/Caps.h"
16 #include "src/gpu/graphite/ContextUtils.h"
17 #include "src/gpu/graphite/Log.h"
18 #include "src/gpu/graphite/ReadSwizzle.h"
19 #include "src/gpu/graphite/Renderer.h"
20 #include "src/gpu/graphite/RuntimeEffectDictionary.h"
21 #include "src/gpu/graphite/ShaderInfo.h"
22 #include "src/gpu/graphite/UniformManager.h"
23 #include "src/sksl/SkSLString.h"
24 #include "src/sksl/codegen/SkSLPipelineStageCodeGenerator.h"
25 #include "src/sksl/ir/SkSLVarDeclarations.h"
26
27 using namespace skia_private;
28 using namespace SkKnownRuntimeEffects;
29
30 namespace skgpu::graphite {
31
32 static_assert(static_cast<int>(BuiltInCodeSnippetID::kLast) < kSkiaBuiltInReservedCnt);
33
34 namespace {
35
36 const char* get_known_rte_name(StableKey key) {
37 switch (key) {
38 #define M(type) case StableKey::k##type : return "KnownRuntimeEffect_" #type;
39 #define M1(type)
40 #define M2(type, initializer) case StableKey::k##type : return "KnownRuntimeEffect_" #type;
41 SK_ALL_STABLEKEYS(M, M1, M2)
42 #undef M2
43 #undef M1
44 #undef M
45 }
46
47 SkUNREACHABLE;
48 }
49
50 std::string get_storage_buffer_access(const char* ssboIndex,
51 const char* uniformName) {
52 return SkSL::String::printf("combinedUniformData[%s].%s", ssboIndex, uniformName);
53 }
54
55 std::string get_mangled_name(const std::string& baseName, int manglingSuffix) {
56 return baseName + "_" + std::to_string(manglingSuffix);
57 }
58
59 std::string get_mangled_uniform_name(const ShaderInfo& shaderInfo,
60 const Uniform& uniform,
61 int manglingSuffix) {
62 std::string result;
63
64 if (uniform.isPaintColor()) {
65 // Due to deduplication there will only ever be one of these
66 result = uniform.name();
67 } else {
68 result = uniform.name() + std::string("_") + std::to_string(manglingSuffix);
69 }
70 if (shaderInfo.uniformSsboIndex()) {
71 result = get_storage_buffer_access(shaderInfo.uniformSsboIndex(), result.c_str());
72 }
73 return result;
74 }
75
76 std::string get_mangled_sampler_name(const TextureAndSampler& tex, int manglingSuffix) {
77 return tex.name() + std::string("_") + std::to_string(manglingSuffix);
78 }
79
80 std::string get_mangled_struct_reference(const ShaderInfo& shaderInfo,
81 const ShaderNode* node) {
82 SkASSERT(node->entry()->fUniformStructName);
83 std::string result = "node_" + std::to_string(node->keyIndex()); // Field holding the struct
84 if (shaderInfo.uniformSsboIndex()) {
85 result = get_storage_buffer_access(shaderInfo.uniformSsboIndex(), result.c_str());
86 }
87 return result;
88 }
89
90 std::string stitch_csv(SkSpan<const std::string> args) {
91 std::string code = "";
92 const char* separator = "";
93 for (const std::string& arg : args) {
94 code += separator;
95 code += arg;
96 separator = ", ";
97 }
98
99 return code;
100 }
101
102 // If 'args' is null, the generated list is assumed to be for parameter declarations. If it's non
103 // null, it is assumed to be the expressions to invoke the default signature.
104 void append_defaults(TArray<std::string>* list,
105 const ShaderNode* node,
106 const ShaderSnippet::Args* args) {
107 // Use the node's aggregate required flags so that the provided dynamic variables propagate
108 // to the child nodes that require them.
109 if (node->requiredFlags() & SnippetRequirementFlags::kPriorStageOutput) {
110 list->push_back(args ? args->fPriorStageOutput.c_str() : "half4 inColor");
111 }
112 if (node->requiredFlags() & SnippetRequirementFlags::kBlenderDstColor) {
113 list->push_back(args ? args->fBlenderDstColor.c_str() : "half4 destColor");
114 }
115 if (node->requiredFlags() & SnippetRequirementFlags::kLocalCoords) {
116 list->push_back(args ? args->fFragCoord.c_str() : "float2 pos");
117 }
118
119 // Special variables and/or "global" scope variables that have to propagate
120 // through the node tree.
121 if (node->requiredFlags() & SnippetRequirementFlags::kPrimitiveColor) {
122 list->push_back(args ? "primitiveColor" : "half4 primitiveColor");
123 }
124 }
125
126 void append_uniforms(TArray<std::string>* list,
127 const ShaderInfo& shaderInfo,
128 const ShaderNode* node,
129 SkSpan<const std::string> childOutputs) {
130 const ShaderSnippet* entry = node->entry();
131
132 if (entry->fUniformStructName) {
133 // The node's uniforms are aggregated in a sub-struct within the global uniforms so we just
134 // need to append a reference to the node's instance
135 list->push_back(get_mangled_struct_reference(shaderInfo, node));
136 } else {
137 // The uniforms are in the global scope, so just pass in the ones bound to 'node'
138 for (int i = 0; i < entry->fUniforms.size(); ++i) {
139 list->push_back(get_mangled_uniform_name(shaderInfo,
140 entry->fUniforms[i],
141 node->keyIndex()));
142 }
143 }
144
145 // Append samplers
146 for (int i = 0; i < entry->fTexturesAndSamplers.size(); ++i) {
147 list->push_back(get_mangled_sampler_name(entry->fTexturesAndSamplers[i], node->keyIndex()));
148 }
149
150 // Append gradient buffer.
151 if (node->requiredFlags() & SnippetRequirementFlags::kGradientBuffer) {
152 list->push_back(ShaderInfo::kGradientBufferName);
153 }
154
155 // Append child output names.
156 if (!childOutputs.empty()) {
157 list->push_back_n(childOutputs.size(), childOutputs.data());
158 }
159 }
160
161 // If we have no children, the default expression just calls a built-in snippet with the signature:
162 // half4 BuiltinFunctionName(/* required variable inputs (e.g. float2 pos) */,
163 // /* all uniforms as parameters (bound to node's values) */) { ... }
164 // If we do have children, we will have created a glue function in the preamble and that is called
165 // instead. Its signature looks like this:
166 // half4 SnippetName_N(/* required variable inputs (e.g. float2 pos) */) { ... }
167 std::string invoke_node(const ShaderInfo& shaderInfo,
168 const ShaderNode* node,
169 const ShaderSnippet::Args& args) {
170 std::string fnName;
171 STArray<3, std::string> params; // 1-2 inputs and a uniform struct or texture
172
173 if (node->numChildren() == 0 && node->entry()->fStaticFunctionName) {
174 // We didn't generate a helper function in the preamble, so add uniforms to the parameter
175 // list and call the static function directly.
176 fnName = node->entry()->fStaticFunctionName;
177 append_defaults(&params, node, &args);
178 append_uniforms(&params, shaderInfo, node, /*childOutputs=*/{});
179 } else {
180 // Invoke the generated helper function added to the preamble, which will handle invoking
181 // any children and appending their values to the rest of the static fn's arguments.
182 fnName = get_mangled_name(node->entry()->fName, node->keyIndex());
183 append_defaults(&params, node, &args);
184 }
185
186 return SkSL::String::printf("%s(%s)", fnName.c_str(), stitch_csv(params).c_str());
187 }
188
189 // Emit a declaration for a helper function that represents the ShaderNode (named using the node's
190 // mangled name). The dynamic parameters are declared to match kDefaultArgs. The returned string
191 // can either be followed by a "{ body }" to fully define it or a ";" for a forward declaration.
192 std::string emit_helper_declaration(const ShaderNode* node) {
193 const ShaderSnippet* entry = node->entry();
194 std::string helperFnName = get_mangled_name(entry->fName, node->keyIndex());
195
196 STArray<3, std::string> params;
197 append_defaults(&params, node, /*args=*/nullptr); // null args emits declarations
198
199 return SkSL::String::printf("half4 %s(%s)", helperFnName.c_str(), stitch_csv(params).c_str());
200 }
201
202 } // anonymous namespace
203
204 //--------------------------------------------------------------------------------------------------
205 // ShaderSnippet
206
207 const ShaderSnippet::Args ShaderSnippet::kDefaultArgs = {"inColor", "destColor", "pos"};
208
209 //--------------------------------------------------------------------------------------------------
210 // ShaderNode
211
212 // If we have no children, we don't need to add anything into the preamble.
213 // If we have child entries, we create a function in the preamble with a signature of:
214 // half4 SnippetName_N(/* required variable inputs (e.g. float2 pos) */) { ... }
215 // This function invokes each child in sequence, and then calls the built-in function, passing all
216 // uniforms and child outputs along:
217 // half4 BuiltinFunctionName(/* required variable inputs (e.g. float2 pos) */,
218 // /* all uniforms as parameters */,
219 // /* all child output variable names as parameters */);
220 std::string ShaderNode::generateDefaultPreamble(const ShaderInfo& shaderInfo) const {
221 if (this->numChildren() == 0) {
222 // We don't need a helper function to wrap the snippet's static function
223 return "";
224 }
225
226 std::string code = emit_helper_declaration(this) + " {";
227
228 // Invoke each child with unmodified input values and collect in a list of local variables
229 STArray<2, std::string> childOutputVarNames;
230 for (const ShaderNode* child : this->children()) {
231 // Emit glue code into our helper function body (i.e. lifting the child execution up front
232 // so their outputs can be passed to the static module function for the node's snippet).
233 childOutputVarNames.push_back(
234 child->invokeAndAssign(shaderInfo, ShaderSnippet::kDefaultArgs, &code));
235 }
236
237 // Finally, invoke the snippet from the helper function, passing uniforms and child outputs.
238 STArray<3, std::string> params;
239 append_defaults(&params, this, &ShaderSnippet::kDefaultArgs);
240 append_uniforms(&params, shaderInfo, this, childOutputVarNames);
241
242 SkSL::String::appendf(&code,
243 "return %s(%s);"
244 "}",
245 this->entry()->fStaticFunctionName,
246 stitch_csv(params).c_str());
247 return code;
248 }
249
250 // Emit the glue code needed to invoke a single static helper isolated within its own scope.
251 // Glue code will assign the resulting color into a variable `half4 outColor%d`, where the %d is
252 // filled in with 'node->keyIndex()'.
253 std::string ShaderNode::invokeAndAssign(const ShaderInfo& shaderInfo,
254 const ShaderSnippet::Args& args,
255 std::string* funcBody) const {
256 std::string expr = invoke_node(shaderInfo, this, args);
257 std::string outputVar = get_mangled_name("outColor", this->keyIndex());
258 #if defined(SK_DEBUG)
259 SkSL::String::appendf(funcBody,
260 "// [%d] %s\n"
261 "half4 %s = %s;",
262 this->keyIndex(),
263 this->entry()->fName,
264 outputVar.c_str(),
265 expr.c_str());
266 #else
267 SkSL::String::appendf(funcBody,
268 "half4 %s = %s;",
269 outputVar.c_str(),
270 expr.c_str());
271 #endif
272 return outputVar;
273 }
274
275 // Return a name that should be used as a varying passing the result of an expression emitted by
276 // this node, if the expression is being lifted from the fragment shader to the vertex shader. The
277 // choice of name is arbitrary, but it must be used consistently.
278 std::string ShaderNode::getExpressionVaryingName() const {
279 return get_mangled_name(this->entry()->fName, this->keyIndex()) + "_Var";
280 }
281
282 //--------------------------------------------------------------------------------------------------
283 // ShaderCodeDictionary
284
285 UniquePaintParamsID ShaderCodeDictionary::findOrCreate(PaintParamsKeyBuilder* builder) {
286 AutoLockBuilderAsKey keyView{builder};
287
288 return this->findOrCreate(*keyView);
289 }
290
291 UniquePaintParamsID ShaderCodeDictionary::findOrCreate(const PaintParamsKey& ppk) {
292 if (!ppk.isValid()) {
293 return UniquePaintParamsID::Invalid();
294 }
295
296 SkAutoSpinlock lock{fSpinLock};
297
298 UniquePaintParamsID* existingEntry = fPaintKeyToID.find(ppk);
299 if (existingEntry) {
300 SkASSERT(fIDToPaintKey[(*existingEntry).asUInt()] == ppk);
301 return *existingEntry;
302 }
303
304 // Detach from the builder and copy into the arena
305 PaintParamsKey key = ppk.clone(&fArena);
306 UniquePaintParamsID newID{SkTo<uint32_t>(fIDToPaintKey.size())};
307
308 fPaintKeyToID.set(key, newID);
309 fIDToPaintKey.push_back(key);
310 return newID;
311 }
312
313 PaintParamsKey ShaderCodeDictionary::lookup(UniquePaintParamsID codeID) const {
314 if (!codeID.isValid()) {
315 return PaintParamsKey::Invalid();
316 }
317
318 SkAutoSpinlock lock{fSpinLock};
319 SkASSERT(codeID.asUInt() < SkTo<uint32_t>(fIDToPaintKey.size()));
320 return fIDToPaintKey[codeID.asUInt()];
321 }
322
323 const ShaderSnippet* ShaderCodeDictionary::getEntry(int codeSnippetID) const {
324 if (codeSnippetID < 0) {
325 return nullptr;
326 }
327
328 if (codeSnippetID < kBuiltInCodeSnippetIDCount) {
329 return &fBuiltInCodeSnippets[codeSnippetID];
330 }
331
332 SkAutoSpinlock lock{fSpinLock};
333
334 if (IsSkiaKnownRuntimeEffect(codeSnippetID)) {
335 int knownRTECodeSnippetID = codeSnippetID - kSkiaKnownRuntimeEffectsStart;
336
337 // TODO(b/238759147): if the snippet hasn't been initialized, get the SkRuntimeEffect and
338 // initialize it here
339 SkASSERT(fKnownRuntimeEffectCodeSnippets[knownRTECodeSnippetID].fPreambleGenerator);
340 return &fKnownRuntimeEffectCodeSnippets[knownRTECodeSnippetID];
341 }
342
343 if (IsViableUserDefinedKnownRuntimeEffect(codeSnippetID)) {
344 int index = codeSnippetID - kUserDefinedKnownRuntimeEffectsStart;
345 if (index >= fUserDefinedKnownCodeSnippets.size()) {
346 return nullptr;
347 }
348
349 SkASSERT(fUserDefinedKnownCodeSnippets[index].fPreambleGenerator);
350 return &fUserDefinedKnownCodeSnippets[index];
351 }
352
353 if (IsUserDefinedRuntimeEffect(codeSnippetID)) {
354 int userDefinedCodeSnippetID = codeSnippetID - kUnknownRuntimeEffectIDStart;
355 if (userDefinedCodeSnippetID < SkTo<int>(fUserDefinedCodeSnippets.size())) {
356 return &fUserDefinedCodeSnippets[userDefinedCodeSnippetID];
357 }
358 }
359
360 return nullptr;
361 }
362
363 const SkRuntimeEffect* ShaderCodeDictionary::getUserDefinedKnownRuntimeEffect(
364 int codeSnippetID) const {
365 if (codeSnippetID < 0) {
366 return nullptr;
367 }
368
369 if (IsViableUserDefinedKnownRuntimeEffect(codeSnippetID)) {
370 int index = codeSnippetID - kUserDefinedKnownRuntimeEffectsStart;
371 if (index >= fUserDefinedKnownRuntimeEffects.size()) {
372 return nullptr;
373 }
374
375 SkASSERT(fUserDefinedKnownRuntimeEffects[index]);
376 return fUserDefinedKnownRuntimeEffects[index].get();
377 }
378
379 return nullptr;
380 }
381
382 //--------------------------------------------------------------------------------------------------
383 namespace {
384
385 std::string GenerateSolidColorExpression(const ShaderInfo& shaderInfo,
386 const ShaderNode* node,
387 const ShaderSnippet::Args& args) {
388 std::string uniform =
389 get_mangled_uniform_name(shaderInfo, node->entry()->fUniforms[0], node->keyIndex());
390 return SkSL::String::printf("half4(%s)", uniform.c_str());
391 }
392
393 std::string GenerateSolidColorPreamble(const ShaderInfo& shaderInfo,
394 const ShaderNode* node) {
395 std::string code = emit_helper_declaration(node) + " {return ";
396
397 if (node->requiredFlags() & SnippetRequirementFlags::kLiftExpression) {
398 code += node->getExpressionVaryingName();
399 } else if (node->requiredFlags() & SnippetRequirementFlags::kOmitExpression) {
400 code += "half4(0)";
401 } else {
402 code += GenerateSolidColorExpression(shaderInfo, node, ShaderSnippet::kDefaultArgs);
403 }
404
405 return code + ";}";
406 }
407
408 //--------------------------------------------------------------------------------------------------
409
410 // Generate the expression that applies a non-perspective local matrix to coordinates.
411 std::string GenerateLocalMatrixExpression(const ShaderInfo& shaderInfo,
412 const ShaderNode* node,
413 const ShaderSnippet::Args& args) {
414 // NOTE: upper2x2 is a float2x2 packed in column major order into a float4
415 std::string upper2x2 =
416 get_mangled_uniform_name(shaderInfo, node->entry()->fUniforms[0], node->keyIndex());
417 std::string translation =
418 get_mangled_uniform_name(shaderInfo, node->entry()->fUniforms[1], node->keyIndex());
419 return SkSL::String::printf("float2x2(%s.xy, %s.zw)*%s + %s",
420 upper2x2.c_str(),
421 upper2x2.c_str(),
422 args.fFragCoord.c_str(),
423 translation.c_str());
424 }
425
426 static constexpr int kNumCoordinateManipulateChildren = 1;
427
428 std::string GenerateCoordNormalizeExpression(const ShaderInfo& shaderInfo,
429 const ShaderNode* node,
430 const ShaderSnippet::Args& args) {
431 std::string uniform =
432 get_mangled_uniform_name(shaderInfo, node->entry()->fUniforms[0], node->keyIndex());
433 return SkSL::String::printf("(%s * %s)",
434 uniform.c_str(),
435 args.fFragCoord.c_str());
436 }
437
438 // Create a helper function that manipulates the coordinates passed into a child. The specific
439 // manipulation is pre-determined by the code id (local matrix or clamp).
440 // TODO: This is effectively GenerateComposePreamble except that 'node' is counting as the inner.
441 std::string GenerateCoordManipulationPreamble(const ShaderInfo& shaderInfo,
442 const ShaderNode* node) {
443 SkASSERT(node->numChildren() == kNumCoordinateManipulateChildren);
444
445 std::string perspectiveStatement;
446
447 const ShaderSnippet::Args& defaultArgs = ShaderSnippet::kDefaultArgs;
448 ShaderSnippet::Args localArgs = ShaderSnippet::kDefaultArgs;
449 if (node->child(0)->requiredFlags() & SnippetRequirementFlags::kLocalCoords) {
450 std::string controlUni =
451 get_mangled_uniform_name(shaderInfo, node->entry()->fUniforms[0], node->keyIndex());
452
453 if (node->codeSnippetId() == (int) BuiltInCodeSnippetID::kLocalMatrixShader) {
454 if (node->requiredFlags() & SnippetRequirementFlags::kLiftExpression) {
455 localArgs.fFragCoord = node->getExpressionVaryingName();
456 } else if (!(node->requiredFlags() & SnippetRequirementFlags::kOmitExpression)) {
457 localArgs.fFragCoord = GenerateLocalMatrixExpression(shaderInfo, node, defaultArgs);
458 }
459 } else if (node->codeSnippetId() == (int) BuiltInCodeSnippetID::kLocalMatrixShaderPersp) {
460 perspectiveStatement = SkSL::String::printf("float3 perspCoord = %s * %s.xy1;",
461 controlUni.c_str(),
462 defaultArgs.fFragCoord.c_str());
463 localArgs.fFragCoord = "perspCoord.xy / perspCoord.z";
464 } else if (node->codeSnippetId() == (int) BuiltInCodeSnippetID::kCoordNormalizeShader) {
465 if (node->requiredFlags() & SnippetRequirementFlags::kLiftExpression) {
466 localArgs.fFragCoord = node->getExpressionVaryingName();
467 } else if (!(node->requiredFlags() & SnippetRequirementFlags::kOmitExpression)) {
468 localArgs.fFragCoord =
469 GenerateCoordNormalizeExpression(shaderInfo, node, defaultArgs);
470 }
471 } else {
472 SkASSERT(node->codeSnippetId() == (int) BuiltInCodeSnippetID::kCoordClampShader);
473 localArgs.fFragCoord = SkSL::String::printf("clamp(%s, %s.LT, %s.RB)",
474 defaultArgs.fFragCoord.c_str(),
475 controlUni.c_str(), controlUni.c_str());
476 }
477 } // else this is a no-op
478
479 std::string decl = emit_helper_declaration(node);
480 std::string invokeChild = invoke_node(shaderInfo, node->child(0), localArgs);
481 return SkSL::String::printf("%s { %s return %s; }",
482 decl.c_str(),
483 perspectiveStatement.c_str(),
484 invokeChild.c_str());
485 }
486
487 //--------------------------------------------------------------------------------------------------
488
489 // Compose N-1 children into the Nth child, must have at least two children. The ith child provides
490 // the value for the ith enabled ShaderSnippet::Arg.
491 std::string GenerateComposePreamble(const ShaderInfo& shaderInfo, const ShaderNode* node) {
492 SkASSERT(node->numChildren() >= 2);
493
494 const ShaderNode* outer = node->child(node->numChildren() - 1);
495
496 #if defined(SK_DEBUG)
497 const int numOuterParameters =
498 SkToBool((outer->requiredFlags() & SnippetRequirementFlags::kPriorStageOutput)) +
499 SkToBool((outer->requiredFlags() & SnippetRequirementFlags::kBlenderDstColor)) +
500 SkToBool((outer->requiredFlags() & SnippetRequirementFlags::kLocalCoords));
501 SkASSERT(node->numChildren() == numOuterParameters + 1);
502 #endif
503
504 const ShaderSnippet::Args& defaultArgs = ShaderSnippet::kDefaultArgs;
505 ShaderSnippet::Args outerArgs = ShaderSnippet::kDefaultArgs;
506 int child = 0;
507 if (outer->requiredFlags() & SnippetRequirementFlags::kLocalCoords) {
508 outerArgs.fFragCoord = invoke_node(shaderInfo, node->child(child++), defaultArgs);
509 }
510 if (outer->requiredFlags() & SnippetRequirementFlags::kPriorStageOutput) {
511 outerArgs.fPriorStageOutput = invoke_node(shaderInfo, node->child(child++), defaultArgs);
512 }
513 if (outer->requiredFlags() & SnippetRequirementFlags::kBlenderDstColor) {
514 outerArgs.fBlenderDstColor = invoke_node(shaderInfo, node->child(child++), defaultArgs);
515 }
516
517 std::string decl = emit_helper_declaration(node);
518 std::string invokeOuter = invoke_node(shaderInfo, outer, outerArgs);
519 return SkSL::String::printf("%s { return %s; }", decl.c_str(), invokeOuter.c_str());
520 }
521
522 //--------------------------------------------------------------------------------------------------
523 class GraphitePipelineCallbacks : public SkSL::PipelineStage::Callbacks {
524 public:
525 GraphitePipelineCallbacks(const ShaderInfo& shaderInfo,
526 const ShaderNode* node,
527 std::string* preamble,
528 [[maybe_unused]] const SkRuntimeEffect* effect)
529 : fShaderInfo(shaderInfo)
530 , fNode(node)
531 , fPreamble(preamble) {
532 SkDEBUGCODE(fEffect = effect;)
533 }
534
535 std::string declareUniform(const SkSL::VarDeclaration* decl) override {
536 std::string result = get_mangled_name(std::string(decl->var()->name()), fNode->keyIndex());
537 if (fShaderInfo.uniformSsboIndex()) {
538 result =
539 get_storage_buffer_access(fShaderInfo.uniformSsboIndex(), result.c_str());
540 }
541 return result;
542 }
543
544 void defineFunction(const char* decl, const char* body, bool isMain) override {
545 if (isMain) {
546 SkSL::String::appendf(
547 fPreamble,
548 "%s { %s }",
549 emit_helper_declaration(fNode).c_str(),
550 body);
551 } else {
552 SkSL::String::appendf(fPreamble, "%s {%s}\n", decl, body);
553 }
554 }
555
556 void declareFunction(const char* decl) override {
557 *fPreamble += std::string(decl);
558 }
559
560 void defineStruct(const char* definition) override {
561 *fPreamble += std::string(definition);
562 }
563
564 void declareGlobal(const char* declaration) override {
565 *fPreamble += std::string(declaration);
566 }
567
568 std::string sampleShader(int index, std::string coords) override {
569 ShaderSnippet::Args args = ShaderSnippet::kDefaultArgs;
570 args.fFragCoord = coords;
571 return invoke_node(fShaderInfo, fNode->child(index), args);
572 }
573
574 std::string sampleColorFilter(int index, std::string color) override {
575 ShaderSnippet::Args args = ShaderSnippet::kDefaultArgs;
576 args.fPriorStageOutput = color;
577 return invoke_node(fShaderInfo, fNode->child(index), args);
578 }
579
580 std::string sampleBlender(int index, std::string src, std::string dst) override {
581 ShaderSnippet::Args args = ShaderSnippet::kDefaultArgs;
582 args.fPriorStageOutput = src;
583 args.fBlenderDstColor = dst;
584 return invoke_node(fShaderInfo, fNode->child(index), args);
585 }
586
587 std::string toLinearSrgb(std::string color) override {
588 SkASSERT(SkRuntimeEffectPriv::UsesColorTransform(fEffect));
589 // If we use color transforms (e.g. reference [to|from]LinearSrgb(), we dynamically add two
590 // children to the runtime effect's node after all explicitly declared children. The
591 // conversion *to* linear srgb is the second-to-last child node, and the conversion *from*
592 // linear srgb is the last child node.)
593 const ShaderNode* toLinearSrgbNode = fNode->child(fNode->numChildren() - 2);
594 SkASSERT(toLinearSrgbNode->codeSnippetId() ==
595 (int)BuiltInCodeSnippetID::kColorSpaceXformColorFilter ||
596 toLinearSrgbNode->codeSnippetId() ==
597 (int)BuiltInCodeSnippetID::kColorSpaceXformPremul ||
598 toLinearSrgbNode->codeSnippetId() ==
599 (int)BuiltInCodeSnippetID::kColorSpaceXformSRGB);
600
601 ShaderSnippet::Args args = ShaderSnippet::kDefaultArgs;
602 args.fPriorStageOutput = SkSL::String::printf("(%s).rgb1", color.c_str());
603 std::string xformedColor = invoke_node(fShaderInfo, toLinearSrgbNode, args);
604 return SkSL::String::printf("(%s).rgb", xformedColor.c_str());
605 }
606
607
608 std::string fromLinearSrgb(std::string color) override {
609 SkASSERT(SkRuntimeEffectPriv::UsesColorTransform(fEffect));
610 // If we use color transforms (e.g. reference [to|from]LinearSrgb()), we dynamically add two
611 // children to the runtime effect's node after all explicitly declared children. The
612 // conversion *to* linear srgb is the second-to-last child node, and the conversion *from*
613 // linear srgb is the last child node.
614 const ShaderNode* fromLinearSrgbNode = fNode->child(fNode->numChildren() - 1);
615 SkASSERT(fromLinearSrgbNode->codeSnippetId() ==
616 (int)BuiltInCodeSnippetID::kColorSpaceXformColorFilter ||
617 fromLinearSrgbNode->codeSnippetId() ==
618 (int)BuiltInCodeSnippetID::kColorSpaceXformPremul ||
619 fromLinearSrgbNode->codeSnippetId() ==
620 (int)BuiltInCodeSnippetID::kColorSpaceXformSRGB);
621
622 ShaderSnippet::Args args = ShaderSnippet::kDefaultArgs;
623 args.fPriorStageOutput = SkSL::String::printf("(%s).rgb1", color.c_str());
624 std::string xformedColor = invoke_node(fShaderInfo, fromLinearSrgbNode, args);
625 return SkSL::String::printf("(%s).rgb", xformedColor.c_str());
626 }
627
628 std::string getMangledName(const char* name) override {
629 return get_mangled_name(name, fNode->keyIndex());
630 }
631
632 private:
633 const ShaderInfo& fShaderInfo;
634 const ShaderNode* fNode;
635 std::string* fPreamble;
636 SkDEBUGCODE(const SkRuntimeEffect* fEffect;)
637 };
638
639 std::string GenerateRuntimeShaderPreamble(const ShaderInfo& shaderInfo,
640 const ShaderNode* node) {
641 // Find this runtime effect in the shader-code or runtime-effect dictionary.
642 SkASSERT(node->codeSnippetId() >= kBuiltInCodeSnippetIDCount);
643 const SkRuntimeEffect* effect;
644
645 if (IsSkiaKnownRuntimeEffect(node->codeSnippetId())) {
646 effect = GetKnownRuntimeEffect(static_cast<StableKey>(node->codeSnippetId()));
647 } else if (SkKnownRuntimeEffects::IsViableUserDefinedKnownRuntimeEffect(
648 node->codeSnippetId())) {
649 effect = shaderInfo.shaderCodeDictionary()->getUserDefinedKnownRuntimeEffect(
650 node->codeSnippetId());
651 } else {
652 SkASSERT(IsUserDefinedRuntimeEffect(node->codeSnippetId()));
653 effect = shaderInfo.runtimeEffectDictionary()->find(node->codeSnippetId());
654 }
655 // This should always be true given the circumstances in which we call convertRuntimeEffect
656 SkASSERT(effect);
657
658 const SkSL::Program& program = SkRuntimeEffectPriv::Program(*effect);
659 const ShaderSnippet::Args& args = ShaderSnippet::kDefaultArgs;
660 std::string preamble;
661 GraphitePipelineCallbacks callbacks{shaderInfo, node, &preamble, effect};
662 SkSL::PipelineStage::ConvertProgram(program,
663 args.fFragCoord.c_str(),
664 args.fPriorStageOutput.c_str(),
665 args.fBlenderDstColor.c_str(),
666 &callbacks);
667 return preamble;
668 }
669
670 } // anonymous namespace
671
672 #if defined(SK_DEBUG)
673 bool ShaderCodeDictionary::isValidID(int snippetID) const {
674 if (snippetID < 0) {
675 return false;
676 }
677
678 if (snippetID < kBuiltInCodeSnippetIDCount) {
679 return true;
680 }
681 if (IsSkiaKnownRuntimeEffect(snippetID)) {
682 return true;
683 }
684
685 if (this->isUserDefinedKnownRuntimeEffect(snippetID)) {
686 return true;
687 }
688
689 SkAutoSpinlock lock{fSpinLock};
690
691 if (IsUserDefinedRuntimeEffect(snippetID)) {
692 int userDefinedCodeSnippetID = snippetID - kUnknownRuntimeEffectIDStart;
693 return userDefinedCodeSnippetID < SkTo<int>(fUserDefinedCodeSnippets.size());
694 }
695
696 return false;
697 }
698
699 void ShaderCodeDictionary::dump(const Caps* caps, UniquePaintParamsID id) const {
700 this->lookup(id).dump(caps, this, id);
701 }
702 #endif
703
704 static SkSLType uniform_type_to_sksl_type(const SkRuntimeEffect::Uniform& u) {
705 using Type = SkRuntimeEffect::Uniform::Type;
706 if (u.flags & SkRuntimeEffect::Uniform::kHalfPrecision_Flag) {
707 switch (u.type) {
708 case Type::kFloat: return SkSLType::kHalf;
709 case Type::kFloat2: return SkSLType::kHalf2;
710 case Type::kFloat3: return SkSLType::kHalf3;
711 case Type::kFloat4: return SkSLType::kHalf4;
712 case Type::kFloat2x2: return SkSLType::kHalf2x2;
713 case Type::kFloat3x3: return SkSLType::kHalf3x3;
714 case Type::kFloat4x4: return SkSLType::kHalf4x4;
715 // NOTE: shorts cannot be uniforms, so we shouldn't ever get here.
716 // Defensively return the full precision integer type.
717 case Type::kInt: SkDEBUGFAIL("unsupported uniform type"); return SkSLType::kInt;
718 case Type::kInt2: SkDEBUGFAIL("unsupported uniform type"); return SkSLType::kInt2;
719 case Type::kInt3: SkDEBUGFAIL("unsupported uniform type"); return SkSLType::kInt3;
720 case Type::kInt4: SkDEBUGFAIL("unsupported uniform type"); return SkSLType::kInt4;
721 }
722 } else {
723 switch (u.type) {
724 case Type::kFloat: return SkSLType::kFloat;
725 case Type::kFloat2: return SkSLType::kFloat2;
726 case Type::kFloat3: return SkSLType::kFloat3;
727 case Type::kFloat4: return SkSLType::kFloat4;
728 case Type::kFloat2x2: return SkSLType::kFloat2x2;
729 case Type::kFloat3x3: return SkSLType::kFloat3x3;
730 case Type::kFloat4x4: return SkSLType::kFloat4x4;
731 case Type::kInt: return SkSLType::kInt;
732 case Type::kInt2: return SkSLType::kInt2;
733 case Type::kInt3: return SkSLType::kInt3;
734 case Type::kInt4: return SkSLType::kInt4;
735 }
736 }
737 SkUNREACHABLE;
738 }
739
740 const char* ShaderCodeDictionary::addTextToArena(std::string_view text) {
741 char* textInArena = fArena.makeArrayDefault<char>(text.size() + 1);
742 memcpy(textInArena, text.data(), text.size());
743 textInArena[text.size()] = '\0';
744 return textInArena;
745 }
746
747 SkSpan<const Uniform> ShaderCodeDictionary::convertUniforms(const SkRuntimeEffect* effect) {
748 using rteUniform = SkRuntimeEffect::Uniform;
749 SkSpan<const rteUniform> uniforms = effect->uniforms();
750
751 const int numUniforms = uniforms.size();
752
753 // Convert the SkRuntimeEffect::Uniform array into its Uniform equivalent.
754 Uniform* uniformArray = fArena.makeInitializedArray<Uniform>(numUniforms, [&](int index) {
755 const rteUniform* u;
756 u = &uniforms[index];
757
758 // The existing uniform names live in the passed-in SkRuntimeEffect and may eventually
759 // disappear. Copy them into fArena. (It's safe to do this within makeInitializedArray; the
760 // entire array is allocated in one big slab before any initialization calls are done.)
761 const char* name = this->addTextToArena(u->name);
762
763 // Add one Uniform to our array.
764 SkSLType type = uniform_type_to_sksl_type(*u);
765 return (u->flags & rteUniform::kArray_Flag) ? Uniform(name, type, u->count)
766 : Uniform(name, type);
767 });
768
769 return SkSpan<const Uniform>(uniformArray, numUniforms);
770 }
771
772 static bool all_sample_usages_are_passthrough(const SkRuntimeEffect* effect) {
773 for (size_t i = 0; i < effect->children().size(); ++i) {
774 if (!SkRuntimeEffectPriv::ChildSampleUsage(effect, i).isPassThrough()) {
775 return false;
776 }
777 }
778 return true;
779 }
780
781 ShaderSnippet ShaderCodeDictionary::convertRuntimeEffect(const SkRuntimeEffect* effect,
782 const char* name) {
783 SkEnumBitMask<SnippetRequirementFlags> snippetFlags = SnippetRequirementFlags::kNone;
784 if (effect->allowShader()) {
785 // TODO(b/412621191) Ideally we would have a way to tell exactly which children of a runtime
786 // shader are sampled with modified coords, or whether coordinates are required at all. For
787 // now we assume all runtime shaders need coordinates, and if any children are sampled with
788 // modified coords, we assume they all are.
789 snippetFlags |= SnippetRequirementFlags::kLocalCoords;
790 if (all_sample_usages_are_passthrough(effect)) {
791 snippetFlags |= SnippetRequirementFlags::kPassthroughLocalCoords;
792 }
793 } else if (effect->allowColorFilter()) {
794 snippetFlags |= SnippetRequirementFlags::kPriorStageOutput;
795 } else if (effect->allowBlender()) {
796 snippetFlags |= SnippetRequirementFlags::kPriorStageOutput; // src
797 snippetFlags |= SnippetRequirementFlags::kBlenderDstColor; // dst
798 }
799
800 // If the runtime effect references toLinearSrgb() or fromLinearSrgb(), we append two
801 // color space transform children that are invoked when converting those "built-in" expressions.
802 int numChildrenIncColorTransforms = SkTo<int>(effect->children().size()) +
803 (SkRuntimeEffectPriv::UsesColorTransform(effect) ? 2 : 0);
804
805 // TODO: We can have the custom runtime effect preamble generator define structs for its
806 // uniforms if it has a lot of uniforms, and then calculate the required alignment here.
807 return ShaderSnippet(name,
808 /*staticFn=*/nullptr,
809 snippetFlags,
810 this->convertUniforms(effect),
811 /*texturesAndSamplers=*/{},
812 GenerateRuntimeShaderPreamble,
813 numChildrenIncColorTransforms);
814 }
815
816 int ShaderCodeDictionary::findOrCreateRuntimeEffectSnippet(const SkRuntimeEffect* effect) {
817 SkAutoSpinlock lock{fSpinLock};
818
819 if (int stableKey = SkRuntimeEffectPriv::StableKey(*effect)) {
820 if (IsSkiaKnownRuntimeEffect(stableKey)) {
821 int index = stableKey - kSkiaKnownRuntimeEffectsStart;
822
823 if (!fKnownRuntimeEffectCodeSnippets[index].fPreambleGenerator) {
824 const char* name = get_known_rte_name(static_cast<StableKey>(stableKey));
825 fKnownRuntimeEffectCodeSnippets[index] = this->convertRuntimeEffect(effect, name);
826 }
827
828 return stableKey;
829 } else if (IsViableUserDefinedKnownRuntimeEffect(stableKey)) {
830 int index = stableKey - kUserDefinedKnownRuntimeEffectsStart;
831 if (index >= fUserDefinedKnownCodeSnippets.size()) {
832 return -1;
833 }
834
835 return stableKey;
836 }
837
838 return -1;
839 }
840
841 // Use the combination of {SkSL program hash, uniform size} as our key.
842 // In the unfortunate event of a hash collision, at least we'll have the right amount of
843 // uniform data available.
844 RuntimeEffectKey key;
845 key.fHash = SkRuntimeEffectPriv::Hash(*effect);
846 key.fUniformSize = effect->uniformSize();
847
848 int32_t* existingCodeSnippetID = fRuntimeEffectMap.find(key);
849 if (existingCodeSnippetID) {
850 return *existingCodeSnippetID;
851 }
852
853 // TODO: the memory for user-defined entries could go in the dictionary's arena but that
854 // would have to be a thread safe allocation since the arena also stores entries for
855 // 'fHash' and 'fEntryVector'
856 static const char* kDefaultName = "RuntimeEffect";
857 fUserDefinedCodeSnippets.push_back(this->convertRuntimeEffect(
858 effect,
859 SkRuntimeEffectPriv::HasName(*effect) ? SkRuntimeEffectPriv::GetName(*effect)
860 : kDefaultName));
861 int newCodeSnippetID = kUnknownRuntimeEffectIDStart + fUserDefinedCodeSnippets.size() - 1;
862
863 fRuntimeEffectMap.set(key, newCodeSnippetID);
864 return newCodeSnippetID;
865 }
866
867 void ShaderCodeDictionary::registerUserDefinedKnownRuntimeEffects(
868 SkSpan<sk_sp<SkRuntimeEffect>> userDefinedKnownRuntimeEffects) {
869 // This is a formality to guard 'fRuntimeEffectMap'. This method should only be called by
870 // the constructor.
871 SkAutoSpinlock lock{fSpinLock};
872
873 for (const sk_sp<SkRuntimeEffect>& u : userDefinedKnownRuntimeEffects) {
874 if (!u) {
875 continue;
876 }
877
878 if (fUserDefinedKnownCodeSnippets.size() >= kUserDefinedKnownRuntimeEffectsReservedCnt) {
879 SKGPU_LOG_W("Too many user-defined known runtime effects. Only %d out of %zu "
880 "will be known.\n",
881 kUserDefinedKnownRuntimeEffectsReservedCnt,
882 userDefinedKnownRuntimeEffects.size());
883 // too many user-defined known runtime effects
884 return;
885 }
886
887 RuntimeEffectKey key;
888 key.fHash = SkRuntimeEffectPriv::Hash(*u);
889 key.fUniformSize = u->uniformSize();
890
891 int32_t* existingCodeSnippetID = fRuntimeEffectMap.find(key);
892 if (existingCodeSnippetID) {
893 continue; // This is a duplicate
894 }
895
896 static const char* kDefaultName = "UserDefinedKnownRuntimeEffect";
897 fUserDefinedKnownCodeSnippets.push_back(this->convertRuntimeEffect(
898 u.get(),
899 SkRuntimeEffectPriv::HasName(*u) ? SkRuntimeEffectPriv::GetName(*u)
900 : kDefaultName));
901 int stableID = kUserDefinedKnownRuntimeEffectsStart +
902 fUserDefinedKnownCodeSnippets.size() - 1;
903
904 SkRuntimeEffectPriv::SetStableKey(u.get(), stableID);
905
906 fUserDefinedKnownRuntimeEffects.push_back(u);
907
908 // We register the key with the runtime effect map so that, if the user uses the same code
909 // in a separate runtime effect (which they should *not* do), it will be discovered during
910 // the unknown-runtime-effect processing and mapped back to the registered user-defined
911 // known runtime effect.
912 fRuntimeEffectMap.set(key, stableID);
913 }
914
915 SkASSERT(fUserDefinedKnownCodeSnippets.size() == fUserDefinedKnownRuntimeEffects.size());
916 }
917
918 bool ShaderCodeDictionary::isUserDefinedKnownRuntimeEffect(int candidate) const {
919 if (!SkKnownRuntimeEffects::IsViableUserDefinedKnownRuntimeEffect(candidate)) {
920 return false;
921 }
922
923 int index = candidate - kUserDefinedKnownRuntimeEffectsStart;
924 if (index >= fUserDefinedKnownCodeSnippets.size()) {
925 return false;
926 }
927
928 return true;
929 }
930
931 #if defined(GPU_TEST_UTILS)
932 int ShaderCodeDictionary::numUserDefinedRuntimeEffects() const {
933 SkAutoSpinlock lock{fSpinLock};
934
935 return fUserDefinedCodeSnippets.size();
936 }
937
938 int ShaderCodeDictionary::numUserDefinedKnownRuntimeEffects() const {
939 return fUserDefinedKnownCodeSnippets.size();
940 }
941 #endif
942
943 ShaderCodeDictionary::ShaderCodeDictionary(
944 Layout layout,
945 SkSpan<sk_sp<SkRuntimeEffect>> userDefinedKnownRuntimeEffects)
946 : fLayout(layout) {
947 // The 0th index is reserved as invalid
948 fIDToPaintKey.push_back(PaintParamsKey::Invalid());
949
950 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kError] = {
951 /*name=*/"Error",
952 /*staticFn=*/"sk_error",
953 SnippetRequirementFlags::kNone,
954 /*uniforms=*/{}
955 };
956 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kPriorOutput] = {
957 /*name=*/"Passthrough",
958 /*staticFn=*/"sk_passthrough",
959 SnippetRequirementFlags::kPriorStageOutput,
960 /*uniforms=*/{}
961 };
962 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kSolidColorShader] = {
963 /*name=*/"SolidColor",
964 /*staticFn=*/nullptr,
965 SnippetRequirementFlags::kNone,
966 /*uniforms=*/{{ { "color", SkSLType::kFloat4 } }},
967 /*texturesAndSamplers=*/{},
968 GenerateSolidColorPreamble,
969 /*numChildren=*/0,
970 /*liftableExpression=*/GenerateSolidColorExpression,
971 /*liftableExpressionType=*/ShaderSnippet::LiftableExpressionType::kPriorStageOutput,
972 /*liftableExpressionInterpolation=*/Interpolation::kLinear
973 };
974 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kRGBPaintColor] = {
975 /*name=*/"RGBPaintColor",
976 /*staticFn=*/"sk_rgb_opaque",
977 SnippetRequirementFlags::kNone,
978 /*uniforms=*/{{ Uniform::PaintColor() }}
979 };
980 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kAlphaOnlyPaintColor] = {
981 /*name=*/"AlphaOnlyPaintColor",
982 /*staticFn=*/"sk_alpha_only",
983 SnippetRequirementFlags::kNone,
984 /*uniforms=*/{{ Uniform::PaintColor() }}
985 };
986 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kLinearGradientShader4] = {
987 /*name=*/"LinearGradient4",
988 /*staticFn=*/"sk_linear_grad_4_shader",
989 SnippetRequirementFlags::kLocalCoords,
990 /*uniforms=*/{{{ "colors", SkSLType::kFloat4, 4 },
991 { "offsets", SkSLType::kFloat4 },
992 { "tilemode", SkSLType::kInt },
993 { "colorSpace", SkSLType::kInt },
994 { "doUnPremul", SkSLType::kInt }}},
995 };
996 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kLinearGradientShader8] = {
997 /*name=*/"LinearGradient8",
998 /*staticFn=*/"sk_linear_grad_8_shader",
999 SnippetRequirementFlags::kLocalCoords,
1000 /*uniforms=*/{{{ "colors", SkSLType::kFloat4, 8 },
1001 { "offsets", SkSLType::kFloat4, 2 },
1002 { "tilemode", SkSLType::kInt },
1003 { "colorSpace", SkSLType::kInt },
1004 { "doUnPremul", SkSLType::kInt }}}
1005 };
1006 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kLinearGradientShaderTexture] = {
1007 /*name=*/"LinearGradientTexture",
1008 /*staticFn=*/"sk_linear_grad_tex_shader",
1009 SnippetRequirementFlags::kLocalCoords,
1010 /*uniforms=*/{{{ "numStops", SkSLType::kInt },
1011 { "tilemode", SkSLType::kInt },
1012 { "colorSpace", SkSLType::kInt },
1013 { "doUnPremul", SkSLType::kInt }}},
1014 /*texturesAndSamplers=*/{{"colorAndOffsetSampler"}}
1015 };
1016 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kLinearGradientShaderBuffer] = {
1017 /*name=*/"LinearGradientBuffer",
1018 /*staticFn=*/"sk_linear_grad_buf_shader",
1019 SnippetRequirementFlags::kLocalCoords | SnippetRequirementFlags::kGradientBuffer,
1020 /*uniforms=*/{{{ "numStops", SkSLType::kInt },
1021 { "bufferOffset", SkSLType::kInt },
1022 { "tilemode", SkSLType::kInt },
1023 { "colorSpace", SkSLType::kInt },
1024 { "doUnPremul", SkSLType::kInt }}}
1025 };
1026 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kRadialGradientShader4] = {
1027 /*name=*/"RadialGradient4",
1028 /*staticFn=*/ "sk_radial_grad_4_shader",
1029 SnippetRequirementFlags::kLocalCoords,
1030 /*uniforms=*/{{{ "colors", SkSLType::kFloat4, 4 },
1031 { "offsets", SkSLType::kFloat4 },
1032 { "tilemode", SkSLType::kInt },
1033 { "colorSpace", SkSLType::kInt },
1034 { "doUnPremul", SkSLType::kInt }}}
1035 };
1036 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kRadialGradientShader8] = {
1037 /*name=*/"RadialGradient8",
1038 /*staticFn=*/"sk_radial_grad_8_shader",
1039 SnippetRequirementFlags::kLocalCoords,
1040 /*uniforms=*/{{{ "colors", SkSLType::kFloat4, 8 },
1041 { "offsets", SkSLType::kFloat4, 2 },
1042 { "tilemode", SkSLType::kInt },
1043 { "colorSpace", SkSLType::kInt },
1044 { "doUnPremul", SkSLType::kInt }}}
1045 };
1046 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kRadialGradientShaderTexture] = {
1047 /*name=*/"RadialGradientTexture",
1048 /*staticFn=*/"sk_radial_grad_tex_shader",
1049 SnippetRequirementFlags::kLocalCoords,
1050 /*uniforms=*/{{{ "numStops", SkSLType::kInt },
1051 { "tilemode", SkSLType::kInt },
1052 { "colorSpace", SkSLType::kInt },
1053 { "doUnPremul", SkSLType::kInt }}},
1054 /*texturesAndSamplers=*/{{"colorAndOffsetSampler"}}
1055 };
1056 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kRadialGradientShaderBuffer] = {
1057 /*name=*/"RadialGradientBuffer",
1058 /*staticFn=*/"sk_radial_grad_buf_shader",
1059 SnippetRequirementFlags::kLocalCoords | SnippetRequirementFlags::kGradientBuffer,
1060 /*uniforms=*/{{{ "numStops", SkSLType::kInt },
1061 { "bufferOffset", SkSLType::kInt },
1062 { "tilemode", SkSLType::kInt },
1063 { "colorSpace", SkSLType::kInt },
1064 { "doUnPremul", SkSLType::kInt }}}
1065 };
1066 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kSweepGradientShader4] = {
1067 /*name=*/"SweepGradient4",
1068 /*staticFn=*/"sk_sweep_grad_4_shader",
1069 SnippetRequirementFlags::kLocalCoords,
1070 /*uniforms=*/{{{ "colors", SkSLType::kFloat4, 4 },
1071 { "offsets", SkSLType::kFloat4 },
1072 { "bias", SkSLType::kFloat },
1073 { "scale", SkSLType::kFloat },
1074 { "tilemode", SkSLType::kInt },
1075 { "colorSpace", SkSLType::kInt },
1076 { "doUnPremul", SkSLType::kInt }}}
1077 };
1078 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kSweepGradientShader8] = {
1079 /*name=*/"SweepGradient8",
1080 /*staticFn=*/"sk_sweep_grad_8_shader",
1081 SnippetRequirementFlags::kLocalCoords,
1082 /*uniforms=*/{{{ "colors", SkSLType::kFloat4, 8 },
1083 { "offsets", SkSLType::kFloat4, 2 },
1084 { "bias", SkSLType::kFloat },
1085 { "scale", SkSLType::kFloat },
1086 { "tilemode", SkSLType::kInt },
1087 { "colorSpace", SkSLType::kInt },
1088 { "doUnPremul", SkSLType::kInt }}}
1089 };
1090 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kSweepGradientShaderTexture] = {
1091 /*name=*/"SweepGradientTexture",
1092 /*staticFn=*/"sk_sweep_grad_tex_shader",
1093 SnippetRequirementFlags::kLocalCoords,
1094 /*uniforms=*/{{{ "bias", SkSLType::kFloat },
1095 { "scale", SkSLType::kFloat },
1096 { "numStops", SkSLType::kInt },
1097 { "tilemode", SkSLType::kInt },
1098 { "colorSpace", SkSLType::kInt },
1099 { "doUnPremul", SkSLType::kInt }}},
1100 /*texturesAndSamplers=*/{{"colorAndOffsetSampler"}}
1101 };
1102 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kSweepGradientShaderBuffer] = {
1103 /*name=*/"SweepGradientBuffer",
1104 /*staticFn=*/"sk_sweep_grad_buf_shader",
1105 SnippetRequirementFlags::kLocalCoords | SnippetRequirementFlags::kGradientBuffer,
1106 /*uniforms=*/{{{ "bias", SkSLType::kFloat },
1107 { "scale", SkSLType::kFloat },
1108 { "numStops", SkSLType::kInt },
1109 { "bufferOffset", SkSLType::kInt },
1110 { "tilemode", SkSLType::kInt },
1111 { "colorSpace", SkSLType::kInt },
1112 { "doUnPremul", SkSLType::kInt }}}
1113 };
1114 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kConicalGradientShader4] = {
1115 /*name=*/"ConicalGradient4",
1116 /*staticFn=*/"sk_conical_grad_4_shader",
1117 SnippetRequirementFlags::kLocalCoords,
1118 /*uniforms=*/{{{ "colors", SkSLType::kFloat4, 4 },
1119 { "offsets", SkSLType::kFloat4 },
1120 { "radius0", SkSLType::kFloat },
1121 { "dRadius", SkSLType::kFloat },
1122 { "a", SkSLType::kFloat },
1123 { "invA", SkSLType::kFloat },
1124 { "tilemode", SkSLType::kInt },
1125 { "colorSpace", SkSLType::kInt },
1126 { "doUnPremul", SkSLType::kInt }}}
1127 };
1128 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kConicalGradientShader8] = {
1129 /*name=*/"ConicalGradient8",
1130 /*staticFn=*/"sk_conical_grad_8_shader",
1131 SnippetRequirementFlags::kLocalCoords,
1132 /*uniforms=*/{{{ "colors", SkSLType::kFloat4, 8 },
1133 { "offsets", SkSLType::kFloat4, 2 },
1134 { "radius0", SkSLType::kFloat },
1135 { "dRadius", SkSLType::kFloat },
1136 { "a", SkSLType::kFloat },
1137 { "invA", SkSLType::kFloat },
1138 { "tilemode", SkSLType::kInt },
1139 { "colorSpace", SkSLType::kInt },
1140 { "doUnPremul", SkSLType::kInt }}}
1141 };
1142 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kConicalGradientShaderTexture] = {
1143 /*name=*/"ConicalGradientTexture",
1144 /*staticFn=*/"sk_conical_grad_tex_shader",
1145 SnippetRequirementFlags::kLocalCoords,
1146 /*uniforms=*/{{{ "radius0", SkSLType::kFloat },
1147 { "dRadius", SkSLType::kFloat },
1148 { "a", SkSLType::kFloat },
1149 { "invA", SkSLType::kFloat },
1150 { "numStops", SkSLType::kInt },
1151 { "tilemode", SkSLType::kInt },
1152 { "colorSpace", SkSLType::kInt },
1153 { "doUnPremul", SkSLType::kInt }}},
1154 /*texturesAndSamplers=*/{{"colorAndOffsetSampler"}}
1155 };
1156 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kConicalGradientShaderBuffer] = {
1157 /*name=*/"ConicalGradientBuffer",
1158 /*staticFn=*/"sk_conical_grad_buf_shader",
1159 SnippetRequirementFlags::kLocalCoords | SnippetRequirementFlags::kGradientBuffer,
1160 /*uniforms=*/{{{ "radius0", SkSLType::kFloat },
1161 { "dRadius", SkSLType::kFloat },
1162 { "a", SkSLType::kFloat },
1163 { "invA", SkSLType::kFloat },
1164 { "numStops", SkSLType::kInt },
1165 { "bufferOffset", SkSLType::kInt },
1166 { "tilemode", SkSLType::kInt },
1167 { "colorSpace", SkSLType::kInt },
1168 { "doUnPremul", SkSLType::kInt }}}
1169 };
1170
1171 // This snippet operates on local coords if the child requires local coords (hence why it does
1172 // not mask off the child's local coord requirement), but does nothing if the child does not
1173 // actually use coordinates.
1174 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kLocalMatrixShader] = {
1175 /*name=*/"LocalMatrix",
1176 /*staticFn=*/nullptr,
1177 SnippetRequirementFlags::kNone,
1178 /*uniforms=*/{{{ "upper2x2", SkSLType::kFloat4 },
1179 { "translation", SkSLType::kFloat2 }}},
1180 /*texturesAndSamplers=*/{},
1181 GenerateCoordManipulationPreamble,
1182 /*numChildren=*/kNumCoordinateManipulateChildren,
1183 /*liftableExpression=*/GenerateLocalMatrixExpression,
1184 /*liftableExpressionType=*/ShaderSnippet::LiftableExpressionType::kLocalCoords
1185 };
1186 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kLocalMatrixShaderPersp] = {
1187 /*name=*/"LocalMatrixShaderPersp",
1188 /*staticFn=*/nullptr,
1189 SnippetRequirementFlags::kNone,
1190 /*uniforms=*/{{{ "localMatrix", SkSLType::kFloat3x3 }}},
1191 /*texturesAndSamplers=*/{},
1192 GenerateCoordManipulationPreamble,
1193 /*numChildren=*/kNumCoordinateManipulateChildren
1194 };
1195
1196 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kImageShader] = {
1197 /*name=*/"Image",
1198 /*staticFn=*/"sk_image_shader",
1199 SnippetRequirementFlags::kLocalCoords | SnippetRequirementFlags::kStoresSamplerDescData,
1200 /*uniforms=*/{{{ "invImgSize", SkSLType::kFloat2 },
1201 { "subset", SkSLType::kFloat4 },
1202 { "tilemodeX", SkSLType::kInt },
1203 { "tilemodeY", SkSLType::kInt },
1204 { "filterMode", SkSLType::kInt }}},
1205 /*texturesAndSamplers=*/{{"image"}}
1206 };
1207 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kCubicImageShader] = {
1208 /*name=*/"CubicImage",
1209 /*staticFn=*/"sk_cubic_image_shader",
1210 SnippetRequirementFlags::kLocalCoords | SnippetRequirementFlags::kStoresSamplerDescData,
1211 /*uniforms=*/{{{ "invImgSize", SkSLType::kFloat2 },
1212 { "subset", SkSLType::kFloat4 },
1213 { "tilemodeX", SkSLType::kInt },
1214 { "tilemodeY", SkSLType::kInt },
1215 { "cubicCoeffs", SkSLType::kHalf4x4 }}},
1216 /*texturesAndSamplers=*/{{"image"}}
1217 };
1218 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kHWImageShader] = {
1219 /*name=*/"HardwareImage",
1220 /*staticFn=*/"sk_hw_image_shader",
1221 SnippetRequirementFlags::kLocalCoords | SnippetRequirementFlags::kStoresSamplerDescData,
1222 /*uniforms=*/{},
1223 /*texturesAndSamplers=*/{{"image"}}
1224 };
1225
1226 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kImageShaderClamp] = {
1227 /*name=*/"ImageShaderClamp",
1228 /*staticFn=*/"sk_image_shader_clamp",
1229 SnippetRequirementFlags::kLocalCoords | SnippetRequirementFlags::kStoresSamplerDescData,
1230 /*uniforms=*/{{{ "invImgSize", SkSLType::kFloat2 },
1231 { "subsetInsetClamp", SkSLType::kFloat4 }}},
1232 /*texturesAndSamplers=*/{{"image"}}
1233 };
1234
1235 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kYUVImageShader] = {
1236 /*name=*/"YUVImage",
1237 /*staticFn=*/"sk_yuv_image_shader",
1238 SnippetRequirementFlags::kLocalCoords,
1239 /*uniforms=*/{{{ "invImgSizeY", SkSLType::kFloat2 },
1240 { "invImgSizeUV", SkSLType::kFloat2 }, // Relative to Y's texels
1241 { "subset", SkSLType::kFloat4 },
1242 { "linearFilterUVInset", SkSLType::kFloat2 },
1243 { "tilemodeX", SkSLType::kInt },
1244 { "tilemodeY", SkSLType::kInt },
1245 { "filterModeY", SkSLType::kInt },
1246 { "filterModeUV", SkSLType::kInt },
1247 { "channelSelectY", SkSLType::kHalf4 },
1248 { "channelSelectU", SkSLType::kHalf4 },
1249 { "channelSelectV", SkSLType::kHalf4 },
1250 { "channelSelectA", SkSLType::kHalf4 },
1251 { "yuvToRGBMatrix", SkSLType::kHalf3x3 },
1252 { "yuvToRGBTranslate", SkSLType::kHalf3 }}},
1253 /*texturesAndSamplers=*/{{{ "samplerY" },
1254 { "samplerU" },
1255 { "samplerV" },
1256 { "samplerA" }}}
1257 };
1258 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kCubicYUVImageShader] = {
1259 /*name=*/"CubicYUVImage",
1260 /*staticFn=*/"sk_cubic_yuv_image_shader",
1261 SnippetRequirementFlags::kLocalCoords,
1262 /*uniforms=*/{{{ "invImgSizeY", SkSLType::kFloat2 },
1263 { "invImgSizeUV", SkSLType::kFloat2 }, // Relative to Y's texels
1264 { "subset", SkSLType::kFloat4 },
1265 { "tilemodeX", SkSLType::kInt },
1266 { "tilemodeY", SkSLType::kInt },
1267 { "cubicCoeffs", SkSLType::kHalf4x4 },
1268 { "channelSelectY", SkSLType::kHalf4 },
1269 { "channelSelectU", SkSLType::kHalf4 },
1270 { "channelSelectV", SkSLType::kHalf4 },
1271 { "channelSelectA", SkSLType::kHalf4 },
1272 { "yuvToRGBMatrix", SkSLType::kHalf3x3 },
1273 { "yuvToRGBTranslate", SkSLType::kHalf3 }}},
1274 /*texturesAndSamplers=*/{{{ "samplerY" },
1275 { "samplerU" },
1276 { "samplerV" },
1277 { "samplerA" }}}
1278 };
1279 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kHWYUVImageShader] = {
1280 /*name=*/"HWYUVImage",
1281 /*staticFn=*/"sk_hw_yuv_image_shader",
1282 SnippetRequirementFlags::kLocalCoords,
1283 /*uniforms=*/{{{ "invImgSizeY", SkSLType::kFloat2 },
1284 { "invImgSizeUV", SkSLType::kFloat2 }, // Relative to Y's texels
1285 { "subset", SkSLType::kFloat4 },
1286 { "linearFilterUVInset", SkSLType::kFloat2 },
1287 { "channelSelectY", SkSLType::kHalf4 },
1288 { "channelSelectU", SkSLType::kHalf4 },
1289 { "channelSelectV", SkSLType::kHalf4 },
1290 { "channelSelectA", SkSLType::kHalf4 },
1291 { "yuvToRGBMatrix", SkSLType::kHalf3x3 },
1292 { "yuvToRGBTranslate", SkSLType::kHalf3 }}},
1293 /*texturesAndSamplers=*/{{{ "samplerY" },
1294 { "samplerU" },
1295 { "samplerV" },
1296 { "samplerA" }}}
1297 };
1298
1299 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kHWYUVNoSwizzleImageShader] = {
1300 /*name=*/"HWYUVImageNoSwizzle",
1301 /*staticFn=*/"sk_hw_yuv_no_swizzle_image_shader",
1302 SnippetRequirementFlags::kLocalCoords,
1303 /*uniforms=*/{{{ "invImgSizeY", SkSLType::kFloat2 },
1304 { "invImgSizeUV", SkSLType::kFloat2 }, // Relative to Y space
1305 { "subset", SkSLType::kFloat4 },
1306 { "linearFilterUVInset", SkSLType::kFloat2 },
1307 { "yuvToRGBMatrix", SkSLType::kHalf3x3 },
1308 { "yuvToRGBXlateAlphaParams", SkSLType::kHalf4 }}},
1309 /*texturesAndSamplers=*/{{{ "samplerY" },
1310 { "samplerU" },
1311 { "samplerV" },
1312 { "samplerA" }}}
1313 };
1314
1315 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kCoordNormalizeShader] = {
1316 /*name=*/"CoordNormalize",
1317 /*staticFn=*/nullptr,
1318 SnippetRequirementFlags::kNone,
1319 /*uniforms=*/{{{ "invDimensions", SkSLType::kFloat2 }}},
1320 /*texturesAndSamplers=*/{},
1321 GenerateCoordManipulationPreamble,
1322 /*numChildren=*/kNumCoordinateManipulateChildren,
1323 /*liftableExpression=*/GenerateCoordNormalizeExpression,
1324 /*liftableExpressionType=*/ShaderSnippet::LiftableExpressionType::kLocalCoords
1325 };
1326
1327 // Like the local matrix shader, this is a no-op if the child doesn't need coords
1328 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kCoordClampShader] = {
1329 /*name=*/"CoordClamp",
1330 /*staticFn=*/nullptr,
1331 SnippetRequirementFlags::kNone,
1332 /*uniforms=*/{{{ "subset", SkSLType::kFloat4 }}},
1333 /*texturesAndSamplers=*/{},
1334 GenerateCoordManipulationPreamble,
1335 /*numChildren=*/kNumCoordinateManipulateChildren
1336 };
1337
1338 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kDitherShader] = {
1339 /*name=*/"Dither",
1340 /*staticFn=*/"sk_dither",
1341 SnippetRequirementFlags::kPriorStageOutput,
1342 /*uniforms=*/{{{ "range", SkSLType::kHalf }}},
1343 /*texturesAndSamplers=*/{ { "ditherLUT" } }
1344 };
1345
1346 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kPerlinNoiseShader] = {
1347 /*name=*/"PerlinNoise",
1348 /*staticFn=*/"sk_perlin_noise_shader",
1349 SnippetRequirementFlags::kLocalCoords,
1350 /*uniforms=*/{{{ "baseFrequency", SkSLType::kFloat2 },
1351 { "stitchData", SkSLType::kFloat2 },
1352 { "noiseType", SkSLType::kInt },
1353 { "numOctaves", SkSLType::kInt },
1354 { "stitching", SkSLType::kInt }}},
1355 /*texturesAndSamplers=*/{{{ "permutationsSampler" },
1356 { "noiseSampler" }}}
1357 };
1358
1359 // SkColorFilter snippets
1360 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kMatrixColorFilter] = {
1361 /*name=*/"MatrixColorFilter",
1362 /*staticFn=*/"sk_matrix_colorfilter",
1363 SnippetRequirementFlags::kPriorStageOutput,
1364 /*uniforms=*/{{{ "colorMatrix", SkSLType::kHalf4x4 },
1365 { "colorTranslate", SkSLType::kHalf4 },
1366 { "minMaxRGB", SkSLType::kHalf2 }}}
1367 };
1368 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kHSLMatrixColorFilter] = {
1369 /*name=*/"HSLMatrixColorFilter",
1370 /*staticFn=*/"sk_hsl_matrix_colorfilter",
1371 SnippetRequirementFlags::kPriorStageOutput,
1372 /*uniforms=*/{{{ "colorMatrix", SkSLType::kHalf4x4 },
1373 { "colorTranslate", SkSLType::kHalf4 }}}
1374 };
1375 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kTableColorFilter] = {
1376 /*name=*/"TableColorFilter",
1377 /*staticFn=*/"sk_table_colorfilter",
1378 SnippetRequirementFlags::kPriorStageOutput,
1379 /*uniforms=*/{},
1380 /*texturesAndSamplers=*/{ {"table"} }};
1381 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kGaussianColorFilter] = {
1382 /*name=*/"GaussianColorFilter",
1383 /*staticFn=*/"sk_gaussian_colorfilter",
1384 SnippetRequirementFlags::kPriorStageOutput,
1385 /*uniforms=*/{}
1386 };
1387 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kColorSpaceXformColorFilter] = {
1388 /*name=*/"ColorSpaceTransform",
1389 /*staticFn=*/"sk_color_space_transform",
1390 SnippetRequirementFlags::kPriorStageOutput,
1391 /*uniforms=*/{{{ "gamut", SkSLType::kHalf3x3 },
1392 { "srcGABC", SkSLType::kFloat4 },
1393 { "srcDEF_args", SkSLType::kFloat4 },
1394 { "dstGABC", SkSLType::kFloat4 },
1395 { "dstDEF_args", SkSLType::kFloat4 },
1396 { "srcOOTF_args", SkSLType::kFloat4 },
1397 { "dstOOTF_args", SkSLType::kFloat4 }}}
1398 };
1399
1400 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kColorSpaceXformPremul] = {
1401 /*name=*/"ColorSpaceTransformPremul",
1402 /*staticFn=*/"sk_color_space_transform_premul",
1403 SnippetRequirementFlags::kPriorStageOutput,
1404 /*uniforms=*/{{{ "args", SkSLType::kHalf2 }}}
1405 };
1406 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kColorSpaceXformSRGB] = {
1407 /*name=*/"ColorSpaceTransformSRGB",
1408 /*staticFn=*/"sk_color_space_transform_srgb",
1409 SnippetRequirementFlags::kPriorStageOutput,
1410 /*uniforms=*/{{{ "gamut", SkSLType::kHalf3x3 },
1411 { "srcGABC", SkSLType::kFloat4 },
1412 { "srcDEF_args", SkSLType::kFloat4 },
1413 { "dstGABC", SkSLType::kFloat4 },
1414 { "dstDEF_args", SkSLType::kFloat4 }}}
1415 };
1416
1417 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kPrimitiveColor] = {
1418 /*name=*/"PrimitiveColor",
1419 /*staticFn=*/"sk_passthrough",
1420 SnippetRequirementFlags::kPrimitiveColor,
1421 /*uniforms=*/{}
1422 };
1423
1424 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kAnalyticClip] = {
1425 /*name=*/"AnalyticClip",
1426 /*staticFn=*/"sk_analytic_clip",
1427 SnippetRequirementFlags::kLocalCoords,
1428 /*uniforms=*/{{{ "rect", SkSLType::kFloat4 },
1429 { "radiusPlusHalf", SkSLType::kFloat2 },
1430 { "edgeSelect", SkSLType::kHalf4 }}}
1431 };
1432
1433 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kAnalyticAndAtlasClip] = {
1434 /*name=*/"AnalyticAndAtlasClip",
1435 /*staticFn=*/"sk_analytic_and_atlas_clip",
1436 SnippetRequirementFlags::kLocalCoords,
1437 /*uniforms=*/{{{ "rect", SkSLType::kFloat4 },
1438 { "radiusPlusHalf", SkSLType::kFloat2 },
1439 { "edgeSelect", SkSLType::kHalf4 },
1440 { "texCoordOffset", SkSLType::kFloat2 },
1441 { "maskBounds", SkSLType::kFloat4 },
1442 { "invAtlasSize", SkSLType::kFloat2 }}},
1443 /*texturesAndSamplers=*/{{"atlasSampler"}}
1444 };
1445
1446 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kCompose] = {
1447 /*name=*/"Compose",
1448 /*staticFn=*/nullptr,
1449 SnippetRequirementFlags::kPassthroughLocalCoords,
1450 /*uniforms=*/{},
1451 /*texturesAndSamplers=*/{},
1452 GenerateComposePreamble,
1453 /*numChildren=*/2
1454 };
1455 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kBlendCompose] = {
1456 /*name=*/"BlendCompose",
1457 /*staticFn=*/nullptr,
1458 SnippetRequirementFlags::kPassthroughLocalCoords,
1459 /*uniforms=*/{},
1460 /*texturesAndSamplers=*/{},
1461 GenerateComposePreamble,
1462 /*numChildren=*/3
1463 };
1464
1465 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kPorterDuffBlender] = {
1466 /*name=*/"PorterDuffBlender",
1467 /*staticFn=*/"sk_porter_duff_blend",
1468 SnippetRequirementFlags::kPriorStageOutput | SnippetRequirementFlags::kBlenderDstColor,
1469 /*uniforms=*/{{{ "coeffs", SkSLType::kHalf4 }}}
1470 };
1471 fBuiltInCodeSnippets[(int) BuiltInCodeSnippetID::kHSLCBlender] = {
1472 /*name=*/"HSLCBlender",
1473 /*staticFn=*/"sk_hslc_blend",
1474 SnippetRequirementFlags::kPriorStageOutput | SnippetRequirementFlags::kBlenderDstColor,
1475 /*uniforms=*/{{{ "flipSat", SkSLType::kHalf2 }}}
1476 };
1477
1478 // Fixed-function blend mode snippets are all the same, their functionality is entirely defined
1479 // by their unique code snippet IDs.
1480 for (int i = 0; i <= (int) SkBlendMode::kLastMode; ++i) {
1481 int ffBlendModeID = kFixedBlendIDOffset + i;
1482 fBuiltInCodeSnippets[ffBlendModeID] = {
1483 /*name=*/SkBlendMode_Name(static_cast<SkBlendMode>(i)),
1484 /*staticFn=*/skgpu::BlendFuncName(static_cast<SkBlendMode>(i)),
1485 SnippetRequirementFlags::kPriorStageOutput |
1486 SnippetRequirementFlags::kBlenderDstColor,
1487 /*uniforms=*/{}
1488 };
1489 }
1490
1491 // Complete layout calculations for builtin snippets
1492 for (int i = 0; i < kBuiltInCodeSnippetIDCount; ++i) {
1493 ShaderSnippet& snippet = fBuiltInCodeSnippets[i];
1494 SkASSERT(snippet.fName); // Should not have missed a built-in
1495
1496 if (snippet.fUniformStructName) {
1497 auto offsetCalculator = UniformOffsetCalculator::ForStruct(fLayout);
1498 for (int j = 0; j < snippet.fUniforms.size(); ++j) {
1499 SkASSERT(!snippet.fUniforms[j].isPaintColor()); // paint color shouldn't be embedded
1500 offsetCalculator.advanceOffset(snippet.fUniforms[j].type(),
1501 snippet.fUniforms[j].count());
1502 }
1503 snippet.fRequiredAlignment = offsetCalculator.requiredAlignment();
1504 }
1505 }
1506
1507 // Check for duplicate snippet names.
1508 SkDEBUGCODE(
1509 THashSet<std::string> snippetNames;
1510 for (const ShaderSnippet& snippet : fBuiltInCodeSnippets) {
1511 std::string name = snippet.fName;
1512 SkASSERT(!snippetNames.contains(name));
1513 snippetNames.add(name);
1514 }
1515 )
1516
1517 this->registerUserDefinedKnownRuntimeEffects(userDefinedKnownRuntimeEffects);
1518 }
1519
1520 // clang-format off
1521
1522 // Verify that the built-in code IDs for fixed function blending are consistent with SkBlendMode.
1523 static_assert((int)SkBlendMode::kClear == (int)BuiltInCodeSnippetID::kFixedBlend_Clear - kFixedBlendIDOffset);
1524 static_assert((int)SkBlendMode::kSrc == (int)BuiltInCodeSnippetID::kFixedBlend_Src - kFixedBlendIDOffset);
1525 static_assert((int)SkBlendMode::kDst == (int)BuiltInCodeSnippetID::kFixedBlend_Dst - kFixedBlendIDOffset);
1526 static_assert((int)SkBlendMode::kSrcOver == (int)BuiltInCodeSnippetID::kFixedBlend_SrcOver - kFixedBlendIDOffset);
1527 static_assert((int)SkBlendMode::kDstOver == (int)BuiltInCodeSnippetID::kFixedBlend_DstOver - kFixedBlendIDOffset);
1528 static_assert((int)SkBlendMode::kSrcIn == (int)BuiltInCodeSnippetID::kFixedBlend_SrcIn - kFixedBlendIDOffset);
1529 static_assert((int)SkBlendMode::kDstIn == (int)BuiltInCodeSnippetID::kFixedBlend_DstIn - kFixedBlendIDOffset);
1530 static_assert((int)SkBlendMode::kSrcOut == (int)BuiltInCodeSnippetID::kFixedBlend_SrcOut - kFixedBlendIDOffset);
1531 static_assert((int)SkBlendMode::kDstOut == (int)BuiltInCodeSnippetID::kFixedBlend_DstOut - kFixedBlendIDOffset);
1532 static_assert((int)SkBlendMode::kSrcATop == (int)BuiltInCodeSnippetID::kFixedBlend_SrcATop - kFixedBlendIDOffset);
1533 static_assert((int)SkBlendMode::kDstATop == (int)BuiltInCodeSnippetID::kFixedBlend_DstATop - kFixedBlendIDOffset);
1534 static_assert((int)SkBlendMode::kXor == (int)BuiltInCodeSnippetID::kFixedBlend_Xor - kFixedBlendIDOffset);
1535 static_assert((int)SkBlendMode::kPlus == (int)BuiltInCodeSnippetID::kFixedBlend_Plus - kFixedBlendIDOffset);
1536 static_assert((int)SkBlendMode::kModulate == (int)BuiltInCodeSnippetID::kFixedBlend_Modulate - kFixedBlendIDOffset);
1537 static_assert((int)SkBlendMode::kScreen == (int)BuiltInCodeSnippetID::kFixedBlend_Screen - kFixedBlendIDOffset);
1538 static_assert((int)SkBlendMode::kOverlay == (int)BuiltInCodeSnippetID::kFixedBlend_Overlay - kFixedBlendIDOffset);
1539 static_assert((int)SkBlendMode::kDarken == (int)BuiltInCodeSnippetID::kFixedBlend_Darken - kFixedBlendIDOffset);
1540 static_assert((int)SkBlendMode::kColorDodge == (int)BuiltInCodeSnippetID::kFixedBlend_ColorDodge - kFixedBlendIDOffset);
1541 static_assert((int)SkBlendMode::kColorBurn == (int)BuiltInCodeSnippetID::kFixedBlend_ColorBurn - kFixedBlendIDOffset);
1542 static_assert((int)SkBlendMode::kHardLight == (int)BuiltInCodeSnippetID::kFixedBlend_HardLight - kFixedBlendIDOffset);
1543 static_assert((int)SkBlendMode::kSoftLight == (int)BuiltInCodeSnippetID::kFixedBlend_SoftLight - kFixedBlendIDOffset);
1544 static_assert((int)SkBlendMode::kDifference == (int)BuiltInCodeSnippetID::kFixedBlend_Difference - kFixedBlendIDOffset);
1545 static_assert((int)SkBlendMode::kExclusion == (int)BuiltInCodeSnippetID::kFixedBlend_Exclusion - kFixedBlendIDOffset);
1546 static_assert((int)SkBlendMode::kMultiply == (int)BuiltInCodeSnippetID::kFixedBlend_Multiply - kFixedBlendIDOffset);
1547 static_assert((int)SkBlendMode::kHue == (int)BuiltInCodeSnippetID::kFixedBlend_Hue - kFixedBlendIDOffset);
1548 static_assert((int)SkBlendMode::kSaturation == (int)BuiltInCodeSnippetID::kFixedBlend_Saturation - kFixedBlendIDOffset);
1549 static_assert((int)SkBlendMode::kColor == (int)BuiltInCodeSnippetID::kFixedBlend_Color - kFixedBlendIDOffset);
1550 static_assert((int)SkBlendMode::kLuminosity == (int)BuiltInCodeSnippetID::kFixedBlend_Luminosity - kFixedBlendIDOffset);
1551
1552 static_assert(0 == static_cast<int>(SkTileMode::kClamp), "ImageShader code depends on SkTileMode");
1553 static_assert(1 == static_cast<int>(SkTileMode::kRepeat), "ImageShader code depends on SkTileMode");
1554 static_assert(2 == static_cast<int>(SkTileMode::kMirror), "ImageShader code depends on SkTileMode");
1555 static_assert(3 == static_cast<int>(SkTileMode::kDecal), "ImageShader code depends on SkTileMode");
1556
1557 static_assert(0 == static_cast<int>(SkFilterMode::kNearest), "ImageShader code depends on SkFilterMode");
1558 static_assert(1 == static_cast<int>(SkFilterMode::kLinear), "ImageShader code depends on SkFilterMode");
1559
1560 // clang-format on
1561
1562 } // namespace skgpu::graphite