Debian Codegraph @

Sources/nCine/Graphics/RHI/GU/GuDevice.h

raw
1 #pragma once
2
3 #include "../RhiTypes.h"
4 #include "../../../Primitives/Rect.h"
5 #include "../../../Primitives/Colorf.h"
6
7 #include <cstddef>
8 #include <cstdint>
9 #include <vector>
10
11 namespace nCine::RHI::GU
12 {
13 class GuShaderProgram;
14 class GuRenderTarget;
15 class GuTexture;
16 // Defined by the generated fixed-function effect table the device translation unit includes
17 // (Shaders/Generated/GuGeneratedEffects.h, exactly like the PVR and GX backends consume theirs);
18 // everyone else only ever holds an opaque entry pointer resolved at program load, so the incomplete
19 // type is enough here
20 struct FixedFunctionGeneratedEffect;
21
22 /**
23 @brief Pipeline-state and draw-call facade of the GU backend (aliased as `RHI::Device`)
24
25 The PlayStation Portable twin of the GX and PVR devices: each draw decodes the bound program's
26 instance block(s) exactly like `SwDevice::Dispatch`, CPU-transforms the four sprite corners to
27 screen pixels and submits them to the Allegrex GE as `GU_TRANSFORM_2D` primitives - the GE's
28 "through" mode, which skips transform and lighting and takes screen coordinates and texel-space
29 texture coordinates directly. Axis-aligned quads (nearly everything: UI, tiles, unrotated sprites)
30 go out as `GU_SPRITES`, two vertices per quad; rotated ones as triangle pairs.
31
32 Everything the frame draws is written into one display list the GE consumes while it is being
33 filled, and vertices come out of a per-frame arena that is written back from the data cache before
34 each draw call - the GE reads main memory without seeing the CPU's cache, which is the classic
35 source of "nothing renders" on this hardware. Consecutive primitives that share their whole GE
36 state are accumulated into a single `sceGuDrawArray`, so a tile layer or a text run costs one draw
37 call.
38
39 Unlike the PowerVR, the GE has a real raster scissor (`sceGuScissor`), so scissored draws are not
40 clipped geometrically - the rect is programmed and the hardware cuts the primitives. Indexed
41 textures are resolved by the hardware CLUT (`GU_PSM_T8`), loaded per draw from whatever palette
42 texture the material bound, which is the direct analogue of the PVR's palette banks and the GX's
43 TLUTs; RG8 index+alpha content has no paletted form and takes the same per-palette-row CPU bake the
44 other consoles use.
45
46 Because the GE has no programmable shaders, the game runs the direct tier (see `RhiFwd.h`): the
47 scene is rendered straight to the display at the logical resolution and the CPU lightmap is handed
48 to the device through @ref SetPendingSoftwareLighting() instead of a compositing shader pass.
49 */
50 class GuDevice
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 GetSceneCounter() {
55 return _sceneCounter;
56 }
57
58 /**
59 @brief Returns the generated fixed-function effect of a (program, variant) key, or `nullptr`
60
61 Called once per program load from @ref GuShaderProgram::SetProgramIdentity(). Scans the
62 fixed-function effect table of this backend; a program that is absent from it has no
63 `fixed_function` block in its `.shader` file (Lighting, Blur, the Resize* family, ...) and its
64 draws are skipped with a one-time warning, exactly as on the other fixed-function backends.
65 */
66 static const FixedFunctionGeneratedEffect* FindGeneratedEffect(const char* program, const char* variant);
67
68 GuDevice() = delete;
69 ~GuDevice() = 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 Closes the frame's display list and flips the display buffers (called by the Psp window backend once per frame) */
160 static void PresentFrame();
161
162 /** @brief The dimension a single GE texture cannot exceed (9-bit u/v addressing - a hardware limit) */
163 static constexpr std::int32_t HardwareTextureDimension = 512;
164
165 /**
166 @brief Returns the maximum supported texture dimension (drives the tileset chunking)
167
168 The GE's true limit, reported honestly: it makes `ContentResolver` cut tileset atlases into
169 chunks that each fit one GE texture, which is what the number is for. Prebaked content that is
170 larger anyway (the small font atlas is 128x529) is NOT rejected - @ref GuTexture splits such an
171 image into 512x512 pages internally and the draw path picks the page a primitive samples - so
172 `Texture::Initialize()` only warns about it on this backend instead of asserting.
173 */
174 static inline std::int32_t GetMaxTextureDimension() {
175 return HardwareTextureDimension;
176 }
177
178 // -- Direct-tier presentation contract (see RhiFwd.h) --
179
180 /** @brief Sets the logical resolution the scene is rendered at (scaled to 480x272 at submit) */
181 static void ResizeScreenFramebuffer(std::int32_t width, std::int32_t height);
182
183 // -- GU session, driven by the Psp window backend --
184
185 /** @brief Brings up the GE (sceGuInit, the double-buffered 480x272 display, the initial pipeline state) */
186 static void InitializeGu();
187 /** @brief Tears the GE session down again (sceGuTerm), so the exit path leaves the hardware idle */
188 static void ShutdownGu();
189
190 // -- GU backend extensions (called by the resource types and read by the draw dispatch) --
191
192 /** @brief Records the currently bound shader program */
193 static void BindProgram(GuShaderProgram* program);
194 /** @brief Returns the currently bound shader program */
195 static GuShaderProgram* CurrentProgram();
196 /** @brief Records the texture bound to a texture unit */
197 static void BindTexture(std::uint32_t unit, const GuTexture* texture);
198 /** @brief Clears a texture from every unit it is bound to (called from ~GuTexture) */
199 static void UnbindTexture(const GuTexture* texture);
200 /** @brief Returns the texture bound to a texture unit */
201 static const GuTexture* GetBoundTexture(std::uint32_t unit);
202 /** @brief Records the host data range bound to a uniform binding point */
203 static void BindUniformRange(std::uint32_t index, const std::uint8_t* data, std::uint32_t size);
204 /** @brief Records the current draw render target (draws redirect the GE's draw buffer to it) */
205 static void SetRenderTarget(GuRenderTarget* renderTarget);
206 /** @brief Clears a render target from the device if it is the current one (called from ~GuRenderTarget) */
207 static void UnbindRenderTarget(const GuRenderTarget* renderTarget);
208
209 /** @brief Registers the intercepted shared palette texture (rows become hardware CLUTs) */
210 static void RegisterPaletteTexture(GuTexture* texture);
211 /** @brief Invalidates the CLUT copies (and RG8 bakes) built from the given palette rows after an upload */
212 static void NotifyPaletteTextureChanged(GuTexture* texture, std::int32_t firstRow, std::int32_t rowCount);
213
214 /**
215 @brief Allocates a block of video memory, or `nullptr` when none is left
216
217 The 2 MB of embedded video memory is laid out by hand (there is no allocator behind
218 `sceGeEdramGetAddr()`): the display buffers and the depth buffer sit at the front, and whatever
219 follows them is handed out through this first-fit allocator to the surfaces that are worth
220 keeping there - render targets. Sprite atlases deliberately stay in main memory, which the GE
221 samples too.
222 */
223 static void* AllocateVram(std::size_t size);
224 /** @brief Returns a block obtained from @ref AllocateVram() */
225 static void FreeVram(void* ptr);
226
227 /** @brief Queues the CPU lightmap/water combine for the next `Combine` draw (the direct-tier lighting contract) */
228 static void SetPendingSoftwareLighting(const float* lightmap, std::int32_t lmW, std::int32_t lmH, std::int32_t scale,
229 std::int32_t vpX, std::int32_t vpY, std::int32_t vpW, std::int32_t vpH, float ambR, float ambG, float ambB,
230 bool waterActive = false, float waterLevelPx = 0.0f, float waterTime = 0.0f, float waterCamY = 0.0f);
231 /** @brief Drops any lighting entries not consumed this frame (called by the window backend at present) */
232 static void EndFrame();
233
234 private:
235 static constexpr std::uint32_t MaxTextureUnits = 8;
236 static constexpr std::uint32_t MaxUniformBindings = 8;
237
238 struct UniformRange
239 {
240 const std::uint8_t* Data = nullptr;
241 std::uint32_t Size = 0;
242 };
243
244 struct PendingSoftwareLight
245 {
246 const float* Lightmap = nullptr;
247 std::int32_t LmW = 0, LmH = 0, Scale = 1;
248 std::int32_t VpX = 0, VpY = 0, VpW = 0, VpH = 0;
249 float AmbR = 0.0f, AmbG = 0.0f, AmbB = 0.0f;
250 bool WaterActive = false;
251 float WaterLevelPx = 0.0f, WaterTime = 0.0f, WaterCamY = 0.0f;
252 };
253
254 static BlendingState _blending;
255 static DepthTestState _depthTest;
256 static CullFaceState _cullFace;
257 static ScissorState _scissor;
258 static Recti _viewport;
259 static Colorf _clearColor;
260
261 static GuShaderProgram* _currentProgram;
262 static const GuTexture* _boundTextures[MaxTextureUnits];
263 static UniformRange _boundUniformRanges[MaxUniformBindings];
264 static GuRenderTarget* _currentRenderTarget;
265
266 static bool _guInitialized;
267 static bool _listOpen;
268 static std::int32_t _logicalWidth;
269 static std::int32_t _logicalHeight;
270 static std::uint32_t _sceneCounter;
271
272 static GuTexture* _paletteTexture;
273 static std::uint32_t _paletteGeneration;
274
275 static std::vector<PendingSoftwareLight> _pendingSoftwareLights;
276
277 /** @brief Opens the frame's display list if it is not open yet (the draw paths and Clear() call this) */
278 static void EnsureList();
279 /** @brief Points the GE at the current draw surface (the flipped display buffer or a render target) */
280 static void ApplyDrawTarget();
281 /** @brief Programs the hardware scissor for the current target from the tracked engine state */
282 static void ApplyScissor();
283 /** @brief Maps the logical space onto the current target (scale of the 480x272 panel, or 1:1 for a target) */
284 static void GetTargetScale(float& scaleX, float& scaleY);
285
286 static void Dispatch(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices);
287 // Draws a whole tile-layer mesh (a triangle list of position/texcoord/colour vertices)
288 static void DispatchTileMesh(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices);
289 // Draws a vertex-fed textured line strip (the weapon wheel) through the GE's native line primitive
290 static void DispatchLineStrip(std::int32_t firstVertex, std::int32_t numVertices);
291 static void ApplyPendingSoftwareLighting();
292 };
293 }