Debian Codegraph @

Sources/nCine/Graphics/RHI/GXM/GxmTexture.cpp

raw
1 #include "GxmTexture.h"
2 #include "GxmDevice.h"
3
4 #include "../../../../Main.h"
5
6 #include <cstring>
7
8 namespace nCine::RHI::GXM
9 {
10 namespace
11 {
12 // Copies one packed row into the store, expanding a narrower source (RGB8, R8, RG8) to the RGBA8
13 // store by filling the extra channels with 255 (opaque). A same-width copy is a plain memcpy.
14 void CopyExpandRow(std::uint8_t* dst, std::int32_t dstBpp, const std::uint8_t* src, std::int32_t srcBpp, std::int32_t width)
15 {
16 if (srcBpp == dstBpp) {
17 std::memcpy(dst, src, std::size_t(width) * std::size_t(dstBpp));
18 return;
19 }
20 const std::int32_t shared = (srcBpp < dstBpp ? srcBpp : dstBpp);
21 for (std::int32_t x = 0; x < width; x++) {
22 std::int32_t c = 0;
23 for (; c < shared; c++) {
24 dst[x * dstBpp + c] = src[x * srcBpp + c];
25 }
26 for (; c < dstBpp; c++) {
27 dst[x * dstBpp + c] = 255;
28 }
29 }
30 }
31
32 inline SceGxmTextureFilter TranslateFilter(nCine::SamplerFilter filter)
33 {
34 switch (filter) {
35 case nCine::SamplerFilter::Linear:
36 case nCine::SamplerFilter::LinearMipmapNearest:
37 case nCine::SamplerFilter::LinearMipmapLinear:
38 return SCE_GXM_TEXTURE_FILTER_LINEAR;
39 default:
40 return SCE_GXM_TEXTURE_FILTER_POINT;
41 }
42 }
43
44 inline SceGxmTextureAddrMode TranslateWrap(SamplerWrapping wrap)
45 {
46 switch (wrap) {
47 case SamplerWrapping::Repeat: return SCE_GXM_TEXTURE_ADDR_REPEAT;
48 case SamplerWrapping::MirroredRepeat: return SCE_GXM_TEXTURE_ADDR_MIRROR;
49 default: return SCE_GXM_TEXTURE_ADDR_CLAMP;
50 }
51 }
52 }
53
54 std::uint32_t GxmTexture::_nextHandle = 1;
55
56 GxmTexture::GxmTexture(TextureTarget target)
57 : _handle(_nextHandle++), _target(target), _format(PixelFormat::Unknown), _uploadFormat(PixelFormat::Unknown),
58 _width(0), _height(0), _strideBytes(0),
59 _minFilter(nCine::SamplerFilter::Nearest), _magFilter(nCine::SamplerFilter::Nearest), _wrap(SamplerWrapping::ClampToEdge),
60 _textureUnit(0), _isRenderTarget(false), _gpuStride(0), _gpuStrided(false), _gpuValid(false), _contentsDirty(false), _samplerDirty(true)
61 {
62 _swizzle[0] = SwizzleChannel::Red;
63 _swizzle[1] = SwizzleChannel::Green;
64 _swizzle[2] = SwizzleChannel::Blue;
65 _swizzle[3] = SwizzleChannel::Alpha;
66 std::memset(&_gpuTexture, 0, sizeof(_gpuTexture));
67 }
68
69 GxmTexture::~GxmTexture()
70 {
71 // Unbind from the device first so a later draw can't dereference this freed texture through the
72 // bound-texture table, and make sure no scene the GPU has not consumed yet still samples it
73 GxmDevice::UnbindTexture(this);
74 ReleaseGpu();
75 }
76
77 void GxmTexture::ReleaseGpu() const
78 {
79 if (_gpuBlock.IsValid()) {
80 // The GPU may still be reading these texels from a scene that has been submitted but not yet
81 // consumed, and the memory is about to be unmapped
82 GxmDevice::FinishScene();
83 // Whether this block is a render target's - which is retired for reuse at the same address instead
84 // of released - is decided by who owns it rather than by _isRenderTarget, which a detach has already
85 // flipped by the time this runs
86 GxmMemory::ReleaseSurface(_gpuBlock);
87 }
88 _gpuValid = false;
89 _gpuStride = 0;
90 _gpuStrided = false;
91 }
92
93 std::int32_t GxmTexture::BytesPerPixel(PixelFormat format)
94 {
95 switch (format) {
96 case PixelFormat::R8: return 1;
97 case PixelFormat::RG8: return 2;
98 case PixelFormat::RGB565:
99 case PixelFormat::RGB5A1:
100 case PixelFormat::RGBA4: return 2;
101 case PixelFormat::RGB8: return 3;
102 case PixelFormat::RGBA8: return 4;
103 case PixelFormat::RGBA16F: return 8;
104 case PixelFormat::RGBA32F: return 16;
105 default: return 0;
106 }
107 }
108
109 bool GxmTexture::IsIdentitySwizzle() const
110 {
111 return (_swizzle[0] == SwizzleChannel::Red && _swizzle[1] == SwizzleChannel::Green &&
112 _swizzle[2] == SwizzleChannel::Blue && _swizzle[3] == SwizzleChannel::Alpha);
113 }
114
115 void GxmTexture::Allocate(PixelFormat format, std::int32_t width, std::int32_t height)
116 {
117 // Keep a self-consistent 4-byte-per-texel store for the runtime formats: promote the narrower ones
118 // (RGB8 render targets and the palette-index formats R8 / RG8) to an RGBA8 store, remembering the
119 // original in _uploadFormat. One GPU-side format means one texture layout to get right, and it is
120 // what lets the sampling swizzle be baked into the texels below.
121 _uploadFormat = format;
122 _format = (format == PixelFormat::RGB8 || format == PixelFormat::R8 || format == PixelFormat::RG8) ? PixelFormat::RGBA8 : format;
123 _width = width;
124 _height = height;
125 const std::int32_t bpp = BytesPerPixel(_format);
126 _strideBytes = width * bpp;
127 _pixels.assign(std::size_t(_strideBytes) * std::size_t(height > 0 ? height : 0), std::uint8_t(0));
128 // The size/format changed, so the GPU copy has to be rebuilt on the next bind
129 ReleaseGpu();
130 _contentsDirty = true;
131 }
132
133 void GxmTexture::SetRenderTarget(bool isRenderTarget)
134 {
135 if (isRenderTarget == _isRenderTarget) {
136 return;
137 }
138 _isRenderTarget = isRenderTarget;
139 // A colour attachment is written by the GPU, so its copy needs the write attribute; rebuild it
140 ReleaseGpu();
141 _contentsDirty = true;
142 }
143
144 bool GxmTexture::EnsureGpuTexture() const
145 {
146 if (_width <= 0 || _height <= 0 || _format != PixelFormat::RGBA8) {
147 // Only the promoted RGBA8 store has a GPU-side counterpart; the float and packed formats are
148 // accepted by the uploads but never sampled by this backend's shaders
149 return false;
150 }
151
152 if (!_gpuBlock.IsValid()) {
153 // A colour attachment gets the **tiled** layout, not a linear one. A linear texture cannot address
154 // outside [0, 1] at all - the addressing mode is accepted and then simply does not happen - and every
155 // render target here is sampled by a later pass that needs exactly that: the scrolling background
156 // tiles its target with `SamplerWrapping::Repeat`, and the blur passes read past the edges of theirs.
157 // Both produced a dark seam along the sampled edge for that reason. A tiled surface stores 32x32
158 // tiles, so its memory is padded to a multiple of 32 in both directions while the *texture* keeps the
159 // real size - which is why the padding costs nothing in texture coordinates, unlike the linear
160 // strided layout it replaces. Sampled-only textures stay linear: they are read inside their own
161 // bounds and would need their texels reordered into tiles on upload.
162 const bool tiled = _isRenderTarget;
163 const std::uint32_t alignedWidth = (tiled
164 ? ((std::uint32_t(_width) + 31u) & ~31u) : std::uint32_t(_width));
165 const std::uint32_t alignedHeight = (tiled
166 ? ((std::uint32_t(_height) + 31u) & ~31u) : std::uint32_t(_height));
167 _gpuStride = alignedWidth * 4u;
168 _gpuStrided = (!tiled && (_width % 8) != 0);
169 const std::uint32_t size = _gpuStride * alignedHeight;
170 // A colour attachment is rendered into every frame, so it belongs in the memory the GPU writes
171 // fastest; sampled-only texels are uploaded once and stay in main memory, of which there is far more.
172 // A colour attachment additionally wants the address it had last time the pipeline built this target
173 // (see GxmMemory::AcquireSurface()), which is why it does not go through the plain allocator
174 _gpuBlock = (_isRenderTarget
175 ? GxmMemory::AcquireSurface("Jazz2:RenderTarget", _gpuStride, alignedHeight)
176 : GxmMemory::Alloc("Jazz2:Texture", size, SCE_GXM_MEMORY_ATTRIB_READ));
177 if (!_gpuBlock.IsValid()) {
178 LOGE("Failed to allocate {}x{} texture ({} bytes) in GPU-visible memory", _width, _height, size);
179 return false;
180 }
181
182 std::int32_t result;
183 if (tiled) {
184 result = sceGxmTextureInitTiled(&_gpuTexture, _gpuBlock.Base,
185 SCE_GXM_TEXTURE_FORMAT_U8U8U8U8_ABGR, std::uint32_t(_width), std::uint32_t(_height), 0);
186 } else if (_gpuStrided) {
187 result = sceGxmTextureInitLinearStrided(&_gpuTexture, _gpuBlock.Base,
188 SCE_GXM_TEXTURE_FORMAT_U8U8U8U8_ABGR, std::uint32_t(_width), std::uint32_t(_height), _gpuStride);
189 } else {
190 result = sceGxmTextureInitLinear(&_gpuTexture, _gpuBlock.Base,
191 SCE_GXM_TEXTURE_FORMAT_U8U8U8U8_ABGR, std::uint32_t(_width), std::uint32_t(_height), 0);
192 }
193 if (result < 0) {
194 LOGE("sceGxmTextureInit{}({}x{}) failed with 0x{:.8x}",
195 tiled ? "Tiled" : (_gpuStrided ? "LinearStrided" : "Linear"),
196 _width, _height, std::uint32_t(result));
197 GxmMemory::ReleaseSurface(_gpuBlock);
198 return false;
199 }
200
201 _gpuValid = true;
202 _samplerDirty = true;
203 // A render target's texels are produced by the GPU, so there is nothing to upload into it - and
204 // uploading the (empty) host store would wipe a target that has already been rendered into
205 _contentsDirty = !_isRenderTarget;
206 }
207
208 if (_samplerDirty) {
209 ApplySamplerState();
210 _samplerDirty = false;
211 }
212 if (_contentsDirty) {
213 UploadPixels();
214 _contentsDirty = false;
215 }
216 return _gpuValid;
217 }
218
219 void GxmTexture::ApplySamplerState() const
220 {
221 // A strided texture has one filter field for both directions and no mip filter at all; programming
222 // either of the two rejects the call with SCE_GXM_ERROR_UNSUPPORTED, so only the shared one is set
223 sceGxmTextureSetMagFilter(&_gpuTexture, TranslateFilter(_magFilter));
224 if (!_gpuStrided) {
225 sceGxmTextureSetMinFilter(&_gpuTexture, TranslateFilter(_minFilter));
226 sceGxmTextureSetMipFilter(&_gpuTexture, SCE_GXM_TEXTURE_MIP_FILTER_DISABLED);
227 // None of these textures has a mip chain, and the level count has to say so rather than be left at
228 // whatever the init call defaulted to. It matters where a shader's texture coordinates jump between
229 // neighbouring pixels: the textured background mirrors its layer about the horizon, so the row at
230 // the fold has a derivative hundreds of times the rest of the image, and a level of detail chosen
231 // from that reaches past the only level that exists. OpenGL clamps to the base level for an
232 // incomplete chain, which is why that row is a black line here and not there.
233 sceGxmTextureSetMipmapCount(&_gpuTexture, 1);
234 sceGxmTextureSetLodBias(&_gpuTexture, 0);
235 }
236 // A linear layout - which is what every texture here has, strided or not - is documented to support
237 // fewer addressing modes than a tiled or swizzled one, and a rejected mode leaves whatever the texture
238 // was initialized with in place. That shows up as a seam wherever sampling reaches an edge: a repeating
239 // background that clamps instead of wrapping draws a line at the wrap, and a blur that reads past an
240 // edge picks up whatever is outside. Reported once per mode so the log says which textures wanted what.
241 const SceGxmTextureAddrMode addrMode = TranslateWrap(_wrap);
242 const std::int32_t uResult = sceGxmTextureSetUAddrMode(&_gpuTexture, addrMode);
243 const std::int32_t vResult = sceGxmTextureSetVAddrMode(&_gpuTexture, addrMode);
244
245 if (uResult < 0 || vResult < 0) {
246 static std::uint32_t reportedModes = 0;
247 const std::uint32_t modeBit = (1u << std::uint32_t(addrMode));
248 if ((reportedModes & modeBit) == 0) {
249 reportedModes |= modeBit;
250 LOGW("A {}x{} {} texture rejected addressing mode {} with 0x{:.8x}/0x{:.8x}, so it keeps the one "
251 "it was created with", _width, _height, _gpuStrided ? "linear-strided" : "linear",
252 std::uint32_t(addrMode), std::uint32_t(uResult), std::uint32_t(vResult));
253 }
254 }
255 }
256
257 void GxmTexture::UploadPixels() const
258 {
259 if (!_gpuBlock.IsValid() || _pixels.empty()) {
260 return;
261 }
262
263 std::uint8_t* dst = static_cast<std::uint8_t*>(_gpuBlock.Base);
264 const std::uint32_t rowBytes = std::uint32_t(_width) * 4u;
265 if (IsIdentitySwizzle()) {
266 if (_gpuStride == rowBytes) {
267 // Same stride on both sides, so the whole image is one copy
268 std::memcpy(dst, _pixels.data(), std::size_t(rowBytes) * std::size_t(_height));
269 } else {
270 // A padded stride (a colour attachment) is filled row by row, leaving its padding untouched
271 for (std::int32_t y = 0; y < _height; y++) {
272 std::memcpy(dst + std::size_t(y) * _gpuStride, _pixels.data() + std::size_t(y) * rowBytes, rowBytes);
273 }
274 }
275 return;
276 }
277
278 // sceGxm can express a channel swizzle in the texture format, but only for a fixed set of patterns -
279 // not the arbitrary mapping GL's GL_TEXTURE_SWIZZLE_* allows - so a non-identity swizzle (e.g. the
280 // palette-index RG8 textures set A<-Green so the shader's `src.a` reads the packed alpha byte) is
281 // baked into the uploaded texels instead. Without this, `src.a` would always be 1.0 and RG8 sprites
282 // (gems, pre-packed index+alpha) would lose their transparency.
283 auto pick = [](SwizzleChannel channel, const std::uint8_t* texel) -> std::uint8_t {
284 switch (channel) {
285 case SwizzleChannel::Red: return texel[0];
286 case SwizzleChannel::Green: return texel[1];
287 case SwizzleChannel::Blue: return texel[2];
288 case SwizzleChannel::Alpha: return texel[3];
289 case SwizzleChannel::Zero: return 0;
290 case SwizzleChannel::One: return 255;
291 default: return texel[0];
292 }
293 };
294 for (std::int32_t y = 0; y < _height; y++) {
295 const std::uint8_t* in = _pixels.data() + std::size_t(y) * rowBytes;
296 std::uint8_t* out = dst + std::size_t(y) * _gpuStride;
297 for (std::int32_t x = 0; x < _width; x++, in += 4, out += 4) {
298 out[0] = pick(_swizzle[0], in);
299 out[1] = pick(_swizzle[1], in);
300 out[2] = pick(_swizzle[2], in);
301 out[3] = pick(_swizzle[3], in);
302 }
303 }
304 }
305
306 const SceGxmTexture* GxmTexture::GetGxmTexture() const
307 {
308 return (EnsureGpuTexture() ? &_gpuTexture : nullptr);
309 }
310
311 void* GxmTexture::GetSurfaceData() const
312 {
313 return (EnsureGpuTexture() ? _gpuBlock.Base : nullptr);
314 }
315
316 bool GxmTexture::Bind(std::uint32_t textureUnit) const
317 {
318 _textureUnit = textureUnit;
319 GxmDevice::BindTexture(textureUnit, this);
320 return true;
321 }
322
323 bool GxmTexture::Unbind() const
324 {
325 GxmDevice::BindTexture(_textureUnit, nullptr);
326 return true;
327 }
328
329 bool GxmTexture::Unbind(std::uint32_t textureUnit)
330 {
331 GxmDevice::BindTexture(textureUnit, nullptr);
332 return true;
333 }
334
335 void GxmTexture::TexImage2D(std::int32_t level, PixelFormat format, bool bgr, std::int32_t width, std::int32_t height, const void* data)
336 {
337 static_cast<void>(bgr);
338 if (level != 0) {
339 return;
340 }
341
342 Allocate(format, width, height);
343 if (data != nullptr && !_pixels.empty()) {
344 const std::int32_t srcBpp = BytesPerPixel(format);
345 const std::int32_t dstBpp = BytesPerPixel(_format);
346 if (srcBpp == dstBpp) {
347 std::memcpy(_pixels.data(), data, _pixels.size());
348 } else {
349 const std::uint8_t* src = static_cast<const std::uint8_t*>(data);
350 for (std::int32_t y = 0; y < _height; y++) {
351 CopyExpandRow(_pixels.data() + std::size_t(y) * _strideBytes,
352 dstBpp, src + std::size_t(y) * std::size_t(_width) * srcBpp, srcBpp, _width);
353 }
354 }
355 }
356 }
357
358 void GxmTexture::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)
359 {
360 static_cast<void>(bgr);
361 if (level != 0 || data == nullptr || _pixels.empty()) {
362 return;
363 }
364 if (xoffset < 0 || yoffset < 0 || xoffset + width > _width || yoffset + height > _height) {
365 return;
366 }
367
368 _contentsDirty = true;
369 const std::int32_t srcBpp = BytesPerPixel(format);
370 const std::int32_t dstBpp = BytesPerPixel(_format);
371 const std::uint8_t* src = static_cast<const std::uint8_t*>(data);
372 for (std::int32_t y = 0; y < height; y++) {
373 CopyExpandRow(_pixels.data() + std::size_t(yoffset + y) * _strideBytes + std::size_t(xoffset) * dstBpp,
374 dstBpp, src + std::size_t(y) * std::size_t(width) * srcBpp, srcBpp, width);
375 }
376 }
377
378 void GxmTexture::TexStorage2D(std::int32_t levels, PixelFormat format, std::int32_t width, std::int32_t height)
379 {
380 static_cast<void>(levels);
381 Allocate(format, width, height);
382 }
383
384 void GxmTexture::CompressedTexImage2D(std::int32_t level, PixelFormat format, std::int32_t width, std::int32_t height, std::int32_t imageSize, const void* data)
385 {
386 static_cast<void>(level);
387 static_cast<void>(format);
388 static_cast<void>(width);
389 static_cast<void>(height);
390 static_cast<void>(imageSize);
391 static_cast<void>(data);
392 }
393
394 void GxmTexture::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)
395 {
396 static_cast<void>(level);
397 static_cast<void>(xoffset);
398 static_cast<void>(yoffset);
399 static_cast<void>(width);
400 static_cast<void>(height);
401 static_cast<void>(format);
402 static_cast<void>(imageSize);
403 static_cast<void>(data);
404 }
405
406 void GxmTexture::GetTexImage(std::int32_t level, PixelFormat format, bool bgr, void* pixels)
407 {
408 static_cast<void>(bgr);
409 if (level != 0 || pixels == nullptr || _width <= 0 || _height <= 0) {
410 return;
411 }
412
413 // A render target's texels live only in its GPU copy, and the GPU has to be done writing them first
414 const std::uint8_t* source = _pixels.data();
415 if (_isRenderTarget && _gpuBlock.IsValid()) {
416 GxmDevice::FinishScene();
417 if (SceGxmContext* context = GxmDevice::GetContext()) {
418 sceGxmFinish(context);
419 }
420 source = static_cast<const std::uint8_t*>(_gpuBlock.Base);
421 }
422 if (source == nullptr) {
423 return;
424 }
425
426 const std::int32_t dstBpp = BytesPerPixel(format);
427 const std::int32_t srcBpp = BytesPerPixel(_format);
428 // A render target's rows may be padded to the stride its colour surface needed
429 const std::size_t sourceStride = (source == _pixels.data()
430 ? std::size_t(_strideBytes) : std::size_t(_gpuStride));
431 std::uint8_t* dst = static_cast<std::uint8_t*>(pixels);
432 if (dstBpp == srcBpp) {
433 const std::size_t rowBytes = std::size_t(_width) * std::size_t(srcBpp);
434 for (std::int32_t y = 0; y < _height; y++) {
435 std::memcpy(dst + std::size_t(y) * rowBytes, source + std::size_t(y) * sourceStride, rowBytes);
436 }
437 return;
438 }
439 // Narrowing readback (an RGBA8 store read back as RGB8): drop the trailing channels per texel
440 const std::int32_t shared = (srcBpp < dstBpp ? srcBpp : dstBpp);
441 for (std::int32_t y = 0; y < _height; y++) {
442 const std::uint8_t* in = source + std::size_t(y) * sourceStride;
443 std::uint8_t* out = dst + std::size_t(y) * std::size_t(_width) * std::size_t(dstBpp);
444 for (std::int32_t x = 0; x < _width; x++, in += srcBpp, out += dstBpp) {
445 std::int32_t c = 0;
446 for (; c < shared; c++) {
447 out[c] = in[c];
448 }
449 for (; c < dstBpp; c++) {
450 out[c] = 255;
451 }
452 }
453 }
454 }
455
456 void GxmTexture::SetMinFiltering(nCine::SamplerFilter filter)
457 {
458 if (_minFilter != filter) {
459 _minFilter = filter;
460 _samplerDirty = true;
461 }
462 }
463
464 void GxmTexture::SetMagFiltering(nCine::SamplerFilter filter)
465 {
466 if (_magFilter != filter) {
467 _magFilter = filter;
468 _samplerDirty = true;
469 }
470 }
471
472 void GxmTexture::SetWrap(SamplerWrapping wrap)
473 {
474 if (_wrap != wrap) {
475 _wrap = wrap;
476 _samplerDirty = true;
477 }
478 }
479
480 void GxmTexture::SetSwizzle(SwizzleChannel r, SwizzleChannel g, SwizzleChannel b, SwizzleChannel a)
481 {
482 if (_swizzle[0] == r && _swizzle[1] == g && _swizzle[2] == b && _swizzle[3] == a) {
483 return;
484 }
485 _swizzle[0] = r;
486 _swizzle[1] = g;
487 _swizzle[2] = b;
488 _swizzle[3] = a;
489 // The swizzle is baked into the uploaded texels, so the GPU copy is now stale
490 _contentsDirty = true;
491 }
492
493 void GxmTexture::SetMaxLevel(std::int32_t maxLevel)
494 {
495 static_cast<void>(maxLevel);
496 }
497
498 void GxmTexture::SetUnpackAlignment(std::int32_t alignment)
499 {
500 static_cast<void>(alignment);
501 }
502
503 void GxmTexture::SetObjectLabel(StringView label)
504 {
505 static_cast<void>(label);
506 }
507 }