Debian Codegraph @

Sources/nCine/Graphics/RHI/PVR/PvrTexture.cpp

raw
1 #include "PvrTexture.h"
2 #include "PvrDevice.h"
3
4 #include "../../../../Main.h"
5
6 #include <cstring>
7
8 #include <dc/sq.h>
9
10 using namespace Death::Containers::Literals;
11
12 namespace nCine::RHI::PVR
13 {
14 namespace
15 {
16 // Rounds a texture dimension up to the next power of two within the PVR's [8, 1024] window
17 std::int32_t NextPow2(std::int32_t value)
18 {
19 std::int32_t result = 8;
20 while (result < value && result < 1024) {
21 result <<= 1;
22 }
23 return result;
24 }
25
26 inline std::uint16_t Argb4444FromRgba(std::uint8_t r, std::uint8_t g, std::uint8_t b, std::uint8_t a)
27 {
28 return std::uint16_t(((a >> 4) << 12) | ((r >> 4) << 8) | ((g >> 4) << 4) | (b >> 4));
29 }
30
31 // PackBits run-length coding for the host pixel stores. Indexed pixel art is dominated by runs
32 // (transparent texels, flat fills), and measured on the stock levels the R8/RG8 stores shrink to
33 // 33-42% - about 3 MB less main memory per level, which is what makes the biggest levels (e.g.
34 // "secretf/04_haunted1", "xmas99/02_xmas2") fit into the console's 16 MB at all. Header byte n:
35 // 0..127 = copy the next n+1 bytes verbatim, 129..255 = repeat the next byte 257-n times; worst
36 // case grows by 1 byte per 128 (on data that would not stay compressed anyway - see StorePixels).
37 void EncodePackBits(const std::uint8_t* src, std::size_t size, SmallVector<std::uint8_t, 0>& out)
38 {
39 out.clear();
40 // Half is a safe upper estimate for the content that qualifies; growing past it is harmless
41 out.reserve(size / 2);
42
43 std::size_t i = 0;
44 while (i < size) {
45 // A repeat packet only pays off from 3 bytes (2 bytes of output either way at 2,
46 // but a run of 2 inside a literal costs nothing extra and avoids a packet break)
47 std::size_t run = 1;
48 while (i + run < size && run < 128 && src[i + run] == src[i]) {
49 run++;
50 }
51 if (run >= 3) {
52 out.push_back(std::uint8_t(257 - run));
53 out.push_back(src[i]);
54 i += run;
55 continue;
56 }
57
58 // Literal packet: extend until a worthwhile run starts or the packet is full
59 std::size_t literal = run;
60 while (i + literal < size && literal < 128) {
61 std::size_t nextRun = 1;
62 while (i + literal + nextRun < size && nextRun < 3 && src[i + literal + nextRun] == src[i + literal]) {
63 nextRun++;
64 }
65 if (nextRun >= 3) {
66 break;
67 }
68 literal += nextRun;
69 }
70 if (literal > 128) {
71 literal = 128;
72 }
73 out.push_back(std::uint8_t(literal - 1));
74 const std::uint8_t* from = &src[i];
75 for (std::size_t b = 0; b < literal; b++) {
76 out.push_back(from[b]);
77 }
78 i += literal;
79 }
80 }
81
82 // Streaming PackBits decoder: the consumers (VRAM rebuild, palette bake) walk the image strictly
83 // front to back one row at a time, so the store never has to be inflated whole - each Read() call
84 // hands out the next `count` bytes and keeps the packet state across calls
85 struct RlePixelReader
86 {
87 const std::uint8_t* Src;
88 // Remaining bytes of the packet in progress; positive = literal (copied from Src),
89 // negative = repeat (of RunValue)
90 std::int32_t Pending;
91 std::uint8_t RunValue;
92
93 explicit RlePixelReader(const std::uint8_t* src)
94 : Src(src), Pending(0), RunValue(0) {}
95
96 void Read(std::uint8_t* DEATH_RESTRICT dst, std::size_t count)
97 {
98 while (count > 0) {
99 if (Pending == 0) {
100 std::uint8_t header = *Src++;
101 if (header < 128) {
102 Pending = std::int32_t(header) + 1;
103 } else {
104 Pending = -(257 - std::int32_t(header));
105 RunValue = *Src++;
106 }
107 }
108 if (Pending > 0) {
109 std::size_t n = (std::size_t(Pending) < count ? std::size_t(Pending) : count);
110 std::memcpy(dst, Src, n);
111 Src += n;
112 dst += n;
113 Pending -= std::int32_t(n);
114 count -= n;
115 } else {
116 std::size_t n = (std::size_t(-Pending) < count ? std::size_t(-Pending) : count);
117 std::memset(dst, RunValue, n);
118 dst += n;
119 Pending += std::int32_t(n);
120 count -= n;
121 }
122 }
123 }
124 };
125
126 // Texture memory only supports 16 and 32-bit accesses. libc memcpy is free to fall back to byte
127 // writes for unaligned heads and odd tails, which silently corrupts texels on real hardware while
128 // emulators tolerate it - so copies into video memory spell their access width out
129 void CopyTexelsToVram(std::uint16_t* DEATH_RESTRICT dst, const std::uint16_t* DEATH_RESTRICT src, std::size_t count)
130 {
131 if (((reinterpret_cast<std::uintptr_t>(dst) | reinterpret_cast<std::uintptr_t>(src)) & 3) == 0) {
132 std::uint32_t* DEATH_RESTRICT dst32 = reinterpret_cast<std::uint32_t*>(dst);
133 const std::uint32_t* DEATH_RESTRICT src32 = reinterpret_cast<const std::uint32_t*>(src);
134 const std::size_t words = count >> 1;
135 for (std::size_t i = 0; i < words; i++) {
136 dst32[i] = src32[i];
137 }
138 if ((count & 1) != 0) {
139 dst[count - 1] = src[count - 1];
140 }
141 } else {
142 for (std::size_t i = 0; i < count; i++) {
143 dst[i] = src[i];
144 }
145 }
146 }
147 }
148
149 std::uint32_t PvrTexture::_nextHandle = 1;
150 std::uint32_t PvrTexture::_nextContentVersion = 0;
151
152 PvrTexture::PvrTexture(TextureTarget target)
153 : _handle(_nextHandle++), _contentVersion(0), _target(target), _format(PixelFormat::Unknown), _uploadFormat(PixelFormat::Unknown),
154 _width(0), _height(0), _strideBytes(0), _bytesPerPixel(0),
155 _minFilter(nCine::SamplerFilter::Nearest), _magFilter(nCine::SamplerFilter::Nearest), _wrap(SamplerWrapping::ClampToEdge),
156 _textureUnit(0), _pixelsCompressed(false), _isRenderTarget(false), _isPaletteTexture(false),
157 _vram(nullptr), _vramFormat(0), _vramBytesPerTexel(0), _paddedWidth(0), _paddedHeight(0), _uScale(1.0f), _vScale(1.0f),
158 _bakedSlots{}, _nextBakedSlot(0), _livePrev(nullptr), _liveNext(nullptr), _lastUsedScene(NeverUsed)
159 {
160 _swizzle[0] = SwizzleChannel::Red;
161 _swizzle[1] = SwizzleChannel::Green;
162 _swizzle[2] = SwizzleChannel::Blue;
163 _swizzle[3] = SwizzleChannel::Alpha;
164 }
165
166 PvrTexture::~PvrTexture()
167 {
168 PvrDevice::UnbindTexture(this);
169 FreeVramStores();
170 Unlink();
171 }
172
173 PvrTexture* PvrTexture::_liveHead = nullptr;
174 PvrTexture* PvrTexture::_liveTail = nullptr;
175
176 void PvrTexture::Unlink()
177 {
178 if (_livePrev != nullptr) {
179 _livePrev->_liveNext = _liveNext;
180 } else if (_liveHead == this) {
181 _liveHead = _liveNext;
182 }
183 if (_liveNext != nullptr) {
184 _liveNext->_livePrev = _livePrev;
185 } else if (_liveTail == this) {
186 _liveTail = _livePrev;
187 }
188 _livePrev = nullptr;
189 _liveNext = nullptr;
190 }
191
192 void PvrTexture::Touch()
193 {
194 _lastUsedScene = PvrDevice::GetSceneCounter();
195 if (_liveHead == this) {
196 return;
197 }
198 Unlink();
199 _liveNext = _liveHead;
200 if (_liveHead != nullptr) {
201 _liveHead->_livePrev = this;
202 }
203 _liveHead = this;
204 if (_liveTail == nullptr) {
205 _liveTail = this;
206 }
207 }
208
209 void PvrTexture::LinkAsLeastRecent()
210 {
211 if (_livePrev != nullptr || _liveNext != nullptr || _liveHead == this) {
212 return; // Already in the list, keep its position (and its scene stamp)
213 }
214 _livePrev = _liveTail;
215 if (_liveTail != nullptr) {
216 _liveTail->_liveNext = this;
217 }
218 _liveTail = this;
219 if (_liveHead == nullptr) {
220 _liveHead = this;
221 }
222 }
223
224 pvr_ptr_t PvrTexture::AllocateVram(std::size_t size, const PvrTexture* keepAlive)
225 {
226 if (pvr_ptr_t result = pvr_mem_malloc(size)) {
227 return result;
228 }
229
230 // Out of video memory: drop the stores of the textures that have gone unused the longest and try
231 // again. The first pass spares anything already drawn into the scene being assembled, as the tile
232 // accelerator still reads those when the scene is submitted.
233 const std::uint32_t currentScene = PvrDevice::GetSceneCounter();
234 for (std::int32_t pass = 0; pass < 2; pass++) {
235 // Nothing outside the current scene was left to free. Rather than fail the allocation - which
236 // used to abort the whole frame and take the process with it, as happens when a level's working
237 // set suddenly has to make room for the pause menu's - the second pass evicts from the current
238 // scene too. The tile accelerator then samples a store that has been reused, so the primitives
239 // already submitted this frame can come out wrong; that is a single frame of artifacts against
240 // a hard crash, and the store is rebuilt from main memory on the next draw.
241 const bool sparingCurrentScene = (pass == 0);
242 PvrTexture* victim = _liveTail;
243 while (victim != nullptr) {
244 PvrTexture* next = victim->_livePrev;
245 // Render targets have no copy in main memory to rebuild from, so they are never evicted
246 const bool evictable = (victim != keepAlive && !victim->_isRenderTarget &&
247 (!sparingCurrentScene || victim->_lastUsedScene != currentScene));
248 if (evictable) {
249 victim->FreeVramStores();
250 victim->Unlink();
251
252 if (pvr_ptr_t result = pvr_mem_malloc(size)) {
253 return result;
254 }
255 }
256 victim = next;
257 }
258 }
259
260 return nullptr;
261 }
262
263 pvr_ptr_t PvrTexture::AcquireVramPointer()
264 {
265 if (_vram == nullptr) {
266 RefreshVramStore();
267 }
268 if (_vram != nullptr) {
269 Touch();
270 }
271 return _vram;
272 }
273
274 void PvrTexture::FreeVramStores()
275 {
276 if (_vram != nullptr) {
277 pvr_mem_free(_vram);
278 _vram = nullptr;
279 _vramBytesPerTexel = 0;
280 }
281 for (std::int32_t i = 0; i < BakedSlotCount; i++) {
282 if (_bakedSlots[i].Vram != nullptr) {
283 pvr_mem_free(_bakedSlots[i].Vram);
284 _bakedSlots[i].Vram = nullptr;
285 }
286 _bakedSlots[i].Valid = false;
287 }
288 }
289
290 std::int32_t PvrTexture::BytesPerPixel(PixelFormat format)
291 {
292 switch (format) {
293 case PixelFormat::R8: return 1;
294 case PixelFormat::RG8: return 2;
295 case PixelFormat::RGB565: return 2;
296 case PixelFormat::RGB8: return 3;
297 case PixelFormat::RGBA8: return 4;
298 default: return 0;
299 }
300 }
301
302 void PvrTexture::Allocate(PixelFormat format, std::int32_t width, std::int32_t height)
303 {
304 _uploadFormat = format;
305 _format = format;
306 _width = width;
307 _height = height;
308 _bytesPerPixel = BytesPerPixel(_format);
309 _strideBytes = width * _bytesPerPixel;
310 if (CanCompressPixels()) {
311 // The compressible formats defer their host store to the first upload (StorePixels), so the
312 // full-size linear buffer never exists for them - not even between allocation and upload
313 _pixels.clear();
314 } else {
315 _pixels.assign(std::size_t(_strideBytes) * std::size_t(height > 0 ? height : 0), std::uint8_t(0));
316 }
317 _pixelsCompressed = false;
318 FreeVramStores();
319 _paddedWidth = NextPow2(width);
320 _paddedHeight = NextPow2(height);
321 _uScale = (_paddedWidth > 0 ? float(width) / float(_paddedWidth) : 1.0f);
322 _vScale = (_paddedHeight > 0 ? float(height) / float(_paddedHeight) : 1.0f);
323 if (width > 1024 || height > 1024) {
324 LOGE("Texture {}x{} exceeds the PowerVR 1024 limit", width, height);
325 }
326 _contentVersion = ++_nextContentVersion;
327 }
328
329 bool PvrTexture::CanCompressPixels() const
330 {
331 // Only static indexed content: R8 (paletted tiles/sprites) and RG8 (index + alpha). Their host
332 // stores are consumed strictly sequentially (RefreshVramStore, EnsureBakedArgb4444), so they can
333 // be streamed out of the compressed form. RGB565 belongs to the streaming path (cinematics) that
334 // rewrites the store every frame, RGBA8 covers the palette texture (read in place by the device)
335 // and the few baked sheets, and render targets have no host content to keep at all. The width
336 // limit matches both the bake path's fixed row scratch and the widest texture the PVR can sample.
337 return (_uploadFormat == PixelFormat::R8 || _uploadFormat == PixelFormat::RG8) &&
338 !_isPaletteTexture && !_isRenderTarget && _width <= 1024;
339 }
340
341 void PvrTexture::StorePixels(const std::uint8_t* data)
342 {
343 const std::size_t rawSize = std::size_t(RawPixelsSize());
344 if (rawSize == 0) {
345 return;
346 }
347 if (CanCompressPixels()) {
348 EncodePackBits(data, rawSize, _pixels);
349 if (_pixels.size() < rawSize) {
350 _pixelsCompressed = true;
351 } else {
352 // Content that does not compress is kept linear, so the read paths skip the decoder
353 _pixels.assign(data, data + rawSize);
354 _pixelsCompressed = false;
355 }
356 } else {
357 _pixels.assign(data, data + rawSize);
358 _pixelsCompressed = false;
359 }
360 }
361
362 void PvrTexture::MaterializePixelsRaw()
363 {
364 const std::size_t rawSize = std::size_t(RawPixelsSize());
365 if (rawSize == 0) {
366 return;
367 }
368 if (_pixelsCompressed) {
369 SmallVector<std::uint8_t, 0> raw;
370 raw.resize_for_overwrite(rawSize);
371 RlePixelReader reader(_pixels.data());
372 reader.Read(raw.data(), rawSize);
373 _pixels = std::move(raw);
374 _pixelsCompressed = false;
375 } else if (_pixels.empty()) {
376 // A compressible texture defers its store until the first upload; a partial first upload
377 // gets the zero-filled base the uncompressed formats always had
378 _pixels.assign(rawSize, std::uint8_t(0));
379 }
380 }
381
382 void PvrTexture::RecompressPixels()
383 {
384 const std::size_t rawSize = std::size_t(RawPixelsSize());
385 if (!CanCompressPixels() || _pixelsCompressed || _pixels.size() != rawSize || rawSize == 0) {
386 return;
387 }
388 SmallVector<std::uint8_t, 0> compressed;
389 EncodePackBits(_pixels.data(), rawSize, compressed);
390 if (compressed.size() < rawSize) {
391 _pixels = std::move(compressed);
392 _pixelsCompressed = true;
393 }
394 }
395
396 bool PvrTexture::EnsureVramStore(std::int32_t bytesPerTexel)
397 {
398 if (_vram != nullptr && _vramBytesPerTexel != bytesPerTexel) {
399 pvr_mem_free(_vram);
400 _vram = nullptr;
401 }
402 if (_vram == nullptr) {
403 _vram = AllocateVram(std::size_t(_paddedWidth) * std::size_t(_paddedHeight) * std::size_t(bytesPerTexel), this);
404 if (_vram == nullptr) {
405 return false;
406 }
407 }
408 _vramBytesPerTexel = bytesPerTexel;
409 // The store has to be reachable by the eviction walk immediately, not only from the first draw
410 LinkAsLeastRecent();
411 return true;
412 }
413
414 void* PvrTexture::MapStreamingTexels(std::int32_t& strideBytes)
415 {
416 if (_uploadFormat != PixelFormat::RGB565 || _isRenderTarget || _isPaletteTexture) {
417 return nullptr;
418 }
419
420 // The store is allocated on demand and can be reclaimed when video memory runs short, so it is asked
421 // for again every frame rather than remembered
422 pvr_ptr_t vram = AcquireVramPointer();
423 if (vram == nullptr) {
424 return nullptr;
425 }
426
427 strideBytes = _paddedWidth * 2;
428 return vram;
429 }
430
431 void PvrTexture::RefreshVramStore()
432 {
433 if (_pixels.empty() || _width <= 0 || _height <= 0 || _isPaletteTexture || _isRenderTarget) {
434 return;
435 }
436
437 if (_uploadFormat == PixelFormat::R8) {
438 // 8bpp paletted, twiddled; the palette bank is or-ed into the format word per draw
439 const std::size_t size = std::size_t(_paddedWidth) * std::size_t(_paddedHeight);
440 if (!EnsureVramStore(1)) {
441 LOGE("Out of PVR memory allocating {} B (8bpp {}x{}, source {}x{})", size, _paddedWidth, _paddedHeight, _width, _height);
442 return;
443 }
444 // Pad the linear image into a power-of-two staging buffer, then let the loader twiddle it.
445 // The buffer persists across uploads (the renderer is single-threaded), and only the padding
446 // is zeroed - the image area is overwritten right after. A compressed store streams its rows
447 // through the decoder (it is walked strictly front to back), so it is never inflated whole.
448 static SmallVector<std::uint8_t, 0> staging;
449 staging.resize_for_overwrite(size);
450 RlePixelReader reader(_pixels.data());
451 for (std::int32_t y = 0; y < _height; y++) {
452 if (_pixelsCompressed) {
453 reader.Read(staging.data() + std::size_t(y) * _paddedWidth, std::size_t(_width));
454 } else {
455 std::memcpy(staging.data() + std::size_t(y) * _paddedWidth, _pixels.data() + std::size_t(y) * _strideBytes, std::size_t(_width));
456 }
457 std::memset(staging.data() + std::size_t(y) * _paddedWidth + _width, 0, std::size_t(_paddedWidth - _width));
458 }
459 if (_height < _paddedHeight) {
460 std::memset(staging.data() + std::size_t(_height) * _paddedWidth, 0, std::size_t(_paddedHeight - _height) * _paddedWidth);
461 }
462 pvr_txr_load_ex(staging.data(), _vram, std::uint32_t(_paddedWidth), std::uint32_t(_paddedHeight), PVR_TXRLOAD_8BPP);
463 _vramFormat = PVR_TXRFMT_PAL8BPP | PVR_TXRFMT_TWIDDLED;
464 } else if (_uploadFormat == PixelFormat::RGB565) {
465 // Already in a format the hardware samples directly, so the rows go straight into video memory -
466 // no conversion and no twiddling. This is the cheap path for textures that are replaced every
467 // frame (the cinematic player), where a twiddle would cost more than the whole upload.
468 const std::size_t size = std::size_t(_paddedWidth) * std::size_t(_paddedHeight) * 2;
469 if (!EnsureVramStore(2)) {
470 LOGE("Out of PVR memory allocating {} B (RGB565 {}x{})", size, _paddedWidth, _paddedHeight);
471 return;
472 }
473
474 std::uint16_t* dst = static_cast<std::uint16_t*>(_vram);
475 const std::uint16_t* src = reinterpret_cast<const std::uint16_t*>(_pixels.data());
476 if (_paddedWidth == _width) {
477 CopyTexelsToVram(dst, src, std::size_t(_width) * _height);
478 } else {
479 for (std::int32_t y = 0; y < _height; y++) {
480 CopyTexelsToVram(dst + std::size_t(y) * _paddedWidth, src + std::size_t(y) * (_strideBytes / 2),
481 std::size_t(_width));
482 }
483 }
484 _vramFormat = PVR_TXRFMT_RGB565 | PVR_TXRFMT_NONTWIDDLED;
485 } else if (_uploadFormat == PixelFormat::RGB8 || _uploadFormat == PixelFormat::RGBA8) {
486 // True-color converts to twiddled ARGB4444 (the PVR has no 32-bit sampled format)
487 const std::size_t size = std::size_t(_paddedWidth) * std::size_t(_paddedHeight) * 2;
488 if (!EnsureVramStore(2)) {
489 LOGE("Out of PVR memory allocating {} B (ARGB4444 {}x{})", size, _paddedWidth, _paddedHeight);
490 return;
491 }
492 // Converted without the twiddling pass: interleaving the texel order costs more than the
493 // conversion itself, and it only pays off for the sampling patterns of 3D geometry - these
494 // are axis-aligned sprite blits. Each row is converted into a small cached scratch line and
495 // then burst out through the store queues: texture memory is uncached, and the per-texel
496 // 16-bit stores made an eviction rebuild several times more expensive than the conversion.
497 // Only rows narrower than one 32-byte block (padded width 8) keep the direct stores; the
498 // padded width never exceeds 1024 (see NextPow2).
499 std::uint16_t* dst = static_cast<std::uint16_t*>(_vram);
500 alignas(32) static std::uint16_t scratchRow[1024];
501 const std::size_t rowBytes = std::size_t(_paddedWidth) * 2;
502 const bool useStoreQueues = ((rowBytes & 31) == 0);
503 if (useStoreQueues) {
504 sq_lock(dst);
505 }
506 for (std::int32_t y = 0; y < _height; y++) {
507 const std::uint8_t* DEATH_RESTRICT src = _pixels.data() + std::size_t(y) * _strideBytes;
508 std::uint16_t* DEATH_RESTRICT row = (useStoreQueues ? scratchRow : dst + std::size_t(y) * _paddedWidth);
509 if (_bytesPerPixel >= 4) {
510 for (std::int32_t x = 0; x < _width; x++) {
511 row[x] = Argb4444FromRgba(src[0], src[1], src[2], src[3]);
512 src += 4;
513 }
514 } else {
515 for (std::int32_t x = 0; x < _width; x++) {
516 row[x] = Argb4444FromRgba(src[0], src[1], src[2], 255);
517 src += _bytesPerPixel;
518 }
519 }
520 // The padding columns are only sampled through the compensated texture coordinates, but
521 // leaving them uninitialised would show up as fringing on the last texel
522 for (std::int32_t x = _width; x < _paddedWidth; x++) {
523 row[x] = 0;
524 }
525 if (useStoreQueues) {
526 sq_fast_cpy(SQ_MASK_DEST(dst + std::size_t(y) * _paddedWidth), scratchRow, rowBytes / 32);
527 }
528 }
529 if (useStoreQueues) {
530 // One zeroed line serves every padding row below the image
531 for (std::int32_t x = 0; x < _paddedWidth; x++) {
532 scratchRow[x] = 0;
533 }
534 for (std::int32_t y = _height; y < _paddedHeight; y++) {
535 sq_fast_cpy(SQ_MASK_DEST(dst + std::size_t(y) * _paddedWidth), scratchRow, rowBytes / 32);
536 }
537 sq_unlock();
538 } else {
539 for (std::int32_t y = _height; y < _paddedHeight; y++) {
540 // Word stores - video memory only takes 16/32-bit accesses (padded width is even)
541 std::uint32_t* DEATH_RESTRICT fill = reinterpret_cast<std::uint32_t*>(dst + std::size_t(y) * _paddedWidth);
542 for (std::int32_t x = 0, n = _paddedWidth / 2; x < n; x++) {
543 fill[x] = 0;
544 }
545 }
546 }
547 _vramFormat = PVR_TXRFMT_ARGB4444 | PVR_TXRFMT_NONTWIDDLED;
548 }
549 // RG8 keeps only the linear store; the ARGB4444 copy is baked per palette row on demand
550 }
551
552 pvr_ptr_t PvrTexture::EnsureBakedArgb4444(const std::uint32_t* paletteRow, std::uint32_t paletteRowIndex, std::uint32_t paletteGeneration, const void* palette)
553 {
554 if (_pixels.empty() || _uploadFormat != PixelFormat::RG8 || paletteRow == nullptr) {
555 return nullptr;
556 }
557 const std::uint32_t currentScene = PvrDevice::GetSceneCounter();
558
559 // Bakes that have gone unused for a while give their video memory back proactively instead of
560 // waiting for an allocation failure to evict them - each one costs as much as the texture itself.
561 // Far older than anything the tile accelerator could still read.
562 constexpr std::uint32_t ReclaimAfterScenes = 300;
563 for (std::int32_t i = 0; i < BakedSlotCount; i++) {
564 if (_bakedSlots[i].Vram != nullptr && currentScene - _bakedSlots[i].LastUsedScene > ReclaimAfterScenes) {
565 pvr_mem_free(_bakedSlots[i].Vram);
566 _bakedSlots[i].Vram = nullptr;
567 _bakedSlots[i].Valid = false;
568 }
569 }
570
571 BakedSlot* slot = nullptr;
572 for (std::int32_t i = 0; i < BakedSlotCount; i++) {
573 if (_bakedSlots[i].Valid && _bakedSlots[i].PaletteRow == paletteRowIndex && _bakedSlots[i].Palette == palette) {
574 if (_bakedSlots[i].PaletteGeneration == paletteGeneration && _bakedSlots[i].ContentVersion == _contentVersion) {
575 _bakedSlots[i].LastUsedScene = currentScene;
576 Touch();
577 return _bakedSlots[i].Vram;
578 }
579 slot = &_bakedSlots[i]; // Stale bake of the same row, refresh it in place
580 break;
581 }
582 }
583 if (slot == nullptr) {
584 for (std::int32_t i = 0; i < BakedSlotCount; i++) {
585 if (!_bakedSlots[i].Valid) {
586 slot = &_bakedSlots[i];
587 break;
588 }
589 }
590 }
591 if (slot == nullptr) {
592 // Never evict a bake the current scene still references - the tile accelerator reads the
593 // textures only at scene end, so overwriting one would corrupt the already submitted quads
594 for (std::int32_t i = 0; i < BakedSlotCount; i++) {
595 const std::int32_t candidate = (_nextBakedSlot + i) % BakedSlotCount;
596 if (_bakedSlots[candidate].LastUsedScene != currentScene) {
597 slot = &_bakedSlots[candidate];
598 _nextBakedSlot = (candidate + 1) % BakedSlotCount;
599 break;
600 }
601 }
602 }
603 if (slot == nullptr) {
604 static bool warnedSlots = false;
605 if (!warnedSlots) {
606 warnedSlots = true;
607 LOGW("More than {} palette rows used with one texture in a single scene, expect glitches", BakedSlotCount);
608 }
609 slot = &_bakedSlots[_nextBakedSlot];
610 _nextBakedSlot = (_nextBakedSlot + 1) % BakedSlotCount;
611 }
612
613 const std::size_t size = std::size_t(_paddedWidth) * std::size_t(_paddedHeight) * 2;
614 if (slot->Vram == nullptr) {
615 slot->Vram = AllocateVram(size, this);
616 if (slot->Vram == nullptr) {
617 LOGE("Out of PVR memory allocating {} B (baked ARGB4444 {}x{})", size, _paddedWidth, _paddedHeight);
618 return nullptr;
619 }
620 }
621
622 // The 256 palette entries collapse into packed 12-bit RGB once per bake, so the texel loop below
623 // is one table lookup and an alpha merge instead of unpacking and requantizing every pixel
624 std::uint16_t rgb444[256];
625 for (std::int32_t i = 0; i < 256; i++) {
626 const std::uint32_t color = paletteRow[i];
627 rgb444[i] = std::uint16_t(((( color & 0xFF) >> 4) << 8)
628 | ((((color >> 8) & 0xFF) >> 4) << 4)
629 | (((color >> 16) & 0xFF) >> 4));
630 }
631
632 // The staging buffer persists across bakes (the renderer is single-threaded); only the padding
633 // is zeroed, the image area is overwritten right after. A compressed store is streamed row by
634 // row through a fixed scratch line - the bake walks the image strictly front to back, so the
635 // linear form never has to exist in full.
636 static SmallVector<std::uint16_t, 0> staging;
637 staging.resize_for_overwrite(std::size_t(_paddedWidth) * std::size_t(_paddedHeight));
638 // Widest supported source row: 1024 texels of 2 bytes (see NextPow2's 1024 clamp)
639 static std::uint8_t rowScratch[1024 * 2];
640 RlePixelReader reader(_pixels.data());
641 for (std::int32_t y = 0; y < _height; y++) {
642 const std::uint8_t* DEATH_RESTRICT src;
643 if (_pixelsCompressed) {
644 reader.Read(rowScratch, std::size_t(_strideBytes));
645 src = rowScratch;
646 } else {
647 src = _pixels.data() + std::size_t(y) * _strideBytes;
648 }
649 std::uint16_t* DEATH_RESTRICT dst = staging.data() + std::size_t(y) * _paddedWidth;
650 for (std::int32_t x = 0; x < _width; x++) {
651 dst[x] = std::uint16_t(rgb444[src[x * 2]] | ((src[x * 2 + 1] >> 4) << 12));
652 }
653 std::memset(dst + _width, 0, std::size_t(_paddedWidth - _width) * 2);
654 }
655 if (_height < _paddedHeight) {
656 std::memset(staging.data() + std::size_t(_height) * _paddedWidth, 0,
657 std::size_t(_paddedHeight - _height) * _paddedWidth * 2);
658 }
659 pvr_txr_load_ex(staging.data(), slot->Vram, std::uint32_t(_paddedWidth), std::uint32_t(_paddedHeight), PVR_TXRLOAD_16BPP);
660
661 slot->Valid = true;
662 slot->PaletteRow = paletteRowIndex;
663 slot->PaletteGeneration = paletteGeneration;
664 slot->ContentVersion = _contentVersion;
665 slot->LastUsedScene = currentScene;
666 slot->Palette = palette;
667 Touch();
668 return slot->Vram;
669 }
670
671 void PvrTexture::SetRenderTarget(bool isRenderTarget)
672 {
673 _isRenderTarget = isRenderTarget;
674 if (isRenderTarget && _width > 0 && _height > 0) {
675 // The tile accelerator renders into a non-twiddled RGB565 surface of power-of-two width
676 const std::size_t size = std::size_t(_paddedWidth) * std::size_t(_paddedHeight) * 2;
677 if (!EnsureVramStore(2)) {
678 LOGE("Out of PVR memory allocating {} B (RTT {}x{})", size, _paddedWidth, _paddedHeight);
679 return;
680 }
681 _vramFormat = PVR_TXRFMT_RGB565 | PVR_TXRFMT_NONTWIDDLED;
682 }
683 }
684
685 bool PvrTexture::Bind(std::uint32_t textureUnit) const
686 {
687 _textureUnit = textureUnit;
688 PvrDevice::BindTexture(textureUnit, this);
689 return true;
690 }
691
692 bool PvrTexture::Unbind() const
693 {
694 PvrDevice::BindTexture(_textureUnit, nullptr);
695 return true;
696 }
697
698 bool PvrTexture::Unbind(std::uint32_t textureUnit)
699 {
700 PvrDevice::BindTexture(textureUnit, nullptr);
701 return true;
702 }
703
704 void PvrTexture::TexImage2D(std::int32_t level, PixelFormat format, bool bgr, std::int32_t width, std::int32_t height, const void* data)
705 {
706 static_cast<void>(bgr);
707 if (level != 0) {
708 return; // Level 0 only
709 }
710 Allocate(format, width, height);
711 if (data != nullptr && RawPixelsSize() > 0) {
712 // Full upload - the store is (re)built straight from the caller's buffer, compressed when
713 // the format qualifies, so the linear copy never exists on this side
714 StorePixels(static_cast<const std::uint8_t*>(data));
715 _contentVersion = ++_nextContentVersion;
716 }
717 if (_isPaletteTexture) {
718 PvrDevice::NotifyPaletteTextureChanged(this, 0, _height);
719 } else {
720 RefreshVramStore();
721 }
722 }
723
724 void PvrTexture::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)
725 {
726 static_cast<void>(bgr);
727 if (level != 0 || data == nullptr || RawPixelsSize() <= 0) {
728 return;
729 }
730 const std::int32_t srcBpp = BytesPerPixel(format);
731 const std::int32_t dstBpp = _bytesPerPixel;
732 const std::int32_t copyBpp = (srcBpp < dstBpp ? srcBpp : dstBpp);
733
734 if (xoffset == 0 && yoffset == 0 && width == _width && height == _height && srcBpp == dstBpp) {
735 // Full replacement (the common upload path goes TexStorage2D + full-rect TexSubImage2D):
736 // skip the patch loop and rebuild the store from the caller's buffer directly, compressed
737 // when the format qualifies - the full-size linear copy never exists on this side
738 StorePixels(static_cast<const std::uint8_t*>(data));
739 } else {
740 // Partial patch (tileset overrides): the only writer that needs the store linear. Rare and
741 // load-time only, so the compressed form is inflated for the patch and compressed again after
742 MaterializePixelsRaw();
743 for (std::int32_t y = 0; y < height; y++) {
744 const std::int32_t dstY = yoffset + y;
745 if (dstY < 0 || dstY >= _height) {
746 continue;
747 }
748 std::int32_t dstX = xoffset;
749 std::int32_t copyW = width;
750 std::int32_t srcX0 = 0;
751 if (dstX < 0) {
752 srcX0 = -dstX;
753 copyW += dstX;
754 dstX = 0;
755 }
756 if (dstX + copyW > _width) {
757 copyW = _width - dstX;
758 }
759 if (copyW <= 0) {
760 continue;
761 }
762 const std::uint8_t* srcRow = static_cast<const std::uint8_t*>(data) + std::size_t(y) * std::size_t(width) * srcBpp + std::size_t(srcX0) * srcBpp;
763 std::uint8_t* dstRow = _pixels.data() + std::size_t(dstY) * _strideBytes + std::size_t(dstX) * dstBpp;
764 if (srcBpp == dstBpp) {
765 std::memcpy(dstRow, srcRow, std::size_t(copyW) * dstBpp);
766 } else {
767 for (std::int32_t x = 0; x < copyW; x++) {
768 std::int32_t c = 0;
769 for (; c < copyBpp; c++) {
770 dstRow[x * dstBpp + c] = srcRow[x * srcBpp + c];
771 }
772 for (; c < dstBpp; c++) {
773 dstRow[x * dstBpp + c] = 255;
774 }
775 }
776 }
777 }
778 RecompressPixels();
779 }
780 _contentVersion = ++_nextContentVersion;
781 if (_isPaletteTexture) {
782 PvrDevice::NotifyPaletteTextureChanged(this, yoffset, height);
783 } else {
784 // v1: any sub-update re-uploads the whole level (sub-updates are rare - tileset overrides and
785 // the palette, which is intercepted above)
786 RefreshVramStore();
787 }
788 }
789
790 void PvrTexture::TexStorage2D(std::int32_t levels, PixelFormat format, std::int32_t width, std::int32_t height)
791 {
792 static_cast<void>(levels);
793 Allocate(format, width, height);
794 if (_isRenderTarget) {
795 SetRenderTarget(true);
796 }
797 }
798
799 void PvrTexture::CompressedTexImage2D(std::int32_t level, PixelFormat format, std::int32_t width, std::int32_t height, std::int32_t imageSize, const void* data)
800 {
801 static_cast<void>(level); static_cast<void>(format); static_cast<void>(width);
802 static_cast<void>(height); static_cast<void>(imageSize); static_cast<void>(data);
803 }
804
805 void PvrTexture::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)
806 {
807 static_cast<void>(level); static_cast<void>(xoffset); static_cast<void>(yoffset); static_cast<void>(width);
808 static_cast<void>(height); static_cast<void>(format); static_cast<void>(imageSize); static_cast<void>(data);
809 }
810
811 void PvrTexture::GetTexImage(std::int32_t level, PixelFormat format, bool bgr, void* pixels)
812 {
813 static_cast<void>(level);
814 static_cast<void>(format);
815 static_cast<void>(bgr);
816 if (pixels != nullptr && !_pixels.empty()) {
817 if (_pixelsCompressed) {
818 RlePixelReader reader(_pixels.data());
819 reader.Read(static_cast<std::uint8_t*>(pixels), std::size_t(RawPixelsSize()));
820 } else {
821 std::memcpy(pixels, _pixels.data(), _pixels.size());
822 }
823 }
824 }
825
826 void PvrTexture::SetMinFiltering(nCine::SamplerFilter filter)
827 {
828 _minFilter = filter;
829 }
830
831 void PvrTexture::SetMagFiltering(nCine::SamplerFilter filter)
832 {
833 _magFilter = filter;
834 }
835
836 void PvrTexture::SetWrap(SamplerWrapping wrap)
837 {
838 _wrap = wrap;
839 }
840
841 void PvrTexture::SetSwizzle(SwizzleChannel r, SwizzleChannel g, SwizzleChannel b, SwizzleChannel a)
842 {
843 _swizzle[0] = r;
844 _swizzle[1] = g;
845 _swizzle[2] = b;
846 _swizzle[3] = a;
847 }
848
849 void PvrTexture::SetMaxLevel(std::int32_t maxLevel)
850 {
851 static_cast<void>(maxLevel);
852 }
853
854 void PvrTexture::SetUnpackAlignment(std::int32_t alignment)
855 {
856 static_cast<void>(alignment);
857 }
858
859 void PvrTexture::SetObjectLabel(StringView label)
860 {
861 // The shared palette texture is uploaded by ContentResolver under this exact name; its rows are
862 // loaded into the hardware palette banks by the device instead of a sampled texture
863 if (label == "Palettes"_s) {
864 _isPaletteTexture = true;
865 FreeVramStores();
866 PvrDevice::RegisterPaletteTexture(this);
867 }
868 }
869 }