Debian Codegraph @

Sources/nCine/Graphics/RHI/RSX/RsxShaderProgram.h

raw
1 #pragma once
2
3 #include "RsxShaderTypes.h"
4 #include "RsxVertexFormat.h"
5 #include "RsxVram.h"
6 #include "../RhiTypes.h"
7
8 #include <cstdint>
9 #include <string>
10
11 #include <Containers/ArrayView.h>
12 #include <Containers/SmallVector.h>
13 #include <Containers/String.h>
14 #include <Containers/StringView.h>
15
16 #include <rsx/rsx_program.h>
17
18 using namespace Death::Containers;
19
20 namespace ShaderCompiler
21 {
22 struct ProgramVariant;
23 }
24
25 namespace nCine::RHI::RSX
26 {
27 class RsxShaderUniforms;
28 class RsxShaderUniformBlocks;
29 class RsxBufferObject;
30
31 /**
32 @brief One reflected RSX program constant the draw path writes a uniform into
33
34 Resolving the constants once at link time keeps `rsxVertexProgramGetConst()` - a linear scan over the
35 program's name table, with a `strcmp` per entry - off the per-draw path.
36
37 `Param` is the microcode's own descriptor, which the `rsxSet*ProgramParameter()` commands take
38 directly; it points into the embedded program blob and so outlives this program. `ByteSize` comes
39 from the engine-side reflection rather than from the shader, because it is the size of the value the
40 pipeline will hand over, which is what bounds the copy.
41 */
42 struct RsxUniformSlot
43 {
44 const char* Name; // the reflection's own string, which outlives the program
45 const rsxProgramConst* Param; // the microcode's descriptor for this constant
46 std::uint32_t ByteSize; // bytes the engine-side reflection declares for the value
47 };
48
49 /**
50 @brief One vertex attribute the compiled stage declares, as the shader itself reports it
51
52 The offline reflection cannot supply this list. It describes the *modern GLSL* source, where the
53 sprite shaders take no vertex input at all and synthesize the quad corner from `gl_VertexID` - while
54 the Cg lowering has no vertex-ID input and reads `aQuadCorner` / `aInstanceIndex` instead, attributes
55 that @ref ShaderCompiler::VertexIdRewrite invents and the reflection has never heard of. Asking the
56 compiled program is therefore the only way to know a sprite shader has vertex inputs at all.
57
58 `Name` points into the compiled program's own string table, which lives in the executable's rodata.
59 */
60 struct RsxStageAttribute
61 {
62 const char* Name;
63 std::uint8_t RegIndex; // the attribute register `rsxBindVertexArrayAttrib()` takes
64 };
65
66 /**
67 @brief Shader program of the RSX backend (aliased as `RHI::ShaderProgram`)
68
69 Carries the offline ShaderCompiler reflection (set with @ref SetReflection() like the OpenGL backend)
70 from which it imports uniforms, uniform blocks and attributes, and gets its two stage *binaries* from
71 the identity @ref SetProgramIdentity() plumbs in - the generated `RsxGeneratedShaders.h` table.
72
73 **Everything about this class follows from there being no shader compiler on the console.** The Vita
74 backend this otherwise mirrors ships Cg source and compiles it at link time through SceShaccCg; the
75 PS3 has no such thing, so the same Cg is compiled to NV40 microcode offline by cgcomp and embedded as
76 a `rsxVertexProgram` / `rsxFragmentProgram` blob. Linking is therefore not a compile at all - it
77 looks the pair up, copies the fragment half where the hardware can fetch it, and resolves names.
78
79 A consequence worth stating plainly: a shader whose Cg exceeded what the `vp40`/`fp40` profiles can
80 express has no entry in that table, and @ref Link() fails for it at load time with a message naming
81 the variant. That is a **build-time** fact rather than a runtime one - it cannot change on the
82 console - so it is reported once and the program stays unlinked rather than being retried.
83
84 There is also far less caching here than the sceGxm backend needs. sceGxm bakes the vertex layout
85 into a patched vertex program and the blend state into a patched fragment program, so it keeps a
86 cache of each; the RSX takes both as ordinary state - attributes through
87 `rsxBindVertexArrayAttrib()` at draw time, blending through `rsxSetBlendFunc()` - so one program
88 object serves every layout and every blend configuration.
89
90 **Fragment constants are the one genuinely awkward part.** The RSX patches a fragment program's
91 constants *into its microcode* rather than into a register file, which is why
92 `rsxSetFragmentProgramParameter()` needs the microcode's address and location, and why each program
93 owns a private copy of its fragment microcode in local memory (@ref _fragmentUcode) rather than
94 pointing at the shared blob in the executable. Two programs sharing one blob would overwrite each
95 other's constants.
96 */
97 class RsxShaderProgram
98 {
99 friend class RsxShaderUniforms;
100 friend class RsxShaderUniformBlocks;
101
102 public:
103 enum class Introspection
104 {
105 Enabled,
106 NoUniformsInBlocks,
107 Disabled
108 };
109
110 enum class Status
111 {
112 NotLinked,
113 CompilationFailed,
114 LinkingFailed,
115 Linked,
116 LinkedWithDeferredQueries,
117 LinkedWithIntrospection
118 };
119
120 enum class QueryPhase
121 {
122 Immediate,
123 Deferred
124 };
125
126 /** @brief Default batch size, indicating the shader is not batched */
127 static constexpr std::int32_t DefaultBatchSize = -1;
128
129 RsxShaderProgram();
130 explicit RsxShaderProgram(QueryPhase queryPhase);
131 RsxShaderProgram(StringView vertexFile, StringView fragmentFile, Introspection introspection, QueryPhase queryPhase);
132 RsxShaderProgram(StringView vertexFile, StringView fragmentFile, Introspection introspection);
133 RsxShaderProgram(StringView vertexFile, StringView fragmentFile);
134 ~RsxShaderProgram();
135
136 RsxShaderProgram(const RsxShaderProgram&) = delete;
137 RsxShaderProgram& operator=(const RsxShaderProgram&) = delete;
138
139 /** @brief Returns a backend-neutral identifier uniquely identifying the program (feeds material sort keys) */
140 inline std::uint32_t GetUniqueId() const {
141 return _handle;
142 }
143 inline Status GetStatus() const {
144 return _status;
145 }
146 inline Introspection GetIntrospection() const {
147 return _introspection;
148 }
149 inline QueryPhase GetQueryPhase() const {
150 return _queryPhase;
151 }
152 inline std::uint32_t GetBatchSize() const {
153 return _batchSize;
154 }
155 inline void SetBatchSize(std::uint32_t value) {
156 _batchSize = value;
157 }
158
159 bool IsLinked() const;
160
161 std::uint32_t RetrieveInfoLogLength() const {
162 return 0;
163 }
164 void RetrieveInfoLog(std::string& infoLog) const {
165 static_cast<void>(infoLog);
166 }
167
168 inline std::uint32_t GetUniformsSize() const {
169 return _uniformsSize;
170 }
171 inline std::uint32_t GetUniformBlocksSize() const {
172 return _uniformBlocksSize;
173 }
174
175 bool AttachShaderFromFile(ShaderStage stage, StringView filename);
176 bool AttachShaderFromString(ShaderStage stage, StringView string);
177 bool AttachShaderFromStrings(ShaderStage stage, ArrayView<const StringView> strings);
178 bool AttachShaderFromStringsAndFile(ShaderStage stage, ArrayView<const StringView> strings, StringView filename);
179
180 /** @brief Sets the offline reflection consumed by @ref Link() to import uniforms/blocks/attributes */
181 inline void SetReflection(const ShaderCompiler::ProgramVariant* reflection) {
182 _reflection = reflection;
183 }
184 /**
185 @brief Records the true (program, variant) identity of the loaded shader
186
187 This backend resolves its generated microcode from this identity, the same way the fixed-function
188 console backends resolve their generated effect tables from it.
189 */
190 inline void SetProgramIdentity(const char* programName, const char* variantName) {
191 _programName = programName;
192 _variantName = variantName;
193 }
194 /** @brief Returns the generated program's name, or `nullptr` for one that carries no identity */
195 inline const char* GetProgramName() const {
196 return _programName;
197 }
198
199 bool Link(Introspection introspection);
200 void Use();
201 bool Validate() {
202 return true;
203 }
204 bool FinalizeAfterLinking(Introspection introspection);
205
206 inline std::uint32_t GetAttributeCount() const {
207 return std::uint32_t(_attributes.size());
208 }
209 bool HasAttribute(const char* name) const;
210 /** @brief Returns `true` if the reflection declares @p name with an integer type (a batch element index) */
211 bool IsIntegerAttribute(const char* name) const;
212 RsxVertexFormat::Attribute* GetAttribute(const char* name);
213
214 inline void DefineVertexFormat(const RsxBufferObject* vbo) {
215 DefineVertexFormat(vbo, nullptr, 0);
216 }
217 inline void DefineVertexFormat(const RsxBufferObject* vbo, const RsxBufferObject* ibo) {
218 DefineVertexFormat(vbo, ibo, 0);
219 }
220 void DefineVertexFormat(const RsxBufferObject* vbo, const RsxBufferObject* ibo, std::uint32_t vboOffset);
221
222 void Reset();
223 void SetObjectLabel(StringView label);
224
225 inline bool GetLogOnErrors() const {
226 return _shouldLogOnErrors;
227 }
228 inline void SetLogOnErrors(bool shouldLogOnErrors) {
229 _shouldLogOnErrors = shouldLogOnErrors;
230 }
231
232 // -- Backend extensions (used by the uniform caches and the device draw path) --
233
234 /** @brief Publishes a committed loose-uniform value pointer for the device to upload */
235 void SetResolvedUniform(const char* name, const std::uint8_t* data);
236 /** @brief Returns the last published value pointer of the named loose uniform, or `nullptr` */
237 const std::uint8_t* ResolveUniform(const char* name) const;
238
239 /** @brief Returns the embedded vertex microcode descriptor, or `nullptr` if the program did not link */
240 inline const rsxVertexProgram* GetVertexProgram() const {
241 return _vertexProgram;
242 }
243 /** @brief Returns the embedded fragment microcode descriptor, or `nullptr` */
244 inline const rsxFragmentProgram* GetFragmentProgram() const {
245 return _fragmentProgram;
246 }
247 /** @brief Returns the vertex microcode the device hands to `rsxLoadVertexProgram()` */
248 inline const void* GetVertexUcode() const {
249 return _vertexUcode;
250 }
251 /** @brief Returns this program's private copy of the fragment microcode in local memory */
252 inline const RsxVram::Block& GetFragmentUcodeBlock() const {
253 return _fragmentUcode;
254 }
255
256 /** @brief Loose-uniform slots of the vertex stage (resolved once at link time) */
257 inline const SmallVector<RsxUniformSlot, 0>& GetVertexUniformSlots() const {
258 return _vertexUniformSlots;
259 }
260 /** @brief Loose-uniform slots of the fragment stage */
261 inline const SmallVector<RsxUniformSlot, 0>& GetFragmentUniformSlots() const {
262 return _fragmentUniformSlots;
263 }
264
265 /**
266 @brief Where one uniform block's bytes go among a stage's constants
267
268 The Cg dialect has no counterpart to a std140 block - its emitter hoists each block member to a
269 top-level `uniform` - so a block is uploaded member by member, exactly as on the Vita.
270 */
271 struct RsxBlockUpload
272 {
273 const rsxProgramConst* Param; // the microcode descriptor of the member's constant
274 std::uint32_t BindingIndex; // uniform binding point the pipeline bound the range to
275 std::uint32_t SourceOffset; // byte offset of the member within that range
276 std::uint32_t MaxByteSize; // bytes the engine's block layout declares (an upper bound on a copy)
277 const char* Name; // the reflection's member name, for diagnostics
278 };
279
280 /**
281 @brief One field of a batched instance element, and where it sits on each side
282
283 A batched instance array cannot go through @ref RsxBlockUpload, because the two sides disagree
284 about the element layout. The engine writes std140, which packs a trailing `vec2` and `float`
285 into one 16-byte slot; cgcomp gives every field its own constant register. For the sprite
286 element that is 7 vec4 on the engine's side and 8 registers on the shader's - so the element
287 cannot be handed over as one block, and its 5 fields cannot be handed over one register write
288 each either without costing 5 writes per sprite.
289
290 Instead the draw path repacks: it gathers an element's fields out of the std140 range into a
291 scratch buffer laid out the way the registers are, and issues **one**
292 `rsxSetVertexProgramConstants()` per element. This structure is what that repacking is driven by.
293 */
294 struct RsxInstanceField
295 {
296 std::uint32_t SourceOffset; // byte offset of the field within one std140 element
297 std::uint32_t RegisterOffset; // register offset of the field within one compiled element
298 std::uint32_t RegisterCount; // registers the field occupies (4 for a mat4, 1 otherwise)
299 std::uint32_t ByteSize; // bytes to copy out of the std140 element
300 const char* Name; // for diagnostics
301 };
302
303 /**
304 @brief The batched instance array of a stage, if it has one
305
306 Derived at link time from the compiled microcode's own constant table - the offline reflection
307 describes the array only as one opaque `Struct` member, so the field layout is recovered from the
308 `instances[0].<field>` constants cgcomp emitted and their declared types (see
309 @ref RsxShaderProgram::ResolveInstanceArray()).
310 */
311 struct RsxInstanceArray
312 {
313 bool Valid = false;
314 std::uint32_t BindingIndex = 0; // uniform binding point the pipeline bound the range to
315 std::uint32_t BaseRegister = 0; // register of element 0's first field
316 std::uint32_t RegistersPerElement = 0;
317 std::uint32_t SourceStride = 0; // std140 element stride the pipeline writes
318 std::uint32_t ElementCount = 0;
319 SmallVector<RsxInstanceField, 0> Fields;
320 };
321
322 /** @brief The vertex stage's batched instance array (never present on the fragment stage) */
323 inline const RsxInstanceArray& GetInstanceArray() const {
324 return _instanceArray;
325 }
326
327 /** @brief Uniform-block member uploads of the vertex stage */
328 inline const SmallVector<RsxBlockUpload, 0>& GetVertexBlockUploads() const {
329 return _vertexBlockUploads;
330 }
331 /** @brief Uniform-block member uploads of the fragment stage */
332 inline const SmallVector<RsxBlockUpload, 0>& GetFragmentBlockUploads() const {
333 return _fragmentBlockUploads;
334 }
335
336 /**
337 @brief Where one of a stage's samplers takes its texture from
338
339 The two indices are not the same thing: `EngineUnit` is the texture unit the pipeline binds a
340 texture to, `HardwareUnit` is the RSX texture unit the compiled shader samples. The Cg emitter
341 tags each sampler with a `TEXUNIT<n>` semantic taken from the offline reflection, so the two
342 normally agree - but they are resolved separately so a shader that renames or reorders its
343 samplers cannot silently sample the wrong one.
344 */
345 struct RsxSamplerBinding
346 {
347 const char* Name;
348 std::uint32_t EngineUnit;
349 std::uint32_t HardwareUnit;
350 };
351
352 /** @brief Samplers the fragment stage declares (the vertex stage never samples in this engine) */
353 inline const SmallVector<RsxSamplerBinding, 0>& GetFragmentSamplers() const {
354 return _fragmentSamplers;
355 }
356
357 /** @brief Vertex attributes the compiled stage declares (see @ref RsxStageAttribute) */
358 inline const SmallVector<RsxStageAttribute, 0>& GetStageAttributes() const {
359 return _stageAttributes;
360 }
361 /** @brief Returns the attribute register of the named compiled attribute, or -1 */
362 std::int32_t GetStageAttributeRegister(const char* name) const;
363 /**
364 @brief Returns the attribute register the compiled stage reads a reflection location from, or -1
365
366 The pipeline addresses a vertex attribute by its location in the reflection's numbering, but the
367 register the microcode actually fetches is cgcomp's own and need not match. Resolved by name once
368 at link time (see @ref ResolveStageInterface), because binding a stream to the reflection's number
369 leaves the stage reading a register nothing filled - which is a mesh that renders nothing at all.
370 */
371 inline std::int32_t GetAttributeRegisterForLocation(std::uint32_t location) const {
372 return (location < MaxAttributeLocations ? _attributeRegisterByLocation[location] : -1);
373 }
374
375 /** @brief Returns the vertex format the pipeline last defined on this program */
376 inline RsxVertexFormat& GetVertexFormat() {
377 return _vertexFormat;
378 }
379
380 private:
381 static std::uint32_t _nextHandle;
382
383 std::uint32_t _handle;
384 Status _status;
385 Introspection _introspection;
386 QueryPhase _queryPhase;
387 std::uint32_t _batchSize;
388 bool _shouldLogOnErrors;
389
390 const ShaderCompiler::ProgramVariant* _reflection;
391 const char* _programName;
392 const char* _variantName;
393
394 // The embedded microcode of the resolved (program, variant). Both point into the executable's
395 // rodata, so neither is owned; only the fragment half is copied, into _fragmentUcode below.
396 const rsxVertexProgram* _vertexProgram;
397 const rsxFragmentProgram* _fragmentProgram;
398 const void* _vertexUcode;
399 /** @brief This program's private copy of the fragment microcode (see the class documentation) */
400 RsxVram::Block _fragmentUcode;
401
402 SmallVector<RsxUniform, 0> _uniforms;
403 SmallVector<RsxUniformBlock, 0> _uniformBlocks;
404 SmallVector<RsxAttribute, 0> _attributes;
405 std::uint32_t _uniformsSize;
406 std::uint32_t _uniformBlocksSize;
407
408 SmallVector<RsxUniformSlot, 0> _vertexUniformSlots;
409 SmallVector<RsxUniformSlot, 0> _fragmentUniformSlots;
410 SmallVector<RsxBlockUpload, 0> _vertexBlockUploads;
411 SmallVector<RsxBlockUpload, 0> _fragmentBlockUploads;
412 RsxInstanceArray _instanceArray;
413 SmallVector<RsxSamplerBinding, 0> _fragmentSamplers;
414 SmallVector<RsxStageAttribute, 0> _stageAttributes;
415 /** @brief Largest reflection attribute location @ref _attributeRegisterByLocation covers */
416 static constexpr std::uint32_t MaxAttributeLocations = 16;
417 /** @brief Reflection location -> compiled attribute register, or -1 where the stage declares none */
418 std::int8_t _attributeRegisterByLocation[MaxAttributeLocations];
419
420 /** @brief Committed loose-uniform value pointers, published by the uniform caches */
421 SmallVector<std::pair<const char*, const std::uint8_t*>, 0> _resolvedUniforms;
422
423 RsxVertexFormat _vertexFormat;
424
425 /** @brief Looks the embedded microcode pair up from the program identity; `false` if there is none */
426 bool ResolveGeneratedProgram();
427 /** @brief Copies the fragment microcode into local memory, where the fragment engine can fetch it */
428 bool UploadFragmentUcode();
429 /** @brief Imports uniforms, blocks and attributes from the offline reflection */
430 void ImportReflection(Introspection introspection);
431 /** @brief Resolves every imported uniform and block member against the microcode's name tables */
432 void ResolveConstants();
433 /**
434 @brief Recovers a batched instance array's field layout from the compiled microcode
435
436 @param blockIndex Binding point the pipeline bound the block's range to
437 @param memberName Name of the array member in the shader (e.g. "instances")
438 @param sourceStride std140 element stride the engine writes
439 @param elementCount Elements the batch covers
440 */
441 void ResolveInstanceArray(std::uint32_t blockIndex, const char* memberName,
442 std::uint32_t sourceStride, std::uint32_t elementCount);
443 /** @brief Records the attributes and samplers the compiled stages declare */
444 void ResolveStageInterface();
445 };
446 }