Debian Codegraph @

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

raw
1 #pragma once
2
3 #include <cstdint>
4
5 namespace nCine::RHI::GS
6 {
7 /**
8 @brief Pixel storage mode of a Graphics Synthesizer buffer (the `PSM` field of `TEX0`/`FRAME`)
9
10 Only the modes this backend can actually place in video memory are listed. The enumerator values are
11 the hardware ones, so they can be written into a register field directly.
12 */
13 enum class GsPsm : std::uint8_t
14 {
15 Ct32 = 0x00, /**< RGBA8888 */
16 Ct24 = 0x01, /**< RGB888 (stored in 32-bit cells, upper byte unused) */
17 Ct16 = 0x02, /**< RGBA5551 */
18 Ct16S = 0x0A, /**< RGBA5551, "scrambled" page layout */
19 T8 = 0x13, /**< 8-bit indexed, colours through a CLUT */
20 T4 = 0x14 /**< 4-bit indexed, colours through a CLUT */
21 };
22
23 /**
24 @brief Static layout of the Graphics Synthesizer's local memory, as requested by the device
25
26 Passed to @ref GsVram::Initialize(), which places the display buffers first, then the render-target
27 reserve, then the CLUT slab, and gives every page left over to the texture cache.
28 */
29 struct GsVramLayout
30 {
31 /** @brief Width of a display buffer in pixels (must be a multiple of 64, the `FBW` unit) */
32 std::int32_t DisplayWidth = 640;
33 /** @brief Height of a display buffer in pixels */
34 std::int32_t DisplayHeight = 448;
35 /** @brief Pixel storage mode of the display buffers */
36 GsPsm DisplayPsm = GsPsm::Ct16;
37 /** @brief Number of display buffers (1 for single-buffered, 2 for the usual flip) */
38 std::int32_t DisplayBufferCount = 2;
39 /**
40 @brief Pages statically reserved for render targets
41
42 Render targets have no host copy to rebuild from, so they must never be evicted (the PVR
43 backend spares them in its eviction walk for the same reason). Rather than let them compete
44 with the texture cache for space and fail unpredictably - which is how the Dreamcast's
45 256x256 `TexturedBackgroundPass` target used to fail to allocate - the ones the engine is
46 known to want are reserved up front out of a fixed pool.
47 */
48 std::uint32_t ReservedRttPages = 16;
49 /** @brief Number of 1 KB CLUT slots in the slab (a 256-entry 32-bit CLUT is exactly one slot) */
50 std::uint32_t ClutSlotCount = 32;
51 };
52
53 /**
54 @brief Page allocator for the Graphics Synthesizer's 4 MB of local memory
55
56 The GS has no memory allocator of its own: a buffer is simply a base address written into a register
57 (`TEX0.TBP0` for a texture, `FRAME.FBP` for a render target), and it is the program's job to make sure
58 two buffers never overlap. This class is that bookkeeping. It hands out **pages**, and only pages.
59
60 @section GsVram-granularity Why the granularity is a whole page
61
62 Local memory is organised as 512 pages of 8 KB, each page 32 blocks of 256 bytes. Within a page the
63 mapping from a texel coordinate to a block is a swizzle that **depends on the pixel storage mode** -
64 `PSMT8` and `PSMCT32` order the blocks of a page differently, and each mode covers a different number
65 of texels per page (see @ref GetPageGeometry()). Two buffers of different modes that share a page
66 therefore interleave unpredictably and corrupt each other, which is a failure mode the Dreamcast's
67 byte-granular `pvr_mem_malloc()` simply does not have.
68
69 Allocating whole pages removes the hazard by construction rather than by care: if no page is ever
70 shared by two buffers, no page can ever mix two storage modes, and the swizzle stays a private matter
71 inside each allocation. The cost is internal fragmentation of up to one page per texture - and for the
72 sheets this engine actually loads it is usually zero, because a power-of-two sheet at least as large as
73 one page in each direction covers an exact number of pages (a 256x256 `PSMT8` sheet is exactly 8).
74
75 @section GsVram-fragmentation Placement
76
77 Every request takes **exactly** the pages it needs, placed in the shortest free run long enough to
78 hold it (best fit, lowest address first).
79
80 It used to round the request up to a power of two and align it to its own size, which buys a buddy
81 allocator's freedom from external fragmentation. That trade is wrong for a cache this small: the
82 rounding costs up to *twice* the pages a buffer actually needs, and the page counts it was assumed
83 to be free for - power-of-two sheets - are only half the content. The stores that are not
84 power-of-two are exactly the large ones, where the waste is measured in hundreds of kilobytes: a
85 640x448 `PSMCT32` cinematic frame is 140 pages and was rounded to 256, throwing away 928 KB of a
86 3.3 MB cache, and a level's own mix of sheets lost about a fifth of the window to the same rounding.
87 External fragmentation costs nothing like that here, because it is not fatal: a request that cannot
88 be placed makes the caller evict and retry (see @ref GsVram-residency), and best fit keeps the long
89 runs the big atlases need intact by consuming the short ones first.
90
91 @section GsVram-residency Residency
92
93 This class only places and frees; it does not decide what should be resident. That is the caller's
94 job - `GsTexture` keeps the same most-recently-used list, per-frame stamp and host-store rebuild the
95 PVR backend uses, and calls @ref AllocatePages() through it. A failed allocation is reported, not
96 fatal: the caller evicts and retries, exactly as `PvrTexture::AllocateVram()` does.
97 */
98 class GsVram
99 {
100 public:
101 /** @brief Size of one block, the unit of `TEX0.TBP0` and `TEX0.CBP` */
102 static constexpr std::uint32_t BlockBytes = 256;
103 /** @brief Size of one page, the unit of `FRAME.FBP` */
104 static constexpr std::uint32_t PageBytes = 8192;
105 /** @brief Blocks per page */
106 static constexpr std::uint32_t BlocksPerPage = PageBytes / BlockBytes;
107 /** @brief Total local memory of the Graphics Synthesizer */
108 static constexpr std::uint32_t TotalBytes = 4 * 1024 * 1024;
109 /** @brief Total pages of local memory */
110 static constexpr std::uint32_t TotalPages = TotalBytes / PageBytes;
111 /** @brief Total blocks of local memory */
112 static constexpr std::uint32_t TotalBlocks = TotalBytes / BlockBytes;
113 /** @brief Texels of buffer width one unit of `TEX0.TBW`/`FRAME.FBW` stands for */
114 static constexpr std::int32_t BufferWidthUnit = 64;
115 /** @brief Bytes of one CLUT slot (256 entries of 32 bits) */
116 static constexpr std::uint32_t ClutSlotBytes = 1024;
117
118 /** @brief Returned by the allocators when the request could not be placed */
119 static constexpr std::uint32_t InvalidPage = ~std::uint32_t(0);
120 /** @brief Returned by @ref AllocateClut() when the slab is full */
121 static constexpr std::uint32_t InvalidBlock = ~std::uint32_t(0);
122
123 /** @brief Returns the number of texels one page covers horizontally and vertically in @p psm */
124 static void GetPageGeometry(GsPsm psm, std::int32_t& width, std::int32_t& height);
125 /**
126 @brief Returns the pages a @p width x @p height buffer of @p psm occupies
127
128 Both dimensions are rounded up to the page geometry of the storage mode, so the result is the
129 number of *whole* pages the buffer's addressing can reach - which is what has to be reserved.
130 */
131 static std::uint32_t GetPageCount(GsPsm psm, std::int32_t width, std::int32_t height);
132 /**
133 @brief Returns the `TBW`/`FBW` value for a buffer @p width texels wide in @p psm
134
135 The buffer pitch is padded to the page geometry like @ref GetPageCount() pads it, because the
136 pages behind it were reserved for the padded pitch. Note that a padded pitch costs no texture
137 coordinate compensation the way the PowerVR's power-of-two padding does: `TBW` is the pitch and
138 `TW`/`TH` are the sampled extent, and the two are independent fields.
139 */
140 static std::int32_t GetBufferWidth(GsPsm psm, std::int32_t width);
141 /**
142 @brief Returns the buffer pitch of a @p width texel wide buffer of @p psm, **in texels**
143
144 The same padded pitch @ref GetBufferWidth() reports, but not divided into `TBW` units. Both forms
145 are needed and they are easy to confuse: the raw register field wants `TBW`, while PS2SDK's
146 `libdraw` takes `texbuffer_t::width`/`framebuffer_t::width` in texels and divides by 64 itself.
147 Handing it a `TBW` value silently samples a 64-times-too-narrow buffer.
148 */
149 static std::int32_t GetPaddedWidth(GsPsm psm, std::int32_t width);
150
151 /**
152 @brief Places the static regions of @p layout and gives the rest to the texture cache
153
154 Resets every allocation, so it is also how a test starts from a known state. Returns `false` if
155 the static regions alone do not fit in local memory, in which case nothing is initialised.
156 */
157 static bool Initialize(const GsVramLayout& layout);
158 /** @brief Returns `true` once @ref Initialize() has succeeded */
159 static bool IsInitialized();
160
161 /** @brief Returns the first page of display buffer @p index (`FRAME.FBP` is a page number) */
162 static std::uint32_t GetDisplayBufferPage(std::int32_t index);
163 /** @brief Returns the `FBW` of the display buffers */
164 static std::int32_t GetDisplayBufferWidth();
165 /** @brief Returns the pixel storage mode of the display buffers */
166 static GsPsm GetDisplayPsm();
167
168 /**
169 @brief Allocates exactly @p pageCount pages from the texture cache
170
171 Returns the first page, or @ref InvalidPage when no run that long is free - the caller is expected
172 to evict and retry rather than treat it as fatal.
173 */
174 static std::uint32_t AllocatePages(std::uint32_t pageCount);
175 /** @brief Returns a run obtained from @ref AllocatePages() to the cache */
176 static void FreePages(std::uint32_t firstPage, std::uint32_t pageCount);
177
178 /**
179 @brief Allocates pages from the render-target reserve
180
181 Kept apart from the texture cache so that a render target - which has no host copy and so cannot
182 be evicted and rebuilt - can never be crowded out by streaming textures. A target that does not
183 fit here is not fatal either: @ref GsTexture::SetRenderTarget() falls back to the cache, where it
184 is still exempt from eviction. The reserve is what keeps the common case off the streaming
185 window, not a hard ceiling on render targets.
186 */
187 static std::uint32_t AllocateReservedPages(std::uint32_t pageCount);
188 /** @brief Returns a run obtained from @ref AllocateReservedPages() */
189 static void FreeReservedPages(std::uint32_t firstPage, std::uint32_t pageCount);
190
191 /**
192 @brief Allocates one CLUT slot, returning its block address (the unit of `TEX0.CBP`)
193
194 Every slot holds a 256-entry 32-bit CLUT, so all of them share the one storage mode and may
195 share pages - the slab is the single place this class sub-allocates a page, and it is safe for
196 exactly that reason. Returns @ref InvalidBlock when the slab is full.
197 */
198 static std::uint32_t AllocateClut();
199 /** @brief Returns a CLUT slot obtained from @ref AllocateClut() */
200 static void FreeClut(std::uint32_t block);
201
202 /** @brief Returns the first page of the texture cache */
203 static std::uint32_t GetCacheFirstPage();
204 /** @brief Returns the number of pages in the texture cache */
205 static std::uint32_t GetCachePageCount();
206 /** @brief Returns the number of texture-cache pages currently allocated */
207 static std::uint32_t GetUsedPageCount();
208 /** @brief Returns the high-water mark of @ref GetUsedPageCount() */
209 static std::uint32_t GetPeakUsedPageCount();
210 /**
211 @brief Returns the length of the longest free run in the texture cache
212
213 The difference between this and `GetCachePageCount() - GetUsedPageCount()` is the fragmentation,
214 which is the number to look at when an allocation fails while the cache is not full.
215 */
216 static std::uint32_t GetLargestFreeRun();
217 /**
218 @brief Returns how many allocations have failed since @ref Initialize()
219
220 The Dreamcast work used exactly this counter to tell a working set that fits from one that
221 thrashes (a level went from 2972 failed allocations to none), and it is the first number to look
222 at when bringing a level up here.
223 */
224 static std::uint32_t GetFailedAllocationCount();
225
226 private:
227 GsVram() = delete;
228
229 /** @brief Returns `true` when the page is free */
230 static bool IsPageFree(std::uint32_t page);
231 /** @brief Marks every page of the run allocated or free */
232 static void MarkRange(std::uint32_t firstPage, std::uint32_t pageCount, bool used);
233 /** @brief Places a run of exactly @p pageCount pages in the shortest free run of a page window that holds it */
234 static std::uint32_t AllocateWithin(std::uint32_t windowFirstPage, std::uint32_t windowPageCount, std::uint32_t pageCount);
235 /** @brief Returns the longest free run of a page window */
236 static std::uint32_t LargestFreeRunWithin(std::uint32_t windowFirstPage, std::uint32_t windowPageCount);
237
238 static constexpr std::uint32_t BitmapWords = TotalPages / 64;
239
240 static std::uint64_t _pageBitmap[BitmapWords];
241 static std::uint32_t _clutBitmap;
242 static std::uint32_t _clutSlotCount;
243 static std::uint32_t _clutFirstBlock;
244 static std::uint32_t _displayBufferPage[2];
245 static std::int32_t _displayBufferCount;
246 static std::int32_t _displayBufferWidth;
247 static GsPsm _displayPsm;
248 static std::uint32_t _reserveFirstPage;
249 static std::uint32_t _reservePageCount;
250 static std::uint32_t _cacheFirstPage;
251 static std::uint32_t _cachePageCount;
252 static std::uint32_t _usedPageCount;
253 static std::uint32_t _peakUsedPageCount;
254 static std::uint32_t _failedAllocationCount;
255 static bool _initialized;
256 };
257 }