Debian Codegraph @

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

raw
1 #pragma once
2
3 #include "../RhiTypes.h"
4
5 #include <cstddef>
6 #include <cstdint>
7
8 #include <Containers/SmallVector.h>
9 #include <Containers/StringView.h>
10
11 using namespace Death::Containers;
12
13 namespace nCine::RHI::GU
14 {
15 /**
16 @brief Texture object of the GU backend (aliased as `RHI::Texture`)
17
18 Keeps a LINEAR host store of level 0 in the uploaded pixel format (the same native R8/RG8/RGBA8
19 layout the software and PVR backends use) plus a second store the Allegrex GE can sample directly.
20 The GE reads textures out of ordinary addressable memory, so that store lives in main memory rather
21 than in the 2 MB of video memory - only render targets and the display buffers are worth putting
22 there - but it still has to satisfy three hardware requirements the host store does not:
23
24 - **Power-of-two dimensions, at most 512 per axis** (the texture size register holds log2 of each
25 axis in 4 bits, and u/v addressing is 9-bit). Anything larger is split into @ref Page "pages" of
26 at most 512x512, and the draw path selects the page a primitive's texture rectangle falls into and
27 rebases its texture coordinates onto it (see @ref AcquirePage()). Every sprite/tile draw samples
28 one small sub-rect of an atlas, so a primitive practically never straddles a page boundary.
29 - **A format the GE samples.** R8 index textures become `GU_PSM_T8` read through a hardware CLUT
30 (the direct analogue of the PowerVR's palette banks and the GX's TLUTs) - the CLUT itself is
31 loaded per draw by the device from whatever palette texture the material bound. RG8 (index +
32 per-pixel alpha) has no paletted equivalent, because a paletted texel's alpha comes from the CLUT
33 entry, so those get the same per-palette-row CPU bake the other consoles use, into `GU_PSM_4444`
34 (@ref EnsureBakedStore()). RGB8/RGBA8 convert to `GU_PSM_4444` as well, and RGB565 to
35 `GU_PSM_5650` (whose channel order is the reverse of the engine's).
36 - **The CPU cache written back**, since the GE reads main memory without seeing the data cache. Every
37 store rebuild ends in a writeback of exactly the bytes it wrote.
38
39 Static content is additionally stored *swizzled* (the GE's 16-byte x 8-row block interleave), which
40 is substantially cheaper to sample; content that is replaced repeatedly (the cinematic frames)
41 drops the swizzle after its second upload, because interleaving it every frame would cost more than
42 it saves. @ref MapStreamingTexels() lets such a texture be built straight in the GE store.
43
44 Mip levels above 0 and compressed formats are accepted but not stored, exactly like on the other
45 fixed-function backends: the game never uses either.
46 */
47 class GuTexture
48 {
49 public:
50 /** @brief Number of texture units tracked by the device */
51 static constexpr std::uint32_t MaxTextureUnits = 8;
52
53 /** @brief The dimension a single GE texture cannot exceed, per axis (a hardware limit) */
54 static constexpr std::int32_t MaxPageDimension = 512;
55
56 /**
57 @brief One GE-addressable piece of the texture
58
59 A texture no larger than @ref MaxPageDimension on either axis has exactly one page covering it
60 whole, which is the case for practically all content; bigger images are tiled by pages (see the
61 class documentation).
62 */
63 struct Page
64 {
65 /** @brief 16-byte aligned base of the page's texels, in a format the GE samples */
66 const void* Data = nullptr;
67 /** @brief Position of the page's first texel within the source image */
68 std::int32_t OriginX = 0, OriginY = 0;
69 /** @brief Size of the source region the page covers */
70 std::int32_t Width = 0, Height = 0;
71 /** @brief Power-of-two size the GE is told about (the region above padded up) */
72 std::int32_t PaddedWidth = 0, PaddedHeight = 0;
73 /** @brief Whether the texels are stored in the GE's block interleave */
74 bool Swizzled = false;
75 };
76
77 explicit GuTexture(TextureTarget target);
78 ~GuTexture();
79
80 GuTexture(const GuTexture&) = delete;
81 GuTexture& operator=(const GuTexture&) = delete;
82
83 /** @brief Returns a backend-neutral identifier uniquely identifying the texture (feeds material sort keys) */
84 inline std::uint32_t GetUniqueId() const {
85 return _handle;
86 }
87 /** @brief Returns the texture target */
88 inline TextureTarget GetTarget() const {
89 return _target;
90 }
91
92 /** @brief Returns the width of level 0 in texels */
93 inline std::int32_t GetWidth() const {
94 return _width;
95 }
96 /** @brief Returns the height of level 0 in texels */
97 inline std::int32_t GetHeight() const {
98 return _height;
99 }
100 /** @brief Returns the pixel format of the linear host store (native, like the software backend) */
101 inline PixelFormat GetFormat() const {
102 return _format;
103 }
104 /** @brief Returns the original upload format (R8/RG8 kept so the palette path can tell them apart) */
105 inline PixelFormat GetUploadFormat() const {
106 return _uploadFormat;
107 }
108 /** @brief Returns the byte distance between two consecutive rows of the linear host store */
109 inline std::int32_t GetStrideBytes() const {
110 return _strideBytes;
111 }
112 /** @brief Returns the base pointer of the linear host store (may be `nullptr` before an upload) */
113 inline const std::uint8_t* GetPixels(std::int32_t level = 0) const {
114 static_cast<void>(level);
115 return (_pixels.empty() ? nullptr : _pixels.data());
116 }
117 /** @brief Returns a writable base pointer of the linear host store (`nullptr` before an upload) */
118 inline std::uint8_t* MutablePixels() {
119 return (_pixels.empty() ? nullptr : _pixels.data());
120 }
121 /** @brief Returns the horizontal texture-coordinate wrap mode */
122 inline SamplerWrapping GetWrapS() const {
123 return _wrap;
124 }
125 /** @brief Returns the vertical texture-coordinate wrap mode (single stored mode) */
126 inline SamplerWrapping GetWrapT() const {
127 return _wrap;
128 }
129 /** @brief Returns the four-channel sampling swizzle (identity by default; informational on GU) */
130 inline const SwizzleChannel* GetSwizzle() const {
131 return _swizzle;
132 }
133 /** @brief Returns the magnification filter */
134 inline nCine::SamplerFilter GetMagFiltering() const {
135 return _magFilter;
136 }
137 /** @brief Alias of @ref GetMagFiltering() */
138 inline nCine::SamplerFilter GetMagFilter() const {
139 return _magFilter;
140 }
141 /** @brief Returns `true` if the texture is bound as a color render target */
142 inline bool IsRenderTarget() const {
143 return _isRenderTarget;
144 }
145 /** @brief Marks the texture as (or no longer as) a color render target; becoming one allocates its surface */
146 void SetRenderTarget(bool isRenderTarget);
147 /** @brief Returns a globally monotonic stamp of the texel store, advanced by every allocation or upload */
148 inline std::uint32_t GetContentVersion() const {
149 return _contentVersion;
150 }
151
152 /** @brief Returns `true` when the store holds palette indices (draws resolve them through a CLUT) */
153 inline bool IsIndexed() const {
154 return (_uploadFormat == PixelFormat::R8);
155 }
156 /** @brief Returns `true` when the texture needs the per-palette-row CPU bake (RG8 index + alpha) */
157 inline bool NeedsPaletteBake() const {
158 return (_uploadFormat == PixelFormat::RG8);
159 }
160 /** @brief Returns `true` when this is the intercepted shared palette texture (its rows become CLUTs) */
161 inline bool IsPaletteTexture() const {
162 return _isPaletteTexture;
163 }
164
165 // -- GE store (read by the draw dispatch) --
166
167 /**
168 @brief Builds the GE store if it is missing and returns the page holding the given source texel
169
170 @p texelX / @p texelY are clamped into the image, so the min corner of any texture rectangle is a
171 valid argument. Returns `nullptr` when there is nothing to sample (no upload yet, an unsupported
172 format, or an RG8 store whose bake has not been requested - see @ref EnsureBakedStore()).
173 */
174 const Page* AcquirePage(std::int32_t texelX, std::int32_t texelY);
175 /** @brief Returns the `GU_PSM_*` pixel format of the GE store (valid once a page exists) */
176 inline std::int32_t GetGuPixelFormat() const {
177 return _guFormat;
178 }
179 /** @brief Number of pages the image is split into along each axis (1 x 1 for anything up to 512x512) */
180 inline std::int32_t GetPageCountX() const {
181 return _pagesX;
182 }
183 /** @brief Number of pages the image is split into along each axis */
184 inline std::int32_t GetPageCountY() const {
185 return _pagesY;
186 }
187
188 /**
189 @brief Makes the GE store hold this RG8 texture baked through one palette row
190
191 Index resolved through @p paletteRow (256 RGBA8 entries), alpha from the texel's own alpha byte,
192 written as `GU_PSM_4444` - the analogue of @ref PVR::PvrTexture::EnsureBakedArgb4444(). A small
193 number of bakes is cached, so the common "one extra palette row" case (a sprite and its
194 recolored twin) does not rebuild anything; @ref AcquirePage() then hands out the pages of the
195 matching bake. Returns `false` when the bake could not be produced.
196 */
197 bool EnsureBakedStore(const std::uint32_t* paletteRow, std::uint32_t paletteRowIndex,
198 std::uint32_t paletteGeneration, const void* palette);
199
200 /**
201 @brief Returns a writable pointer to the GE store, for content that is rebuilt every frame
202
203 Answered only for the format the hardware samples verbatim out of memory (RGB565), which is what
204 lets the cinematics build a frame straight where the GE will read it instead of into a buffer that
205 is then copied into the host store and converted a second time. Returns `nullptr` for anything
206 else, and whenever the store cannot be allocated.
207
208 @p strideBytes receives the row pitch, which is the power-of-two padded page width rather than the
209 texture's own. Nothing written here reaches the host copy, so such a texture must be rewritten in
210 full every frame and never read back. The channel order is the GE's (`GU_PSM_5650`, red in the low
211 bits) rather than the engine's, so the bytes are swapped in place once per frame before the GE
212 sees them (@ref AcquirePage()).
213 */
214 void* MapStreamingTexels(std::int32_t& strideBytes);
215
216 /** @brief Returns the surface the GE renders into when this texture is a render target, or `nullptr` */
217 inline void* GetRenderTargetSurface() const {
218 return _renderTargetSurface;
219 }
220 /** @brief Returns the row pitch in texels of @ref GetRenderTargetSurface() */
221 inline std::int32_t GetRenderTargetStride() const {
222 return _renderTargetStride;
223 }
224
225 /** @brief Binds the texture to the specified texture unit on the device */
226 bool Bind(std::uint32_t textureUnit) const;
227 /** @brief Binds the texture to texture unit 0 */
228 inline bool Bind() const {
229 return Bind(0);
230 }
231 /** @brief Unbinds the texture from the unit it was last bound to */
232 bool Unbind() const;
233 /** @brief Unbinds any texture from the specified texture unit */
234 static bool Unbind(std::uint32_t textureUnit);
235
236 /** @brief Allocates level-0 storage of the given format/size and optionally uploads its texels */
237 void TexImage2D(std::int32_t level, PixelFormat format, bool bgr, std::int32_t width, std::int32_t height, const void* data);
238 /** @brief Updates a rectangular subregion of level 0 */
239 void TexSubImage2D(std::int32_t level, std::int32_t xoffset, std::int32_t yoffset, std::int32_t width, std::int32_t height, PixelFormat format, bool bgr, const void* data);
240 /** @brief Allocates immutable level-0 storage of the given format/size (no texels yet) */
241 void TexStorage2D(std::int32_t levels, PixelFormat format, std::int32_t width, std::int32_t height);
242 /** @brief Compressed upload (unsupported, accepted as a no-op) */
243 void CompressedTexImage2D(std::int32_t level, PixelFormat format, std::int32_t width, std::int32_t height, std::int32_t imageSize, const void* data);
244 /** @brief Compressed sub-upload (unsupported, accepted as a no-op) */
245 void CompressedTexSubImage2D(std::int32_t level, std::int32_t xoffset, std::int32_t yoffset, std::int32_t width, std::int32_t height, PixelFormat format, std::int32_t imageSize, const void* data);
246 /** @brief Reads back level-0 texels of the linear host store into client memory */
247 void GetTexImage(std::int32_t level, PixelFormat format, bool bgr, void* pixels);
248
249 /** @brief Sets the minification filter */
250 void SetMinFiltering(nCine::SamplerFilter filter);
251 /** @brief Sets the magnification filter */
252 void SetMagFiltering(nCine::SamplerFilter filter);
253 /** @brief Sets the wrap mode */
254 void SetWrap(SamplerWrapping wrap);
255 /** @brief Sets the sampling swizzle (stored, informational - the palette path keys off the upload format instead) */
256 void SetSwizzle(SwizzleChannel r, SwizzleChannel g, SwizzleChannel b, SwizzleChannel a);
257 /** @brief Sets the highest defined mipmap level (ignored) */
258 void SetMaxLevel(std::int32_t maxLevel);
259 /** @brief Sets the client pixel-row alignment of uploads (ignored, uploads are tightly packed) */
260 static void SetUnpackAlignment(std::int32_t alignment);
261
262 /** @brief Sets a debug label; "Palettes" marks the shared palette texture whose rows become CLUTs */
263 void SetObjectLabel(StringView label);
264
265 static bool SupportsImmutableStorage() {
266 return false;
267 }
268 static bool SupportsTextureReadback() {
269 return true;
270 }
271 static void ClearErrors() {}
272 static bool CheckErrors() {
273 return false;
274 }
275 static void CheckFormatSupport(PixelFormat format) {
276 static_cast<void>(format);
277 }
278
279 /** @brief Returns the number of bytes occupied by one texel of the given format (0 if unsupported) */
280 static std::int32_t BytesPerPixel(PixelFormat format);
281
282 private:
283 // The bake cache of an RG8 texture. Two entries, because a sprite drawn through two palette rows in
284 // the same frame is a real pattern (a recolored twin next to the original) and rebuilding one bake
285 // twice per frame would both cost the whole conversion twice and let the GE - which runs behind the
286 // CPU on its own display list - sample the second row's texels for the first row's draws. Anything
287 // beyond two rows falls back to rebuilding, with a one-time warning.
288 static constexpr std::int32_t BakedStoreCount = 2;
289
290 static std::uint32_t _nextHandle;
291 static std::uint32_t _nextContentVersion;
292
293 std::uint32_t _handle;
294 std::uint32_t _contentVersion;
295 TextureTarget _target;
296 PixelFormat _format;
297 PixelFormat _uploadFormat;
298 std::int32_t _width;
299 std::int32_t _height;
300 std::int32_t _strideBytes;
301 std::int32_t _bytesPerPixel;
302 nCine::SamplerFilter _minFilter;
303 nCine::SamplerFilter _magFilter;
304 SamplerWrapping _wrap;
305 SwizzleChannel _swizzle[4];
306 mutable std::uint32_t _textureUnit;
307 SmallVector<std::uint8_t, 0> _pixels;
308 bool _isRenderTarget;
309 bool _isPaletteTexture;
310
311 // The GE store: one allocation holding every page back to back (pages are laid out row-major).
312 // Rebuilt lazily from the host store, so an upload only invalidates it.
313 std::uint8_t* _geStore;
314 std::size_t _geStoreSize;
315 std::int32_t _guFormat;
316 std::int32_t _geBytesPerTexel;
317 std::int32_t _pagesX;
318 std::int32_t _pagesY;
319 SmallVector<Page, 1> _pages;
320 bool _geStoreValid;
321 // Which bake the GE store currently holds (RG8 only) and the two cached bakes it can be switched
322 // between without a rebuild
323 struct BakedStore
324 {
325 std::uint8_t* Data = nullptr;
326 std::uint32_t PaletteRow = 0;
327 std::uint32_t PaletteGeneration = 0;
328 std::uint32_t ContentVersion = 0;
329 const void* Palette = nullptr;
330 bool Valid = false;
331 };
332 BakedStore _bakedStores[BakedStoreCount];
333 std::int32_t _activeBakedStore;
334 std::int32_t _nextBakedStore;
335 // Number of full uploads the texture has received. Content that is replaced again (video frames)
336 // stops being swizzled, because interleaving it every frame costs more than the sampling saves.
337 std::uint32_t _uploadCount;
338 // Whether MapStreamingTexels() handed the GE store out and its channel order still has to be
339 // flipped into the GE's before a draw can read it
340 bool _streamingSwapPending;
341
342 // The render-target surface the GE draws into (video memory when it fits, main memory otherwise);
343 // it doubles as the texture's single page when the target is sampled afterwards
344 void* _renderTargetSurface;
345 std::int32_t _renderTargetStride;
346 bool _renderTargetSurfaceInVram;
347
348 void Allocate(PixelFormat format, std::int32_t width, std::int32_t height);
349 /** @brief Recomputes the page grid and the GE pixel format from the upload format and size */
350 void PlanGeStore();
351 /** @brief Builds (or rebuilds) the GE store from the host store; returns `false` on failure */
352 bool RefreshGeStore();
353 /** @brief Converts and pads one page out of the host store into @p dst, then swizzles it if wanted */
354 void BuildPage(const Page& page, std::uint8_t* dst, bool swizzle);
355 /** @brief Converts and pads one page out of the host store baked through a palette row */
356 void BuildBakedPage(const Page& page, std::uint8_t* dst, const std::uint16_t* rgb444, bool swizzle);
357 /** @brief Drops the GE store (and every bake), so the next draw rebuilds it */
358 void InvalidateGeStore();
359 void FreeGeStores();
360 void FreeRenderTargetSurface();
361
362 /** @brief Returns the size of the linear (uncompressed) level-0 image in bytes */
363 inline std::int32_t RawPixelsSize() const {
364 return _strideBytes * (_height > 0 ? _height : 0);
365 }
366 };
367 }