Debian Codegraph @

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

raw
1 #pragma once
2
3 #include "RsxVram.h"
4 #include "RsxShaderProgram.h"
5 #include "../RhiTypes.h"
6 #include "../../../Primitives/Rect.h"
7 #include "../../../Primitives/Colorf.h"
8
9 #include <cstdint>
10
11 #include <Containers/SmallVector.h>
12
13 #include <rsx/gcm_sys.h>
14
15 using namespace Death::Containers;
16
17 namespace nCine::RHI::RSX
18 {
19 class RsxShaderProgram;
20 class RsxRenderTarget;
21 class RsxTexture;
22
23 /**
24 @brief Pipeline-state and draw-call facade of the RSX backend (aliased as `RHI::Device`)
25
26 Exposes the OpenGL device's surface (blending, depth, cull, scissor, viewport, clear and the draw
27 calls) so the backend-neutral render pipeline drives it unchanged, and owns the whole RSX session
28 behind it: the command FIFO, the negotiated video mode, the display buffers and the shared depth
29 buffer.
30
31 Three properties of the hardware shape everything below.
32
33 **The RSX is immediate-mode, which is what makes this simpler than the sceGxm backend.** There is no
34 scene to begin and end and no tile buffer whose contents start undefined: a render target is a set of
35 addresses in a state register, `rsxSetSurface()` changes it, and `rsxClearSurface()` is a real
36 hardware clear rather than a full-screen quad standing in for one. A target can be re-entered
37 mid-frame without discarding what an earlier pass drew, so the pipeline's viewport chain needs no
38 special handling at all.
39
40 **The output resolution is negotiated with the display.** Unlike every other console backend here,
41 the panel is not fixed: @ref CreateSwapchain() walks a preference list through
42 `videoGetResolutionAvailability()` and takes the first mode the attached display accepts, so
43 @ref GetDisplayWidth() and @ref GetDisplayHeight() are only known after the session is up. The
44 logical (game) resolution remains a render-target size driven separately by the render pipeline.
45
46 **The display scans out top-down.** The engine renders in the OpenGL convention, and this backend
47 replays it faithfully: every viewport is programmed so clip -Y lands on row 0 and every surface - the
48 screen and each off-screen render target - is stored bottom-up exactly like OpenGL. That is what
49 keeps a texture's V axis and its viewport's Y axis pointing the same way, so an off-screen round trip
50 does not flip the image (the property that makes the scene composite and the directly drawn HUD
51 agree). The scan-out then needs the one correction that convention implies: "screen" (no render
52 target bound) is an intermediate surface, and @ref PresentFrame() flips it into the display buffer
53 with a built-in shader - the same single OpenGL-to-native flip the sceGxm and Direct3D 11 backends
54 do, which also scales the logical resolution up to the panel for free.
55 */
56 class RsxDevice
57 {
58 public:
59 RsxDevice() = delete;
60 ~RsxDevice() = delete;
61
62 struct ScissorState
63 {
64 bool Enabled = false;
65 Recti Rect = Recti(0, 0, 0, 0);
66 };
67
68 struct BlendingState
69 {
70 bool Enabled = false;
71 nCine::BlendingFactor SrcRgb = nCine::BlendingFactor::One;
72 nCine::BlendingFactor DstRgb = nCine::BlendingFactor::Zero;
73 nCine::BlendingFactor SrcAlpha = nCine::BlendingFactor::One;
74 nCine::BlendingFactor DstAlpha = nCine::BlendingFactor::Zero;
75 };
76
77 struct DepthTestState
78 {
79 bool TestEnabled = false;
80 bool MaskEnabled = true;
81 };
82
83 struct CullFaceState
84 {
85 bool Enabled = false;
86 CullFaceMode Mode = CullFaceMode::Back;
87 };
88
89 static void SetBlendingEnabled(bool enabled);
90 static void SetBlendingFactors(nCine::BlendingFactor srcRgb, nCine::BlendingFactor dstRgb, nCine::BlendingFactor srcAlpha, nCine::BlendingFactor dstAlpha);
91 static BlendingState GetBlendingState();
92 static void SetBlendingState(const BlendingState& state);
93
94 static void SetDepthTestEnabled(bool enabled);
95 static void SetDepthMaskEnabled(bool enabled);
96 static DepthTestState GetDepthTestState();
97 static void SetDepthTestState(const DepthTestState& state);
98
99 static void SetCullFaceEnabled(bool enabled);
100 static CullFaceState GetCullFaceState();
101 static void SetCullFaceState(const CullFaceState& state);
102
103 static ScissorState GetScissorState();
104 static void SetScissorState(const ScissorState& state);
105 static void SetScissor(const Recti& rect);
106 static void SetScissorTestEnabled(bool enabled);
107
108 static Recti GetViewport();
109 static void SetViewport(const Recti& rect);
110 static void InitViewport(std::int32_t x, std::int32_t y, std::int32_t width, std::int32_t height);
111
112 static Colorf GetClearColor();
113 static void SetClearColor(const Colorf& color);
114 static void Clear(ClearFlags flags);
115
116 static void DrawArrays(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices);
117 static void DrawArraysInstanced(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices, std::int32_t numInstances);
118 static void DrawElements(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t baseVertex);
119 static inline void DrawElements(PrimitiveType primitive, std::uint32_t numIndices, std::uintptr_t indexOffset, std::int32_t baseVertex) {
120 DrawElements(primitive, numIndices, IndexFormat::UInt16, indexOffset, baseVertex);
121 }
122 static void DrawElementsInstanced(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex);
123 static inline void DrawElementsInstanced(PrimitiveType primitive, std::uint32_t numIndices, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex) {
124 DrawElementsInstanced(primitive, numIndices, IndexFormat::UInt16, indexOffset, numInstances, baseVertex);
125 }
126
127 static FenceHandle InsertFence();
128 static void DeleteFence(FenceHandle& fence);
129 static bool ClientWaitFence(FenceHandle fence, std::uint64_t timeoutNs);
130
131 static void SetupInitialState();
132
133 // -- Backend extensions (called by the resource types) --
134
135 /** @brief Records the currently bound shader program */
136 static void BindProgram(RsxShaderProgram* program);
137 /** @brief Returns the currently bound shader program */
138 static RsxShaderProgram* CurrentProgram();
139 /** @brief Records the texture bound to a texture unit */
140 static void BindTexture(std::uint32_t unit, const RsxTexture* texture);
141 /** @brief Clears a texture from every unit it is bound to (called from ~RsxTexture to avoid a dangling pointer) */
142 static void UnbindTexture(const RsxTexture* texture);
143 /** @brief Returns the texture bound to a texture unit */
144 static const RsxTexture* GetBoundTexture(std::uint32_t unit);
145 /** @brief Records the host data range bound to a uniform binding point */
146 static void BindUniformRange(std::uint32_t index, const std::uint8_t* data, std::uint32_t size);
147 /** @brief Returns the host data range bound to a uniform binding point (read by the draw path) */
148 static void GetUniformRange(std::uint32_t index, const std::uint8_t*& data, std::uint32_t& size);
149 /** @brief Clears a render target from the device if it is the current one (called from ~RsxRenderTarget) */
150 static void UnbindRenderTarget(const RsxRenderTarget* renderTarget);
151 /** @brief Records the current draw render target (its bound colour attachment receives the pixels) */
152 static void SetRenderTarget(RsxRenderTarget* renderTarget);
153 /** @brief Clears a destroyed program from the device's current-program tracking (called from ~RsxShaderProgram) */
154 static void OnProgramDestroyed(const RsxShaderProgram* program);
155
156 /** @brief Returns the command context, or `nullptr` before @ref CreateSwapchain() */
157 static gcmContextData* GetContext();
158
159 /**
160 @brief Blocks until the GPU has consumed everything submitted so far
161
162 Used by the two operations that read what the GPU wrote - a render target's readback and the
163 teardown - and by nothing on a frame path.
164 */
165 static void Finish();
166
167 /**
168 @brief Holds @p block until the frame that may still reference it is done, and invalidates it
169
170 The command FIFO runs behind the CPU, so memory freed the moment a resource is destroyed may
171 still be read by commands already queued. Retired blocks are released after the next present.
172 */
173 static void RetireBlock(RsxVram::Block& block);
174
175 /** @brief Monotonic count of presented frames */
176 static std::uint32_t GetFrameCounter();
177
178 /**
179 @brief Returns the static vertex stream feeding `aQuadCorner` for the 4-vertex sprite strip
180
181 The corners are in the order of the single-quad `TRIANGLE_STRIP` draw - {(1,0), (1,1), (0,0),
182 (0,1)} - which is what the Cg emitter's rewrite of the engine's `gl_VertexID` corner formula
183 expects (see `ShaderCompiler::VertexIdRewrite`). Two floats per vertex.
184 */
185 static const void* GetQuadCornerStream();
186 /**
187 @brief Returns the static vertex stream feeding `aQuadCorner` + `aInstanceIndex` for batched sprites
188
189 Six vertices per sprite (two triangles) carrying the batched corner order {(1,1), (0,1), (0,0),
190 (0,0), (1,0), (1,1)} and the sprite's index within the batch, so a batched draw of `6 * n`
191 vertices reproduces the `gl_VertexID / 6` instance lookup and the corner formula the emitter
192 rewrote. Three floats per vertex; covers @ref MaxBatchSize sprites.
193 */
194 static const void* GetBatchedCornerStream();
195 /** @brief Offset of the quad corner stream, as `rsxBindVertexArrayAttrib()` takes it */
196 static std::uint32_t GetQuadCornerStreamOffset();
197 /** @brief Offset of the batched corner stream */
198 static std::uint32_t GetBatchedCornerStreamOffset();
199
200 /**
201 @brief Largest batch the @ref GetBatchedCornerStream() covers
202
203 Far smaller than the sceGxm backend's 682, and for a hardware reason rather than a policy one: a
204 batched instance array reaches the vertex program through its constant registers, and the `vp40`
205 profile allows a program 544 of them in total. The compiler's own accounting is not a simple
206 product of that and the element width - measured against the batched shaders, they stop compiling
207 somewhere above 40 instances - so 32 is the value they all accept with margin.
208 */
209 static constexpr std::uint32_t MaxBatchSize = 32;
210
211 // -- RSX session lifecycle (called by the window backend) --
212
213 /**
214 @brief Brings up the whole RSX session
215
216 @param windowHandle Ignored (the console has one display, so there is no window to attach to);
217 accepted only to keep the uniform swap-chain contract of the other backends
218 @param width Ignored, the mode is negotiated with the attached display
219 @param height Ignored
220 @param vsync Whether the present waits for vertical blank
221 @returns `true` if the FIFO, the video mode, the surfaces and the built-in shaders all came up
222 */
223 static bool CreateSwapchain(void* windowHandle, std::int32_t width, std::int32_t height, bool vsync);
224 /** @brief Tears the session down (waits for the GPU, then releases everything in creation order) */
225 static void DestroySwapchain();
226 /** @brief No-op: the display mode is negotiated once (the logical resolution is a render-target size) */
227 static void ResizeSwapchain(std::int32_t width, std::int32_t height);
228 /** @brief Flips the intermediate screen surface into the next display buffer and queues it for scan-out */
229 static void PresentFrame();
230
231 // The console has no multi-window support, so the ImGui multi-viewport hooks are inert here
232 /** @brief Not supported on this platform (returns `nullptr`) */
233 static inline void* CreateSecondarySwapchain(void* windowHandle, std::int32_t width, std::int32_t height) {
234 static_cast<void>(windowHandle);
235 static_cast<void>(width);
236 static_cast<void>(height);
237 return nullptr;
238 }
239 /** @brief Not supported on this platform */
240 static inline void DestroySecondarySwapchain(void* handle) {
241 static_cast<void>(handle);
242 }
243 /** @brief Not supported on this platform */
244 static inline void ResizeSecondarySwapchain(void* handle, std::int32_t width, std::int32_t height) {
245 static_cast<void>(handle);
246 static_cast<void>(width);
247 static_cast<void>(height);
248 }
249 /** @brief Not supported on this platform */
250 static inline void BeginSecondaryFrame(void* handle, bool clear) {
251 static_cast<void>(handle);
252 static_cast<void>(clear);
253 }
254 /** @brief Not supported on this platform */
255 static inline void EndSecondaryFrame() {}
256 /** @brief Not supported on this platform */
257 static inline void PresentSecondaryFrame(void* handle) {
258 static_cast<void>(handle);
259 }
260
261 /** @brief Width in pixels of the negotiated display mode (0 before @ref CreateSwapchain()) */
262 static std::int32_t GetDisplayWidth();
263 /** @brief Height in pixels of the negotiated display mode */
264 static std::int32_t GetDisplayHeight();
265
266 /**
267 @brief Returns the largest supported 2D texture dimension
268
269 4096 is the NV47's limit; it only feeds the tileset chunking in `ContentResolver` and the
270 texture-load assert, both of which the console's content stays well below.
271 */
272 static constexpr std::int32_t GetMaxTextureDimension() {
273 return 4096;
274 }
275 /** @brief Byte alignment the engine suballocates bound uniform ranges with (one std140 `vec4`) */
276 static constexpr std::int32_t GetUniformBufferOffsetAlignment() {
277 return 16;
278 }
279 /**
280 @brief Byte budget of one uniform block, which here is the vertex constant-register file
281
282 The RSX gives a vertex program constant registers and nothing else to read uniforms from - there
283 is no uniform buffer to bind - and the `vp40` profile allows a program 544 of them. The engine's
284 batcher divides the figure published here by the instance stride to decide how large a batch may
285 be, so it is set conservatively rather than at the ceiling; @ref MaxBatchSize bounds the result
286 again in any case. What matters is only that it never lets the batcher build a batch whose later
287 elements the shader cannot address.
288 */
289 static constexpr std::int32_t GetMaxUniformBlockSize() {
290 return 460 * 16;
291 }
292
293 private:
294 static constexpr std::uint32_t MaxTextureUnits = 8;
295 static constexpr std::uint32_t MaxUniformBindings = 8;
296 /** @brief Display buffers cycled by the flip; two keeps the GPU and the scan-out off one surface */
297 static constexpr std::uint32_t DisplayBufferCount = 2;
298 /** @brief Blocks retired by a destroyed resource, released once the GPU is past the frame that used them */
299 static constexpr std::uint32_t RetiredBlockCount = 64;
300 /**
301 @brief Frames a retired block is held for before its memory is handed back
302
303 Presenting only *queues* a frame - the GPU is still executing it, and usually the one before it -
304 so a block freed at present time can still be being read. Two frames covers the depth this
305 backend keeps in flight (see @ref DisplayBufferCount) with a frame to spare.
306
307 Getting this wrong is not a subtle corruption: a fragment program's microcode is fetched from
308 exactly this kind of block, so reissuing its memory to a texture while the GPU is still fetching
309 from it makes the hardware execute whatever the new owner wrote as shader instructions.
310 */
311 static constexpr std::uint32_t RetiredBlockFrameDelay = 2;
312
313 struct UniformRange
314 {
315 const std::uint8_t* Data = nullptr;
316 std::uint32_t Size = 0;
317 };
318
319 static BlendingState _blending;
320 static DepthTestState _depthTest;
321 static CullFaceState _cullFace;
322 static ScissorState _scissor;
323 static Recti _viewport;
324 static Colorf _clearColor;
325
326 static RsxShaderProgram* _currentProgram;
327 static const RsxTexture* _boundTextures[MaxTextureUnits];
328 static UniformRange _boundUniformRanges[MaxUniformBindings];
329 static RsxRenderTarget* _currentRenderTarget;
330
331 // -- The RSX session (owned) --
332
333 static gcmContextData* _context;
334 /** @brief Host region `rsxInit()` maps into the GPU's IO window, which RsxVram suballocates */
335 static void* _hostMemory;
336
337 static std::int32_t _displayWidth;
338 static std::int32_t _displayHeight;
339 static RsxVram::Block _displayBuffers[DisplayBufferCount];
340 static std::uint32_t _displayPitch;
341 static std::uint32_t _backBufferIndex;
342
343 // The intermediate surface every draw that is not aimed at a render target lands in, kept bottom-up
344 // like OpenGL and flipped into the display buffer at present time (see the class documentation)
345 static RsxVram::Block _screenBuffer;
346 static std::uint32_t _screenPitch;
347 static gcmTexture _screenTexture;
348
349 /** @brief Depth/stencil surface shared by the screen and every render target (see @ref RsxRenderTarget) */
350 static RsxVram::Block _depthBuffer;
351 static std::uint32_t _depthPitch;
352
353 static bool _initialized;
354 static bool _vsync;
355 static bool _firstFlip;
356 static std::uint32_t _frameCounter;
357 /** @brief Set whenever the surface state has to be re-programmed before the next draw */
358 static bool _surfaceDirty;
359 /** @brief Program whose microcode was last sent through the FIFO, to avoid re-sending it every draw */
360 static const rsxVertexProgram* _lastVertexProgram;
361 /** @brief Microcode that went with @ref _lastVertexProgram */
362 static const void* _lastVertexUcode;
363 /** @brief Fragment program last pointed at, which costs a pointer rather than a microcode upload */
364 static const rsxFragmentProgram* _lastFragmentProgram;
365 /** @brief Local-memory offset that went with @ref _lastFragmentProgram */
366 static std::uint32_t _lastFragmentUcodeOffset;
367 /** @brief Attribute registers the last draw bound, so the next one can turn off what it does not use */
368 static std::uint32_t _boundAttributeRegisters;
369
370 /** @brief Finds a stage attribute by name, tolerating the struct qualifier cgcomp records */
371 static const rsxProgramAttrib* FindVertexAttribute(const rsxVertexProgram* program, const char* name);
372
373 /** @brief A retired block together with the frame it stopped being referenced in */
374 struct RetiredBlock
375 {
376 RsxVram::Block Block;
377 std::uint32_t RetiredAtFrame = 0;
378 };
379 static RetiredBlock _retiredBlocks[RetiredBlockCount];
380
381 // -- Built-in shaders --
382
383 // Present: the screen surface sampled with a flipped V into the display buffer
384 static const rsxVertexProgram* _presentVertexProgram;
385 static const rsxFragmentProgram* _presentFragmentProgram;
386 static const void* _presentVertexUcode;
387 static RsxVram::Block _presentFragmentUcode;
388 static RsxVram::Block _presentVertices;
389
390 // The two static streams feeding the vertex-ID-free sprite shaders (see GetQuadCornerStream())
391 static RsxVram::Block _quadCornerStream;
392 static RsxVram::Block _batchedCornerStream;
393
394 /** @brief Negotiates a video mode with the attached display and configures the scan-out */
395 static bool ConfigureVideo();
396 /** @brief Programs the surface (colour + depth) the current target renders into, if it changed */
397 static void ApplySurface();
398 /** @brief Programs the viewport and scissor of the current target from the tracked engine state */
399 static void ApplyViewportAndScissor(std::int32_t targetWidth, std::int32_t targetHeight);
400 /** @brief Returns the dimensions of whatever the current target is */
401 static void GetCurrentTargetSize(std::int32_t& width, std::int32_t& height);
402 /** @brief Creates the static corner streams and the present shader's geometry */
403 static bool CreateBuiltinResources();
404 /** @brief Resolves the built-in present shader pair from the generated table */
405 static bool CreatePresentShader();
406 /**
407 @brief Frees the retired blocks the GPU can no longer be reading
408
409 @param force Release everything regardless of age; only correct after a @ref Finish(), which is
410 what the teardown and the out-of-slots path in @ref RetireBlock() do
411 */
412 static void ReleaseRetiredBlocks(bool force = false);
413 /** @brief Uploads a stage's loose uniforms and bound uniform-block ranges into its constants */
414 static void UploadUniforms();
415 /** @brief Repacks and uploads the current program's batched instance array, if it has one */
416 static void UploadInstanceArray();
417 /**
418 @brief Largest element the instance repacking scratch buffer covers, in constant registers
419
420 The widest instance the engine writes is a mat4 plus four vec4-shaped fields, which cgcomp lays
421 out as eight registers; sixteen leaves room for a wider one without putting the buffer on the heap.
422 */
423 static constexpr std::uint32_t MaxInstanceRegisters = 16;
424 /** @brief Vertex attribute registers the NV47 exposes, which bounds the stale-binding sweep */
425 static constexpr std::uint32_t MaxVertexAttributeRegisters = 16;
426 /** @brief Binds the current program's vertex attributes from its vertex format */
427 static void ApplyVertexFormat(std::int32_t baseVertex);
428 /** @brief Binds the current program, its resources and state, then issues the draw */
429 static void DrawCommon(PrimitiveType primitive, std::int32_t firstVertex, std::uint32_t count,
430 bool indexed, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t baseVertex);
431 };
432 }