Debian Codegraph @

src/gpu/graphite/ShaderInfo.cpp

raw
1 /*
2 * Copyright 2024 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/ShaderInfo.h"
9
10 #include "src/gpu/BlendFormula.h"
11 #include "src/gpu/graphite/ContextUtils.h"
12 #include "src/gpu/graphite/PaintParamsKey.h"
13 #include "src/gpu/graphite/RenderPassDesc.h"
14 #include "src/gpu/graphite/Renderer.h"
15 #include "src/gpu/graphite/ShaderCodeDictionary.h"
16 #include "src/gpu/graphite/TextureFormat.h"
17 #include "src/gpu/graphite/UniformManager.h"
18 #include "src/sksl/SkSLString.h"
19 #include "src/sksl/SkSLUtil.h"
20
21 using namespace skia_private;
22
23 namespace skgpu::graphite {
24
25 namespace {
26
27 struct LiftedExpression {
28 // The node who's expression should be lifted.
29 const ShaderNode* fNode;
30 // The arguments to use as input to the lifted expression.
31 ShaderSnippet::Args fArgs;
32 // If true, capture the expression's resolved value in a varying.
33 // This is false for expressions whose output is only used in other lifted expressions.
34 bool fEmitVarying = true;
35 };
36
37 std::string get_uniform_header(int set, int bufferID) {
38 std::string result;
39 SkSL::String::appendf(
40 &result, "layout (set=%d, binding=%d) uniform CombinedUniforms {\n", set, bufferID);
41 return result;
42 }
43
44 std::string get_uniforms(UniformOffsetCalculator* offsetter,
45 SkSpan<const Uniform> uniforms,
46 int manglingSuffix,
47 bool* wrotePaintColor) {
48 std::string result;
49 std::string uniformName;
50 for (const Uniform& u : uniforms) {
51 uniformName = u.name();
52
53 if (u.isPaintColor() && wrotePaintColor) {
54 if (*wrotePaintColor) {
55 SkSL::String::appendf(&result, " // deduplicated %s\n", u.name());
56 continue;
57 }
58
59 *wrotePaintColor = true;
60 } else {
61 if (manglingSuffix >= 0) {
62 uniformName.append("_");
63 uniformName.append(std::to_string(manglingSuffix));
64 }
65 }
66
67 SkSL::String::appendf(&result,
68 " layout(offset=%d) %s %s",
69 offsetter->advanceOffset(u.type(), u.count()),
70 SkSLTypeString(u.type()),
71 uniformName.c_str());
72 if (u.count()) {
73 result.append("[");
74 result.append(std::to_string(u.count()));
75 result.append("]");
76 }
77 result.append(";\n");
78 }
79
80 return result;
81 }
82
83 std::string get_node_uniforms(UniformOffsetCalculator* offsetter,
84 const ShaderNode* node,
85 int* numUniforms,
86 int* numUnliftedUniforms,
87 bool* wrotePaintColor) {
88 std::string result;
89 SkSpan<const Uniform> uniforms = node->entry()->fUniforms;
90
91 if (!uniforms.empty()) {
92 *numUniforms += uniforms.size();
93 if (!((node->requiredFlags() & SnippetRequirementFlags::kLiftExpression) ||
94 (node->requiredFlags() & SnippetRequirementFlags::kOmitExpression))) {
95 *numUnliftedUniforms += uniforms.size();
96 }
97
98 if (node->entry()->fUniformStructName) {
99 auto substruct = UniformOffsetCalculator::ForStruct(offsetter->layout());
100 for (const Uniform& u : uniforms) {
101 substruct.advanceOffset(u.type(), u.count());
102 }
103
104 const int structOffset = offsetter->advanceStruct(substruct);
105 SkSL::String::appendf(&result,
106 "layout(offset=%d) %s node_%d;",
107 structOffset,
108 node->entry()->fUniformStructName,
109 node->keyIndex());
110 } else {
111 #if defined(SK_DEBUG)
112 SkSL::String::appendf(&result, "// %d - %s uniforms\n",
113 node->keyIndex(), node->entry()->fName);
114 #endif
115 result += get_uniforms(offsetter, uniforms, node->keyIndex(), wrotePaintColor);
116 }
117 }
118
119 for (const ShaderNode* child : node->children()) {
120 result += get_node_uniforms(
121 offsetter, child, numUniforms, numUnliftedUniforms, wrotePaintColor);
122 }
123 return result;
124 }
125
126 std::string get_ssbo_fields(SkSpan<const Uniform> uniforms,
127 int manglingSuffix,
128 bool* wrotePaintColor) {
129 std::string result;
130
131 std::string uniformName;
132 for (const Uniform& u : uniforms) {
133 uniformName = u.name();
134
135 if (u.isPaintColor() && wrotePaintColor) {
136 if (*wrotePaintColor) {
137 #if defined(SK_DEBUG)
138 SkSL::String::appendf(&result, " // deduplicated %s\n", u.name());
139 #endif
140 continue;
141 }
142
143 *wrotePaintColor = true;
144 } else {
145 if (manglingSuffix >= 0) {
146 uniformName.append("_");
147 uniformName.append(std::to_string(manglingSuffix));
148 }
149 }
150
151 SkSL::String::appendf(&result, " %s %s", SkSLTypeString(u.type()), uniformName.c_str());
152 if (u.count()) {
153 SkSL::String::appendf(&result, "[%d]", u.count());
154 }
155 result.append(";\n");
156 }
157
158 return result;
159 }
160
161 std::string get_node_ssbo_fields(const ShaderNode* node,
162 int* numUniforms,
163 int* numUnliftedUniforms,
164 bool* wrotePaintColor) {
165 std::string result;
166 SkSpan<const Uniform> uniforms = node->entry()->fUniforms;
167
168 if (!uniforms.empty()) {
169 *numUniforms += uniforms.size();
170 if (!((node->requiredFlags() & SnippetRequirementFlags::kLiftExpression) ||
171 (node->requiredFlags() & SnippetRequirementFlags::kOmitExpression))) {
172 *numUnliftedUniforms += uniforms.size();
173 }
174
175 if (node->entry()->fUniformStructName) {
176 SkSL::String::appendf(&result, "%s node_%d;",
177 node->entry()->fUniformStructName, node->keyIndex());
178 } else {
179 #if defined(SK_DEBUG)
180 SkSL::String::appendf(&result, "// %d - %s uniforms\n",
181 node->keyIndex(), node->entry()->fName);
182 #endif
183 result += get_ssbo_fields(uniforms, node->keyIndex(), wrotePaintColor);
184 }
185 }
186
187 for (const ShaderNode* child : node->children()) {
188 result += get_node_ssbo_fields(child, numUniforms, numUnliftedUniforms, wrotePaintColor);
189 }
190 return result;
191 }
192
193 std::string emit_intrinsic_constants(const ResourceBindingRequirements& bindingReqs) {
194 std::string result;
195 auto offsetter = UniformOffsetCalculator::ForTopLevel(bindingReqs.fUniformBufferLayout);
196
197 if (bindingReqs.fUsePushConstantsForIntrinsicConstants) {
198 SkASSERT(bindingReqs.fBackendApi == BackendApi::kVulkan ||
199 bindingReqs.fBackendApi == BackendApi::kDawn);
200 result = SkSL::String::printf(
201 "layout (%s, push_constant) uniform IntrinsicUniforms {\n",
202 bindingReqs.fBackendApi == BackendApi::kVulkan ? "vulkan" : "webgpu");
203 } else {
204 std::string header;
205 SkSL::String::appendf(&header,
206 "layout (set=%d, binding=%d) uniform IntrinsicUniforms {\n",
207 bindingReqs.fUniformsSetIdx,
208 bindingReqs.fIntrinsicBufferBinding);
209 result = std::move(header);
210 }
211 result += get_uniforms(&offsetter, kIntrinsicUniforms, -1, /* wrotePaintColor= */ nullptr);
212 result.append("};\n\n");
213 SkASSERTF(bindingReqs.fUsePushConstantsForIntrinsicConstants ||
214 result.find('[') == std::string::npos,
215 "Arrays are not supported in intrinsic uniforms");
216 return result;
217 }
218
219 std::string emit_combined_uniforms(int set,
220 int bufferID,
221 const Layout layout,
222 SkSpan<const ShaderNode*> nodes,
223 SkSpan<const Uniform> stepUniforms,
224 int* numPaintUniforms,
225 int* numUnliftedPaintUniforms,
226 bool* wrotePaintColor) {
227 auto offsetter = UniformOffsetCalculator::ForTopLevel(layout);
228
229 std::string result = get_uniform_header(set, bufferID);
230 for (const ShaderNode* n : nodes) {
231 result += get_node_uniforms(
232 &offsetter, n, numPaintUniforms, numUnliftedPaintUniforms, wrotePaintColor);
233 }
234
235 // Paint and RenderStep uniforms share a binding. When RenderSteps are processed in DrawList,
236 // the paint uniforms are always processed before the render step ones, so the emitted uniforms
237 // must respect that ordering.
238 if (!stepUniforms.empty()) {
239 result += get_uniforms(&offsetter, stepUniforms, -1, /* wrotePaintColor= */ nullptr);
240 }
241
242 result.append("};\n\n");
243
244 if (*numPaintUniforms == 0 && stepUniforms.empty()) {
245 // No uniforms were added
246 return {};
247 }
248
249 return result;
250 }
251
252 std::string emit_combined_storage_buffer(int set,
253 int bufferID,
254 SkSpan<const ShaderNode*> nodes,
255 SkSpan<const Uniform> stepUniforms,
256 int* numPaintUniforms,
257 int* numUnliftedPaintUniforms,
258 bool* wrotePaintColor) {
259 std::string fields;
260 for (const ShaderNode* n : nodes) {
261 fields += get_node_ssbo_fields(
262 n, numPaintUniforms, numUnliftedPaintUniforms, wrotePaintColor);
263 }
264
265 if (!stepUniforms.empty()) {
266 fields += get_ssbo_fields(stepUniforms, -1, /*wrotePaintColor=*/nullptr);
267 }
268
269 if (*numPaintUniforms == 0 && stepUniforms.empty()) {
270 // No uniforms were added
271 return {};
272 }
273
274 return SkSL::String::printf(
275 "struct CombinedUniformData {\n"
276 " %s\n"
277 "};\n\n"
278 "layout (set=%d, binding=%d) readonly buffer CombinedUniforms {\n"
279 " CombinedUniformData combinedUniformData[];\n"
280 "};\n",
281 fields.c_str(),
282 set,
283 bufferID);
284 }
285
286 std::string emit_uniforms_from_storage_buffer(const char* indexVariableName,
287 SkSpan<const Uniform> uniforms) {
288 std::string result;
289
290 for (const Uniform& u : uniforms) {
291 SkSL::String::appendf(&result, "%s %s", SkSLTypeString(u.type()), u.name());
292 if (u.count()) {
293 SkSL::String::appendf(&result, "[%d]", u.count());
294 }
295 SkSL::String::appendf(&result,
296 " = combinedUniformData[%s].%s;\n",
297 indexVariableName,
298 u.name());
299 }
300
301 return result;
302 }
303
304 void append_sampler_descs(const SkSpan<const uint32_t> samplerData,
305 skia_private::TArray<SamplerDesc>& outDescs) {
306 // Sampler data consists of variable-length SamplerDesc representations which can differ based
307 // upon a sampler's immutability and format. For this reason, handle incrementing i in the loop.
308 for (size_t i = 0; i < samplerData.size();) {
309 // Create a default-initialized SamplerDesc (which only takes up one uint32). If we are
310 // using a dynamic sampler, this will be directly inserted into outDescs. Otherwise, it will
311 // be populated with actual immutable sampler data and then inserted.
312 SamplerDesc desc{};
313 size_t samplerDescLength = 1;
314 SkASSERT(desc.asSpan().size() == samplerDescLength);
315
316 // Isolate the ImmutableSamplerInfo portion of the SamplerDesc represented by samplerData.
317 // If immutableSamplerInfo is non-zero, that means we are using an immutable sampler.
318 uint32_t immutableSamplerInfo = samplerData[i] >> SamplerDesc::kImmutableSamplerInfoShift;
319 if (immutableSamplerInfo != 0) {
320 // Consult the first bit of immutableSamplerInfo which tells us whether the sampler uses
321 // a known or external format. With this, update sampler description length.
322 bool usesExternalFormat = immutableSamplerInfo & 0b1;
323 samplerDescLength = usesExternalFormat ? SamplerDesc::kInt32sNeededExternalFormat
324 : SamplerDesc::kInt32sNeededKnownFormat;
325 // Populate a SamplerDesc with samplerDescLength quantity of immutable sampler data
326 memcpy(&desc, samplerData.data() + i, samplerDescLength * sizeof(uint32_t));
327 }
328 outDescs.push_back(desc);
329 i += samplerDescLength;
330 }
331 }
332
333 std::string get_node_texture_samplers(const ResourceBindingRequirements& bindingReqs,
334 const ShaderNode* node,
335 int* binding,
336 skia_private::TArray<SamplerDesc>* outDescs) {
337 std::string result;
338 SkSpan<const TextureAndSampler> samplers = node->entry()->fTexturesAndSamplers;
339
340 if (!samplers.empty()) {
341 #if defined(SK_DEBUG)
342 SkSL::String::appendf(&result, "// %d - %s samplers\n",
343 node->keyIndex(), node->entry()->fName);
344 #endif
345
346 // Determine whether we need to analyze & interpret a ShaderNode's data as immutable
347 // SamplerDescs based upon whether:
348 // 1) A backend passes in a non-nullptr outImmutableSamplers param (may be nullptr in
349 // backends or circumstances where we know immutable sampler data is never stored)
350 // 2) Any data is stored on the ShaderNode
351 // 3) Whether the ShaderNode snippet's ID matches that of any snippet ID that could store
352 // immutable sampler data.
353 int32_t snippetId = node->codeSnippetId();
354 if (outDescs) {
355 // TODO(b/369846881): Refactor checking snippet ID to instead having a named
356 // snippet requirement flag that we can check here to decrease fragility.
357 if (!node->data().empty() &&
358 (snippetId == static_cast<int32_t>(BuiltInCodeSnippetID::kImageShader) ||
359 snippetId == static_cast<int32_t>(BuiltInCodeSnippetID::kImageShaderClamp) ||
360 snippetId == static_cast<int32_t>(BuiltInCodeSnippetID::kCubicImageShader) ||
361 snippetId == static_cast<int32_t>(BuiltInCodeSnippetID::kHWImageShader))) {
362 append_sampler_descs(node->data(), *outDescs);
363 } else {
364 // Add default SamplerDescs for any dynamic samplers to outDescs.
365 outDescs->push_back_n(samplers.size());
366 }
367 }
368
369 for (const TextureAndSampler& t : samplers) {
370 result += EmitSamplerLayout(bindingReqs, binding);
371 SkSL::String::appendf(&result, " sampler2D %s_%d;\n", t.name(), node->keyIndex());
372 }
373 }
374
375 for (const ShaderNode* child : node->children()) {
376 result += get_node_texture_samplers(bindingReqs, child, binding, outDescs);
377 }
378 return result;
379 }
380
381 std::string emit_textures_and_samplers(const ResourceBindingRequirements& bindingReqs,
382 SkSpan<const ShaderNode*> nodes,
383 int* binding,
384 skia_private::TArray<SamplerDesc>* outDescs) {
385 std::string result;
386 for (const ShaderNode* n : nodes) {
387 result += get_node_texture_samplers(bindingReqs, n, binding, outDescs);
388 }
389 return result;
390 }
391
392 SkSLType sksl_type_for_lifted_expression(
393 ShaderSnippet::LiftableExpressionType liftedExpressionType) {
394 switch (liftedExpressionType) {
395 case ShaderSnippet::LiftableExpressionType::kNone:
396 return SkSLType::kVoid;
397 case ShaderSnippet::LiftableExpressionType::kLocalCoords:
398 return SkSLType::kFloat2;
399 case ShaderSnippet::LiftableExpressionType::kPriorStageOutput:
400 return SkSLType::kHalf4;
401 }
402 return SkSLType::kVoid;
403 }
404
405 std::string emit_varyings(const RenderStep* step,
406 const char* direction,
407 SkSpan<const LiftedExpression> liftedExpressions,
408 bool emitSsboIndexVarying,
409 bool emitLocalCoordsVarying) {
410 std::string result;
411 int location = 0;
412
413 auto appendVarying = [&](const Varying& v) {
414 const char* interpolation;
415 switch (v.interpolation()) {
416 case Interpolation::kPerspective: interpolation = ""; break;
417 case Interpolation::kLinear: interpolation = "noperspective "; break;
418 case Interpolation::kFlat: interpolation = "flat "; break;
419 }
420 SkSL::String::appendf(&result, "layout(location=%d) %s %s%s %s;\n",
421 location++,
422 direction,
423 interpolation,
424 SkSLTypeString(v.gpuType()),
425 v.name());
426 };
427
428 if (emitSsboIndexVarying) {
429 appendVarying({RenderStep::ssboIndexVarying(), SkSLType::kUInt});
430 }
431
432 if (emitLocalCoordsVarying) {
433 appendVarying({"localCoordsVar", SkSLType::kFloat2});
434 }
435
436 for (const LiftedExpression& expr : liftedExpressions) {
437 if (expr.fEmitVarying) {
438 const ShaderNode* node = expr.fNode;
439 const std::string name = node->getExpressionVaryingName();
440 appendVarying({name.c_str(),
441 sksl_type_for_lifted_expression(node->entry()->fLiftableExpressionType),
442 node->entry()->fLiftableExpressionInterpolation});
443 }
444 }
445
446 for (auto v : step->varyings()) {
447 appendVarying(v);
448 }
449
450 return result;
451 }
452
453 // Walk the node tree and generate all preambles, accumulating into 'preamble'.
454 void emit_preambles(const ShaderInfo& shaderInfo,
455 SkSpan<const ShaderNode*> nodes,
456 std::string treeLabel,
457 std::string* preamble) {
458 for (int i = 0; i < SkTo<int>(nodes.size()); ++i) {
459 const ShaderNode* node = nodes[i];
460 std::string nodeLabel = std::to_string(i);
461 std::string nextLabel = treeLabel.empty() ? nodeLabel : (treeLabel + "<-" + nodeLabel);
462
463 if (node->numChildren() > 0) {
464 emit_preambles(shaderInfo, node->children(), nextLabel, preamble);
465 }
466
467 std::string nodePreamble = node->entry()->fPreambleGenerator
468 ? node->entry()->fPreambleGenerator(shaderInfo, node)
469 : node->generateDefaultPreamble(shaderInfo);
470 if (!nodePreamble.empty()) {
471 SkSL::String::appendf(preamble,
472 "// [%d] %s: %s\n"
473 "%s\n",
474 node->keyIndex(),
475 nextLabel.c_str(),
476 node->entry()->fName,
477 nodePreamble.c_str());
478 }
479 }
480 }
481
482 std::string emit_color_output(BlendFormula::OutputType outputType,
483 const char* outColor,
484 const char* inColor) {
485 switch (outputType) {
486 case BlendFormula::kNone_OutputType:
487 return SkSL::String::printf("%s = half4(0.0);", outColor);
488
489 case BlendFormula::kCoverage_OutputType:
490 return SkSL::String::printf("%s = outputCoverage;", outColor);
491
492 case BlendFormula::kModulate_OutputType:
493 return SkSL::String::printf("%s = %s * outputCoverage;", outColor, inColor);
494
495 case BlendFormula::kSAModulate_OutputType:
496 return SkSL::String::printf("%s = %s.a * outputCoverage;", outColor, inColor);
497
498 case BlendFormula::kISAModulate_OutputType:
499 return SkSL::String::printf("%s = (1.0 - %s.a) * outputCoverage;", outColor, inColor);
500
501 case BlendFormula::kISCModulate_OutputType:
502 return SkSL::String::printf(
503 "%s = (half4(1.0) - %s) * outputCoverage;", outColor, inColor);
504
505 default:
506 SkUNREACHABLE;
507 }
508 }
509
510 std::string emit_advanced_blend_color_output(const char* outColor, const char* inColor) {
511 /*
512 When using hardware for advanced blend modes, we apply coverage for advanced blend modes by
513 multiplying it into the src color before blending. This will "just work" given the following:
514
515 The general SVG blend equation is defined in the spec as follows:
516
517 Dca' = B(Sc, Dc) * Sa * Da + Y * Sca * (1-Da) + Z * Dca * (1-Sa)
518 Da' = X * Sa * Da + Y * Sa * (1-Da) + Z * Da * (1-Sa)
519
520 (Note that Sca, Dca indicate RGB vectors that are premultiplied by alpha,
521 and that B(Sc, Dc) is a mode-specific function that accepts non-multiplied
522 RGB colors.)
523
524 For every blend mode supported by this class, i.e. the "advanced" blend
525 modes, X=Y=Z=1 and this equation reduces to the PDF blend equation.
526
527 It can be shown that when X=Y=Z=1, these equations can modulate alpha for
528 coverage.
529
530
531 == Color ==
532
533 We substitute Y=Z=1 and define a blend() function that calculates Dca' in
534 terms of premultiplied alpha only:
535
536 blend(Sca, Dca, Sa, Da) = {
537 Dca : if Sa == 0,
538 Sca : if Da == 0,
539 B(Sca/Sa, Dca/Da) * Sa * Da + Sca * (1-Da) + Dca * (1-Sa) : if Sa,Da != 0}
540
541 And for coverage modulation, we use a post blend src-over model:
542
543 Dca'' = f * blend(Sca, Dca, Sa, Da) + (1-f) * Dca
544
545 (Where f is the fractional coverage.)
546
547 Next we show that we can multiply coverage into the src color by proving the
548 following relationship:
549
550 blend(f*Sca, Dca, f*Sa, Da) == f * blend(Sca, Dca, Sa, Da) + (1-f) * Dca
551
552 General case (f,Sa,Da != 0):
553
554 f * blend(Sca, Dca, Sa, Da) + (1-f) * Dca
555 = f * (B(Sca/Sa, Dca/Da) * Sa * Da + Sca * (1-Da) + Dca * (1-Sa)) + (1-f) * Dca
556 [Sa,Da != 0, definition of blend()]
557 = B(Sca/Sa, Dca/Da) * f*Sa * Da + f*Sca * (1-Da) + f*Dca * (1-Sa) + Dca - f*Dca
558 = B(Sca/Sa, Dca/Da) * f*Sa * Da + f*Sca - f*Sca * Da + f*Dca - f*Dca * Sa + Dca - f*Dca
559 = B(Sca/Sa, Dca/Da) * f*Sa * Da + f*Sca - f*Sca * Da - f*Dca * Sa + Dca
560 = B(Sca/Sa, Dca/Da) * f*Sa * Da + f*Sca * (1-Da) - f*Dca * Sa + Dca
561 = B(Sca/Sa, Dca/Da) * f*Sa * Da + f*Sca * (1-Da) + Dca * (1 - f*Sa)
562 = B(f*Sca/f*Sa, Dca/Da) * f*Sa * Da + f*Sca * (1-Da) + Dca * (1 - f*Sa) [f!=0]
563 = blend(f*Sca, Dca, f*Sa, Da) [definition of blend()]
564
565 Corner cases (Sa=0, Da=0, and f=0):
566
567 Sa=0: f * blend(Sca, Dca, Sa, Da) + (1-f) * Dca
568 = f * Dca + (1-f) * Dca [Sa=0, definition of blend()]
569 = Dca
570 = blend(0, Dca, 0, Da) [definition of blend()]
571 = blend(f*Sca, Dca, f*Sa, Da) [Sa=0]
572
573 Da=0: f * blend(Sca, Dca, Sa, Da) + (1-f) * Dca
574 = f * Sca + (1-f) * Dca [Da=0, definition of blend()]
575 = f * Sca [Da=0]
576 = blend(f*Sca, 0, f*Sa, 0) [definition of blend()]
577 = blend(f*Sca, Dca, f*Sa, Da) [Da=0]
578
579 f=0: f * blend(Sca, Dca, Sa, Da) + (1-f) * Dca
580 = Dca [f=0]
581 = blend(0, Dca, 0, Da) [definition of blend()]
582 = blend(f*Sca, Dca, f*Sa, Da) [f=0]
583
584 == Alpha ==
585
586 We substitute X=Y=Z=1 and define a blend() function that calculates Da':
587
588 blend(Sa, Da) = Sa * Da + Sa * (1-Da) + Da * (1-Sa)
589 = Sa * Da + Sa - Sa * Da + Da - Da * Sa
590 = Sa + Da - Sa * Da
591
592 We use the same model for coverage modulation as we did with color:
593
594 Da'' = f * blend(Sa, Da) + (1-f) * Da
595
596 And show that show that we can multiply coverage into src alpha by proving the following
597 relationship:
598
599 blend(f*Sa, Da) == f * blend(Sa, Da) + (1-f) * Da
600
601 f * blend(Sa, Da) + (1-f) * Da
602 = f * (Sa + Da - Sa * Da) + (1-f) * Da
603 = f*Sa + f*Da - f*Sa * Da + Da - f*Da
604 = f*Sa - f*Sa * Da + Da
605 = f*Sa + Da - f*Sa * Da
606 = blend(f*Sa, Da)
607 */
608 return emit_color_output(BlendFormula::OutputType::kModulate_OutputType, outColor, inColor);
609 }
610
611 void collect_lifted_expressions(SkSpan<const ShaderNode*> nodes,
612 const ShaderSnippet::Args& args,
613 std::vector<LiftedExpression>& lifted) {
614 for (const ShaderNode* node : nodes) {
615 const bool emitVaryingInFS =
616 static_cast<bool>(node->requiredFlags() & SnippetRequirementFlags::kLiftExpression);
617 const bool emitExpressionInVS =
618 emitVaryingInFS ||
619 (node->requiredFlags() & SnippetRequirementFlags::kOmitExpression);
620 SkASSERT(!emitExpressionInVS || node->entry()->fLiftableExpressionGenerator);
621
622 ShaderSnippet::Args childArgs = args;
623 if (emitExpressionInVS && node->entry()->fLiftableExpressionGenerator) {
624 lifted.push_back({node, args, emitVaryingInFS});
625 switch (node->entry()->fLiftableExpressionType) {
626 case ShaderSnippet::LiftableExpressionType::kLocalCoords:
627 childArgs.fFragCoord = node->getExpressionVaryingName();
628 break;
629 case ShaderSnippet::LiftableExpressionType::kPriorStageOutput:
630 childArgs.fPriorStageOutput = node->getExpressionVaryingName();
631 break;
632 default:
633 SkUNREACHABLE;
634 }
635 }
636
637 collect_lifted_expressions(node->children(), childArgs, lifted);
638 }
639 }
640
641 std::vector<LiftedExpression> collect_lifted_expressions(SkSpan<const ShaderNode*> nodes) {
642 std::vector<LiftedExpression> lifted;
643 ShaderSnippet::Args args = ShaderSnippet::kDefaultArgs;
644 args.fFragCoord = "stepLocalCoords"; // Render Steps' stepLocalCoords
645 collect_lifted_expressions(nodes, args, lifted);
646 return lifted;
647 }
648
649 std::string dst_read_strategy_to_str(DstReadStrategy strategy) {
650 switch (strategy) {
651 case DstReadStrategy::kNoneRequired:
652 return "NoneRequired";
653 case DstReadStrategy::kTextureCopy:
654 return "TextureCopy";
655 case DstReadStrategy::kTextureSample:
656 return "TextureSample";
657 case DstReadStrategy::kReadFromInput:
658 return "ReadFromInput";
659 case DstReadStrategy::kFramebufferFetch:
660 return "FramebufferFetch";
661 }
662 SkUNREACHABLE;
663 }
664
665 constexpr skgpu::BlendInfo make_simple_blendInfo(skgpu::BlendCoeff srcCoeff,
666 skgpu::BlendCoeff dstCoeff) {
667 return { skgpu::BlendEquation::kAdd,
668 srcCoeff,
669 dstCoeff,
670 SK_PMColor4fTRANSPARENT,
671 skgpu::BlendModifiesDst(skgpu::BlendEquation::kAdd, srcCoeff, dstCoeff) };
672 }
673
674
675 constexpr skgpu::BlendEquation get_advanced_blend_equation(SkBlendMode mode) {
676 SkASSERT(mode > SkBlendMode::kLastCoeffMode);
677
678 constexpr int kEqOffset = ((int)skgpu::BlendEquation::kOverlay - (int)SkBlendMode::kOverlay);
679 static_assert((int)skgpu::BlendEquation::kOverlay ==
680 (int)SkBlendMode::kOverlay + kEqOffset);
681 static_assert((int)skgpu::BlendEquation::kDarken ==
682 (int)SkBlendMode::kDarken + kEqOffset);
683 static_assert((int)skgpu::BlendEquation::kLighten ==
684 (int)SkBlendMode::kLighten + kEqOffset);
685 static_assert((int)skgpu::BlendEquation::kColorDodge ==
686 (int)SkBlendMode::kColorDodge + kEqOffset);
687 static_assert((int)skgpu::BlendEquation::kColorBurn ==
688 (int)SkBlendMode::kColorBurn + kEqOffset);
689 static_assert((int)skgpu::BlendEquation::kHardLight ==
690 (int)SkBlendMode::kHardLight + kEqOffset);
691 static_assert((int)skgpu::BlendEquation::kSoftLight ==
692 (int)SkBlendMode::kSoftLight + kEqOffset);
693 static_assert((int)skgpu::BlendEquation::kDifference ==
694 (int)SkBlendMode::kDifference + kEqOffset);
695 static_assert((int)skgpu::BlendEquation::kExclusion ==
696 (int)SkBlendMode::kExclusion + kEqOffset);
697 static_assert((int)skgpu::BlendEquation::kMultiply ==
698 (int)SkBlendMode::kMultiply + kEqOffset);
699 static_assert((int)skgpu::BlendEquation::kHSLHue ==
700 (int)SkBlendMode::kHue + kEqOffset);
701 static_assert((int)skgpu::BlendEquation::kHSLSaturation ==
702 (int)SkBlendMode::kSaturation + kEqOffset);
703 static_assert((int)skgpu::BlendEquation::kHSLColor ==
704 (int)SkBlendMode::kColor + kEqOffset);
705 static_assert((int)skgpu::BlendEquation::kHSLLuminosity ==
706 (int)SkBlendMode::kLuminosity + kEqOffset);
707 // There's an illegal BlendEquation that corresponds to no SkBlendMode, hence the extra +1.
708 static_assert(skgpu::kBlendEquationCnt == (int)SkBlendMode::kLastMode + 1 + 1 + kEqOffset);
709
710 return static_cast<skgpu::BlendEquation>((int)mode + kEqOffset);
711 }
712
713 constexpr skgpu::BlendInfo make_hardware_advanced_blendInfo(SkBlendMode advancedBlendMode) {
714 BlendInfo blendInfo;
715 blendInfo.fEquation = get_advanced_blend_equation(advancedBlendMode);
716 return blendInfo;
717 }
718
719 static constexpr skgpu::BlendInfo gBlendTable[kSkBlendModeCount] = {
720 /* Porter-Duff blend modes */
721 /* clear */ make_simple_blendInfo(skgpu::BlendCoeff::kZero, skgpu::BlendCoeff::kZero),
722 /* src */ make_simple_blendInfo(skgpu::BlendCoeff::kOne, skgpu::BlendCoeff::kZero),
723 /* dst */ make_simple_blendInfo(skgpu::BlendCoeff::kZero, skgpu::BlendCoeff::kOne),
724 /* src-over */ make_simple_blendInfo(skgpu::BlendCoeff::kOne, skgpu::BlendCoeff::kISA),
725 /* dst-over */ make_simple_blendInfo(skgpu::BlendCoeff::kIDA, skgpu::BlendCoeff::kOne),
726 /* src-in */ make_simple_blendInfo(skgpu::BlendCoeff::kDA, skgpu::BlendCoeff::kZero),
727 /* dst-in */ make_simple_blendInfo(skgpu::BlendCoeff::kZero, skgpu::BlendCoeff::kSA),
728 /* src-out */ make_simple_blendInfo(skgpu::BlendCoeff::kIDA, skgpu::BlendCoeff::kZero),
729 /* dst-out */ make_simple_blendInfo(skgpu::BlendCoeff::kZero, skgpu::BlendCoeff::kISA),
730 /* src-atop */ make_simple_blendInfo(skgpu::BlendCoeff::kDA, skgpu::BlendCoeff::kISA),
731 /* dst-atop */ make_simple_blendInfo(skgpu::BlendCoeff::kIDA, skgpu::BlendCoeff::kSA),
732 /* xor */ make_simple_blendInfo(skgpu::BlendCoeff::kIDA, skgpu::BlendCoeff::kISA),
733 /* plus */ make_simple_blendInfo(skgpu::BlendCoeff::kOne, skgpu::BlendCoeff::kOne),
734 /* modulate */ make_simple_blendInfo(skgpu::BlendCoeff::kZero, skgpu::BlendCoeff::kSC),
735 /* screen */ make_simple_blendInfo(skgpu::BlendCoeff::kOne, skgpu::BlendCoeff::kISC),
736
737 /* BlendInfo for advanced blend modes */
738 make_hardware_advanced_blendInfo(SkBlendMode::kOverlay),
739 make_hardware_advanced_blendInfo(SkBlendMode::kDarken),
740 make_hardware_advanced_blendInfo(SkBlendMode::kLighten),
741 make_hardware_advanced_blendInfo(SkBlendMode::kColorDodge),
742 make_hardware_advanced_blendInfo(SkBlendMode::kColorBurn),
743 make_hardware_advanced_blendInfo(SkBlendMode::kHardLight),
744 make_hardware_advanced_blendInfo(SkBlendMode::kSoftLight),
745 make_hardware_advanced_blendInfo(SkBlendMode::kDifference),
746 make_hardware_advanced_blendInfo(SkBlendMode::kExclusion),
747 make_hardware_advanced_blendInfo(SkBlendMode::kMultiply),
748 make_hardware_advanced_blendInfo(SkBlendMode::kHue),
749 make_hardware_advanced_blendInfo(SkBlendMode::kSaturation),
750 make_hardware_advanced_blendInfo(SkBlendMode::kColor),
751 make_hardware_advanced_blendInfo(SkBlendMode::kLuminosity)
752 };
753
754 } // anonymous namespace
755
756 struct ShaderInfo::SharedGeneratorData {
757 SharedGeneratorData(const Caps* caps,
758 const ShaderCodeDictionary* dict,
759 SkArenaAlloc* alloc,
760 const RenderStep* step,
761 UniquePaintParamsID paintID,
762 const char* uniformSsboIndex)
763 : fRootNodes(SkSpan<const ShaderNode*>())
764 , fHasStepUniforms(step->numUniforms() > 0) {
765
766 // Decompress Root Nodes & Determine Local Coords
767 if (paintID.isValid()) {
768 PaintParamsKey key = dict->lookup(paintID);
769 SkASSERT(key.isValid());
770
771 constexpr int kFixedVaryings = 2;
772 const int availableVaryings =
773 caps->maxVaryings() - kFixedVaryings - step->varyings().size();
774
775 fRootNodes = key.getRootNodes(caps, dict, alloc, availableVaryings);
776
777 fNeedsLocalCoords = !fRootNodes.empty() &&
778 SkToBool(fRootNodes[0]->requiredFlags() &
779 SnippetRequirementFlags::kLocalCoords);
780 } else {
781 fNeedsLocalCoords = false;
782 }
783
784 // Lift Expressions & Check Uniforms
785 bool vsHasLiftedPaintUniforms = false;
786 fLiftedExpr = collect_lifted_expressions(fRootNodes);
787 for (const auto& expr : fLiftedExpr) {
788 if (!expr.fNode->entry()->fUniforms.empty()) {
789 vsHasLiftedPaintUniforms = true;
790 break;
791 }
792 }
793
794 bool needsCombinedBufferVS = fHasStepUniforms || vsHasLiftedPaintUniforms;
795 fUseUniformStorageBufferVS = caps->storageBufferSupport() && needsCombinedBufferVS;
796 fUseUniformStorageBufferFS = caps->storageBufferSupport() && step->performsShading();
797 bool useUniformStorageBuffer = fUseUniformStorageBufferVS || fUseUniformStorageBufferFS;
798
799 // Emit Preamble
800 int numPaintUniforms = 0;
801 int numUnliftedPaintUniforms = 0;
802 bool wrotePaintColor = false;
803 SkSpan<const Uniform> allStepUniforms = step->uniforms();
804 const ResourceBindingRequirements& bindingReqs = caps->resourceBindingRequirements();
805
806 if (useUniformStorageBuffer) {
807 fSharedPreamble = emit_combined_storage_buffer(
808 bindingReqs.fUniformsSetIdx,
809 bindingReqs.fCombinedUniformBufferBinding,
810 fRootNodes,
811 allStepUniforms,
812 &numPaintUniforms,
813 &numUnliftedPaintUniforms,
814 &wrotePaintColor);
815 } else {
816 fSharedPreamble = emit_combined_uniforms(
817 bindingReqs.fUniformsSetIdx,
818 bindingReqs.fCombinedUniformBufferBinding,
819 bindingReqs.fUniformBufferLayout,
820 fRootNodes,
821 allStepUniforms,
822 &numPaintUniforms,
823 &numUnliftedPaintUniforms,
824 &wrotePaintColor);
825 }
826
827 // Calculate Final Flags
828 fHasPaintUniforms = numPaintUniforms > 0;
829 fHasLiftedPaintUniforms = (numPaintUniforms - numUnliftedPaintUniforms) > 0;
830 bool hasUnliftedPaintUniforms = numUnliftedPaintUniforms > 0;
831
832 fHasSsboIndexVarying = useUniformStorageBuffer &&
833 (hasUnliftedPaintUniforms ||
834 (fHasStepUniforms && step->usesUniformsInFragmentSkSL()));
835
836 // Append SSBO Index to preamble if required
837 if (useUniformStorageBuffer && uniformSsboIndex) {
838 SkSL::String::appendf(&fSharedPreamble, "uint %s;\n", uniformSsboIndex);
839 }
840 }
841
842 // The decompressed shader tree
843 SkSpan<const ShaderNode*> fRootNodes;
844
845 // The expressions lifted from the shader tree
846 // Changed from const& to value to allow ownership
847 std::vector<LiftedExpression> fLiftedExpr;
848
849 // The base SkSL preamble (uniforms, varyings) shared by both stages
850 std::string fSharedPreamble;
851
852 // Shared calculated properties
853 bool fNeedsLocalCoords;
854 bool fHasSsboIndexVarying;
855 bool fHasStepUniforms;
856 bool fHasPaintUniforms;
857 bool fHasLiftedPaintUniforms;
858
859 // Buffer usage flags needed by generators
860 bool fUseUniformStorageBufferVS;
861 bool fUseUniformStorageBufferFS;
862 };
863
864 std::unique_ptr<ShaderInfo> ShaderInfo::Make(const Caps* caps,
865 const ShaderCodeDictionary* dict,
866 const RuntimeEffectDictionary* rteDict,
867 const RenderPassDesc& rpDesc,
868 const RenderStep* step,
869 UniquePaintParamsID paintID,
870 skia_private::TArray<SamplerDesc>* outDescs) {
871 // Determine if an SSBO index is needed at all (by either stage)
872 bool needsSsboIndex =
873 caps->storageBufferSupport() && (step->performsShading() || step->numUniforms() > 0);
874 const char* uniformSsboIndex = needsSsboIndex ? "uniformSsboIndex" : nullptr;
875
876 const bool hasFragShader = paintID.isValid() && step->performsShading();
877
878 // Create the final ShaderInfo object.
879 auto result = std::unique_ptr<ShaderInfo>(new ShaderInfo(dict, rteDict, uniformSsboIndex,
880 hasFragShader ? rpDesc.fDstReadStrategy
881 : DstReadStrategy::kNoneRequired));
882
883 // This arena holds all the ShaderNodes. It must live for the duration of 'Make' so the
884 // rootNodes span is valid when passed to helpers.
885 SkArenaAlloc shaderNodeAlloc{256};
886 SharedGeneratorData sharedData(
887 caps, dict, &shaderNodeAlloc, step, paintID, result->uniformSsboIndex());
888 result->fHasCombinedUniforms = sharedData.fHasStepUniforms || sharedData.fHasPaintUniforms;
889
890 SkString paintLabel = dict->idToString(caps, paintID);
891 if (hasFragShader) {
892 result->generateFragmentSkSL(caps,
893 dict,
894 paintLabel.c_str(),
895 step,
896 paintID,
897 rpDesc.fColorAttachment.fFormat,
898 rpDesc.fWriteSwizzle,
899 outDescs,
900 sharedData);
901 } else {
902 result->fBlendInfo.fWritesColor = false;
903 }
904
905 result->generateVertexSkSL(caps, step, sharedData);
906 result->fVSLabel = step->name();
907 if (sharedData.fNeedsLocalCoords) {
908 result->fVSLabel += " (w/ local coords)";
909 }
910
911 result->fFSLabel = step->name();
912 result->fFSLabel += " + ";
913 result->fFSLabel += paintLabel.c_str();
914 if (rpDesc.fWriteSwizzle != Swizzle::RGBA() ||
915 result->fDstReadStrategy != DstReadStrategy::kNoneRequired) {
916 result->fFSLabel += "(";
917 result->fFSLabel += rpDesc.fWriteSwizzle.asString().c_str();
918 if (result->fDstReadStrategy != DstReadStrategy::kNoneRequired) {
919 result->fFSLabel += ", ";
920 result->fFSLabel += dst_read_strategy_to_str(result->fDstReadStrategy);
921 }
922 result->fFSLabel += ")";
923 }
924
925 // KEEP IN SYNC with ContextUtils::GetPipelineLabel()
926 result->fPipelineLabel = rpDesc.toPipelineLabel().c_str();
927 result->fPipelineLabel += " + ";
928 result->fPipelineLabel += step->name();
929 result->fPipelineLabel += " + ";
930 result->fPipelineLabel += paintLabel.c_str();
931
932 return result;
933 }
934
935 ShaderInfo::ShaderInfo(const ShaderCodeDictionary* shaderCodeDictionary,
936 const RuntimeEffectDictionary* rteDict,
937 const char* uniformSsboIndex,
938 DstReadStrategy dstReadStrategy)
939 : fShaderCodeDictionary(shaderCodeDictionary)
940 , fRuntimeEffectDictionary(rteDict)
941 , fUniformSsboIndex(uniformSsboIndex)
942 , fDstReadStrategy(dstReadStrategy) {}
943
944 // The current, incomplete, model for shader construction is:
945 // - Static code snippets (which can have an arbitrary signature) live in the Graphite
946 // pre-compiled module, which is located at `src/sksl/sksl_graphite_frag.sksl`.
947 // - Glue code is generated in a `main` method which calls these static code snippets.
948 // The glue code is responsible for:
949 // 1) gathering the correct (mangled) uniforms
950 // 2) passing the uniforms and any other parameters to the helper method
951 // - The result of the final code snippet is then copied into "sk_FragColor".
952 // Note: each entry's 'fStaticFunctionName' field is expected to match the name of a function
953 // in the Graphite pre-compiled module, or be null if the preamble and expression generators are
954 // overridden to not use a static function.
955 void ShaderInfo::generateFragmentSkSL(const Caps* caps,
956 const ShaderCodeDictionary* dict,
957 const char* label,
958 const RenderStep* step,
959 UniquePaintParamsID paintID,
960 TextureFormat targetFormat,
961 Swizzle writeSwizzle,
962 skia_private::TArray<SamplerDesc>* outDescs,
963 const SharedGeneratorData& sharedData) {
964 #if defined(SK_DEBUG)
965 // Validate the root node structure of the key.
966 SkASSERT(sharedData.fRootNodes.size() == 2 || sharedData.fRootNodes.size() == 3);
967 // First node produces the source color (all snippets return a half4), so we just require that
968 // its signature takes no extra args or just local coords.
969 const ShaderSnippet* srcSnippet = dict->getEntry(sharedData.fRootNodes[0]->codeSnippetId());
970 SkASSERT(!srcSnippet->needsBlenderDstColor());
971 // TODO(b/349997190): Once SkEmptyShader doesn't use the passthrough snippet, we can assert
972 // that srcSnippet->needsPriorStageOutput() is false.
973 SkASSERT(!srcSnippet->needsBlenderDstColor());
974 // Second node is the final blender, so it must take both the src color and dst color, and not
975 // any local coordinate.
976 const ShaderSnippet* blendSnippet = dict->getEntry(sharedData.fRootNodes[1]->codeSnippetId());
977 SkASSERT(blendSnippet->needsPriorStageOutput() && blendSnippet->needsBlenderDstColor());
978 SkASSERT(!blendSnippet->needsLocalCoords());
979 // Optional third node is the clip
980 const ShaderSnippet* clipSnippet = sharedData.fRootNodes.size() > 2 ?
981 dict->getEntry(sharedData.fRootNodes[2]->codeSnippetId()) : nullptr;
982 SkASSERT(!clipSnippet ||
983 (!clipSnippet->needsPriorStageOutput() && !clipSnippet->needsBlenderDstColor()));
984 #endif
985
986 // Check for unexpected corruption / illegal instructions occurring in the wild.
987 SkASSERTF_RELEASE(sharedData.fRootNodes.size() == 2 || sharedData.fRootNodes.size() == 3,
988 "root node size = %zu, label = %s", sharedData.fRootNodes.size(), label);
989
990 // Extract the root nodes for clarity
991 const ShaderNode* const srcColorRoot = sharedData.fRootNodes[0];
992 const ShaderNode* const finalBlendRoot = sharedData.fRootNodes[1];
993 const int32_t finalBlendRootSnippetId = finalBlendRoot->codeSnippetId();
994 const ShaderNode* const clipRoot =
995 sharedData.fRootNodes.size() > 2 ? sharedData.fRootNodes[2] : nullptr;
996
997 // Determine the algorithm for final blending: direct HW blending, coverage-modified HW
998 // blending (w/ or w/o dual-source blending) or via dst-read requirement.
999 Coverage finalCoverage = step->coverage();
1000 if (finalCoverage == Coverage::kNone && SkToBool(clipRoot)) {
1001 finalCoverage = Coverage::kSingleChannel;
1002 }
1003
1004 // Initialize the final blend mode to the final snippet's blend mode. It may be changed based
1005 // upon whether or not we can use hardware blending.
1006 std::optional<SkBlendMode> finalBlendMode;
1007 if (finalBlendRootSnippetId < kBuiltInCodeSnippetIDCount &&
1008 finalBlendRootSnippetId >= kFixedBlendIDOffset) {
1009 finalBlendMode = static_cast<SkBlendMode>(finalBlendRootSnippetId - kFixedBlendIDOffset);
1010 }
1011 if (finalBlendMode.has_value() &&
1012 CanUseHardwareBlending(caps, targetFormat, *finalBlendMode, finalCoverage)) {
1013 // If we can use hardware blending, update the dstReadStrategy to be kNoneRequired to ensure
1014 // that ShaderInfo properly informs PipelineInfo of the pipeline's dst read requirement.
1015 fDstReadStrategy = DstReadStrategy::kNoneRequired;
1016 } else {
1017 // If we cannot use hardware blending, then we must perform a dst read within the shader.
1018 // Therefore we should assert that a valid strategy to do so was passed in. Later operations
1019 // also expect the blend mode to be kSrc, so update that here.
1020 SkASSERT(fDstReadStrategy != DstReadStrategy::kNoneRequired);
1021 finalBlendMode = SkBlendMode::kSrc;
1022 }
1023
1024 auto allReqFlags = srcColorRoot->requiredFlags() | finalBlendRoot->requiredFlags();
1025 if (clipRoot) {
1026 allReqFlags |= clipRoot->requiredFlags();
1027 }
1028
1029 std::string fsPreamble;
1030 const ResourceBindingRequirements& bindingReqs = caps->resourceBindingRequirements();
1031 fsPreamble += emit_intrinsic_constants(bindingReqs);
1032 fsPreamble += emit_varyings(step, "in",
1033 sharedData.fLiftedExpr,
1034 sharedData.fHasSsboIndexVarying,
1035 sharedData.fNeedsLocalCoords);
1036
1037 if (fDstReadStrategy == DstReadStrategy::kReadFromInput) {
1038 // If this shader reads the dst texture as an input attachment, assert that a valid set
1039 // index has been assigned within ResourceBindingRequirements.
1040 SkASSERT(bindingReqs.fInputAttachmentSetIdx != ResourceBindingRequirements::kUnassigned);
1041 // TODO: The following SkSL depends upon the fact that Vulkan is currently the only backend
1042 // that utilizes DstReadStrategy::kReadFromInput. Update accordingly if other backends add
1043 // support for this DstReadStrategy.
1044 SkSL::String::appendf(
1045 &fsPreamble,
1046 "layout (vulkan, input_attachment_index=%d, set=%d, binding=%d) "
1047 "subpassInput DstTextureInput;\n",
1048 /*input attachment idx within set=*/0,
1049 /*input attachment set idx=*/bindingReqs.fInputAttachmentSetIdx,
1050 /*binding=*/0);
1051 }
1052
1053 bool useGradientBuffer = caps->gradientBufferSupport() &&
1054 (allReqFlags & SnippetRequirementFlags::kGradientBuffer);
1055 if (useGradientBuffer) {
1056 SkSL::String::appendf(&fsPreamble,
1057 "layout (set=%d, binding=%d) readonly buffer FSGradientBuffer {\n"
1058 " float %s[];\n"
1059 "};\n",
1060 bindingReqs.fUniformsSetIdx,
1061 bindingReqs.fGradientBufferBinding,
1062 ShaderInfo::kGradientBufferName);
1063 fHasGradientBuffer = true;
1064 }
1065
1066 const bool useDstSampler = fDstReadStrategy == DstReadStrategy::kTextureCopy ||
1067 fDstReadStrategy == DstReadStrategy::kTextureSample;
1068 {
1069 int binding = 0;
1070 fsPreamble += emit_textures_and_samplers(bindingReqs, sharedData.fRootNodes, &binding,
1071 outDescs);
1072 int paintTextureCount = binding;
1073 if (step->hasTextures()) {
1074 fsPreamble += step->texturesAndSamplersSkSL(bindingReqs, &binding);
1075 if (outDescs) {
1076 // Determine how many render step samplers were used by comparing the binding value
1077 // against paintTextureCount, taking into account the binding requirements. We
1078 // assume and do not anticipate the render steps to use immutable samplers.
1079 int renderStepSamplerCount = bindingReqs.fSeparateTextureAndSamplerBinding
1080 ? (binding - paintTextureCount) / 2
1081 : binding - paintTextureCount;
1082 // Add default SamplerDescs for all the dynamic samplers used by the render step so
1083 // the size of outDescs will be equivalent to the total number of samplers.
1084 outDescs->push_back_n(renderStepSamplerCount);
1085 }
1086 }
1087 if (useDstSampler) {
1088 fsPreamble += EmitSamplerLayout(bindingReqs, &binding);
1089 fsPreamble += " sampler2D dstSampler;";
1090 // Add default SamplerDesc for the intrinsic dstSampler to stay consistent with
1091 // `fNumFragmentTexturesAndSamplers`.
1092 if (outDescs) {
1093 outDescs->push_back({});
1094 }
1095 }
1096
1097 // Record how many textures and samplers are used.
1098 fNumFragmentTexturesAndSamplers = binding;
1099 }
1100
1101 // Emit preamble declarations and helper functions required for snippets. In the default case
1102 // this adds functions that bind a node's specific mangled uniforms to the snippet's
1103 // implementation in the SkSL modules.
1104 emit_preambles(*this, sharedData.fRootNodes, /*treeLabel=*/"", &fsPreamble);
1105
1106 std::string mainBody = "void main() {";
1107
1108 if (sharedData.fHasSsboIndexVarying) {
1109 SkSL::String::appendf(&mainBody,
1110 "%s = %s;\n",
1111 this->uniformSsboIndex(),
1112 RenderStep::ssboIndexVarying());
1113 }
1114
1115 if (step->emitsPrimitiveColor()) {
1116 mainBody += "half4 primitiveColor;";
1117 mainBody += step->fragmentColorSkSL();
1118 } else {
1119 SkASSERT(!(sharedData.fRootNodes[0]->requiredFlags() &
1120 SnippetRequirementFlags::kPrimitiveColor));
1121 }
1122
1123 // Using kDefaultArgs as the initial value means it will refer to undefined variables, but the
1124 // root nodes should--at most--be depending on the coordinate when "needsLocalCoords" is true.
1125 // If the PaintParamsKey violates that structure, this will produce SkSL compile errors.
1126 ShaderSnippet::Args args = ShaderSnippet::kDefaultArgs;
1127 args.fFragCoord = "localCoordsVar"; // the varying added in emit_varyings()
1128 // TODO(b/349997190): The paint root node should not depend on any prior stage's output, but
1129 // it can happen with how SkEmptyShader is currently mapped to `sk_passthrough`. In this case
1130 // it requires that prior stage color to be transparent black. When SkEmptyShader can instead
1131 // cause the draw to be skipped, this can go away.
1132 args.fPriorStageOutput = "half4(0)";
1133
1134 // Calculate the src color and stash its output variable in `args`
1135 args.fPriorStageOutput = srcColorRoot->invokeAndAssign(*this, args, &mainBody);
1136
1137 // If not using hardware blending, we perform a dst read in the shader and must add SkSL
1138 // accordingly.
1139 if (fDstReadStrategy != DstReadStrategy::kNoneRequired) {
1140 // Get the current dst color into a local variable, it may be used later on for coverage
1141 // blending as well as the final blend.
1142 mainBody += "half4 dstColor;";
1143 if (useDstSampler) {
1144 // dstReadBounds is in frag coords and already includes the replay translation. The
1145 // reciprocol of the dstCopy dimensions are in ZW.
1146 mainBody += "dstColor = sample(dstSampler,"
1147 "dstReadBounds.zw*(sk_FragCoord.xy - dstReadBounds.xy));";
1148 } else if (fDstReadStrategy == DstReadStrategy::kReadFromInput) {
1149 // The dst texture should have been written to with the appropriate write swizzle, so we
1150 // do not need to worry about the read swizzle when accessing that value for blending.
1151 mainBody += "// Read color from input attachment\n";
1152 mainBody += "dstColor = subpassLoad(DstTextureInput);\n";
1153 } else {
1154 SkASSERT(fDstReadStrategy == DstReadStrategy::kFramebufferFetch);
1155 mainBody += "dstColor = sk_LastFragColor;";
1156 }
1157
1158 args.fBlenderDstColor = "dstColor";
1159 args.fPriorStageOutput = finalBlendRoot->invokeAndAssign(*this, args, &mainBody);
1160 }
1161
1162 if (writeSwizzle != Swizzle::RGBA()) {
1163 SkSL::String::appendf(&mainBody, "%s = %s.%s;", args.fPriorStageOutput.c_str(),
1164 args.fPriorStageOutput.c_str(),
1165 writeSwizzle.asString().c_str());
1166 }
1167
1168 if (finalCoverage == Coverage::kNone) {
1169 // Either direct HW blending or a dst-read w/o any extra coverage. In both cases we just
1170 // need to assign directly to sk_FragCoord and update the HW blend info to finalBlendMode.
1171 SkASSERT(finalBlendMode.has_value());
1172 fBlendInfo = gBlendTable[static_cast<int>(*finalBlendMode)];
1173 SkSL::String::appendf(&mainBody, "sk_FragColor = %s;", args.fPriorStageOutput.c_str());
1174 } else {
1175 // Accumulate the output coverage. This will either modify the src color and secondary
1176 // outputs for dual-source blending, or be combined directly with the in-shader blended
1177 // final color if a dst-readback was required.
1178
1179 if (sharedData.fUseUniformStorageBufferFS && sharedData.fHasStepUniforms) {
1180 mainBody +=
1181 emit_uniforms_from_storage_buffer(this->uniformSsboIndex(), step->uniforms());
1182 }
1183
1184 mainBody += "half4 outputCoverage = half4(1);";
1185 if (step->coverage() != Coverage::kNone) {
1186 mainBody += step->fragmentCoverageSkSL();
1187 }
1188
1189 if (clipRoot) {
1190 // The clip block node is invoked with device coords, not local coords like the main
1191 // shading root node. However sk_FragCoord includes any replay translation and we
1192 // need to recover the original device coordinate.
1193 mainBody += "float2 devCoord = sk_FragCoord.xy - viewport.xy;";
1194 args.fFragCoord = "devCoord";
1195 std::string clipBlockOutput = clipRoot->invokeAndAssign(*this, args, &mainBody);
1196 SkSL::String::appendf(&mainBody, "outputCoverage *= %s.a;", clipBlockOutput.c_str());
1197 }
1198
1199 const char* outColor = args.fPriorStageOutput.c_str();
1200 if (fDstReadStrategy != DstReadStrategy::kNoneRequired) {
1201 // If this draw uses a non-coherent dst read, we want to keep the existing dst color (or
1202 // whatever has been previously drawn) when there's no coverage. This helps for batching
1203 // text draws that need to read from a dst copy for blends. However, this only helps the
1204 // case where the outer bounding boxes of each letter overlap and not two actual parts
1205 // of the text.
1206 if (useDstSampler) {
1207 // We don't think any shaders actually output negative coverage, but just as a
1208 // safety check for floating point precision errors, we compare with <= here. We
1209 // just check the RGB values of the coverage, since the alpha may not have been set
1210 // when using LCD. If we are using single-channel coverage, alpha will be equal to
1211 // RGB anyway.
1212 mainBody +=
1213 "if (all(lessThanEqual(outputCoverage.rgb, half3(0)))) {"
1214 "discard;"
1215 "}";
1216 }
1217
1218 // Use kSrc HW BlendInfo and do the coverage blend with dst in the shader.
1219 SkASSERT(finalBlendMode.has_value() && finalBlendMode.value() == SkBlendMode::kSrc);
1220 fBlendInfo = gBlendTable[static_cast<int>(*finalBlendMode)];
1221 SkSL::String::appendf(
1222 &mainBody,
1223 "sk_FragColor = %s * outputCoverage + dstColor * (1.0 - outputCoverage);",
1224 outColor);
1225 if (finalCoverage == Coverage::kLCD) {
1226 SkSL::String::appendf(
1227 &mainBody,
1228 "half3 lerpRGB = mix(dstColor.aaa, %s.aaa, outputCoverage.rgb);"
1229 "sk_FragColor.a = max(max(lerpRGB.r, lerpRGB.g), lerpRGB.b);",
1230 outColor);
1231 }
1232 } else {
1233 // Adjust the shader output(s) to incorporate the coverage so that HW blending produces
1234 // the correct output.
1235 if (finalBlendMode > SkBlendMode::kLastCoeffMode) {
1236 SkASSERT(finalCoverage == Coverage::kSingleChannel);
1237 fBlendInfo = gBlendTable[static_cast<int>(*finalBlendMode)];
1238 mainBody += emit_advanced_blend_color_output("sk_FragColor", outColor);
1239 } else {
1240 // Porter-Duff blend modes can utilize BlendFormula.
1241 // TODO: Determine whether draw is opaque and pass that to GetBlendFormula.
1242 BlendFormula coverageBlendFormula =
1243 finalCoverage == Coverage::kLCD
1244 ? skgpu::GetLCDBlendFormula(*finalBlendMode)
1245 : skgpu::GetBlendFormula(
1246 /*isOpaque=*/false, /*hasCoverage=*/true, *finalBlendMode);
1247 fBlendInfo = {coverageBlendFormula.equation(),
1248 coverageBlendFormula.srcCoeff(),
1249 coverageBlendFormula.dstCoeff(),
1250 SK_PMColor4fTRANSPARENT,
1251 coverageBlendFormula.modifiesDst()};
1252
1253 if (finalCoverage == Coverage::kLCD) {
1254 mainBody += "outputCoverage.a = max(max(outputCoverage.r, "
1255 "outputCoverage.g), "
1256 "outputCoverage.b);";
1257 }
1258
1259 mainBody += emit_color_output(coverageBlendFormula.primaryOutput(),
1260 "sk_FragColor",
1261 outColor);
1262 if (coverageBlendFormula.hasSecondaryOutput()) {
1263 SkASSERT(caps->shaderCaps()->fDualSourceBlendingSupport);
1264 mainBody += emit_color_output(coverageBlendFormula.secondaryOutput(),
1265 "sk_SecondaryFragColor",
1266 outColor);
1267 }
1268 }
1269 }
1270 }
1271 mainBody += "}\n";
1272
1273 SkASSERT(fFragmentSkSL.empty());
1274 fFragmentSkSL.reserve(
1275 sharedData.fSharedPreamble.size() + fsPreamble.size() + mainBody.size() +2);
1276 fFragmentSkSL = sharedData.fSharedPreamble;
1277 fFragmentSkSL += "\n";
1278 fFragmentSkSL += fsPreamble;
1279 fFragmentSkSL += "\n";
1280 fFragmentSkSL += mainBody;
1281 }
1282
1283 void ShaderInfo::generateVertexSkSL(const Caps* caps,
1284 const RenderStep* step,
1285 const SharedGeneratorData& sharedData) {
1286 std::string vsPreamble;
1287 // Fixed program header (intrinsics are always declared as an uniform interface block)
1288 const ResourceBindingRequirements& bindingReqs = caps->resourceBindingRequirements();
1289 vsPreamble = emit_intrinsic_constants(bindingReqs);
1290 // Varyings needed by RenderStep and potentially lifted expressions
1291 vsPreamble += emit_varyings(step, "out",
1292 sharedData.fLiftedExpr,
1293 sharedData.fHasSsboIndexVarying,
1294 sharedData.fNeedsLocalCoords);
1295
1296 // Add vertex attributes
1297 if (step->numStaticAttributes() > 0 || step->numAppendAttributes() > 0) {
1298 int attr = 0;
1299 auto add_attrs = [&vsPreamble, &attr](SkSpan<const Attribute> attrs) {
1300 for (auto a : attrs) {
1301 SkSL::String::appendf(&vsPreamble, " layout(location=%d) in ", attr++);
1302 vsPreamble.append(SkSLTypeString(a.gpuType()));
1303 SkSL::String::appendf(&vsPreamble, " %s;\n", a.name());
1304 }
1305 };
1306 if (step->numStaticAttributes() > 0) {
1307 #if defined(SK_DEBUG)
1308 vsPreamble.append("// static attrs\n");
1309 #endif
1310 add_attrs(step->staticAttributes());
1311 }
1312 if (step->numAppendAttributes() > 0) {
1313 #if defined(SK_DEBUG)
1314 vsPreamble.append("// append attrs\n");
1315 #endif
1316 add_attrs(step->appendAttributes());
1317 }
1318 }
1319
1320 // Vertex shader function declaration
1321 std::string mainBody = "void main() {";
1322 // Create stepLocalCoords which render steps can write to.
1323 mainBody += "float2 stepLocalCoords = float2(0);";
1324
1325 // We define the SSBO index variable immediately if the VS is using storage buffers. This covers
1326 // both the "Step Uniforms" case and the "Lifted Uniforms Only" case.
1327 if (sharedData.fUseUniformStorageBufferVS) {
1328 SkSL::String::appendf(&mainBody, "uint %s = %s;\n", this->uniformSsboIndex(),
1329 RenderStep::ssboIndexAttribute());
1330 if (sharedData.fHasStepUniforms) {
1331 mainBody +=
1332 emit_uniforms_from_storage_buffer(this->uniformSsboIndex(), step->uniforms());
1333 }
1334 }
1335
1336 // Inject RenderStep's main vertex logic
1337 mainBody += step->vertexSkSL();
1338
1339 // Calculate sk_Position
1340 mainBody +=
1341 "sk_Position = float4(viewport.zw*devPosition.xy - sign(viewport.zw)*devPosition.ww,"
1342 "devPosition.zw);";
1343
1344 // Assign local coords to varying if needed
1345 if (sharedData.fNeedsLocalCoords) {
1346 mainBody += "localCoordsVar = stepLocalCoords;";
1347 }
1348
1349 // Generate lifted expressions
1350 if (!sharedData.fLiftedExpr.empty()) {
1351 for (const LiftedExpression& expr : sharedData.fLiftedExpr) {
1352 const ShaderNode* node = expr.fNode;
1353 // Determine the SkSL type string if not emitting directly to a varying
1354 const char* typeStr = expr.fEmitVarying
1355 ? ""
1356 : SkSLTypeString(sksl_type_for_lifted_expression(
1357 node->entry()->fLiftableExpressionType));
1358 const std::string varName = node->getExpressionVaryingName();
1359
1360 // Generate the expression code, potentially extracting uniforms from SSBO if needed
1361 std::string expression;
1362 expression = node->entry()->fLiftableExpressionGenerator(*this, node, expr.fArgs);
1363
1364 // Assign the expression result to the varying or a temporary variable
1365 SkSL::String::appendf(
1366 &mainBody, "%s %s = %s;", typeStr, varName.c_str(), expression.c_str());
1367 }
1368 }
1369
1370 // Assign SSBO index to varying if needed
1371 if (sharedData.fHasSsboIndexVarying) {
1372 if (sharedData.fUseUniformStorageBufferVS) {
1373 // Use the local variable we already defined
1374 SkSL::String::appendf(&mainBody,
1375 "%s = %s;",
1376 RenderStep::ssboIndexVarying(),
1377 this->uniformSsboIndex());
1378 } else {
1379 // No local variable, read directly from attribute
1380 SkSL::String::appendf(&mainBody,
1381 "%s = %s;",
1382 RenderStep::ssboIndexVarying(),
1383 RenderStep::ssboIndexAttribute());
1384 }
1385 }
1386
1387 mainBody += "}"; // End main()
1388
1389 SkASSERT(fVertexSkSL.empty());
1390 fVertexSkSL.reserve(
1391 sharedData.fSharedPreamble.size() + vsPreamble.size() + mainBody.size() + 2);
1392 fVertexSkSL = sharedData.fSharedPreamble;
1393 fVertexSkSL += "\n";
1394 fVertexSkSL += vsPreamble;
1395 fVertexSkSL += "\n";
1396 fVertexSkSL += mainBody;
1397 }
1398
1399 } // namespace skgpu::graphite