Debian Codegraph @

include/effects/SkRuntimeEffect.h

raw ◀ ▶
1 Debian patch touch this file
1 /*
2 * Copyright 2019 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #ifndef SkRuntimeEffect_DEFINED
9 #define SkRuntimeEffect_DEFINED
10
11 #include "include/core/SkBlender.h" // IWYU pragma: keep
12 #include "include/core/SkColorFilter.h" // IWYU pragma: keep
13 #include "include/core/SkData.h"
14 #include "include/core/SkFlattenable.h"
15 #include "include/core/SkMatrix.h"
16 #include "include/core/SkRefCnt.h"
17 #include "include/core/SkShader.h"
18 #include "include/core/SkSpan.h"
19 #include "include/core/SkString.h"
20 #include "include/core/SkTypes.h"
21 #include "include/private/SkSLSampleUsage.h"
22 #include "include/private/base/SkOnce.h"
23 #include "include/private/base/SkTemplates.h"
24 #include "include/private/base/SkTo.h"
25 #include "include/private/base/SkTypeTraits.h"
26 #include "include/sksl/SkSLDebugTrace.h"
27 #include "include/sksl/SkSLVersion.h"
28
29 #include <cstddef>
30 #include <cstdint>
31 #include <cstring>
32 #include <memory>
33 #include <optional>
34 #include <string>
35 #include <string_view>
36 #include <utility>
37 #include <vector>
38
39 struct SkIPoint;
40
41 namespace SkSL {
42 class DebugTracePriv;
43 class FunctionDefinition;
44 struct Program;
45 enum class ProgramKind : int8_t;
46 struct ProgramSettings;
47 } // namespace SkSL
48
49 namespace SkSL::RP {
50 class Program;
51 }
52
53 /*
54 * SkRuntimeEffect supports creating custom SkShader and SkColorFilter objects using Skia's SkSL
55 * shading language.
56 *
57 * NOTE: This API is experimental and subject to change.
58 */
59 class SK_API SkRuntimeEffect : public SkRefCnt {
60 public:
61 // Reflected description of a uniform variable in the effect's SkSL
62 struct SK_API Uniform {
63 enum class Type {
64 kFloat,
65 kFloat2,
66 kFloat3,
67 kFloat4,
68 kFloat2x2,
69 kFloat3x3,
70 kFloat4x4,
71 kInt,
72 kInt2,
73 kInt3,
74 kInt4,
75 };
76
77 enum Flags {
78 // Uniform is declared as an array. 'count' contains array length.
79 kArray_Flag = 0x1,
80
81 // Uniform is declared with layout(color). Colors should be supplied as unpremultiplied,
82 // extended-range (unclamped) sRGB (ie SkColor4f). The uniform will be automatically
83 // transformed to unpremultiplied extended-range working-space colors.
84 kColor_Flag = 0x2,
85
86 // When used with SkMeshSpecification, indicates that the uniform is present in the
87 // vertex shader. Not used with SkRuntimeEffect.
88 kVertex_Flag = 0x4,
89
90 // When used with SkMeshSpecification, indicates that the uniform is present in the
91 // fragment shader. Not used with SkRuntimeEffect.
92 kFragment_Flag = 0x8,
93
94 // This flag indicates that the SkSL uniform uses a medium-precision type
95 // (i.e., `half` instead of `float`).
96 kHalfPrecision_Flag = 0x10,
97 };
98
99 std::string_view name;
100 size_t offset;
101 Type type;
102 int count;
103 uint32_t flags;
104
105 bool isArray() const { return SkToBool(this->flags & kArray_Flag); }
106 bool isColor() const { return SkToBool(this->flags & kColor_Flag); }
107 size_t sizeInBytes() const;
108 };
109
110 // Reflected description of a uniform child (shader or colorFilter) in the effect's SkSL
111 enum class ChildType {
112 kShader,
113 kColorFilter,
114 kBlender,
115 };
116
117 struct Child {
118 std::string_view name;
119 ChildType type;
120 int index;
121 };
122
123 class Options {
124 public:
125 // For testing purposes, disables optimization and inlining. (Normally, Runtime Effects
126 // don't run the inliner directly, but they still get an inlining pass once they are
127 // painted.)
128 bool forceUnoptimized = false;
129 // When possible this name will be used to identify the created runtime effect.
130 std::string_view fName;
131
132 private:
133 friend class SkRuntimeEffect;
134 friend class SkRuntimeEffectPriv;
135
136 // This flag allows Runtime Effects to access Skia implementation details like sk_FragCoord
137 // and functions with private identifiers (e.g. $rgb_to_hsl).
138 bool allowPrivateAccess = false;
139 // When not 0, this field allows Skia to assign a stable key to a known runtime effect
140 uint32_t fStableKey = 0;
141
142 // TODO(skbug.com/40042585) - Replace this with a promised SkCapabilities?
143 // This flag lifts the ES2 restrictions on Runtime Effects that are gated by the
144 // `strictES2Mode` check. Be aware that the software renderer and pipeline-stage effect are
145 // still largely ES3-unaware and can still fail or crash if post-ES2 features are used.
146 // This is only intended for use by tests and certain internally created effects.
147 SkSL::Version maxVersionAllowed = SkSL::Version::k100;
148 };
149
150 // If the effect is compiled successfully, `effect` will be non-null.
151 // Otherwise, `errorText` will contain the reason for failure.
152 struct Result {
153 sk_sp<SkRuntimeEffect> effect;
154 SkString errorText;
155 };
156
157 // MakeForColorFilter and MakeForShader verify that the SkSL code is valid for those stages of
158 // the Skia pipeline. In all of the signatures described below, color parameters and return
159 // values are flexible. They are listed as being 'vec4', but they can also be 'half4' or
160 // 'float4'. ('vec4' is an alias for 'float4').
161
162 // We can't use a default argument for `options` due to a bug in Clang.
163 // https://bugs.llvm.org/show_bug.cgi?id=36684
164
165 // Color filter SkSL requires an entry point that looks like:
166 // vec4 main(vec4 inColor) { ... }
167 // https://fiddle.skia.org/c/@runtimeeffect_colorfilter_grid
168 static Result MakeForColorFilter(SkString sksl, const Options&);
169 static Result MakeForColorFilter(SkString sksl) {
170 return MakeForColorFilter(std::move(sksl), Options{});
171 }
172
173 // Shader SkSL requires an entry point that looks like:
174 // vec4 main(vec2 inCoords) { ... }
175 // The color that is returned should be premultiplied.
176 static Result MakeForShader(SkString sksl, const Options&);
177 static Result MakeForShader(SkString sksl) {
178 return MakeForShader(std::move(sksl), Options{});
179 }
180
181 // Blend SkSL requires an entry point that looks like:
182 // vec4 main(vec4 srcColor, vec4 dstColor) { ... }
183 static Result MakeForBlender(SkString sksl, const Options&);
184 static Result MakeForBlender(SkString sksl) {
185 return MakeForBlender(std::move(sksl), Options{});
186 }
187
188 // Object that allows passing a SkShader, SkColorFilter or SkBlender as a child
189 class SK_API ChildPtr {
190 public:
191 ChildPtr() = default;
192 // Intentionally don't declare these to be explicit for convenience.
193 ChildPtr(sk_sp<SkShader> s) : fChild(std::move(s)) {}
194 ChildPtr(sk_sp<SkColorFilter> cf) : fChild(std::move(cf)) {}
195 ChildPtr(sk_sp<SkBlender> b) : fChild(std::move(b)) {}
196
197 // Asserts that the flattenable is either null, or one of the legal derived types
198 ChildPtr(sk_sp<SkFlattenable> f);
199
200 std::optional<ChildType> type() const;
201
202 SkShader* shader() const;
203 SkColorFilter* colorFilter() const;
204 SkBlender* blender() const;
205 SkFlattenable* flattenable() const { return fChild.get(); }
206
207 using sk_is_trivially_relocatable = std::true_type;
208
209 private:
210 sk_sp<SkFlattenable> fChild;
211
212 static_assert(::sk_is_trivially_relocatable<decltype(fChild)>::value);
213 };
214
215 sk_sp<SkShader> makeShader(sk_sp<const SkData> uniforms,
216 sk_sp<SkShader> children[],
217 size_t childCount,
218 const SkMatrix* localMatrix = nullptr) const;
219 sk_sp<SkShader> makeShader(sk_sp<const SkData> uniforms,
220 SkSpan<const ChildPtr> children,
221 const SkMatrix* localMatrix = nullptr) const;
222
223 sk_sp<SkColorFilter> makeColorFilter(sk_sp<const SkData> uniforms) const;
224 sk_sp<SkColorFilter> makeColorFilter(sk_sp<const SkData> uniforms,
225 sk_sp<SkColorFilter> children[],
226 size_t childCount) const;
227 sk_sp<SkColorFilter> makeColorFilter(sk_sp<const SkData> uniforms,
228 SkSpan<const ChildPtr> children) const;
229
230 sk_sp<SkBlender> makeBlender(sk_sp<const SkData> uniforms,
231 SkSpan<const ChildPtr> children = {}) const;
232
233 /**
234 * Creates a new Runtime Effect patterned after an already-existing one. The new shader behaves
235 * like the original, but also creates a debug trace of its execution at the requested
236 * coordinate. After painting with this shader, the associated DebugTrace object will contain a
237 * shader execution trace. Call `writeTrace` on the debug trace object to generate a full trace
238 * suitable for a debugger, or call `dump` to emit a human-readable trace.
239 *
240 * Debug traces are only supported on a raster (non-GPU) canvas.
241
242 * Debug traces are currently only supported on shaders. Color filter and blender tracing is a
243 * work-in-progress.
244 */
245 struct TracedShader {
246 sk_sp<SkShader> shader;
247 sk_sp<SkSL::DebugTrace> debugTrace;
248 };
249 static TracedShader MakeTraced(sk_sp<SkShader> shader, const SkIPoint& traceCoord);
250
251 // Returns the SkSL source of the runtime effect shader.
252 const std::string& source() const;
253
254 // Combined size of all 'uniform' variables. When calling makeColorFilter or makeShader,
255 // provide an SkData of this size, containing values for all of those variables.
256 size_t uniformSize() const;
257
258 SkSpan<const Uniform> uniforms() const { return SkSpan(fUniforms); }
259 SkSpan<const Child> children() const { return SkSpan(fChildren); }
260
261 // Returns pointer to the named uniform variable's description, or nullptr if not found
262 const Uniform* findUniform(std::string_view name) const;
263
264 // Returns pointer to the named child's description, or nullptr if not found
265 const Child* findChild(std::string_view name) const;
266
267 // Allows the runtime effect type to be identified.
268 bool allowShader() const { return (fFlags & kAllowShader_Flag); }
269 bool allowColorFilter() const { return (fFlags & kAllowColorFilter_Flag); }
270 bool allowBlender() const { return (fFlags & kAllowBlender_Flag); }
271
272 static void RegisterFlattenables();
273 ~SkRuntimeEffect() override;
274
275 private:
276 enum Flags {
277 kUsesSampleCoords_Flag = 0x001,
278 kAllowColorFilter_Flag = 0x002,
279 kAllowShader_Flag = 0x004,
280 kAllowBlender_Flag = 0x008,
281 kSamplesOutsideMain_Flag = 0x010,
282 kUsesColorTransform_Flag = 0x020,
283 kAlwaysOpaque_Flag = 0x040,
284 kAlphaUnchanged_Flag = 0x080,
285 kDisableOptimization_Flag = 0x100,
286 };
287
288 SkRuntimeEffect(std::unique_ptr<SkSL::Program> baseProgram,
289 const Options& options,
290 const SkSL::FunctionDefinition& main,
291 std::vector<Uniform>&& uniforms,
292 std::vector<Child>&& children,
293 std::vector<SkSL::SampleUsage>&& sampleUsages,
294 uint32_t flags);
295
296 sk_sp<SkRuntimeEffect> makeUnoptimizedClone();
297
298 static Result MakeFromSource(SkString sksl, const Options& options, SkSL::ProgramKind kind);
299
300 static Result MakeInternal(std::unique_ptr<SkSL::Program> program,
301 const Options& options,
302 SkSL::ProgramKind kind);
303
304 static SkSL::ProgramSettings MakeSettings(const Options& options);
305
306 uint32_t hash() const { return fHash; }
307 bool usesSampleCoords() const { return (fFlags & kUsesSampleCoords_Flag); }
308 bool samplesOutsideMain() const { return (fFlags & kSamplesOutsideMain_Flag); }
309 bool usesColorTransform() const { return (fFlags & kUsesColorTransform_Flag); }
310 bool alwaysOpaque() const { return (fFlags & kAlwaysOpaque_Flag); }
311 bool isAlphaUnchanged() const { return (fFlags & kAlphaUnchanged_Flag); }
312
313 const SkSL::RP::Program* getRPProgram(SkSL::DebugTracePriv* debugTrace) const;
314
315 friend class GrSkSLFP; // usesColorTransform
316 friend class SkRuntimeShader; // fBaseProgram, fMain, fSampleUsages, getRPProgram()
317 friend class SkRuntimeBlender; //
318 friend class SkRuntimeColorFilter; //
319
320 friend class SkRuntimeEffectPriv;
321
322 uint32_t fHash;
323 // When not 0, this field holds a StableKey value or a user-defined stable key
324 uint32_t fStableKey = 0;
325 SkString fName;
326
•327 std::unique_ptr<const SkSL::Program> fBaseProgram;
328 std::unique_ptr<const SkSL::RP::Program> fRPProgram;
329 mutable SkOnce fCompileRPProgramOnce;
330 const SkSL::FunctionDefinition& fMain;
331 std::vector<Uniform> fUniforms;
332 std::vector<Child> fChildren;
333 std::vector<SkSL::SampleUsage> fSampleUsages;
334
335 uint32_t fFlags; // Flags
336 };
337
338 /**
339 * SkRuntimeEffectBuilder is a utility to simplify creating SkShader, SkColorFilter, and SkBlender
340 * objects from SkRuntimeEffects.
341 *
342 * NOTE: Like SkRuntimeEffect, this API is experimental and subject to change!
343 *
344 * Given an SkRuntimeEffect, the SkRuntimeEffectBuilder manages creating an input data block and
345 * provides named access to the 'uniform' variables in that block, as well as named access
346 * to a list of child shader slots. Usage:
347 *
348 * sk_sp<SkRuntimeEffect> effect = ...;
349 * SkRuntimeEffectBuilder builder(effect);
350 * builder.uniform("some_uniform_float") = 3.14f;
351 * builder.uniform("some_uniform_matrix") = SkM44::Rotate(...);
352 * builder.child("some_child_effect") = mySkImage->makeShader(...);
353 * ...
354 * sk_sp<SkShader> shader = builder.makeShader(nullptr, false);
355 *
356 * Upon calling makeShader, makeColorFilter, or makeBlender, the builder will check the validity
357 * of the SkSL to see if the entry point is correct.
358 *
359 * Note that SkRuntimeEffectBuilder is built entirely on the public API of SkRuntimeEffect,
360 * so can be used as-is or serve as inspiration for other interfaces or binding techniques.
361 */
362 class SK_API SkRuntimeEffectBuilder {
363 public:
364 explicit SkRuntimeEffectBuilder(sk_sp<SkRuntimeEffect> effect)
365 : fEffect(std::move(effect))
366 , fUniforms(SkData::MakeZeroInitialized(fEffect->uniformSize()))
367 , fChildren(fEffect->children().size()) {}
368 explicit SkRuntimeEffectBuilder(sk_sp<SkRuntimeEffect> effect, sk_sp<SkData> uniforms)
369 : fEffect(std::move(effect))
370 , fUniforms(std::move(uniforms))
371 , fChildren(fEffect->children().size()) {}
372
373 // This is currently required by Android Framework but may go away if that dependency
374 // can be removed.
375 SkRuntimeEffectBuilder(const SkRuntimeEffectBuilder&) = default;
376
377 struct BuilderUniform {
378 // Copy 'val' to this variable. No type conversion is performed - 'val' must be same
379 // size as expected by the effect. Information about the variable can be queried by
380 // looking at fVar. If the size is incorrect, no copy will be performed, and debug
381 // builds will abort. If this is the result of querying a missing variable, fVar will
382 // be nullptr, and assigning will also do nothing (and abort in debug builds).
383 template <typename T>
384 std::enable_if_t<std::is_trivially_copyable<T>::value, BuilderUniform&> operator=(
385 const T& val) {
386 if (!fVar) {
387 SkDEBUGFAIL("Assigning to missing variable");
388 } else if (sizeof(val) != fVar->sizeInBytes()) {
389 SkDEBUGFAIL("Incorrect value size");
390 } else {
391 memcpy(SkTAddOffset<void>(fOwner->writableUniformData(), fVar->offset),
392 &val, sizeof(val));
393 }
394 return *this;
395 }
396
397 BuilderUniform& operator=(const SkMatrix& val) {
398 if (!fVar) {
399 SkDEBUGFAIL("Assigning to missing variable");
400 } else if (fVar->sizeInBytes() != 9 * sizeof(float)) {
401 SkDEBUGFAIL("Incorrect value size");
402 } else {
403 float* data = SkTAddOffset<float>(fOwner->writableUniformData(),
404 (ptrdiff_t)fVar->offset);
405 data[0] = val.get(0); data[1] = val.get(3); data[2] = val.get(6);
406 data[3] = val.get(1); data[4] = val.get(4); data[5] = val.get(7);
407 data[6] = val.get(2); data[7] = val.get(5); data[8] = val.get(8);
408 }
409 return *this;
410 }
411
412 template <typename T>
413 bool set(const T val[], const int count) {
414 static_assert(std::is_trivially_copyable<T>::value, "Value must be trivial copyable");
415 if (!fVar) {
416 SkDEBUGFAIL("Assigning to missing variable");
417 return false;
418 } else if (sizeof(T) * count != fVar->sizeInBytes()) {
419 SkDEBUGFAIL("Incorrect value size");
420 return false;
421 } else {
422 memcpy(SkTAddOffset<void>(fOwner->writableUniformData(), fVar->offset),
423 val, sizeof(T) * count);
424 }
425 return true;
426 }
427
428 SkRuntimeEffectBuilder* fOwner;
429 const SkRuntimeEffect::Uniform* fVar; // nullptr if the variable was not found
430 };
431
432 struct BuilderChild {
433 template <typename T> BuilderChild& operator=(sk_sp<T> val) {
434 if (!fChild) {
435 SkDEBUGFAIL("Assigning to missing child");
436 } else {
437 fOwner->fChildren[(size_t)fChild->index] =
438 SkRuntimeEffect::ChildPtr(std::move(val));
439 }
440 return *this;
441 }
442
443 BuilderChild& operator=(std::nullptr_t) {
444 if (!fChild) {
445 SkDEBUGFAIL("Assigning to missing child");
446 } else {
447 fOwner->fChildren[(size_t)fChild->index] = SkRuntimeEffect::ChildPtr{};
448 }
449 return *this;
450 }
451
452 SkRuntimeEffectBuilder* fOwner;
453 const SkRuntimeEffect::Child* fChild; // nullptr if the child was not found
454 };
455
456 const SkRuntimeEffect* effect() const { return fEffect.get(); }
457
458 BuilderUniform uniform(std::string_view name) { return { this, fEffect->findUniform(name) }; }
459 BuilderChild child(std::string_view name) { return { this, fEffect->findChild(name) }; }
460
461 // Get access to the collated uniforms and children (in the order expected by APIs like
462 // makeShader on the effect):
463 sk_sp<const SkData> uniforms() const { return fUniforms; }
464 SkSpan<const SkRuntimeEffect::ChildPtr> children() const { return fChildren; }
465
466 // Build methods, at this point checks are made to ensure the SkSL entry point `main` is correct
467 sk_sp<SkShader> makeShader(const SkMatrix* localMatrix = nullptr) const;
468 sk_sp<SkColorFilter> makeColorFilter() const;
469 sk_sp<SkBlender> makeBlender() const;
470
471 ~SkRuntimeEffectBuilder() = default;
472
473 protected:
474 SkRuntimeEffectBuilder() = delete;
475
476 SkRuntimeEffectBuilder(SkRuntimeEffectBuilder&&) = default;
477
478 SkRuntimeEffectBuilder& operator=(SkRuntimeEffectBuilder&&) = delete;
479 SkRuntimeEffectBuilder& operator=(const SkRuntimeEffectBuilder&) = delete;
480
481 private:
482 void* writableUniformData() {
483 if (!fUniforms->unique()) {
484 fUniforms = SkData::MakeWithCopy(fUniforms->data(), fUniforms->size());
485 }
486 return fUniforms->writable_data();
487 }
488
489 sk_sp<SkRuntimeEffect> fEffect;
490 sk_sp<SkData> fUniforms;
491 std::vector<SkRuntimeEffect::ChildPtr> fChildren;
492
493 friend class SkRuntimeImageFilter;
494 };
495
496 /**
497 * DEPRECATED: Subclass logic has been moved to base class SkRuntimeEffectBuilder.
498 */
499 using SkRuntimeShaderBuilder = SkRuntimeEffectBuilder;
500 using SkRuntimeColorFilterBuilder = SkRuntimeEffectBuilder;
501 using SkRuntimeBlendBuilder = SkRuntimeEffectBuilder;
502
503 #endif // SkRuntimeEffect_DEFINED