Debian Codegraph @

Sources/nCine/Graphics/RHI/GS/GsDevice.h

raw
1 #pragma once
2
3 #include "../RhiTypes.h"
4 #include "../../../Primitives/Rect.h"
5 #include "../../../Primitives/Colorf.h"
6 #include "GsVram.h"
7
8 #include <cstddef>
9 #include <cstdint>
10 #include <vector>
11
12 namespace nCine::RHI::GS
13 {
14 class GsShaderProgram;
15 class GsRenderTarget;
16 class GsTexture;
17 // Defined by the generated GsGeneratedEffects.h inside the device translation unit; everyone else only
18 // ever holds an opaque entry pointer resolved at program load
19 struct FixedFunctionGeneratedEffect;
20
21 /**
22 @brief Pipeline-state and draw-call facade of the GS backend (aliased as `RHI::Device`)
23
24 The PlayStation 2 twin of the PVR and GX devices: each draw decodes the bound program's instance
25 block(s) exactly like `SwDevice::Dispatch`, CPU-transforms the four sprite corners to display
26 coordinates and writes them into a GIF packet as Graphics Synthesizer primitives. The GS takes screen
27 space directly - there is no transform unit in the rasterizer and no matrix register - so the whole
28 model-view-projection is applied on the EE, the same way the PowerVR backend does it on the SH4.
29
30 Register encoding is left to PS2SDK's `libdraw` rather than hand-assembled, in the same way the PVR
31 backend builds on KallistiOS's `pvr.h`: the backend's own logic is corner synthesis, effect dispatch
32 and residency, not GIF tag layout. Two traps of that library are load-bearing here and are repeated
33 wherever they apply, because neither fails loudly:
34 - `draw_texture_transfer()` builds a DMA **chain**, so its packet must be sent with
35 `dma_channel_send_chain()`; sending it as a normal transfer wedges the channel silently.
36 - `texbuffer_t::width` and `framebuffer_t::width` are in **texels**, not `TBW` units.
37
38 Because the GS rasterizes as packets arrive rather than deferring a whole scene like the tile
39 accelerator, a texture whose pages are reused mid-frame could be sampled by a primitive that was
40 already submitted. What makes that safe here is ORDER rather than planning: the GIF consumes
41 everything on its DMA path strictly in sequence, so as long as the re-upload is issued *after* the
42 draws that sample the previous contents - which @ref FlushPendingPackets() is what guarantees - the
43 GS has finished with those draws before the new texels land. A store may still be evicted while it is
44 resident, but never while a submitted primitive is still reading it.
45
46 Palette handling has no bank limit to work around: a CLUT is a 1 KB region of local memory selected
47 per draw through `TEX0.CBP`, so the layout's slab holds many at once and the PowerVR's four-bank LRU
48 becomes a straight slot cache keyed by palette row.
49 */
50 class GsDevice
51 {
52 public:
53 /** @brief Monotonic count of finished frames, used to detect "still referenced by the current frame" resources */
54 static std::uint32_t GetFrameCounter() {
55 return _frameCounter;
56 }
57
58 /**
59 @brief Returns the generated fixed-function effect of a (program, variant) key, or `nullptr`
60
61 Scans the table transpiled from the shaders' `fixed_function` blocks
62 (`Shaders/Generated/GsGeneratedEffects.h`). Called once per program load from
63 @ref GsShaderProgram::SetObjectLabel(), which maps the object label onto the key through its
64 exact-name table - the draw path only ever reads the stored pointer.
65 */
66 static const FixedFunctionGeneratedEffect* FindGeneratedEffect(const char* program, const char* variant);
67
68 GsDevice() = delete;
69 ~GsDevice() = delete;
70
71 struct ScissorState
72 {
73 bool Enabled = false;
74 Recti Rect = Recti(0, 0, 0, 0);
75 };
76
77 struct BlendingState
78 {
79 bool Enabled = false;
80 nCine::BlendingFactor SrcRgb = nCine::BlendingFactor::One;
81 nCine::BlendingFactor DstRgb = nCine::BlendingFactor::Zero;
82 nCine::BlendingFactor SrcAlpha = nCine::BlendingFactor::One;
83 nCine::BlendingFactor DstAlpha = nCine::BlendingFactor::Zero;
84 };
85
86 struct DepthTestState
87 {
88 bool TestEnabled = false;
89 bool MaskEnabled = true;
90 };
91
92 struct CullFaceState
93 {
94 bool Enabled = false;
95 CullFaceMode Mode = CullFaceMode::Back;
96 };
97
98 static void SetBlendingEnabled(bool enabled);
99 static void SetBlendingFactors(nCine::BlendingFactor srcRgb, nCine::BlendingFactor dstRgb, nCine::BlendingFactor srcAlpha, nCine::BlendingFactor dstAlpha);
100 static BlendingState GetBlendingState();
101 static void SetBlendingState(const BlendingState& state);
102
103 static void SetDepthTestEnabled(bool enabled);
104 static void SetDepthMaskEnabled(bool enabled);
105 static DepthTestState GetDepthTestState();
106 static void SetDepthTestState(const DepthTestState& state);
107
108 static void SetCullFaceEnabled(bool enabled);
109 static CullFaceState GetCullFaceState();
110 static void SetCullFaceState(const CullFaceState& state);
111
112 static ScissorState GetScissorState();
113 static void SetScissorState(const ScissorState& state);
114 static void SetScissor(const Recti& rect);
115 static void SetScissorTestEnabled(bool enabled);
116
117 static Recti GetViewport();
118 static void SetViewport(const Recti& rect);
119 static void InitViewport(std::int32_t x, std::int32_t y, std::int32_t width, std::int32_t height);
120
121 static Colorf GetClearColor();
122 static void SetClearColor(const Colorf& color);
123 static void Clear(ClearFlags flags);
124
125 static void DrawArrays(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices);
126 static void DrawArraysInstanced(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices, std::int32_t numInstances);
127 static void DrawElements(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t baseVertex);
128 static inline void DrawElements(PrimitiveType primitive, std::uint32_t numIndices, std::uintptr_t indexOffset, std::int32_t baseVertex) {
129 DrawElements(primitive, numIndices, IndexFormat::UInt16, indexOffset, baseVertex);
130 }
131 static void DrawElementsInstanced(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex);
132 static inline void DrawElementsInstanced(PrimitiveType primitive, std::uint32_t numIndices, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex) {
133 DrawElementsInstanced(primitive, numIndices, IndexFormat::UInt16, indexOffset, numInstances, baseVertex);
134 }
135
136 static FenceHandle InsertFence();
137 static void DeleteFence(FenceHandle& fence);
138 static bool ClientWaitFence(FenceHandle fence, std::uint64_t timeoutNs);
139
140 static void SetupInitialState();
141
142 // -- Swap-chain / presentation surface (uniform across every backend) --
143
144 /** @brief No-op (the window backend owns the presentation path) */
145 static inline bool CreateSwapchain(void* windowHandle, std::int32_t width, std::int32_t height, bool vsync) {
146 static_cast<void>(windowHandle);
147 static_cast<void>(width);
148 static_cast<void>(height);
149 static_cast<void>(vsync);
150 return true;
151 }
152 /** @brief No-op */
153 static inline void DestroySwapchain() {}
154 /** @brief No-op (the logical resolution is driven by ResizeScreenFramebuffer() from the render pipeline) */
155 static inline void ResizeSwapchain(std::int32_t width, std::int32_t height) {
156 static_cast<void>(width);
157 static_cast<void>(height);
158 }
159 /** @brief Flushes the frame's remaining GIF packets and flips the display buffer */
160 static void PresentFrame();
161
162 /** @brief Returns the maximum supported texture dimension (drives the tileset chunking) */
163 static inline std::int32_t GetMaxTextureDimension() {
164 // `TEX0.TW`/`TH` are log2 fields capped at 10
165 return 1024;
166 }
167
168 // -- Direct-tier presentation contract (see RhiFwd.h) --
169
170 /** @brief Sets the logical resolution the scene is rendered at (scaled to the display at submit) */
171 static void ResizeScreenFramebuffer(std::int32_t width, std::int32_t height);
172
173 // -- GS session, driven by the Ps2 window backend --
174
175 /**
176 @brief Brings up the Graphics Synthesizer
177
178 Places the static regions through @ref GsVram::Initialize(), sets the video mode and hands the
179 display buffers' addresses to `libgraph`. The depth test is configured ALWAYS with writes masked:
180 the engine's queue is already in painter's order, so a Z buffer would cost 560 KB of local memory
181 for nothing.
182 */
183 static void InitializeGs();
184
185 // -- GS backend extensions (called by the resource types and read by the draw dispatch) --
186
187 /** @brief Records the currently bound shader program */
188 static void BindProgram(GsShaderProgram* program);
189 /** @brief Returns the currently bound shader program */
190 static GsShaderProgram* CurrentProgram();
191 /** @brief Records the texture bound to a texture unit */
192 static void BindTexture(std::uint32_t unit, const GsTexture* texture);
193 /** @brief Clears a texture from every unit it is bound to (called from ~GsTexture) */
194 static void UnbindTexture(const GsTexture* texture);
195 /** @brief Returns the texture bound to a texture unit */
196 static const GsTexture* GetBoundTexture(std::uint32_t unit);
197 /** @brief Records the host data range bound to a uniform binding point */
198 static void BindUniformRange(std::uint32_t index, const std::uint8_t* data, std::uint32_t size);
199 /** @brief Records the current draw render target (points `FRAME.FBP` at its attachment) */
200 static void SetRenderTarget(GsRenderTarget* renderTarget);
201 /** @brief Clears a render target from the device if it is the current one (called from ~GsRenderTarget) */
202 static void UnbindRenderTarget(const GsRenderTarget* renderTarget);
203
204 /**
205 @brief Sends whatever draws and register writes are still queued, so a later transfer cannot overtake them
206
207 The GS consumes GIF data strictly in order, which is the *only* thing that makes a mid-frame
208 re-upload safe: the transfer must reach it AFTER the draws that sample the store's previous
209 contents. Those draws sit in this device's pending packet until it is flushed, so any code path
210 that hands the GIF a packet of its own - a texture or CLUT transfer, both of which are DMA chains
211 and cannot be appended here - has to call this first. Skipping it inverts the order: the upload
212 lands, and then the draws that were queued before it sample the new data.
213 */
214 static void FlushPendingPackets();
215
216 /**
217 @brief Writes the EE data cache back so a DMA can read @p bytes bytes at @p start
218
219 The second thing every path that hands the GIF a packet of its own has to do, and the one with no
220 symptom until it bites. PS2SDK synchronises the buffer it is *handed* - `dma_channel_send_chain()`
221 calls `SyncDCache()` over the qwords of the chain itself - but `draw_texture_transfer()` builds a
222 chain whose `REF` tags point somewhere else entirely, at the staging image in main memory, and
223 nothing synchronises that. The EE's data cache is 8 KB and **write-back**, so the tail of an image
224 the CPU has just filled is still sitting in it, and the DMA - which reads memory directly, never
225 the cache - transfers whatever was in those addresses beforehand.
226
227 The corruption is therefore intermittent by nature: how much of the image is still dirty depends
228 on what ran between filling it and sending it, and the stale bytes are the *previous* upload
229 through the same staging buffer. A texture comes out garbled for as long as it stays resident and
230 is correct the next time it happens to be re-transferred, which is what it looked like - a frame
231 glitching at random and coming good by itself.
232 */
233 static void WritebackForDma(const void* start, std::size_t bytes);
234
235 /** @brief Registers the intercepted shared palette texture (rows become CLUTs) */
236 static void RegisterPaletteTexture(GsTexture* texture);
237 /** @brief Invalidates the CLUT slots (and RG8 bakes) of the given palette rows after an upload */
238 static void NotifyPaletteTextureChanged(GsTexture* texture, std::int32_t firstRow, std::int32_t rowCount);
239
240 /** @brief Queues the CPU lightmap/water combine for the next `Combine` draw (the direct-tier lighting contract) */
241 static void SetPendingSoftwareLighting(const float* lightmap, std::int32_t lmW, std::int32_t lmH, std::int32_t scale,
242 std::int32_t vpX, std::int32_t vpY, std::int32_t vpW, std::int32_t vpH, float ambR, float ambG, float ambB,
243 bool waterActive = false, float waterLevelPx = 0.0f, float waterTime = 0.0f, float waterCamY = 0.0f);
244 /** @brief Drops any lighting entries not consumed this frame (called by the window backend at present) */
245 static void EndFrame();
246
247 private:
248 static constexpr std::uint32_t MaxTextureUnits = 8;
249 static constexpr std::uint32_t MaxUniformBindings = 8;
250 /** @brief CLUT slots tracked by the device (the slab's capacity, see `GsVramLayout::ClutSlotCount`) */
251 static constexpr std::uint32_t MaxClutSlots = 32;
252 /**
253 @brief Rows of the shared palette texture whose changes are tracked individually
254
255 `ContentResolver` builds a 256x256 palette texture and uploads only the rows it dirtied, and the
256 game dirties a few of them most frames (the animated water and lava ramps). One global "the palette
257 changed" counter therefore invalidates every resident CLUT **and every RG8 bake** on almost every
258 frame - and a bake costs a page allocation plus a DMA per sprite on this hardware, which is enough
259 to exhaust local memory and collapse the frame rate. Stamping rows separately keeps an invalidation
260 as narrow as the upload that caused it.
261 */
262 static constexpr std::int32_t MaxPaletteRows = 256;
263
264 struct UniformRange
265 {
266 const std::uint8_t* Data = nullptr;
267 std::uint32_t Size = 0;
268 };
269
270 struct PendingSoftwareLight
271 {
272 const float* Lightmap = nullptr;
273 std::int32_t LmW = 0, LmH = 0, Scale = 1;
274 std::int32_t VpX = 0, VpY = 0, VpW = 0, VpH = 0;
275 float AmbR = 0.0f, AmbG = 0.0f, AmbB = 0.0f;
276 bool WaterActive = false;
277 float WaterLevelPx = 0.0f, WaterTime = 0.0f, WaterCamY = 0.0f;
278 };
279
280 /** @brief One resident CLUT: a 1 KB slab slot holding 256 entries of one palette row */
281 struct ClutSlot
282 {
283 std::int32_t PaletteOffset = -1;
284 const GsTexture* Palette = nullptr;
285 std::uint32_t PaletteVersion = 0;
286 std::uint32_t LastUse = 0;
287 /** @brief Block address of the slot, the unit of `TEX0.CBP` */
288 std::uint32_t Block = GsVram::InvalidBlock;
289 /**
290 @brief Whether the slot holds the row's COVERAGE rather than its colours
291
292 A silhouette pass needs a flat colour where the texture has alpha, which the GS's four
293 texture functions cannot produce (see @ref AcquireCoverageClut()). The coverage form of a
294 row - white in every entry, the row's own alphas kept - turns MODULATE into exactly that,
295 and it is a different 1 KB payload for the same row, so it needs its own slot.
296 */
297 bool Coverage = false;
298 };
299
300 static BlendingState _blending;
301 static DepthTestState _depthTest;
302 static CullFaceState _cullFace;
303 static ScissorState _scissor;
304 static Recti _viewport;
305 static Colorf _clearColor;
306
307 static GsShaderProgram* _currentProgram;
308 static const GsTexture* _boundTextures[MaxTextureUnits];
309 static UniformRange _boundUniformRanges[MaxUniformBindings];
310 static GsRenderTarget* _currentRenderTarget;
311 /**
312 @brief Whether the current render target has no colour surface in local memory
313
314 `FRAME` still points at whatever was bound before it, so every draw and clear of the pass has to
315 be dropped rather than issued - they would land on the previous target (the display, usually)
316 while being transformed and scissored for this one.
317 */
318 static bool _renderTargetSurfaceMissing;
319
320 static bool _gsInitialized;
321 static std::int32_t _logicalWidth;
322 static std::int32_t _logicalHeight;
323 static std::int32_t _displayBufferIndex;
324
325 static GsTexture* _paletteTexture;
326 static std::uint32_t _paletteGeneration;
327 /** @brief Value of @ref _paletteGeneration when each palette row was last uploaded */
328 static std::uint32_t _paletteRowStamp[MaxPaletteRows];
329 static ClutSlot _clutSlots[MaxClutSlots];
330 static std::uint32_t _clutUseCounter;
331 static std::uint32_t _frameCounter;
332
333 static std::vector<PendingSoftwareLight> _pendingSoftwareLights;
334
335 static void Dispatch(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices);
336 /** @brief Draws a whole tile-layer mesh (a triangle list of position/texcoord/colour vertices) */
337 static void DispatchTileMesh(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices);
338 /**
339 @brief Draws a vertex-fed textured line strip (the weapon wheel)
340
341 The GS does have a LINE primitive, but it has no texture coordinates worth using across a strip,
342 so every segment goes out as a thin screen-space quad exactly as on the PVR.
343 */
344 static void DispatchLineStrip(std::int32_t firstVertex, std::int32_t numVertices);
345 static void ApplyPendingSoftwareLighting();
346 /**
347 @brief Programs `SCISSOR` for the current scissor state and render target
348
349 Called by every clear and every draw. The register is context state that outlives a packet, so
350 the pass that does not scissor has to say so explicitly - otherwise it keeps the rectangle of
351 whichever pass scissored last.
352 */
353 static void ApplyScissor();
354 /** @brief Loads 256 entries into a CLUT slab slot, reusing the slot if they are already there */
355 /**
356 @brief The 256 palette entries at @p paletteOffset, or `nullptr` when the offset is out of range
357
358 The offset carried in an instance is a **flat** index into the palette texture and need not be
359 row-aligned - the gem gradients pack two palettes into one 256-entry row, so theirs are 128, 256,
360 384 and 512. Reading it as a row index walks off the end of the palette.
361 */
362 static const std::uint32_t* ResolvePaletteEntries(const GsTexture* palette, std::int32_t paletteOffset);
363 /**
364 @brief Version of the 256 entries at @p paletteOffset of @p palette
365
366 For the shared palette texture this is the newest stamp of the (at most two) rows those entries
367 span, so a CLUT or a bake is only invalidated when the entries it actually read were rewritten.
368 Any other palette texture is versioned as a whole by its own content version.
369 */
370 static std::uint32_t PaletteVersionForOffset(const GsTexture* palette, std::int32_t paletteOffset);
371 static std::uint32_t AcquireClutForOffset(const GsTexture* palette, std::int32_t paletteOffset);
372 static std::uint32_t AcquireClut(const GsTexture* palette, std::int32_t paletteOffset,
373 std::uint32_t version, const std::uint32_t* entries, bool coverage = false);
374 /**
375 @brief Loads the COVERAGE form of a palette row - white in every entry, its own alphas kept
376
377 The mechanism behind `FixedFunctionPass::TevPreset::Silhouette` for an indexed store. A
378 silhouette is "the pass colour wherever the texture has alpha", and none of the GS's four
379 texture functions produces it: MODULATE multiplies the texel in, DECAL ignores the fragment
380 colour entirely, and both HIGHLIGHT forms can only add the fragment ALPHA (achromatic) on top.
381 But a CLUT is a per-draw table, so replacing every entry's colour with white while keeping its
382 alpha makes MODULATE compute `white * Cf = Cf` and `At * Af` - the silhouette, exactly, with no
383 extra pass and no per-texel arithmetic.
384 */
385 static std::uint32_t AcquireCoverageClutForOffset(const GsTexture* palette, std::int32_t paletteOffset);
386 /**
387 @brief Loads the static alpha-to-coverage CLUT the true-colour stores sample through
388
389 The same silhouette trick as @ref AcquireCoverageClutForOffset(), for a store that has no CLUT of
390 its own. A PSMCT32 store can also be sampled as **PSMT8H**, which reads the high byte of each
391 32-bit cell - the alpha - as an 8-bit index through a CLUT, over identical addressing (8H is a
392 sub-field of the same cells, so the pitch, the page swizzle and `TW`/`TH` are unchanged). Index
393 `i` is therefore the texel's alpha, and one table mapping `i` to (white, alpha `i`) turns
394 MODULATE into the silhouette for EVERY such store - so unlike the per-row form this is a single
395 table for the whole backend, built once and kept in its slot.
396 */
397 static std::uint32_t AcquireAlphaCoverageClut();
398 static void GetTargetScale(float& scaleX, float& scaleY, float& offsetX, float& offsetY);
399 };
400 }