Debian Codegraph @

src/gpu/graphite/PaintParamsKey.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/PaintParamsKey.h"
9
10 #include "src/base/SkArenaAlloc.h"
11 #include "src/base/SkAutoMalloc.h"
12 #include "src/base/SkBase64.h"
13 #include "src/base/SkStringView.h"
14 #include "src/gpu/graphite/Caps.h"
15 #include "src/gpu/graphite/KeyHelpers.h"
16 #include "src/gpu/graphite/Log.h"
17 #include "src/gpu/graphite/ShaderCodeDictionary.h"
18
19 using namespace skia_private;
20
21 namespace skgpu::graphite {
22
23 //--------------------------------------------------------------------------------------------------
24 // PaintParamsKeyBuilder
25
26 #ifdef SK_DEBUG
27
28 void PaintParamsKeyBuilder::checkReset() {
29 SkASSERT(!fLocked);
30 SkASSERT(fData.empty());
31 SkASSERT(fStack.empty());
32 SkASSERT(!fHasError);
33 }
34
35 void PaintParamsKeyBuilder::pushStack(int32_t codeSnippetID) {
36 SkASSERT(fDict->isValidID(codeSnippetID));
37 // If the kError ID is pushed, fHasError must have been set already.
38 SkASSERT(codeSnippetID != (int) BuiltInCodeSnippetID::kError || fHasError);
39
40 if (!fStack.empty()) {
41 fStack.back().fNumActualChildren++;
42 SkASSERT(fStack.back().fNumActualChildren <= fStack.back().fNumExpectedChildren);
43 }
44
45 const ShaderSnippet* snippet = fDict->getEntry(codeSnippetID);
46 fStack.push_back({codeSnippetID, snippet->fNumChildren});
47 }
48
49 void PaintParamsKeyBuilder::validateData(size_t dataSize) {
50 SkASSERT(!fStack.empty()); // addData() called within code snippet block
51 // Check that addData() is only called for snippets that support it and is only called once
52 const ShaderSnippet* snippet = fDict->getEntry(fStack.back().fCodeSnippetID);
53 SkASSERT(snippet->storesSamplerDescData());
54 SkASSERT(fStack.back().fDataSize < 0);
55
56 fStack.back().fDataSize = SkTo<int>(dataSize);
57 }
58
59 void PaintParamsKeyBuilder::popStack() {
60 SkASSERT(!fStack.empty());
61 SkASSERT(fStack.back().fNumActualChildren == fStack.back().fNumExpectedChildren);
62 const bool expectsData = fDict->getEntry(fStack.back().fCodeSnippetID)->storesSamplerDescData();
63 const bool hasData = fStack.back().fDataSize >= 0;
64 SkASSERT(expectsData == hasData);
65 fStack.pop_back();
66 }
67
68 #endif // SK_DEBUG
69
70 //--------------------------------------------------------------------------------------------------
71 // PaintParamsKey
72
73 PaintParamsKey PaintParamsKey::clone(SkArenaAlloc* arena) const {
74 uint32_t* newData = arena->makeArrayDefault<uint32_t>(fData.size());
75 memcpy(newData, fData.data(), fData.size_bytes());
76 return PaintParamsKey({newData, fData.size()});
77 }
78
79 ShaderNode* PaintParamsKey::createNode(const ShaderCodeDictionary* dict,
80 int* currentIndex,
81 SkArenaAlloc* arena) const {
82 SkASSERT(*currentIndex < SkTo<int>(fData.size()));
83 const int32_t index = (*currentIndex)++;
84 const int32_t id = fData[index];
85
86 const ShaderSnippet* entry = dict->getEntry(id);
87 if (!entry) {
88 SKGPU_LOG_E("Unknown snippet ID in key: %d", id);
89 return nullptr;
90 }
91
92 SkSpan<const uint32_t> dataSpan = {};
93 if (entry->storesSamplerDescData()) {
94 // If a snippet stores data, then the subsequent paint key index signifies the length of
95 // its data. Determine this data length and iterate currentIndex past it.
96 const int storedDataLengthIdx = (*currentIndex)++;
97 SkASSERT(storedDataLengthIdx < SkTo<int>(fData.size()));
98 const int dataLength = fData[storedDataLengthIdx];
99 SkASSERT(storedDataLengthIdx + dataLength < SkTo<int>(fData.size()));
100
101 // Gather the data contents (length can now be inferred by the consumers of the data) to
102 // pass into ShaderNode creation. Iterate the paint key index past the data indices.
103 dataSpan = fData.subspan(storedDataLengthIdx + 1, dataLength);
104 *currentIndex += dataLength;
105 }
106
107 ShaderNode** childArray = arena->makeArray<ShaderNode*>(entry->fNumChildren);
108 for (int i = 0; i < entry->fNumChildren; ++i) {
109 ShaderNode* child = this->createNode(dict, currentIndex, arena);
110 if (!child) {
111 return nullptr;
112 }
113 childArray[i] = child;
114 }
115
116 return arena->make<ShaderNode>(entry,
117 SkSpan(childArray, entry->fNumChildren),
118 id,
119 index,
120 dataSpan);
121 }
122
123 // Traverse a ShaderNode tree, attempting to lift any coordinate modification expressions.
124 // Returns whether any of the given nodes need local coordinate inputs after lifting.
125 bool lift_coord_expressions(SkSpan<ShaderNode*> nodes, int* availableVaryings) {
126 bool anyNeedLocalCoords = false;
127
128 for (ShaderNode* node : nodes) {
129 bool curNeedsLocalCoords =
130 SkToBool(node->requiredFlags() & SnippetRequirementFlags::kLocalCoords);
131
132 // Lift expressions from nodes whose liftable expressions are on coordinate inputs.
133 if (*availableVaryings > 0 && curNeedsLocalCoords &&
134 node->entry()->fLiftableExpressionType ==
135 ShaderSnippet::LiftableExpressionType::kLocalCoords) {
136 --*availableVaryings;
137
138 #if !defined(SK_USE_LEGACY_UNIFORM_LIFTING_GRAPHITE)
139 // We can potentially lift the nested expressions under here as well.
140 const bool childNeedsOurCoords =
141 lift_coord_expressions(node->children(), availableVaryings);
142 // If no child needs our lifted coords, we can omit them from the fragment shader
143 // entirely, and only use them in the vertex shader for calculating other coords.
144 if (!childNeedsOurCoords) {
145 node->setOmitExpressionFlag();
146 } else {
147 node->setLiftExpressionFlag();
148 }
149 #else
150 node->setLiftExpressionFlag();
151 #endif
152 // Since we lifted the coordinate expression here, this node no longer needs a local
153 // coords argument.
154 curNeedsLocalCoords = false;
155 node->unsetLocalCoordsFlag();
156
157 #if !defined(SK_USE_LEGACY_UNIFORM_LIFTING_GRAPHITE)
158 // If the node passes through its local coords to its children, we check if those perform
159 // modifications that can be lifted.
160 } else if (*availableVaryings > 0 &&
161 node->requiredFlags() & SnippetRequirementFlags::kPassthroughLocalCoords) {
162 // Assume that this node doesn't need local coordinates unless its actual shader snippet
163 // entry does, or one of its children does even after accounting for lifting.
164 const bool entryNeedsLocalCoords = node->entry()->needsLocalCoords();
165 const bool childNeedsLocalCoords = lift_coord_expressions(node->children(),
166 availableVaryings);
167 curNeedsLocalCoords = entryNeedsLocalCoords || childNeedsLocalCoords;
168 if (!curNeedsLocalCoords) {
169 node->unsetLocalCoordsFlag();
170 }
171 #endif
172 }
173
174 anyNeedLocalCoords |= curNeedsLocalCoords;
175 }
176
177 return anyNeedLocalCoords;
178 }
179
180 // Traverse a list of ShaderNodes, attempting to lift any expressions that resolve to a color.
181 // For now, this does not recurse into ShaderNodes' lists of children. In practice we only lift
182 // solid color expressions, and we only care to lift such expressions if there is no other fragment
183 // shader work (i.e., if the solid color expression is a root node in a shader's ShaderNode tree).
184 // If there is other fragment shader work, we'll likely be accessing other fragment shader uniforms,
185 // the color value will likely be cached, and lifting may not be worth the extra varying.
186 void lift_color_expressions(SkSpan<ShaderNode*> nodes, int* availableVaryings) {
187 #if !defined(SK_USE_LEGACY_UNIFORM_LIFTING_GRAPHITE)
188 for (ShaderNode* node : nodes) {
189 if (*availableVaryings > 0 &&
190 node->entry()->fLiftableExpressionType ==
191 ShaderSnippet::LiftableExpressionType::kPriorStageOutput) {
192 --*availableVaryings;
193 node->setLiftExpressionFlag();
194 }
195 }
196 #endif
197 }
198
199 SkSpan<const ShaderNode*> PaintParamsKey::getRootNodes(const Caps* caps,
200 const ShaderCodeDictionary* dict,
201 SkArenaAlloc* arena,
202 int availableVaryings) const {
203 // TODO: Once the PaintParamsKey creation is organized to represent a single tree starting at
204 // the final blend, there will only be a single root node and this can be simplified.
205 // For now, we don't know how many roots there are, so collect them into a local array before
206 // copying into the arena.
207 const int keySize = SkTo<int>(fData.size());
208
209 // Normal PaintParams creation will have up to 7 roots for the different stages.
210 STArray<7, ShaderNode*> roots;
211 int currentIndex = 0;
212 while (currentIndex < keySize) {
213 ShaderNode* root = this->createNode(dict, &currentIndex, arena);
214 if (!root) {
215 return {}; // a bad key
216 }
217 roots.push_back(root);
218 }
219
220 // See what expressions we can lift to the vertex shader.
221 const bool hasClipNode = roots.size() > 2;
222 SkSpan<ShaderNode*> liftableNodes(roots.data(), hasClipNode ? 2 : roots.size());
223 lift_coord_expressions(liftableNodes, &availableVaryings);
224 // Don't lift constant expressions if we're using regular UBOs, since lifting is likely only
225 // beneficial if we're avoiding a storage buffer access.
226 if (caps->storageBufferSupport()) {
227 lift_color_expressions(liftableNodes, &availableVaryings);
228 }
229
230 // Copy the accumulated roots into a span stored in the arena
231 const ShaderNode** rootSpan = arena->makeArray<const ShaderNode*>(roots.size());
232 memcpy(rootSpan, roots.data(), roots.size_bytes());
233 return SkSpan(rootSpan, roots.size());
234 }
235
236 static void append_as_base64(SkString* str, SkSpan<const uint32_t> data) {
237 str->append("(");
238 str->appendU32(data.size());
239 str->append(": ");
240 // Encode data in base64 to shorten it
241 const size_t srcDataSize = data.size() * sizeof(uint32_t); // size in bytes
242 SkAutoMalloc encodedData{SkBase64::EncodedSize(srcDataSize)};
243 char* dst = static_cast<char*>(encodedData.get());
244 size_t encodedLen = SkBase64::Encode(data.data(), srcDataSize, dst);
245 str->append(dst, encodedLen);
246 str->append(")");
247 }
248
249 static int key_to_string(const Caps* caps,
250 SkString* str,
251 const ShaderCodeDictionary* dict,
252 SkSpan<const uint32_t> keyData,
253 int currentIndex,
254 int indent) {
255 SkASSERT(currentIndex < SkTo<int>(keyData.size()));
256
257 const bool multiline = indent >= 0;
258 if (multiline) {
259 // Format for multi-line printing
260 str->appendf("%*c", 2 * indent, ' ');
261 }
262
263 uint32_t id = keyData[currentIndex++];
264 auto entry = dict->getEntry(id);
265 if (!entry) {
266 str->append("UnknownCodeSnippetID:");
267 str->appendS32(id);
268 str->append(" ");
269 return currentIndex;
270 }
271
272 str->append(entry->fName);
273
274 if (entry->storesSamplerDescData()) {
275 SkASSERT(currentIndex + 1 < SkTo<int>(keyData.size()));
276
277 // If an entry stores data, then the next key value reports the quantity of key indices that
278 // are used to house the data for this snippet. This way, we know how many indices to
279 // iterate over in order to capture the snippet's data before we may encounter another
280 // snippet ID.
281 // For example:
282 // [snippetId using 2 indices worth of data] [2] [dataValue0] [dataValue1] [next snippet ID]
283 const size_t dataIndexCount = keyData[currentIndex++];
284 SkASSERT(currentIndex + dataIndexCount < keyData.size());
285
286 bool descriptiveFormAppended = false;
287 if (dataIndexCount == 0) {
288 // We shorten the string for the common case of no extra data.
289 str->append("(0)");
290 descriptiveFormAppended = true;
291 } else {
292 SkASSERTF(dataIndexCount == 2 || dataIndexCount == 3, "count %zu", dataIndexCount);
293
294 // Attempt to append the sampler data as human-readable YCbCr information
295 SamplerDesc s(keyData[currentIndex],
296 keyData[currentIndex+1],
297 /* extFormatMSB= */ dataIndexCount == 3 ? keyData[currentIndex+2] : 0);
298
299 if (s.isImmutable()) {
300 std::string tmp = caps->toString(s.immutableSamplerInfo());
301 if (!tmp.empty()) {
302 str->append("(");
303 str->append(tmp);
304 str->append(")");
305 descriptiveFormAppended = true;
306 }
307 }
308 }
309
310 if (!descriptiveFormAppended) {
311 append_as_base64(str, { &keyData[currentIndex], dataIndexCount });
312 }
313
314 // Increment current index past the indices which contain data
315 currentIndex += dataIndexCount;
316 }
317
318 if (entry->fNumChildren > 0) {
319 if (multiline) {
320 str->append(":\n");
321 indent++;
322 } else {
323 str->append(" [ ");
324 }
325
326 for (int i = 0; i < entry->fNumChildren; ++i) {
327 currentIndex = key_to_string(caps, str, dict, keyData, currentIndex, indent);
328 }
329
330 if (!multiline) {
331 str->append("]");
332 }
333 }
334
335 if (!multiline) {
336 str->append(" ");
337 } else if (entry->fNumChildren == 0) {
338 str->append("\n");
339 }
340 return currentIndex;
341 }
342
343 SkString PaintParamsKey::toString(const Caps* caps,
344 const ShaderCodeDictionary* dict) const {
345 SkString str;
346 const int keySize = SkTo<int>(fData.size());
347 for (int currentIndex = 0; currentIndex < keySize;) {
348 currentIndex = key_to_string(caps, &str, dict, fData, currentIndex, /*indent=*/-1);
349 }
350 return str.isEmpty() ? SkString("(empty)") : str;
351 }
352
353 #ifdef SK_DEBUG
354
355 void PaintParamsKey::dump(const Caps* caps,
356 const ShaderCodeDictionary* dict,
357 UniquePaintParamsID id) const {
358 const int keySize = SkTo<int>(fData.size());
359
360 SkDebugf("--------------------------------------\n");
361 SkDebugf("PaintParamsKey %u (keySize: %d): ", id.asUInt(), keySize);
362 const uint32_t* data = fData.data();
363 for (int i = 0; i < keySize; ++i) {
364 SkDebugf("%x ", data[i]);
365 }
366 SkDebugf("\n");
367
368 int currentIndex = 0;
369 while (currentIndex < keySize) {
370 SkString nodeStr;
371 currentIndex = key_to_string(caps, &nodeStr, dict, fData, currentIndex, /*indent=*/1);
372 SkDebugf("%s", nodeStr.c_str());
373 }
374 }
375
376 #endif // SK_DEBUG
377
378 namespace {
379
380 // check a single block and, recursively, all its children
381 [[nodiscard]] bool is_block_valid(const ShaderCodeDictionary* dict,
382 SkSpan<const uint32_t> keyData,
383 int* currentIndex) {
384 if (*currentIndex >= SkTo<int>(keyData.size())) {
385 return false;
386 }
387
388 uint32_t id = keyData[(*currentIndex)++];
389 if (id >= kBuiltInCodeSnippetIDCount &&
390 !SkKnownRuntimeEffects::IsSkiaKnownRuntimeEffect(id) &&
391 !dict->isUserDefinedKnownRuntimeEffect(id)) {
392 return false;
393 }
394
395 auto entry = dict->getEntry(id);
396 if (!entry) {
397 return false;
398 }
399
400 if (entry->storesSamplerDescData()) {
401 if (*currentIndex >= SkTo<int>(keyData.size())) {
402 return false;
403 }
404
405 const int dataLength = keyData[(*currentIndex)++];
406
407 if (*currentIndex + dataLength > SkTo<int>(keyData.size())) {
408 return false;
409 }
410
411 *currentIndex += dataLength;
412 }
413
414 if (entry->fNumChildren > 0) {
415 for (int i = 0; i < entry->fNumChildren; ++i) {
416 if (!is_block_valid(dict, keyData, currentIndex)) {
417 return false;
418 }
419 }
420 }
421
422 return true;
423 }
424
425 } // anonymous namespace
426
427
428 bool PaintParamsKey::isSerializable(const ShaderCodeDictionary* dict) const {
429 const int keySize = SkTo<int>(fData.size());
430
431 int currentIndex = 0;
432 while (currentIndex < keySize) {
433 if (!is_block_valid(dict, fData, &currentIndex)) {
434 return false;
435 }
436 }
437
438 return true;
439 }
440
441 } // namespace skgpu::graphite