Debian Codegraph @

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

raw
1 #pragma once
2
3 #include "../RhiTypes.h"
4 #include "GsVram.h"
5
6 #include <cstddef>
7 #include <cstdint>
8
9 #include <Containers/SmallVector.h>
10 #include <Containers/StringView.h>
11
12 using namespace Death::Containers;
13
14 namespace nCine::RHI::GS
15 {
16 /**
17 @brief Texture object of the GS backend (aliased as `RHI::Texture`)
18
19 Keeps a LINEAR host store of level 0 in the uploaded pixel format (the same native R8/RG8/RGBA8 layout
20 the software and PVR backends use) plus a residency in the Graphics Synthesizer's local memory, placed
21 by @ref GsVram in whole pages:
22 - R8 index textures become `PSMT8`, with the colours coming from a CLUT the device selects per draw
23 out of the CLUT slab (from the instance's `palOffset`) - the GS resolves the lookup in the texture
24 read, so indices upload as they are.
25 - RG8 (index + per-pixel alpha) has no paletted GS equivalent, because a `PSMT8` texel's alpha comes
26 from its CLUT entry. Those keep only the host store and the device asks for a per-palette-row CPU
27 bake to `PSMCT32` (@ref EnsureBakedColor), cached until the row or the texel content changes.
28 - RGB8 / RGBA8 upload as `PSMCT32`. Unlike the PowerVR - which has no 32-bit sampled format and had to
29 convert to ARGB4444 - the GS sampples 32-bit directly, so these keep full precision. `PSMCT16` would
30 halve the footprint but its alpha is a single bit, which is useless for blended sprite art, and
31 true-colour sheets are few once the content is indexed.
32 - The shared 256x256 palette texture (labelled "Palettes") is intercepted: it keeps only the host
33 store and the device loads its rows into CLUT slots on demand.
34
35 Render targets take a `PSMCT16` surface out of the layout's render-target reserve rather than the
36 streaming cache, and are never evicted - there is no host copy to rebuild one from.
37
38 @section GsTexture-residency Residency
39
40 The host store is the source of truth and local memory is a cache, exactly as on the Dreamcast: when
41 @ref GsVram runs out of pages the least recently used stores are dropped (see @ref AllocatePages()),
42 and a texture drawn again afterwards is re-uploaded from its host copy by @ref AcquireTexturePage().
43 Unlike the PVR backend the host stores are **not** run-length compressed: a rebuild here is a plain
44 DMA out of main memory (the GS does the block swizzling itself), so keeping the copy in the layout the
45 transfer wants makes a rebuild cost almost no CPU at all. The Dreamcast traded CPU time for main
46 memory because it only had 16 MB and had to twiddle in software; with 32 MB and a DMA engine the trade
47 goes the other way.
48
49 Mip levels above 0 and compressed formats are accepted but not stored.
50 */
51 class GsTexture
52 {
53 public:
54 /** @brief Number of texture units tracked by the device */
55 static constexpr std::uint32_t MaxTextureUnits = 8;
56 /** @brief Number of per-palette-row baked copies kept for RG8 textures */
57 static constexpr std::int32_t BakedSlotCount = 3;
58
59 explicit GsTexture(TextureTarget target);
60 ~GsTexture();
61
62 GsTexture(const GsTexture&) = delete;
63 GsTexture& operator=(const GsTexture&) = delete;
64
65 /** @brief Returns a backend-neutral identifier uniquely identifying the texture (feeds material sort keys) */
66 inline std::uint32_t GetUniqueId() const {
67 return _handle;
68 }
69 /** @brief Returns the texture target */
70 inline TextureTarget GetTarget() const {
71 return _target;
72 }
73
74 /** @brief Returns the width of level 0 in texels */
75 inline std::int32_t GetWidth() const {
76 return _width;
77 }
78 /** @brief Returns the height of level 0 in texels */
79 inline std::int32_t GetHeight() const {
80 return _height;
81 }
82 /** @brief Returns the pixel format of the linear host store */
83 inline PixelFormat GetFormat() const {
84 return _format;
85 }
86 /** @brief Returns the original upload format (R8/RG8 kept so the palette path can tell them apart) */
87 inline PixelFormat GetUploadFormat() const {
88 return _uploadFormat;
89 }
90 /** @brief Returns the byte distance between two consecutive rows of the linear host store */
91 inline std::int32_t GetStrideBytes() const {
92 return _strideBytes;
93 }
94 /** @brief Returns the base pointer of the linear host store (may be `nullptr` before an upload) */
95 inline const std::uint8_t* GetPixels(std::int32_t level = 0) const {
96 static_cast<void>(level);
97 return (_pixels.empty() ? nullptr : _pixels.data());
98 }
99 /** @brief Returns a writable base pointer of the linear host store */
100 inline std::uint8_t* MutablePixels() {
101 return (_pixels.empty() ? nullptr : _pixels.data());
102 }
103 /** @brief Returns the horizontal texture-coordinate wrap mode */
104 inline SamplerWrapping GetWrapS() const {
105 return _wrap;
106 }
107 /** @brief Returns the vertical texture-coordinate wrap mode (single stored mode) */
108 inline SamplerWrapping GetWrapT() const {
109 return _wrap;
110 }
111 /** @brief Returns the four-channel sampling swizzle (identity by default; informational on the GS) */
112 inline const SwizzleChannel* GetSwizzle() const {
113 return _swizzle;
114 }
115 /** @brief Returns the magnification filter */
116 inline nCine::SamplerFilter GetMagFiltering() const {
117 return _magFilter;
118 }
119 /** @brief Alias of @ref GetMagFiltering() */
120 inline nCine::SamplerFilter GetMagFilter() const {
121 return _magFilter;
122 }
123 /** @brief Returns the minification filter */
124 inline nCine::SamplerFilter GetMinFiltering() const {
125 return _minFilter;
126 }
127 /** @brief Returns `true` if the texture is bound as a color render target */
128 inline bool IsRenderTarget() const {
129 return _isRenderTarget;
130 }
131 /** @brief Marks the texture as (or no longer as) a color render target; becoming one allocates its surface */
132 void SetRenderTarget(bool isRenderTarget);
133 /** @brief Returns a globally monotonic stamp of the texel store, advanced by every allocation or upload */
134 inline std::uint32_t GetContentVersion() const {
135 return _contentVersion;
136 }
137
138 /** @brief Returns `true` when the store is `PSMT8` (draws need a CLUT selected) */
139 inline bool IsIndexed() const {
140 return (_uploadFormat == PixelFormat::R8);
141 }
142 /** @brief Returns `true` when the texture needs the per-palette-row CPU bake (RG8 index + alpha) */
143 inline bool NeedsPaletteBake() const {
144 return (_uploadFormat == PixelFormat::RG8);
145 }
146 /** @brief Returns `true` when this is the intercepted shared palette texture (rows become CLUTs) */
147 inline bool IsPaletteTexture() const {
148 return _isPaletteTexture;
149 }
150
151 /** @brief Returns the first page of the local-memory store, or @ref GsVram::InvalidPage when none exists */
152 inline std::uint32_t GetTexturePage() const {
153 return _page;
154 }
155 /**
156 @brief Returns the first page of the store, re-uploading it if it was reclaimed
157
158 Should be used by the draw path: running out of local memory drops the least recently used stores
159 (see @ref AllocatePages()), and a texture that is drawn again afterwards has to be transferred
160 from its main-memory copy once more.
161 */
162 std::uint32_t AcquireTexturePage();
163 /** @brief Returns the pixel storage mode the local-memory store was uploaded in */
164 inline GsPsm GetPsm() const {
165 return _psm;
166 }
167 /** @brief Returns the store's buffer pitch in TEXELS, which is what `libdraw` wants in `texbuffer_t::width` */
168 inline std::int32_t GetBufferPitch() const {
169 return _bufferPitch;
170 }
171 /** @brief Returns the power-of-two sampled width (`TEX0.TW` is a log2 field) */
172 inline std::int32_t GetPaddedWidth() const {
173 return _paddedWidth;
174 }
175 /** @brief Returns the power-of-two sampled height (`TEX0.TH` is a log2 field) */
176 inline std::int32_t GetPaddedHeight() const {
177 return _paddedHeight;
178 }
179 /** @brief Returns the U compensation factor for the power-of-two sampled extent (`realW / paddedW`) */
180 inline float GetUScale() const {
181 return _uScale;
182 }
183 /** @brief Returns the V compensation factor for the power-of-two sampled extent (`realH / paddedH`) */
184 inline float GetVScale() const {
185 return _vScale;
186 }
187
188 /**
189 @brief Returns the page of a `PSMCT32` copy of an RG8 store baked through one palette row
190
191 Analogous to the PVR backend's ARGB4444 bake: the index is resolved through @p paletteRow (256
192 RGBA8 entries) and the alpha comes from the texel's own alpha byte. One cached copy per slot,
193 rebuilt when the row, generation or content changes. Returns @ref GsVram::InvalidPage on failure.
194 */
195 std::uint32_t EnsureBakedColor(const std::uint32_t* paletteRow, std::uint32_t paletteRowIndex,
196 std::uint32_t paletteGeneration, const void* palette);
197 /** @brief Returns the buffer pitch in texels of the baked copies (they share the store's sampled extent) */
198 inline std::int32_t GetBakedBufferPitch() const {
199 return _paddedWidth;
200 }
201
202 /**
203 @brief Always returns `nullptr` on the GS - local memory cannot be written by the CPU
204
205 The PVR and GU backends answer this for content that is rebuilt every frame (the cinematics), so
206 a frame can be produced straight where it will be sampled. The Graphics Synthesizer has no host
207 mapping of its local memory at all: everything arrives through a GIF transfer, so there is no
208 pointer to hand out. `RHI_CAP_STREAMING_TEXTURES` is deliberately left undefined for this backend
209 so that no caller reaches here in the first place.
210 */
211 void* MapStreamingTexels(std::int32_t& strideBytes);
212
213 /** @brief Binds the texture to the specified texture unit on the device */
214 bool Bind(std::uint32_t textureUnit) const;
215 /** @brief Binds the texture to texture unit 0 */
216 inline bool Bind() const {
217 return Bind(0);
218 }
219 /** @brief Unbinds the texture from the unit it was last bound to */
220 bool Unbind() const;
221 /** @brief Unbinds any texture from the specified texture unit */
222 static bool Unbind(std::uint32_t textureUnit);
223
224 /** @brief Allocates level-0 storage of the given format/size and optionally uploads its texels */
225 void TexImage2D(std::int32_t level, PixelFormat format, bool bgr, std::int32_t width, std::int32_t height, const void* data);
226 /** @brief Updates a rectangular subregion of level 0 */
227 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);
228 /** @brief Allocates immutable level-0 storage of the given format/size (no texels yet) */
229 void TexStorage2D(std::int32_t levels, PixelFormat format, std::int32_t width, std::int32_t height);
230 /** @brief Compressed upload (unsupported, accepted as a no-op) */
231 void CompressedTexImage2D(std::int32_t level, PixelFormat format, std::int32_t width, std::int32_t height, std::int32_t imageSize, const void* data);
232 /** @brief Compressed sub-upload (unsupported, accepted as a no-op) */
233 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);
234 /** @brief Reads back level-0 texels of the linear host store into client memory */
235 void GetTexImage(std::int32_t level, PixelFormat format, bool bgr, void* pixels);
236
237 /** @brief Sets the minification filter */
238 void SetMinFiltering(nCine::SamplerFilter filter);
239 /** @brief Sets the magnification filter */
240 void SetMagFiltering(nCine::SamplerFilter filter);
241 /** @brief Sets the wrap mode */
242 void SetWrap(SamplerWrapping wrap);
243 /** @brief Sets the sampling swizzle (stored, informational - the palette path keys off the upload format) */
244 void SetSwizzle(SwizzleChannel r, SwizzleChannel g, SwizzleChannel b, SwizzleChannel a);
245 /** @brief Sets the highest defined mipmap level (ignored) */
246 void SetMaxLevel(std::int32_t maxLevel);
247 /** @brief Sets the client pixel-row alignment of uploads (ignored, uploads are tightly packed) */
248 static void SetUnpackAlignment(std::int32_t alignment);
249
250 /** @brief Sets a debug label; "Palettes" marks the shared palette texture whose rows become CLUTs */
251 void SetObjectLabel(StringView label);
252
253 static bool SupportsImmutableStorage() {
254 return false;
255 }
256 static bool SupportsTextureReadback() {
257 return true;
258 }
259 static void ClearErrors() {}
260 static bool CheckErrors() {
261 return false;
262 }
263 static void CheckFormatSupport(PixelFormat format) {
264 static_cast<void>(format);
265 }
266
267 /** @brief Returns the number of bytes occupied by one texel of the given format (0 if unsupported) */
268 static std::int32_t BytesPerPixel(PixelFormat format);
269
270 /**
271 @brief Allocates local-memory pages, freeing the least recently used stores if necessary
272
273 The 4 MB of local memory is shared by the display buffers, the render-target reserve, the CLUT
274 slab and every texture, so a level with many tilesets (or a menu section that pulls in more
275 graphics) exhausts it - the measured working set of a whole level is larger than the cache by
276 design. The stores are a cache of the copies kept in main memory, so instead of failing the
277 allocation the oldest ones are dropped and re-transferred when they are needed again.
278
279 @p keepAlive is spared by the eviction walk, so a texture cannot evict itself while growing.
280 */
281 static std::uint32_t AllocatePages(std::uint32_t pageCount, const GsTexture* keepAlive);
282
283 private:
284 static std::uint32_t _nextHandle;
285 static std::uint32_t _nextContentVersion;
286
287 std::uint32_t _handle;
288 std::uint32_t _contentVersion;
289 TextureTarget _target;
290 PixelFormat _format;
291 PixelFormat _uploadFormat;
292 std::int32_t _width;
293 std::int32_t _height;
294 std::int32_t _strideBytes;
295 std::int32_t _bytesPerPixel;
296 nCine::SamplerFilter _minFilter;
297 nCine::SamplerFilter _magFilter;
298 SamplerWrapping _wrap;
299 SwizzleChannel _swizzle[4];
300 mutable std::uint32_t _textureUnit;
301 SmallVector<std::uint8_t, 0> _pixels;
302 bool _isRenderTarget;
303 bool _isPaletteTexture;
304
305 /** @brief First page of the local-memory store, or @ref GsVram::InvalidPage */
306 std::uint32_t _page;
307 /** @brief Pages the store occupies (kept so it can be freed without recomputing) */
308 std::uint32_t _pageCount;
309 /** @brief Whether @ref _page came from the render-target reserve rather than the streaming cache */
310 bool _pageFromReserve;
311 GsPsm _psm;
312 /** @brief Buffer pitch of the store in texels (padded to the storage mode's page width) */
313 std::int32_t _bufferPitch;
314 std::int32_t _paddedWidth;
315 std::int32_t _paddedHeight;
316 float _uScale;
317 float _vScale;
318
319 // One baked copy is kept per palette row, for the same reason the PVR backend keeps three: several
320 // rows are commonly alive within one frame (text and its shadow), and re-baking a row a submitted
321 // primitive still references would corrupt it. Each copy costs as much local memory as the texture
322 // itself, so the count stays a compromise between reuse and pressure on the cache.
323 struct BakedSlot
324 {
325 std::uint32_t Page = GsVram::InvalidPage;
326 std::uint32_t PageCount = 0;
327 bool Valid = false;
328 std::uint32_t PaletteRow = 0;
329 std::uint32_t PaletteGeneration = 0;
330 std::uint32_t ContentVersion = 0;
331 std::uint32_t LastUsedFrame = 0;
332 const void* Palette = nullptr;
333 };
334 BakedSlot _bakedSlots[BakedSlotCount];
335 std::int32_t _nextBakedSlot;
336
337 // Every texture with local memory attached is linked into this list, most recently used first, so an
338 // allocation that runs out of pages can reclaim the least recently used stores
339 static GsTexture* _liveHead;
340 static GsTexture* _liveTail;
341 GsTexture* _livePrev;
342 GsTexture* _liveNext;
343 // The frame this texture was last drawn in. NeverUsed marks one that has been uploaded but not drawn
344 // yet, which must stay evictable - during level loading the frame counter does not advance, so an
345 // untouched texture would otherwise look like part of the frame being assembled
346 static constexpr std::uint32_t NeverUsed = ~std::uint32_t(0);
347 std::uint32_t _lastUsedFrame;
348
349 void Allocate(PixelFormat format, std::int32_t width, std::int32_t height);
350 /** @brief Chooses the storage mode and pitch the current upload format wants */
351 void ResolveStorage(GsPsm& psm, std::int32_t& bufferPitch, std::uint32_t& pageCount) const;
352 /**
353 @brief Rows the store occupies: the real height rounded up to @p psm's page height
354
355 Shared by @ref ResolveStorage(), the upload and the RG8 bake so the three cannot disagree about how
356 tall the allocation is - which would either waste pages or transfer past the end of one.
357 */
358 std::int32_t ResolveStoreHeight(GsPsm psm) const;
359 /** @brief Makes sure a store of the right size exists, reallocating it if the storage mode changed */
360 bool EnsureStore();
361 /** @brief Transfers the host store into local memory */
362 void RefreshStore();
363 void FreeStores();
364
365 /** @brief Returns the size of the linear level-0 image in bytes */
366 inline std::int32_t RawPixelsSize() const {
367 return _strideBytes * (_height > 0 ? _height : 0);
368 }
369
370 /** @brief Moves this texture to the front of the live list and stamps it with the current frame */
371 void Touch();
372 /**
373 @brief Links this texture at the back of the live list if it is not in it yet
374
375 Attaching local memory has to make the texture visible to the eviction walk right away - a store
376 uploaded during level loading would otherwise be unreachable (and its pages unreclaimable) until
377 the first draw calls @ref Touch(). Linked least recently used, so untouched uploads are also the
378 first to go when memory runs short.
379 */
380 void LinkAsLeastRecent();
381 /** @brief Unlinks this texture from the live list */
382 void Unlink();
383 };
384 }