Debian Codegraph @

Sources/nCine/Graphics/RHI/GXM/GxmShaderProgram.h

raw
1 #pragma once
2
3 #include "GxmShaderTypes.h"
4 #include "GxmVertexFormat.h"
5 #include "../RhiTypes.h"
6
7 #include <cstdint>
8 #include <string>
9
10 #include <Containers/ArrayView.h>
11 #include <Containers/SmallVector.h>
12 #include <Containers/String.h>
13 #include <Containers/StringView.h>
14
15 #include <psp2/gxm.h>
16
17 using namespace Death::Containers;
18
19 namespace ShaderCompiler
20 {
21 struct ProgramVariant;
22 }
23
24 namespace nCine::RHI::GXM
25 {
26 class GxmShaderUniforms;
27 class GxmShaderUniformBlocks;
28 class GxmBufferObject;
29
30 /**
31 @brief One reflected sceGxm program parameter the draw path writes a uniform into
32
33 `ResourceIndex` is where the value goes: sceGxm addresses a default uniform buffer in 32-bit
34 components, so the bytes land at `ResourceIndex * 4`. That this is the whole story was confirmed on
35 the console - a sprite's block members come back at component 32, 48, 52, 56 and 58, which times four
36 are byte offsets 128, 192, 208, 224 and 232, i.e. exactly the engine's std140 offsets 0, 64, 80, 96
37 and 104 relative to the first. Resolving the parameters once at link time keeps
38 `sceGxmProgramFindParameterByName()` - a linear scan over the program's parameter table - off the
39 per-draw path.
40 */
41 struct GxmUniformSlot
42 {
43 const char* Name; // the reflection's own string, which outlives the program
44 std::uint32_t ResourceIndex; // component offset within the stage's default uniform buffer
45 std::uint32_t ByteSize; // bytes to copy (from the engine-side reflection, not the shader)
46 };
47
48 /**
49 @brief One vertex attribute the compiled stage declares, as the shader itself reports it
50
51 The offline reflection cannot supply this list. It describes the *modern GLSL* source, where the
52 sprite shaders take no vertex input at all and synthesize the quad corner from `gl_VertexID` - while
53 the Cg lowering has no vertex-ID input and reads `aQuadCorner` / `aInstanceIndex` instead, attributes
54 that @ref ShaderCompiler::VertexIdRewrite invents and the reflection has never heard of. Asking the
55 compiled program is therefore the only way to know a sprite shader has vertex inputs at all; the
56 OpenGL|ES 2.0 profile does the same thing with `glGetAttribLocation()` for the same reason.
57
58 `Name` points into the compiled program's own string table (past any `<struct>.` qualifier), which
59 lives as long as the GXP binary this program owns.
60 */
61 struct GxmStageAttribute
62 {
63 const char* Name;
64 std::uint16_t RegIndex; // what SceGxmVertexAttribute::regIndex takes
65 std::uint8_t ComponentCount; // as the shader declares it, before the stream layout narrows it
66 };
67
68 /**
69 @brief Shader program of the sceGxm backend (aliased as `RHI::ShaderProgram`)
70
71 Carries the offline ShaderCompiler reflection (set with @ref SetReflection() like the OpenGL backend)
72 from which it imports uniforms, uniform blocks and attributes, and gets its two stage *sources* from
73 the identity @ref SetProgramIdentity() plumbs in - the generated `CgGeneratedShaders.h` table, which
74 the Cg emitter fills offline. The sources are Cg, so they are compiled **on the console** by
75 SceShaccCg (through vitaShaRK's `shark_compile_shader()`) when the program links: sceGxm consumes
76 GXP binaries and the SDK ships no offline compiler for them, so `libshacccg.suprx` from the console's
77 own firmware is a hard requirement of this backend - @ref GxmDevice::CreateSwapchain() says so
78 explicitly if it is missing.
79
80 Linking then registers both stages with the shader patcher and reflects their parameters into the
81 @ref GxmUniformSlot tables the draw path uploads through. The two *patched* programs sceGxm actually
82 binds are created on demand and cached, because neither is a property of the shader alone:
83
84 - a vertex program bakes in the vertex layout, so there is one per @ref GxmVertexFormat the pipeline
85 binds (usually exactly one),
86 - a fragment program bakes in the blend state, so there is one per blend configuration the material
87 sorting produces (a handful: opaque, alpha-blended, additive, ...).
88 */
89 class GxmShaderProgram
90 {
91 friend class GxmShaderUniforms;
92 friend class GxmShaderUniformBlocks;
93
94 public:
95 enum class Introspection
96 {
97 Enabled,
98 NoUniformsInBlocks,
99 Disabled
100 };
101
102 enum class Status
103 {
104 NotLinked,
105 CompilationFailed,
106 LinkingFailed,
107 Linked,
108 LinkedWithDeferredQueries,
109 LinkedWithIntrospection
110 };
111
112 enum class QueryPhase
113 {
114 Immediate,
115 Deferred
116 };
117
118 /** @brief Default batch size, indicating the shader is not batched */
119 static constexpr std::int32_t DefaultBatchSize = -1;
120
121 GxmShaderProgram();
122 explicit GxmShaderProgram(QueryPhase queryPhase);
123 GxmShaderProgram(StringView vertexFile, StringView fragmentFile, Introspection introspection, QueryPhase queryPhase);
124 GxmShaderProgram(StringView vertexFile, StringView fragmentFile, Introspection introspection);
125 GxmShaderProgram(StringView vertexFile, StringView fragmentFile);
126 ~GxmShaderProgram();
127
128 GxmShaderProgram(const GxmShaderProgram&) = delete;
129 GxmShaderProgram& operator=(const GxmShaderProgram&) = delete;
130
131 /** @brief Returns a backend-neutral identifier uniquely identifying the program (feeds material sort keys) */
132 inline std::uint32_t GetUniqueId() const {
133 return _handle;
134 }
135 inline Status GetStatus() const {
136 return _status;
137 }
138 inline Introspection GetIntrospection() const {
139 return _introspection;
140 }
141 inline QueryPhase GetQueryPhase() const {
142 return _queryPhase;
143 }
144 inline std::uint32_t GetBatchSize() const {
145 return _batchSize;
146 }
147 inline void SetBatchSize(std::uint32_t value) {
148 _batchSize = value;
149 }
150
151 bool IsLinked() const;
152
153 std::uint32_t RetrieveInfoLogLength() const {
154 return 0;
155 }
156 void RetrieveInfoLog(std::string& infoLog) const {
157 static_cast<void>(infoLog);
158 }
159
160 inline std::uint32_t GetUniformsSize() const {
161 return _uniformsSize;
162 }
163 inline std::uint32_t GetUniformBlocksSize() const {
164 return _uniformBlocksSize;
165 }
166
167 bool AttachShaderFromFile(ShaderStage stage, StringView filename);
168 bool AttachShaderFromString(ShaderStage stage, StringView string);
169 bool AttachShaderFromStrings(ShaderStage stage, ArrayView<const StringView> strings);
170 bool AttachShaderFromStringsAndFile(ShaderStage stage, ArrayView<const StringView> strings, StringView filename);
171
172 /** @brief Sets the offline reflection consumed by @ref Link() to import uniforms/blocks/attributes */
173 inline void SetReflection(const ShaderCompiler::ProgramVariant* reflection) {
174 _reflection = reflection;
175 }
176 /**
177 @brief Records the true (program, variant) identity of the loaded shader
178
179 This backend resolves its generated Cg stage sources from this identity, the same way the
180 fixed-function console backends resolve their generated effect tables from it.
181 */
182 inline void SetProgramIdentity(const char* programName, const char* variantName) {
183 _programName = programName;
184 _variantName = variantName;
185 }
186 /** @brief Returns the generated program's name, or `nullptr` for one that carries no identity */
187 inline const char* GetProgramName() const {
188 return _programName;
189 }
190
191 bool Link(Introspection introspection);
192 void Use();
193 bool Validate() {
194 return true;
195 }
196 bool FinalizeAfterLinking(Introspection introspection);
197
198 inline std::uint32_t GetAttributeCount() const {
199 return std::uint32_t(_attributes.size());
200 }
201 bool HasAttribute(const char* name) const;
202 /** @brief Returns `true` if the reflection declares @p name with an integer type (a batch element index) */
203 bool IsIntegerAttribute(const char* name) const;
204 GxmVertexFormat::Attribute* GetAttribute(const char* name);
205
206 inline void DefineVertexFormat(const GxmBufferObject* vbo) {
207 DefineVertexFormat(vbo, nullptr, 0);
208 }
209 inline void DefineVertexFormat(const GxmBufferObject* vbo, const GxmBufferObject* ibo) {
210 DefineVertexFormat(vbo, ibo, 0);
211 }
212 void DefineVertexFormat(const GxmBufferObject* vbo, const GxmBufferObject* ibo, std::uint32_t vboOffset);
213
214 void Reset();
215 void SetObjectLabel(StringView label);
216
217 inline bool GetLogOnErrors() const {
218 return _shouldLogOnErrors;
219 }
220 inline void SetLogOnErrors(bool shouldLogOnErrors) {
221 _shouldLogOnErrors = shouldLogOnErrors;
222 }
223
224 // -- Backend extensions (used by the uniform caches and the device draw path) --
225
226 /** @brief Publishes a committed loose-uniform value pointer for the device to upload */
227 void SetResolvedUniform(const char* name, const std::uint8_t* data);
228 /** @brief Returns the last published value pointer of the named loose uniform, or `nullptr` */
229 const std::uint8_t* ResolveUniform(const char* name) const;
230
231 /** @brief Returns the compiled vertex stage, or `nullptr` if the program did not link */
232 inline const SceGxmProgram* GetVertexStage() const {
233 return _vertexStage;
234 }
235 /** @brief Returns the compiled fragment stage, or `nullptr` */
236 inline const SceGxmProgram* GetFragmentStage() const {
237 return _fragmentStage;
238 }
239 /** @brief Returns/creates the patched vertex program for the currently bound vertex format, or `nullptr` */
240 SceGxmVertexProgram* GetVertexProgram();
241 /**
242 @brief Returns/creates the patched fragment program for a blend configuration, or `nullptr`
243
244 @param blendKey Packed blend state from @ref PackBlendKey(), the cache's key
245 @param blendInfo The blend state to bake in, or `nullptr` for opaque (blending disabled)
246 */
247 SceGxmFragmentProgram* GetFragmentProgram(std::uint32_t blendKey, const SceGxmBlendInfo* blendInfo);
248
249 /** @brief Returns the byte size of the vertex stage's default uniform buffer */
250 inline std::uint32_t GetVertexUniformBufferSize() const {
251 return _vertexUniformBufferSize;
252 }
253 /** @brief Returns the byte size of the fragment stage's default uniform buffer */
254 inline std::uint32_t GetFragmentUniformBufferSize() const {
255 return _fragmentUniformBufferSize;
256 }
257
258 /** @brief Loose-uniform slots of the vertex stage (resolved once at link time) */
259 inline const SmallVector<GxmUniformSlot, 0>& GetVertexUniformSlots() const {
260 return _vertexUniformSlots;
261 }
262 /** @brief Loose-uniform slots of the fragment stage */
263 inline const SmallVector<GxmUniformSlot, 0>& GetFragmentUniformSlots() const {
264 return _fragmentUniformSlots;
265 }
266
267 /**
268 @brief Where one uniform block's bytes go in a stage's default uniform buffer
269
270 The Cg dialect has no counterpart to a std140 block - its emitter hoists each block member to a
271 top-level `uniform` - so a block is uploaded member by member. Both layouts place an
272 array-of-structs element on a 16-byte boundary and pack its fields the same way, so the member's
273 bytes go across verbatim out of the range the pipeline bound, without being repacked.
274
275 A **batched** block does not go through the default uniform buffer at all. Its instance array is
276 tens of kilobytes, far past what the SGX's uniform registers hold, so the compiler places it in a
277 *uniform buffer container* - reported as `SCE_GXM_PARAMETER_CATEGORY_UNIFORM_BUFFER` - which is
278 bound by address rather than written into. That is why the pipeline's uniform buffers are
279 GPU-visible memory (see @ref GxmBufferObject): the range the batcher filled is handed to sceGxm as
280 a pointer, with no copy at all. Mistaking this case for the copied one is invisible at load time
281 and costs every batched draw its instance data - sprites, text and tile layers all at once.
282 */
283 struct GxmBlockUpload
284 {
285 /** @brief How the member reaches the shader */
286 enum class Destination
287 {
288 DefaultUniformBuffer, //!< copied into the draw's reserved default uniform buffer
289 UniformBufferContainer //!< bound by address with sceGxmSet{Vertex,Fragment}UniformBuffer()
290 };
291
292 Destination Where;
293 std::uint32_t BindingIndex; // uniform binding point the pipeline bound the range to
294 std::uint32_t SourceOffset; // byte offset of the member within that range
295 std::uint32_t Index; // component offset in the default buffer, or the container's buffer index
296 std::uint32_t MaxByteSize; // bytes the engine's block layout declares (an upper bound on a copy)
297 const char* Name; // the reflection's member name, for diagnostics
298 // Element strides of a batched instance array, on the engine's side and in the compiled shader; both
299 // zero for anything else. They differ whenever the shader's Instance struct is not the widest one -
300 // BatchedLighting's has no palOffset, so the compiler packs its element into less than the std140
301 // stride the pipeline writes - and then only element zero of a copied-as-one array lands where the
302 // shader reads it, with every later element progressively further out
303 std::uint32_t SourceStride;
304 std::uint32_t CompiledStride;
305 };
306
307 /** @brief Uniform-block member uploads of the vertex stage */
308 inline const SmallVector<GxmBlockUpload, 0>& GetVertexBlockUploads() const {
309 return _vertexBlockUploads;
310 }
311 /** @brief Uniform-block member uploads of the fragment stage */
312 inline const SmallVector<GxmBlockUpload, 0>& GetFragmentBlockUploads() const {
313 return _fragmentBlockUploads;
314 }
315
316 /**
317 @brief Where one of a stage's samplers takes its texture from
318
319 The two indices are not the same thing: `EngineUnit` is the texture unit the pipeline binds a
320 texture to (the reflection's assignment, which the material sets), while `TextureIndex` is the
321 sceGxm texture slot the compiled shader reads it from.
322 */
323 struct GxmSamplerSlot
324 {
325 const char* Name;
326 std::uint32_t EngineUnit;
327 std::uint32_t TextureIndex;
328 };
329
330 /** @brief Sampler slots of the vertex stage (rare, but sceGxm allows vertex texturing) */
331 inline const SmallVector<GxmSamplerSlot, 0>& GetVertexSamplerSlots() const {
332 return _vertexSamplerSlots;
333 }
334 /** @brief Sampler slots of the fragment stage */
335 inline const SmallVector<GxmSamplerSlot, 0>& GetFragmentSamplerSlots() const {
336 return _fragmentSamplerSlots;
337 }
338
339 /** @brief Returns `true` if the vertex stage reads any vertex attribute */
340 inline bool HasVertexAttributes() const {
341 return !_stageAttributes.empty();
342 }
343 /** @brief Returns the vertex attributes the compiled stage declares (see @ref GxmStageAttribute) */
344 inline const SmallVector<GxmStageAttribute, 4>& GetStageAttributes() const {
345 return _stageAttributes;
346 }
347 /** @brief Returns the vertex buffer bound by @ref DefineVertexFormat(), or `nullptr` */
348 inline const GxmBufferObject* GetBoundVbo() const {
349 return _boundVbo;
350 }
351 /** @brief Returns the index buffer bound by @ref DefineVertexFormat(), or `nullptr` */
352 inline const GxmBufferObject* GetBoundIbo() const {
353 return _boundIbo;
354 }
355 /** @brief Returns the byte offset into the bound vertex buffer the attributes start at */
356 inline std::uint32_t GetVboOffset() const {
357 return _vboOffset;
358 }
359 /** @brief Returns `true` if the vertex layout takes its corner (and instance index) from a device static stream */
360 inline bool UsesStaticCornerStream() const {
361 return _usesCornerStream;
362 }
363 /** @brief Returns `true` if the static stream is the batched one (six vertices per sprite, with an instance index) */
364 inline bool UsesBatchedCornerStream() const {
365 return _usesBatchedStream;
366 }
367 /** @brief Returns `true` if the vertex layout reads any attribute out of the pipeline's vertex buffer */
368 inline bool UsesGeometryStream() const {
369 return _usesGeometryStream;
370 }
371 /** @brief Returns the sceGxm stream index the static corner stream is bound to (0 when there is no geometry stream) */
372 inline std::uint32_t GetStaticStreamIndex() const {
373 return (_usesGeometryStream ? 1u : 0u);
374 }
375 /** @brief Returns the per-vertex byte stride of the geometry stream */
376 inline std::uint32_t GetGeometryStride() const {
377 return _geometryStride;
378 }
379
380 /** @brief Packs a blend configuration into the key @ref GetFragmentProgram() caches on */
381 static std::uint32_t PackBlendKey(bool enabled, nCine::BlendingFactor srcRgb, nCine::BlendingFactor dstRgb,
382 nCine::BlendingFactor srcAlpha, nCine::BlendingFactor dstAlpha);
383
384 /**
385 @brief Resolves a vertex attribute of a compiled stage by the name the engine knows it under
386
387 The reflected name of an attribute the entry point receives through an input struct is not
388 guaranteed to be the bare member name - a qualified `<struct>.<member>` form is equally plausible
389 and only the compiler decides - so an exact match is tried first and a match on the last
390 dot-separated component second. Returns `nullptr` and logs the stage's whole attribute list when
391 neither resolves, because a silently dropped attribute renders nothing and explains nothing.
392 */
393 static const SceGxmProgramParameter* FindAttribute(const SceGxmProgram* program, const char* name);
394
395 /**
396 @brief Resolves where a named block member lives in the compiled stage
397
398 Handles all three shapes a member can take: a uniform in the default buffer, a uniform buffer
399 container (the batched instance array), and an array of structs named only through its leaves.
400 @returns `false` if the stage has no uniform belonging to that name at all
401 */
402 static bool FindUniformBase(const SceGxmProgram* program, const char* name,
403 GxmBlockUpload::Destination& destination, std::uint32_t& index);
404
405 /**
406 @brief Routes SceShaccCg's diagnostics into the engine log
407
408 Called once before anything is compiled - including the device's own built-in shaders, which
409 otherwise fail with no explanation but the caller's own message.
410 */
411 static void InstallCompilerLogCallback();
412
413 /**
414 @brief Compiles one Cg stage on the console and returns a GXP binary the caller owns
415
416 This exists to contain a trap. `shark_compile_shader()` hands back a pointer *into* SceShaccCg's
417 compile output (`SceShaccCgCompileOutput::programData`), not a copy of it, and
418 `shark_clear_output()` releases that output through `sceShaccCgDestroyCompileOutput()` - so
419 clearing the output, as any tidy caller would, leaves the returned `SceGxmProgram*` dangling. The
420 symptom is not a crash at the free: the program reads back with **zero reflected parameters** and
421 faults later inside the shader patcher, which points at everything except the real cause. The
422 bytes are therefore copied out before the output is cleared, which is also what sceGxm requires -
423 a registered program's memory has to stay alive for as long as it is registered.
424
425 @param source Cg source, null-terminated
426 @param vertexStage `true` for a vertex stage, `false` for a fragment one
427 @param sizeInBytes Receives the size of the returned binary
428 @returns A GXP binary to release with `std::free()`, or `nullptr` if the compile failed
429 */
430 static SceGxmProgram* CompileCgStage(const char* source, bool vertexStage, std::uint32_t& sizeInBytes);
431
432 private:
433 static std::uint32_t _nextHandle;
434
435 std::uint32_t _handle;
436 Status _status;
437 Introspection _introspection;
438 QueryPhase _queryPhase;
439 std::uint32_t _batchSize;
440 bool _shouldLogOnErrors;
441 std::uint32_t _uniformsSize;
442 std::uint32_t _uniformBlocksSize;
443
444 SmallVector<GxmUniform, 0> _uniforms;
445 SmallVector<GxmUniformBlock, 0> _uniformBlocks;
446 SmallVector<GxmAttribute, 0> _attributes;
447 // What the compiled vertex stage declares, which is not the same set the reflection lists
448 SmallVector<GxmStageAttribute, 4> _stageAttributes;
449
450 const ShaderCompiler::ProgramVariant* _reflection;
451 const char* _programName;
452 const char* _variantName;
453
454 GxmVertexFormat _vertexFormat;
455 const GxmBufferObject* _boundVbo;
456 const GxmBufferObject* _boundIbo;
457 std::uint32_t _vboOffset;
458 bool _usesCornerStream;
459 bool _usesBatchedStream;
460 bool _usesGeometryStream;
461 std::uint32_t _geometryStride;
462
463 struct ResolvedUniform
464 {
465 String Name;
466 const std::uint8_t* Data;
467 };
468 SmallVector<ResolvedUniform, 0> _resolvedUniforms;
469
470 // Compiled stages (owned: allocated by vitaShaRK, released with free()) and their patcher registrations
471 SceGxmProgram* _vertexStage;
472 SceGxmProgram* _fragmentStage;
473 SceGxmShaderPatcherId _vertexStageId;
474 SceGxmShaderPatcherId _fragmentStageId;
475
476 std::uint32_t _vertexUniformBufferSize;
477 std::uint32_t _fragmentUniformBufferSize;
478 SmallVector<GxmUniformSlot, 0> _vertexUniformSlots;
479 SmallVector<GxmUniformSlot, 0> _fragmentUniformSlots;
480 SmallVector<GxmBlockUpload, 0> _vertexBlockUploads;
481 SmallVector<GxmBlockUpload, 0> _fragmentBlockUploads;
482 SmallVector<GxmSamplerSlot, 0> _vertexSamplerSlots;
483 SmallVector<GxmSamplerSlot, 0> _fragmentSamplerSlots;
484
485 // Patched programs, created on demand (see the class documentation)
486 struct CachedVertexProgram
487 {
488 std::uint64_t Fingerprint;
489 SceGxmVertexProgram* Program;
490 };
491 SmallVector<CachedVertexProgram, 2> _vertexPrograms;
492 struct CachedFragmentProgram
493 {
494 std::uint32_t BlendKey;
495 SceGxmFragmentProgram* Program;
496 };
497 SmallVector<CachedFragmentProgram, 4> _fragmentPrograms;
498
499 void PerformIntrospection();
500 /** @brief Fills @ref _stageAttributes from the compiled vertex stage's attribute parameters */
501 void ReflectStageAttributes();
502 void ImportReflection();
503 /** @brief Compiles the generated Cg sources of @ref _programName / @ref _variantName and registers them */
504 bool CompileStages();
505 /** @brief Resolves one stage's parameters into the uniform, block and sampler slot tables */
506 void ReflectStage(const SceGxmProgram* program, SmallVector<GxmUniformSlot, 0>& uniformSlots,
507 SmallVector<GxmBlockUpload, 0>& blockUploads, SmallVector<GxmSamplerSlot, 0>& samplerSlots);
508 /** @brief Releases the patched programs and the compiled stages */
509 void ReleaseGpu();
510 };
511 }