Debian Codegraph @

Sources/nCine/Graphics/RHI/GU/GuDevice.cpp

raw
1 #include "GuDevice.h"
2 #include "GuBuffer.h"
3 #include "GuShaderProgram.h"
4 #include "GuRenderTarget.h"
5 #include "GuTexture.h"
6 #include "../FixedFunctionPass.h"
7
8 #include "../../../../Main.h"
9 #include "../../../../Shaders/Generated/ShaderCompilerTypes.h"
10
11 #include <algorithm>
12 #include <cmath>
13 #include <cstring>
14
15 #include <pspdisplay.h>
16 #include <pspge.h>
17 #include <pspgu.h>
18 #include <psputils.h>
19
20 namespace nCine::RHI::GU
21 {
22 namespace
23 {
24 // The physical panel. Its scanline pitch is 512 rather than 480 because the GE addresses a surface
25 // with a power-of-two-friendly stride, so a row of a 480-wide buffer is followed by 32 unused texels.
26 constexpr std::int32_t ScreenWidth = 480;
27 constexpr std::int32_t ScreenHeight = 272;
28 constexpr std::int32_t ScreenStride = 512;
29
30 // The GE reads its commands out of a list the CPU fills, and the addresses in it are physical, so it
31 // has to be 16-byte aligned; sceGuStart() maps it through the uncached mirror, so the commands
32 // themselves never need a cache writeback (the vertex arena below is a different matter). Sized for a
33 // frame's worth of state changes and draw calls - the vertices do NOT live here.
34 alignas(16) std::uint32_t displayList[128 * 1024 / sizeof(std::uint32_t)];
35
36 // Both framebuffers and the depth buffer live in the 2 MB of video memory, allocated by hand: there
37 // is no allocator behind sceGeEdramGetAddr(), the GE just reads whatever offset it is given. At
38 // 16 bits per texel the three surfaces take 512*272*2 bytes each, which is 816 KB of the 2 MB.
39 constexpr std::uint32_t FramebufferBytes = ScreenStride * ScreenHeight * 2;
40 constexpr std::uint32_t VramBytes = 2 * 1024 * 1024;
41 // Everything past the three fixed surfaces is available to AllocateVram()
42 constexpr std::uint32_t VramHeapStart = FramebufferBytes * 3;
43
44 void* VramOffset(std::uint32_t byteOffset)
45 {
46 // The offsets handed to sceGuDrawBuffer/sceGuDispBuffer are relative to the start of video
47 // memory, not absolute addresses (the GE adds the base itself)
48 return reinterpret_cast<void*>(std::uintptr_t(byteOffset));
49 }
50
51 // First-fit free list of the video memory left after the display and depth buffers. Render targets
52 // are the only clients and there are at most a handful of them, so a tiny fixed table with adjacent
53 // merging is all this needs - it never has to compact.
54 constexpr std::int32_t MaxVramSpans = 8;
55 struct VramSpan
56 {
57 std::uint32_t Offset;
58 std::uint32_t Size;
59 };
60 VramSpan vramFree[MaxVramSpans] = { { VramHeapStart, VramBytes - VramHeapStart } };
61 std::int32_t vramFreeCount = 1;
62 VramSpan vramUsed[MaxVramSpans] = {};
63 std::int32_t vramUsedCount = 0;
64
65 // Vertices are handed to the GE out of this per-frame bump arena rather than out of the display list:
66 // the arena is ordinary cached memory, so building a batch is as cheap as any other memory write, and
67 // each draw call writes back exactly the range it is about to submit. It is reset at present, after
68 // sceGuSync() has established that the GE is done with the previous frame's data.
69 constexpr std::size_t FrameArenaBytes = 256 * 1024;
70 alignas(16) std::uint8_t frameArena[FrameArenaBytes];
71 std::size_t frameArenaUsed = 0;
72 bool warnedFrameArenaFull = false;
73
74 // The GE reads vertex components in a fixed order (weights, texture, colour, normal, position), so
75 // this member order is a hardware contract rather than a choice
76 struct Vertex2D
77 {
78 float U, V;
79 std::uint32_t Color;
80 float X, Y, Z;
81 };
82 // GU_TRANSFORM_2D ("through" mode) hands the coordinates straight to the rasterizer: positions are
83 // screen pixels, texture coordinates are TEXEL indices of the bound texture (the texture scale and
84 // offset registers do not apply), and neither the viewport nor sceGuOffset() is involved
85 constexpr std::int32_t VertexType2D = GU_TEXTURE_32BITF | GU_COLOR_8888 | GU_VERTEX_32BITF | GU_TRANSFORM_2D;
86
87 // An axis-aligned quad can go out as a GU_SPRITES rectangle, which is two vertices instead of the six
88 // a triangle pair needs - a third of the vertex traffic for the overwhelming majority of this game's
89 // primitives (UI, tiles, unrotated sprites). Kept as a switch because the rectangle primitive has its
90 // own fill rule, so it has to be possible to compare the two.
91 constexpr bool PreferSpritePrimitive = true;
92
93 // Per-frame draw statistics, logged when the switch below is on - the only practical way to see how
94 // much geometry reaches the GE, since sceGu is a userspace library and leaves no syscall trace
95 constexpr bool TraceDrawStatistics = false;
96 std::uint32_t frameDrawCalls = 0;
97 std::uint32_t frameVertices = 0;
98 std::uint32_t frameSkippedDraws = 0;
99
100 // The DefaultSprite / DefaultBatchedSprites instance layout is a hard contract of the shader family
101 // (std140 offsets within the InstanceBlock / each batched Instance) - identical to the software and
102 // PowerVR backends' decode (see SwDevice.cpp / PvrDevice.cpp)
103 constexpr std::uint32_t kModelMatrixOffset = 0;
104 constexpr std::uint32_t kColorOffset = 64;
105 constexpr std::uint32_t kTexRectOffset = 80;
106 constexpr std::uint32_t kSpriteSizeOffset = 96;
107 constexpr std::uint32_t kPaletteOffsetOffset = 104;
108 constexpr std::uint32_t kSpriteSizeNoTexOffset = 80;
109
110 const float IdentityMatrix[16] = {
111 1, 0, 0, 0,
112 0, 1, 0, 0,
113 0, 0, 1, 0,
114 0, 0, 0, 1
115 };
116
117 // Column-major 4x4 multiply, out = a * b (matches the software device)
118 void Mat4Mul(const float* DEATH_RESTRICT a, const float* DEATH_RESTRICT b, float* DEATH_RESTRICT out)
119 {
120 for (std::int32_t col = 0; col < 4; col++) {
121 for (std::int32_t row = 0; row < 4; row++) {
122 out[col * 4 + row] =
123 a[0 * 4 + row] * b[col * 4 + 0] +
124 a[1 * 4 + row] * b[col * 4 + 1] +
125 a[2 * 4 + row] * b[col * 4 + 2] +
126 a[3 * 4 + row] * b[col * 4 + 3];
127 }
128 }
129 }
130
131 // Both draw paths only ever transform points of the form (x, y, 0, 1), so just six of the sixteen
132 // products of projection*view*model are ever read back
133 struct Transform2D
134 {
135 float Xx, Xy; // Column 0, rows 0 and 1
136 float Yx, Yy; // Column 1, rows 0 and 1
137 float Tx, Ty; // Column 3, rows 0 and 1
138 };
139
140 void Mat4MulTransform2D(const float* DEATH_RESTRICT pv, const float* DEATH_RESTRICT model, Transform2D& out)
141 {
142 out.Xx = pv[0] * model[0] + pv[4] * model[1] + pv[8] * model[2] + pv[12] * model[3];
143 out.Xy = pv[1] * model[0] + pv[5] * model[1] + pv[9] * model[2] + pv[13] * model[3];
144 out.Yx = pv[0] * model[4] + pv[4] * model[5] + pv[8] * model[6] + pv[12] * model[7];
145 out.Yy = pv[1] * model[4] + pv[5] * model[5] + pv[9] * model[6] + pv[13] * model[7];
146 out.Tx = pv[0] * model[12] + pv[4] * model[13] + pv[8] * model[14] + pv[12] * model[15];
147 out.Ty = pv[1] * model[12] + pv[5] * model[13] + pv[9] * model[14] + pv[13] * model[15];
148 }
149
150 inline std::uint8_t QuantizeChannel(float v)
151 {
152 v = (v < 0.0f ? 0.0f : (v > 1.0f ? 1.0f : v));
153 return std::uint8_t(v * 255.0f + 0.5f);
154 }
155
156 // Straight to the 4 bits a 4444 channel actually keeps, skipping the round trip through 8 bits
157 inline std::uint32_t Quantize4Bit(float v)
158 {
159 v = (v < 0.0f ? 0.0f : (v > 1.0f ? 1.0f : v));
160 return std::uint32_t(v * 15.0f + 0.5f);
161 }
162
163 // The GE takes clear/vertex/environment colors as ABGR, the opposite channel order from the ARGB the
164 // PowerVR wants
165 inline std::uint32_t PackAbgr(std::uint8_t r, std::uint8_t g, std::uint8_t b, std::uint8_t a)
166 {
167 return (std::uint32_t(a) << 24) | (std::uint32_t(b) << 16) | (std::uint32_t(g) << 8) | std::uint32_t(r);
168 }
169
170 // Maps a pipeline-neutral blend factor onto the GE factor set. Factors 0 and 1 mean "the OTHER
171 // side's colour" - the destination colour in the source slot and the other way round - which is
172 // exactly how the engine's SrcColor/DstColor pairs are ever used; One and Zero have no factors of
173 // their own and go through the constant (GU_FIX) slot instead.
174 std::int32_t MapBlendGu(nCine::BlendingFactor factor, std::uint32_t& fix)
175 {
176 switch (factor) {
177 case nCine::BlendingFactor::Zero: fix = 0x000000; return GU_FIX;
178 case nCine::BlendingFactor::One: fix = 0xFFFFFF; return GU_FIX;
179 case nCine::BlendingFactor::SrcColor:
180 case nCine::BlendingFactor::DstColor: return GU_OTHER_COLOR;
181 case nCine::BlendingFactor::OneMinusSrcColor:
182 case nCine::BlendingFactor::OneMinusDstColor: return GU_ONE_MINUS_OTHER_COLOR;
183 case nCine::BlendingFactor::SrcAlpha: return GU_SRC_ALPHA;
184 case nCine::BlendingFactor::OneMinusSrcAlpha: return GU_ONE_MINUS_SRC_ALPHA;
185 case nCine::BlendingFactor::DstAlpha: return GU_DST_ALPHA;
186 case nCine::BlendingFactor::OneMinusDstAlpha: return GU_ONE_MINUS_DST_ALPHA;
187 default: fix = 0xFFFFFF; return GU_FIX;
188 }
189 }
190
191 std::int32_t MapWrapGu(SamplerWrapping wrap)
192 {
193 // Only a store whose real size is already a power of two tiles correctly: the GE wraps at the
194 // TEXTURE size, which is the padded one. That is exactly the case for the tiling layers of the
195 // legacy main menu (16x16 / 32x32 / 128x128), the only content that asks for it.
196 return (wrap == SamplerWrapping::Repeat || wrap == SamplerWrapping::MirroredRepeat ? GU_REPEAT : GU_CLAMP);
197 }
198 }
199
200 /**
201 @brief The whole GE state one primitive is drawn under
202
203 Consecutive primitives whose state matches field for field are accumulated into a single
204 `sceGuDrawArray`, so a tile layer, a text run or a particle batch costs one draw call. The state is
205 derived once per draw from the material (texture page, filter, wrap, blend) and then adjusted per
206 pass by the effect (blend override, texture function) - which is what makes the batching automatic
207 rather than something the effects have to think about.
208
209 At namespace scope rather than in the anonymous namespace below because EffectContext names it in a
210 member type and itself has to be externally visible (see the note there).
211 */
212 struct DrawState
213 {
214 const void* TextureData = nullptr; // nullptr = untextured
215 const std::uint32_t* Clut = nullptr; // The per-frame CLUT copy an indexed page resolves through
216 std::int32_t TexturePsm = 0;
217 std::int32_t TextureWidth = 0, TextureHeight = 0, TextureStride = 0;
218 std::int32_t Filter = GU_NEAREST;
219 std::int32_t WrapU = GU_CLAMP, WrapV = GU_CLAMP;
220 std::int32_t Tfx = GU_TFX_MODULATE;
221 std::int32_t Tcc = GU_TCC_RGBA;
222 std::uint32_t EnvColor = 0;
223 std::int32_t BlendOp = GU_ADD;
224 std::int32_t BlendSrc = GU_SRC_ALPHA, BlendDst = GU_ONE_MINUS_SRC_ALPHA;
225 std::uint32_t BlendSrcFix = 0, BlendDstFix = 0;
226 std::int32_t Prim = GU_SPRITES;
227 bool TextureSwizzled = false;
228 bool BlendEnabled = true;
229 };
230
231 namespace
232 {
233 bool SameDrawState(const DrawState& a, const DrawState& b)
234 {
235 return a.TextureData == b.TextureData && a.Clut == b.Clut && a.TexturePsm == b.TexturePsm &&
236 a.TextureWidth == b.TextureWidth && a.TextureHeight == b.TextureHeight &&
237 a.TextureStride == b.TextureStride && a.Filter == b.Filter &&
238 a.WrapU == b.WrapU && a.WrapV == b.WrapV && a.Tfx == b.Tfx && a.Tcc == b.Tcc &&
239 a.EnvColor == b.EnvColor && a.BlendOp == b.BlendOp && a.BlendSrc == b.BlendSrc &&
240 a.BlendDst == b.BlendDst && a.BlendSrcFix == b.BlendSrcFix && a.BlendDstFix == b.BlendDstFix &&
241 a.Prim == b.Prim && a.TextureSwizzled == b.TextureSwizzled && a.BlendEnabled == b.BlendEnabled;
242 }
243
244 DrawState batchState;
245 std::size_t batchFirstByte = 0;
246 std::int32_t batchVertexCount = 0;
247
248 DrawState appliedState;
249 bool appliedStateValid = false;
250
251 void ApplyDrawState(const DrawState& state)
252 {
253 const bool textureChanged = (!appliedStateValid ||
254 appliedState.TextureData != state.TextureData || appliedState.Clut != state.Clut ||
255 appliedState.TexturePsm != state.TexturePsm || appliedState.TextureWidth != state.TextureWidth ||
256 appliedState.TextureHeight != state.TextureHeight || appliedState.TextureStride != state.TextureStride ||
257 appliedState.TextureSwizzled != state.TextureSwizzled);
258 if (textureChanged) {
259 if (state.TextureData == nullptr) {
260 sceGuDisable(GU_TEXTURE_2D);
261 } else {
262 sceGuEnable(GU_TEXTURE_2D);
263 if (state.Clut != nullptr) {
264 // 8-bit indices address the CLUT directly, so no shift and the full 8-bit mask; 32
265 // blocks of 8 entries are the 256 the format has. The entries are ordinary RGBA8
266 // values, which is byte for byte what GU_PSM_8888 expects.
267 sceGuClutMode(GU_PSM_8888, 0, 0xFF, 0);
268 sceGuClutLoad(32, state.Clut);
269 }
270 sceGuTexMode(state.TexturePsm, 0, 0, state.TextureSwizzled ? GU_TRUE : GU_FALSE);
271 sceGuTexImage(0, state.TextureWidth, state.TextureHeight, state.TextureStride, state.TextureData);
272 // The GE caches texels, and a rebuilt store (or a bake switched to another palette row)
273 // reuses the same addresses, so the cache has to be dropped whenever the binding changes
274 sceGuTexFlush();
275 }
276 }
277 if (state.TextureData != nullptr && (textureChanged ||
278 appliedState.Tfx != state.Tfx || appliedState.Tcc != state.Tcc ||
279 appliedState.EnvColor != state.EnvColor)) {
280 sceGuTexFunc(state.Tfx, state.Tcc);
281 sceGuTexEnvColor(state.EnvColor);
282 }
283 if (state.TextureData != nullptr && (textureChanged || appliedState.Filter != state.Filter)) {
284 sceGuTexFilter(state.Filter, state.Filter);
285 }
286 if (state.TextureData != nullptr && (textureChanged ||
287 appliedState.WrapU != state.WrapU || appliedState.WrapV != state.WrapV)) {
288 sceGuTexWrap(state.WrapU, state.WrapV);
289 }
290 if (!appliedStateValid || appliedState.BlendEnabled != state.BlendEnabled ||
291 (state.BlendEnabled && (appliedState.BlendOp != state.BlendOp ||
292 appliedState.BlendSrc != state.BlendSrc || appliedState.BlendDst != state.BlendDst ||
293 appliedState.BlendSrcFix != state.BlendSrcFix || appliedState.BlendDstFix != state.BlendDstFix))) {
294 if (state.BlendEnabled) {
295 sceGuEnable(GU_BLEND);
296 sceGuBlendFunc(state.BlendOp, state.BlendSrc, state.BlendDst, state.BlendSrcFix, state.BlendDstFix);
297 } else {
298 sceGuDisable(GU_BLEND);
299 }
300 }
301 appliedState = state;
302 appliedStateValid = true;
303 }
304
305 void FlushBatch()
306 {
307 if (batchVertexCount <= 0) {
308 return;
309 }
310 ApplyDrawState(batchState);
311 std::uint8_t* const base = frameArena + batchFirstByte;
312 const std::size_t bytes = std::size_t(batchVertexCount) * sizeof(Vertex2D);
313 // The GE reads main memory without seeing the data cache; this is the writeback that makes the
314 // vertices visible to it (the PSP equivalent of the GX's DCFlushRange)
315 sceKernelDcacheWritebackRange(base, bytes);
316 sceGuDrawArray(batchState.Prim, VertexType2D, batchVertexCount, nullptr, base);
317 frameDrawCalls++;
318 frameVertices += std::uint32_t(batchVertexCount);
319 batchVertexCount = 0;
320 }
321
322 /** @brief Reserves per-frame data (a CLUT copy, a generated texture) the GE will read */
323 void* AllocFrameData(std::size_t size, std::size_t alignment)
324 {
325 // The open batch's vertices have to stay contiguous in the arena, so anything else that takes
326 // space from it closes the batch first
327 FlushBatch();
328 const std::size_t aligned = (frameArenaUsed + alignment - 1) & ~(alignment - 1);
329 if (aligned + size > FrameArenaBytes) {
330 return nullptr;
331 }
332 frameArenaUsed = aligned + size;
333 return frameArena + aligned;
334 }
335
336 /** @brief Reserves @p count vertices of the open (or a new) batch drawn under @p state */
337 Vertex2D* AllocVertices(const DrawState& state, std::int32_t count)
338 {
339 if (batchVertexCount > 0 && !SameDrawState(batchState, state)) {
340 FlushBatch();
341 }
342 const std::size_t bytes = std::size_t(count) * sizeof(Vertex2D);
343 if (batchVertexCount == 0) {
344 frameArenaUsed = (frameArenaUsed + 15) & ~std::size_t(15);
345 batchFirstByte = frameArenaUsed;
346 batchState = state;
347 }
348 if (frameArenaUsed + bytes > FrameArenaBytes) {
349 FlushBatch();
350 if (!warnedFrameArenaFull) {
351 warnedFrameArenaFull = true;
352 LOGW("The {} KB per-frame vertex arena is full; the rest of the frame is dropped", FrameArenaBytes / 1024);
353 }
354 return nullptr;
355 }
356 Vertex2D* const result = reinterpret_cast<Vertex2D*>(frameArena + frameArenaUsed);
357 frameArenaUsed += bytes;
358 batchVertexCount += count;
359 return result;
360 }
361
362 /**
363 @brief Submits one quad, as a GE rectangle when it is axis-aligned and as a triangle pair otherwise
364
365 Corners 0/1 share the sprite's local x = 1 edge and 2/3 its x = 0 edge, 0/2 the y = 0 edge and 1/3
366 the y = 1 edge (see the corner synthesis in Dispatch), so an axis-aligned quad is exactly the case
367 where those pairs agree on the other axis.
368 */
369 void SubmitQuadPrimitive(DrawState state, const float* px, const float* py, const float* pu, const float* pv,
370 std::uint32_t abgr, float dx = 0.0f, float dy = 0.0f)
371 {
372 const bool axisAligned = (px[0] == px[1] && px[2] == px[3] && py[0] == py[2] && py[1] == py[3]);
373 if (axisAligned && PreferSpritePrimitive) {
374 state.Prim = GU_SPRITES;
375 Vertex2D* const v = AllocVertices(state, 2);
376 if (v == nullptr) {
377 return;
378 }
379 // The rectangle primitive takes two opposite corners in increasing order, so a mirrored
380 // sprite (a negative scale in the model matrix) trades them over - and its texture
381 // coordinates travel with them, which is what keeps the flip
382 float x0 = px[2] + dx, u0 = pu[2], x1 = px[0] + dx, u1 = pu[0];
383 if (x0 > x1) {
384 std::swap(x0, x1);
385 std::swap(u0, u1);
386 }
387 float y0 = py[0] + dy, v0 = pv[0], y1 = py[1] + dy, v1 = pv[1];
388 if (y0 > y1) {
389 std::swap(y0, y1);
390 std::swap(v0, v1);
391 }
392 v[0] = { u0, v0, abgr, x0, y0, 0.0f };
393 v[1] = { u1, v1, abgr, x1, y1, 0.0f };
394 } else {
395 state.Prim = GU_TRIANGLES;
396 Vertex2D* const v = AllocVertices(state, 6);
397 if (v == nullptr) {
398 return;
399 }
400 // The two triangles of the v0..v3 strip; culling is off, so the winding is free
401 static const std::int32_t Order[6] = { 0, 1, 2, 2, 1, 3 };
402 for (std::int32_t i = 0; i < 6; i++) {
403 const std::int32_t o = Order[i];
404 v[i] = { pu[o], pv[o], abgr, px[o] + dx, py[o] + dy, 0.0f };
405 }
406 }
407 }
408
409 /** @brief Submits a triangle strip of its own draw call (arbitrary synthesized geometry) */
410 void SubmitStripPrimitive(DrawState state, const float* px, const float* py, const float* pu, const float* pv,
411 std::int32_t count, const std::uint32_t* abgr, std::uint32_t flatAbgr, float dx, float dy)
412 {
413 // A strip cannot share a draw call with anything else - the GE would connect it to whatever
414 // vertices follow - so it is bracketed by flushes
415 state.Prim = GU_TRIANGLE_STRIP;
416 FlushBatch();
417 Vertex2D* const v = AllocVertices(state, count);
418 if (v == nullptr) {
419 return;
420 }
421 for (std::int32_t i = 0; i < count; i++) {
422 v[i].U = (pu != nullptr ? pu[i] : 0.0f);
423 v[i].V = (pv != nullptr ? pv[i] : 0.0f);
424 v[i].Color = (abgr != nullptr ? abgr[i] : flatAbgr);
425 v[i].X = px[i] + dx;
426 v[i].Y = py[i] + dy;
427 v[i].Z = 0.0f;
428 }
429 FlushBatch();
430 }
431
432 /** @brief Folds a pass descriptor's blend mode and texture function into a copy of the material state */
433 void ApplyPassToState(DrawState& state, const FixedFunctionPass& pass)
434 {
435 switch (pass.Blend) {
436 case FixedFunctionPass::BlendMode::Additive:
437 // Deliberately SRCALPHA rather than a literal ONE source factor, matching the PVR: it is
438 // the additive mechanism the split-multiplier passes rely on, whose contributions are
439 // scaled by the pass alpha
440 state.BlendEnabled = true;
441 state.BlendOp = GU_ADD;
442 state.BlendSrc = GU_SRC_ALPHA;
443 state.BlendDst = GU_FIX;
444 state.BlendDstFix = 0xFFFFFF;
445 break;
446 case FixedFunctionPass::BlendMode::Opaque:
447 state.BlendEnabled = false;
448 break;
449 case FixedFunctionPass::BlendMode::Alpha:
450 state.BlendEnabled = true;
451 state.BlendOp = GU_ADD;
452 state.BlendSrc = GU_SRC_ALPHA;
453 state.BlendDst = GU_ONE_MINUS_SRC_ALPHA;
454 break;
455 default:
456 break; // The material's own blending
457 }
458
459 switch (pass.Tev) {
460 case FixedFunctionPass::TevPreset::Silhouette:
461 // The GE has no "flat colour where the texture has alpha" environment of its own, but
462 // GU_TFX_BLEND computes Cv = Cf*(1-Ct) + Cc*Ct, which collapses to exactly Cf - per
463 // channel, whatever the texel is - as soon as the environment colour Cc equals the
464 // fragment colour Cf. With GU_TCC_RGBA the alpha stays At*Af, so this IS the hardware
465 // silhouette the mask/outline/shield family needs, in one pass.
466 state.Tfx = GU_TFX_BLEND;
467 state.Tcc = GU_TCC_RGBA;
468 state.EnvColor = PackAbgr(QuantizeChannel(pass.Color[0]), QuantizeChannel(pass.Color[1]),
469 QuantizeChannel(pass.Color[2]), 0) & 0x00FFFFFFu;
470 break;
471 default:
472 // Modulate. The x2/x4 output scales have no GE equivalent (the texture environment has no
473 // scale stage at all) and the transpiler rejects them for the gu target, exactly as it
474 // rejects the GX-only TintMix/LumaRamp outside a gx block - so nothing but a Modulate
475 // pass can reach this arm from a generated effect.
476 state.Tfx = GU_TFX_MODULATE;
477 state.Tcc = GU_TCC_RGBA;
478 break;
479 }
480 }
481
482 // The CLUT the GE resolves indexed texels through can only hold one 256-entry table at a time, so a
483 // palette row change is a state change like any other. Loads reference their data until the GE
484 // executes them, and the GE runs behind the CPU, so each distinct row of a frame gets its own copy
485 // out of the frame arena - one 1 KB copy per palette row per frame, keyed exactly like the PowerVR's
486 // palette banks so repeated draws of the same row reload nothing.
487 constexpr std::int32_t MaxClutCacheEntries = 8;
488 struct ClutCacheEntry
489 {
490 const void* Palette;
491 std::int32_t Offset;
492 std::uint32_t Version;
493 const std::uint32_t* Data;
494 };
495 ClutCacheEntry clutCache[MaxClutCacheEntries] = {};
496 std::int32_t clutCacheCount = 0;
497 }
498
499 // EffectContext deliberately has EXTERNAL linkage (namespace scope, though it is still defined only in
500 // this translation unit), for the same reason as on the PVR: the effect-table struct below is at
501 // namespace scope - so the backend's ShaderProgram can forward-declare it and hold a typed entry
502 // pointer - and names EffectContext in a member type.
503 // ---------------------------------------------------------- fixed-function quad effects
504 //
505 // The quad-family effects are expressed as FixedFunctionPass descriptors handed to this EffectContext -
506 // the structural contract documented in FixedFunctionPass.h, implemented here against the GE's
507 // batching submission helpers above. The per-effect functions themselves are GENERATED from the
508 // shaders' void fixed_function([gu]) blocks by the ShaderCompiler, exactly as on the PVR and the GX
509 // (Shaders/Generated/GuGeneratedEffects.h, included below), so this file contains no effect-specific
510 // code at all.
511
512 struct EffectContext
513 {
514 // Matches the GX's capacity rather than the PVR's, because nothing here needs the geometry split
515 // into small pieces: the GE takes a strip of any length in one draw call
516 static constexpr std::int32_t MaxStripVertices = 16;
517
518 // Decoded instance data of the draw being dispatched (the documented contract)
519 const float* InstanceColor;
520 float TexelW;
521 float TexelH;
522 bool Batched;
523
524 // The GE state the material resolved to, and the current instance's corner arrays (already in
525 // screen pixels and texel-space texture coordinates)
526 const DrawState* Material;
527 const float* Px;
528 const float* Py;
529 const float* Pu;
530 const float* Pv;
531 const float* TexRect;
532
533 // Pre-clip quad geometry (the quad_origin/quad_axis_* built-ins), the program (for resolved
534 // uniforms) and the conversion from the shader's normalized texture space into the texel
535 // coordinates through mode wants, page origin included
536 float OriginX, OriginY;
537 float AxisXx, AxisXy;
538 float AxisYx, AxisYy;
539 const GuShaderProgram* Program;
540 float UvScaleU, UvScaleV;
541 float UvBiasU, UvBiasV;
542
543 // The strip builder scratch; colours are packed at set time (same quantization as the quad path, so
544 // identical float inputs produce identical vertex words)
545 float StripX[MaxStripVertices];
546 float StripY[MaxStripVertices];
547 float StripU[MaxStripVertices];
548 float StripV[MaxStripVertices];
549 std::uint32_t StripAbgr[MaxStripVertices];
550
551 const float* Color() const { return InstanceColor; }
552 float TexelWidth() const { return TexelW; }
553 float TexelHeight() const { return TexelH; }
554 bool IsBatched() const { return Batched; }
555
556 float QuadOriginX() const { return OriginX; }
557 float QuadOriginY() const { return OriginY; }
558 float QuadAxisXx() const { return AxisXx; }
559 float QuadAxisXy() const { return AxisXy; }
560 float QuadAxisYx() const { return AxisYx; }
561 float QuadAxisYy() const { return AxisYy; }
562
563 bool HasUniform(const char* name) const
564 {
565 return (Program->ResolveUniform(name) != nullptr);
566 }
567 void LoadUniform(const char* name, float* out, std::int32_t floatCount) const
568 {
569 // An unresolved name leaves the caller's zeros in place - blocks guard with has_uniform()
570 const std::uint8_t* bytes = Program->ResolveUniform(name);
571 if (bytes != nullptr) {
572 std::memcpy(out, bytes, std::size_t(floatCount) * sizeof(float));
573 }
574 }
575
576 void SetStripVertexPosition(std::int32_t i, float x, float y)
577 {
578 if (std::uint32_t(i) < std::uint32_t(MaxStripVertices)) {
579 StripX[i] = x;
580 StripY[i] = y;
581 }
582 }
583 void SetStripVertexUv(std::int32_t i, float u, float v)
584 {
585 if (std::uint32_t(i) < std::uint32_t(MaxStripVertices)) {
586 StripU[i] = u * UvScaleU - UvBiasU;
587 StripV[i] = v * UvScaleV - UvBiasV;
588 }
589 }
590 void SetStripVertexColor(std::int32_t i, float r, float g, float b, float a)
591 {
592 if (std::uint32_t(i) < std::uint32_t(MaxStripVertices)) {
593 StripAbgr[i] = PackAbgr(QuantizeChannel(r), QuantizeChannel(g), QuantizeChannel(b), QuantizeChannel(a));
594 }
595 }
596
597 // Whether a UV span can be mapped onto the screen at all (a zero texRect has no scale)
598 bool HasTexelStep() const { return TexRect[0] != 0.0f && TexRect[2] != 0.0f; }
599 // Maps a span in the sprite's UV space onto the quad's on-screen extent - the texel step the
600 // Outline ring taps use. The corners are already in screen space, so the result is a screen-space
601 // displacement.
602 float TexelToScreenX(float uvSpan) const { return (Px[0] - Px[2]) * (uvSpan / TexRect[0]); }
603 float TexelToScreenY(float uvSpan) const { return (Py[1] - Py[0]) * (uvSpan / TexRect[2]); }
604 // The documented texel_size() built-in of the fixed_function contract: the Outline shader family
605 // carries the sprite's UV-space texel size in its instance color.xy (exactly like the GLSL derives
606 // its tap offsets), folded through the screen-space conversion above
607 float TexelStepX() const { return TexelToScreenX(InstanceColor[0]); }
608 float TexelStepY() const { return TexelToScreenY(InstanceColor[1]); }
609
610 // One quad draw for a pass the GE can express directly (no offset colour left on it)
611 void SubmitQuadPass(const FixedFunctionPass& pass)
612 {
613 DrawState state = *Material;
614 ApplyPassToState(state, pass);
615 const std::uint32_t abgr = PackAbgr(QuantizeChannel(pass.Color[0]), QuantizeChannel(pass.Color[1]),
616 QuantizeChannel(pass.Color[2]), QuantizeChannel(pass.Color[3]));
617 SubmitQuadPrimitive(state, Px, Py, Pu, Pv, abgr, pass.ScreenOffset[0], pass.ScreenOffset[1]);
618 }
619
620 /*
621 Submits one pass over the current instance's quad. A pass carrying an offset colour is
622 EXPANDED here, because the GE has no post-texture additive term: GU_TFX_ADD adds the texel to
623 the fragment colour rather than a third value, so `texel*colour + offset` is not any single
624 GE draw. Doing the expansion in the mechanism (rather than spelling both passes in every
625 shader's gu block) is what keeps the portable core portable - the same generic block still
626 describes the effect on all three consoles, exactly as the GX reinterprets an offset colour
627 as its silhouette form.
628
629 The expansion is EXACT, not an approximation. With a = texel.a * colour.a, the PVR's single
630 draw over the destination dst is (its blend being SRCALPHA + INVSRCALPHA):
631
632 dst*(1 - a) + a*(texel*colour.rgb + offset)
633
634 and the two draws below produce, in order,
635
636 pass 1 (modulate, the pass's own blend): dst1 = dst*(1 - a) + a*texel*colour.rgb
637 pass 2 (silhouette, additive): dst2 = dst1 + a*offset
638
639 whose sum is the same expression term for term. Pass 2 is a GE silhouette (flat colour where
640 the texture has alpha) whose vertex AND environment colour is the offset colour, so its own
641 contribution is a*offset with no texel dependence, and its ADDITIVE blend is what keeps it
642 from attenuating the destination a second time.
643
644 When colour.rgb is zero - the "pure offset colour" idiom of the mask/outline/shield family,
645 where the offset colour IS the effect - the modulate term vanishes and the pair collapses to
646 ONE draw: the silhouette under the pass's own (alpha-over) blend already computes
647 dst*(1 - a) + a*offset. That is the common case, so those effects cost the PVR's draw count.
648 */
649 void SubmitQuad(const FixedFunctionPass& pass)
650 {
651 if (pass.HasOffsetColor) {
652 const bool modulateVisible = (pass.Color[0] != 0.0f || pass.Color[1] != 0.0f || pass.Color[2] != 0.0f);
653 if (modulateVisible) {
654 FixedFunctionPass modulate = pass;
655 modulate.HasOffsetColor = false;
656 SubmitQuadPass(modulate);
657 }
658 FixedFunctionPass silhouette = pass;
659 silhouette.HasOffsetColor = false;
660 silhouette.Tev = FixedFunctionPass::TevPreset::Silhouette;
661 silhouette.Color[0] = pass.OffsetColor[0];
662 silhouette.Color[1] = pass.OffsetColor[1];
663 silhouette.Color[2] = pass.OffsetColor[2];
664 // Only the second half of a split pair is additive; a collapsed one keeps the pass's blend
665 // (the alpha-over the effects rely on) so it still attenuates the destination itself
666 if (modulateVisible) {
667 silhouette.Blend = FixedFunctionPass::BlendMode::Additive;
668 }
669 SubmitQuadPass(silhouette);
670 return;
671 }
672 SubmitQuadPass(pass);
673 }
674
675 // Textured strip out of the builder scratch: the pass's flat colour over the material state
676 void SubmitStrip(const FixedFunctionPass& pass, std::int32_t count)
677 {
678 if (count > MaxStripVertices) {
679 count = MaxStripVertices;
680 }
681 if (count < 3) {
682 return;
683 }
684 // Same intent mapping as the GX's SubmitStrip: with no post-texture add on this hardware, an
685 // offset colour becomes the silhouette form filled flat with it at the pass alpha. Deliberately
686 // NOT split into the exact two draws SubmitQuad builds - a strip's geometry would have to be
687 // resubmitted, and no effect asks for it (both strip users, the iris and the warp bands, carry
688 // no offset colour at all).
689 FixedFunctionPass effective = pass;
690 if (pass.HasOffsetColor) {
691 effective.HasOffsetColor = false;
692 effective.Tev = FixedFunctionPass::TevPreset::Silhouette;
693 effective.Color[0] = pass.OffsetColor[0];
694 effective.Color[1] = pass.OffsetColor[1];
695 effective.Color[2] = pass.OffsetColor[2];
696 }
697 DrawState state = *Material;
698 ApplyPassToState(state, effective);
699 const std::uint32_t abgr = PackAbgr(QuantizeChannel(effective.Color[0]), QuantizeChannel(effective.Color[1]),
700 QuantizeChannel(effective.Color[2]), QuantizeChannel(effective.Color[3]));
701 SubmitStripPrimitive(state, StripX, StripY, StripU, StripV, count, nullptr, abgr,
702 pass.ScreenOffset[0], pass.ScreenOffset[1]);
703 }
704
705 // Shaded (per-vertex-colour) strip out of the builder scratch: always UNTEXTURED - a gradient has no
706 // texture to modulate - whose blend comes from the pass
707 void SubmitStripShaded(const FixedFunctionPass& pass, std::int32_t count)
708 {
709 if (count > MaxStripVertices) {
710 count = MaxStripVertices;
711 }
712 if (count < 3) {
713 return;
714 }
715 DrawState state = *Material;
716 ApplyPassToState(state, pass);
717 state.TextureData = nullptr;
718 state.Clut = nullptr;
719 SubmitStripPrimitive(state, StripX, StripY, nullptr, nullptr, count, StripAbgr, 0,
720 pass.ScreenOffset[0], pass.ScreenOffset[1]);
721 }
722 };
723 }
724
725 // The per-effect functions themselves are GENERATED: the ShaderCompiler transpiles each shader's
726 // fixed_function block into C++ over the EffectContext defined above (the type name itself is the
727 // "using EffectContext = ...;" alias the header expects - the anonymous namespace above is the same
728 // namespace the header's payload reopens within this translation unit). Included at global scope
729 // because the header opens nCine::RHI::GU itself. Programs with no fixed_function block are absent
730 // from its table and their draws are skipped with a one-time warning, exactly as on the other
731 // consoles - which is also what keeps the CPU-lightmap tier (Lighting, whose Combine hook IS in the
732 // table) from painting its light quads over the scene.
733 #include "../../../../Shaders/Generated/GuGeneratedEffects.h"
734
735 namespace nCine::RHI::GU
736 {
737 const FixedFunctionGeneratedEffect* GuDevice::FindGeneratedEffect(const char* program, const char* variant)
738 {
739 // A linear scan is fine - the lookup runs once per program load, not per draw
740 for (std::size_t i = 0; i < FixedFunctionGeneratedEffectCount; i++) {
741 const FixedFunctionGeneratedEffect& e = FixedFunctionGeneratedEffects[i];
742 if (std::strcmp(e.Program, program) == 0 && std::strcmp(e.Variant, variant) == 0) {
743 return &e;
744 }
745 }
746 return nullptr;
747 }
748
749 GuDevice::BlendingState GuDevice::_blending;
750 GuDevice::DepthTestState GuDevice::_depthTest;
751 GuDevice::CullFaceState GuDevice::_cullFace;
752 GuDevice::ScissorState GuDevice::_scissor;
753 Recti GuDevice::_viewport(0, 0, 0, 0);
754 Colorf GuDevice::_clearColor(0.0f, 0.0f, 0.0f, 1.0f);
755
756 GuShaderProgram* GuDevice::_currentProgram = nullptr;
757 const GuTexture* GuDevice::_boundTextures[GuDevice::MaxTextureUnits] = {};
758 GuDevice::UniformRange GuDevice::_boundUniformRanges[GuDevice::MaxUniformBindings] = {};
759 GuRenderTarget* GuDevice::_currentRenderTarget = nullptr;
760
761 bool GuDevice::_guInitialized = false;
762 bool GuDevice::_listOpen = false;
763 std::int32_t GuDevice::_logicalWidth = ScreenWidth;
764 std::int32_t GuDevice::_logicalHeight = ScreenHeight;
765 std::uint32_t GuDevice::_sceneCounter = 0;
766
767 GuTexture* GuDevice::_paletteTexture = nullptr;
768 std::uint32_t GuDevice::_paletteGeneration = 1;
769
770 std::vector<GuDevice::PendingSoftwareLight> GuDevice::_pendingSoftwareLights;
771
772 namespace
773 {
774 // Which surface the GE is currently rendering into, so a target switch only re-emits the commands
775 // when it really changes. The screen half alternates with the display flip.
776 std::uint32_t screenDrawOffset = 0;
777 const GuRenderTarget* appliedTarget = nullptr;
778 bool appliedTargetValid = false;
779 // The scissor rect last programmed, in raster pixels of the current target
780 std::int32_t appliedScissor[4] = { -1, -1, -1, -1 };
781 }
782
783 // ------------------------------------------------------------------ session
784
785 void GuDevice::InitializeGu()
786 {
787 if (_guInitialized) {
788 return;
789 }
790
791 sceGuInit();
792
793 sceGuStart(GU_DIRECT, displayList);
794 // Draw into the first framebuffer while the second is being scanned out; the depth buffer follows
795 // them. RGB565 is chosen over RGBA8888 because the game's 2D output needs no destination alpha and
796 // the panel cannot show more, so the wider format would only double the fill bandwidth.
797 sceGuDrawBuffer(GU_PSM_5650, VramOffset(0), ScreenStride);
798 sceGuDispBuffer(ScreenWidth, ScreenHeight, VramOffset(FramebufferBytes), ScreenStride);
799 sceGuDepthBuffer(VramOffset(FramebufferBytes * 2), ScreenStride);
800
801 // The GE rasterizes in a 4096x4096 space whose centre is the screen centre, which is what the
802 // 2048-based offset/viewport pair expresses. Depth runs backwards on this hardware (near = 65535).
803 // Neither applies to the GU_TRANSFORM_2D primitives this backend submits - through mode goes
804 // straight to the rasterizer - but the clear path and any future transformed draw rely on them.
805 sceGuOffset(2048 - (ScreenWidth / 2), 2048 - (ScreenHeight / 2));
806 sceGuViewport(2048, 2048, ScreenWidth, ScreenHeight);
807 sceGuDepthRange(65535, 0);
808
809 sceGuScissor(0, 0, ScreenWidth, ScreenHeight);
810 sceGuEnable(GU_SCISSOR_TEST);
811 // The game draws 2D in painter's order, so there is nothing for the depth test to arbitrate
812 sceGuDepthMask(GU_TRUE);
813 sceGuDisable(GU_DEPTH_TEST);
814 sceGuDisable(GU_CULL_FACE);
815 sceGuShadeModel(GU_SMOOTH);
816 sceGuEnable(GU_BLEND);
817 sceGuBlendFunc(GU_ADD, GU_SRC_ALPHA, GU_ONE_MINUS_SRC_ALPHA, 0, 0);
818 sceGuFinish();
819 sceGuSync(GU_SYNC_FINISH, GU_SYNC_WHAT_DONE);
820
821 sceDisplayWaitVblankStart();
822 sceGuDisplay(GU_TRUE);
823
824 // The display list and the vertex arena are ordinary .bss, so the loader's zero fill may still sit
825 // in the data cache; the GE would read whatever is behind it. One writeback settles that for good.
826 sceKernelDcacheWritebackInvalidateAll();
827
828 _guInitialized = true;
829 LOGI("GU session initialized: {}x{} RGB565 (stride {}), {} KB display list, {} KB vertex arena",
830 ScreenWidth, ScreenHeight, ScreenStride, sizeof(displayList) / 1024, FrameArenaBytes / 1024);
831 }
832
833 void GuDevice::ShutdownGu()
834 {
835 if (!_guInitialized) {
836 return;
837 }
838 if (_listOpen) {
839 FlushBatch();
840 sceGuFinish();
841 sceGuSync(GU_SYNC_FINISH, GU_SYNC_WHAT_DONE);
842 _listOpen = false;
843 }
844 sceGuDisplay(GU_FALSE);
845 sceGuTerm();
846 _guInitialized = false;
847 }
848
849 void GuDevice::EnsureList()
850 {
851 if (!_guInitialized || _listOpen) {
852 return;
853 }
854 sceGuStart(GU_DIRECT, displayList);
855 _listOpen = true;
856 // A fresh list re-sends the draw buffer of the context, and nothing else about the previous frame's
857 // state can be relied upon, so everything is reissued once
858 appliedStateValid = false;
859 appliedTargetValid = false;
860 appliedScissor[0] = -1;
861 }
862
863 void GuDevice::ApplyDrawTarget()
864 {
865 if (appliedTargetValid && appliedTarget == _currentRenderTarget) {
866 return;
867 }
868 FlushBatch();
869
870 if (_currentRenderTarget != nullptr) {
871 GuTexture* texture = _currentRenderTarget->GetColorTexture(0);
872 void* surface = (texture != nullptr ? texture->GetRenderTargetSurface() : nullptr);
873 if (surface == nullptr) {
874 // No surface to render into; the draws will be skipped by their own checks
875 return;
876 }
877 // Only the draw buffer and the scissor matter: through-mode primitives bypass the viewport and
878 // the coordinate offset entirely, so neither has to be reprogrammed for a target
879 sceGuDrawBufferList(GU_PSM_5650, surface, texture->GetRenderTargetStride());
880 } else {
881 sceGuDrawBufferList(GU_PSM_5650, VramOffset(screenDrawOffset), ScreenStride);
882 }
883 appliedTarget = _currentRenderTarget;
884 appliedTargetValid = true;
885 // The rect is expressed in the target's raster space, so it has to be reprogrammed as well
886 appliedScissor[0] = -1;
887 }
888
889 void GuDevice::ApplyScissor()
890 {
891 std::int32_t x = 0, y = 0, w = ScreenWidth, h = ScreenHeight;
892 std::int32_t targetW = ScreenWidth, targetH = ScreenHeight;
893 if (_currentRenderTarget != nullptr) {
894 const GuTexture* texture = _currentRenderTarget->GetColorTexture(0);
895 targetW = (texture != nullptr ? texture->GetWidth() : ScreenWidth);
896 targetH = (texture != nullptr ? texture->GetHeight() : ScreenHeight);
897 w = targetW;
898 h = targetH;
899 }
900 if (_scissor.Enabled) {
901 float scaleX, scaleY;
902 GetTargetScale(scaleX, scaleY);
903 // The engine hands scissor rectangles in top-down logical coordinates. A screen pass maps them
904 // straight onto raster rows (it mirrors NDC, see Dispatch); a render-to-texture pass keeps the
905 // unmirrored top-down store, so its rect is flipped - the same split the GX device makes. A
906 // target renders 1:1, so its logical height IS its raster height.
907 const std::int32_t rasterY = (_currentRenderTarget == nullptr
908 ? _scissor.Rect.Y : targetH - _scissor.Rect.Y - _scissor.Rect.H);
909 x = std::int32_t(float(_scissor.Rect.X) * scaleX);
910 y = std::int32_t(float(rasterY) * scaleY);
911 w = std::int32_t(float(_scissor.Rect.W) * scaleX);
912 h = std::int32_t(float(_scissor.Rect.H) * scaleY);
913 // The GE takes the rect unclamped and a negative origin would wrap, so it is clipped to the
914 // surface here
915 if (x < 0) { w += x; x = 0; }
916 if (y < 0) { h += y; y = 0; }
917 if (x + w > targetW) { w = targetW - x; }
918 if (y + h > targetH) { h = targetH - y; }
919 if (w < 0) { w = 0; }
920 if (h < 0) { h = 0; }
921 }
922 if (appliedScissor[0] == x && appliedScissor[1] == y && appliedScissor[2] == w && appliedScissor[3] == h) {
923 return;
924 }
925 FlushBatch();
926 sceGuScissor(x, y, w, h);
927 appliedScissor[0] = x;
928 appliedScissor[1] = y;
929 appliedScissor[2] = w;
930 appliedScissor[3] = h;
931 }
932
933 void GuDevice::GetTargetScale(float& scaleX, float& scaleY)
934 {
935 if (_currentRenderTarget != nullptr) {
936 // Render-to-texture passes render 1:1 into the target surface
937 scaleX = 1.0f;
938 scaleY = 1.0f;
939 } else {
940 scaleX = (_logicalWidth > 0 ? float(ScreenWidth) / float(_logicalWidth) : 1.0f);
941 scaleY = (_logicalHeight > 0 ? float(ScreenHeight) / float(_logicalHeight) : 1.0f);
942 }
943 }
944
945 void GuDevice::PresentFrame()
946 {
947 if (!_guInitialized) {
948 return;
949 }
950 if (!_listOpen) {
951 // Nothing was drawn this frame; still run a list that clears, so the display keeps its pacing
952 // and a frame that produced no geometry does not show the previous one's contents
953 EnsureList();
954 ApplyDrawTarget();
955 const std::uint32_t abgr = PackAbgr(QuantizeChannel(_clearColor.R), QuantizeChannel(_clearColor.G),
956 QuantizeChannel(_clearColor.B), QuantizeChannel(_clearColor.A));
957 sceGuClearColor(abgr);
958 sceGuClear(GU_COLOR_BUFFER_BIT | GU_DEPTH_BUFFER_BIT | GU_FAST_CLEAR_BIT);
959 } else {
960 FlushBatch();
961 }
962
963 sceGuFinish();
964 // Waits for the GE to finish the list, which is also what makes the frame arena reusable below
965 sceGuSync(GU_SYNC_FINISH, GU_SYNC_WHAT_DONE);
966 _listOpen = false;
967
968 if (TraceDrawStatistics) {
969 // Once a second at 60 Hz, so the trace stays readable while the game runs
970 if ((_sceneCounter % 60) == 0) {
971 LOGI("Frame {}: {} GE draw calls, {} vertices, {} KB of the vertex arena, {} skipped draws",
972 _sceneCounter, frameDrawCalls, frameVertices, frameArenaUsed / 1024, frameSkippedDraws);
973 }
974 }
975
976 sceDisplayWaitVblankStart();
977 sceGuSwapBuffers();
978 // sceGuSwapBuffers() trades the draw and display halves, which this mirrors so ApplyDrawTarget()
979 // can point the GE back at the right one after a render-target pass
980 screenDrawOffset = (screenDrawOffset == 0 ? FramebufferBytes : 0);
981 appliedTargetValid = false;
982 _sceneCounter++;
983
984 // The GE is idle, so the frame's vertices, CLUT copies and generated textures can be overwritten
985 frameArenaUsed = 0;
986 clutCacheCount = 0;
987 frameDrawCalls = 0;
988 frameVertices = 0;
989 frameSkippedDraws = 0;
990 }
991
992 void GuDevice::ResizeScreenFramebuffer(std::int32_t width, std::int32_t height)
993 {
994 if (width > 0 && height > 0) {
995 _logicalWidth = width;
996 _logicalHeight = height;
997 }
998 }
999
1000 // ------------------------------------------------------------------ video memory
1001
1002 void* GuDevice::AllocateVram(std::size_t size)
1003 {
1004 if (size == 0 || vramUsedCount >= MaxVramSpans) {
1005 return nullptr;
1006 }
1007 const std::uint32_t wanted = std::uint32_t((size + 15) & ~std::size_t(15));
1008 for (std::int32_t i = 0; i < vramFreeCount; i++) {
1009 if (vramFree[i].Size < wanted) {
1010 continue;
1011 }
1012 const std::uint32_t offset = vramFree[i].Offset;
1013 vramFree[i].Offset += wanted;
1014 vramFree[i].Size -= wanted;
1015 if (vramFree[i].Size == 0) {
1016 vramFree[i] = vramFree[--vramFreeCount];
1017 }
1018 vramUsed[vramUsedCount++] = { offset, wanted };
1019 return VramOffset(offset);
1020 }
1021 return nullptr;
1022 }
1023
1024 void GuDevice::FreeVram(void* ptr)
1025 {
1026 const std::uint32_t offset = std::uint32_t(reinterpret_cast<std::uintptr_t>(ptr));
1027 for (std::int32_t i = 0; i < vramUsedCount; i++) {
1028 if (vramUsed[i].Offset != offset) {
1029 continue;
1030 }
1031 std::uint32_t size = vramUsed[i].Size;
1032 vramUsed[i] = vramUsed[--vramUsedCount];
1033 // Merge into any span the block is adjacent to, so repeated create/destroy cycles of a target
1034 // cannot fragment the heap
1035 for (std::int32_t j = 0; j < vramFreeCount; j++) {
1036 if (vramFree[j].Offset + vramFree[j].Size == offset) {
1037 vramFree[j].Size += size;
1038 return;
1039 }
1040 if (offset + size == vramFree[j].Offset) {
1041 vramFree[j].Offset = offset;
1042 vramFree[j].Size += size;
1043 return;
1044 }
1045 }
1046 if (vramFreeCount < MaxVramSpans) {
1047 vramFree[vramFreeCount++] = { offset, size };
1048 }
1049 return;
1050 }
1051 }
1052
1053 // ------------------------------------------------------------------ state
1054
1055 void GuDevice::SetBlendingEnabled(bool enabled) { _blending.Enabled = enabled; }
1056 void GuDevice::SetBlendingFactors(nCine::BlendingFactor srcRgb, nCine::BlendingFactor dstRgb, nCine::BlendingFactor srcAlpha, nCine::BlendingFactor dstAlpha)
1057 {
1058 _blending.SrcRgb = srcRgb;
1059 _blending.DstRgb = dstRgb;
1060 _blending.SrcAlpha = srcAlpha;
1061 _blending.DstAlpha = dstAlpha;
1062 }
1063 GuDevice::BlendingState GuDevice::GetBlendingState() { return _blending; }
1064 void GuDevice::SetBlendingState(const BlendingState& state) { _blending = state; }
1065
1066 void GuDevice::SetDepthTestEnabled(bool enabled) { _depthTest.TestEnabled = enabled; }
1067 void GuDevice::SetDepthMaskEnabled(bool enabled) { _depthTest.MaskEnabled = enabled; }
1068 GuDevice::DepthTestState GuDevice::GetDepthTestState() { return _depthTest; }
1069 void GuDevice::SetDepthTestState(const DepthTestState& state) { _depthTest = state; }
1070
1071 void GuDevice::SetCullFaceEnabled(bool enabled) { _cullFace.Enabled = enabled; }
1072 GuDevice::CullFaceState GuDevice::GetCullFaceState() { return _cullFace; }
1073 void GuDevice::SetCullFaceState(const CullFaceState& state) { _cullFace = state; }
1074
1075 GuDevice::ScissorState GuDevice::GetScissorState() { return _scissor; }
1076 void GuDevice::SetScissorState(const ScissorState& state) { _scissor = state; }
1077 void GuDevice::SetScissor(const Recti& rect)
1078 {
1079 // Same contract as the GL device: setting a rect also enables the test (callers like RenderCommand
1080 // and Viewport rely on it and restore via SetScissorState afterwards)
1081 _scissor.Enabled = true;
1082 _scissor.Rect = rect;
1083 }
1084 void GuDevice::SetScissorTestEnabled(bool enabled) { _scissor.Enabled = enabled; }
1085
1086 Recti GuDevice::GetViewport() { return _viewport; }
1087 void GuDevice::SetViewport(const Recti& rect) { _viewport = rect; }
1088 void GuDevice::InitViewport(std::int32_t x, std::int32_t y, std::int32_t width, std::int32_t height)
1089 {
1090 _viewport = Recti(x, y, width, height);
1091 }
1092
1093 Colorf GuDevice::GetClearColor() { return _clearColor; }
1094 void GuDevice::SetClearColor(const Colorf& color) { _clearColor = color; }
1095
1096 void GuDevice::Clear(ClearFlags flags)
1097 {
1098 if (!_guInitialized) {
1099 return;
1100 }
1101 EnsureList();
1102 ApplyDrawTarget();
1103 // The clear is bounded by the scissor, exactly like glClear is by the scissor test
1104 ApplyScissor();
1105 // Whatever is still batched was submitted BEFORE this clear and has to reach the list first,
1106 // otherwise the clear would wipe it (a mid-frame clear is exactly what the render targets do)
1107 FlushBatch();
1108
1109 std::int32_t guFlags = GU_FAST_CLEAR_BIT;
1110 if ((flags & ClearFlags::Color) == ClearFlags::Color) {
1111 guFlags |= GU_COLOR_BUFFER_BIT;
1112 }
1113 // The depth buffer lives at a fixed video-memory offset sized for the display, so clearing it while
1114 // a render target of another size is bound would write outside it; depth is disabled anyway
1115 if ((flags & ClearFlags::Depth) == ClearFlags::Depth && _currentRenderTarget == nullptr) {
1116 guFlags |= GU_DEPTH_BUFFER_BIT;
1117 }
1118 if ((flags & ClearFlags::Stencil) == ClearFlags::Stencil && _currentRenderTarget == nullptr) {
1119 guFlags |= GU_STENCIL_BUFFER_BIT;
1120 }
1121
1122 const std::uint32_t abgr = PackAbgr(QuantizeChannel(_clearColor.R), QuantizeChannel(_clearColor.G),
1123 QuantizeChannel(_clearColor.B), QuantizeChannel(_clearColor.A));
1124 sceGuClearColor(abgr);
1125 sceGuClear(guFlags);
1126 // sceGuClear() draws its own sprite with its own vertex format and leaves the clear-mode register
1127 // touched, so nothing about the cached pipeline state survives it
1128 appliedStateValid = false;
1129 }
1130
1131 // ------------------------------------------------------------------ draw entry points
1132
1133 void GuDevice::DrawArrays(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices)
1134 {
1135 Dispatch(primitive, firstVertex, numVertices);
1136 }
1137 void GuDevice::DrawArraysInstanced(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices, std::int32_t numInstances)
1138 {
1139 static_cast<void>(numInstances);
1140 Dispatch(primitive, firstVertex, numVertices);
1141 }
1142 void GuDevice::DrawElements(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t baseVertex)
1143 {
1144 static_cast<void>(indexFormat);
1145 static_cast<void>(indexOffset);
1146 Dispatch(primitive, baseVertex, std::int32_t(numIndices));
1147 }
1148 void GuDevice::DrawElementsInstanced(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex)
1149 {
1150 static_cast<void>(indexFormat);
1151 static_cast<void>(indexOffset);
1152 static_cast<void>(numInstances);
1153 Dispatch(primitive, baseVertex, std::int32_t(numIndices));
1154 }
1155
1156 FenceHandle GuDevice::InsertFence()
1157 {
1158 return reinterpret_cast<FenceHandle>(std::uintptr_t(1));
1159 }
1160 void GuDevice::DeleteFence(FenceHandle& fence)
1161 {
1162 fence = nullptr;
1163 }
1164 bool GuDevice::ClientWaitFence(FenceHandle fence, std::uint64_t timeoutNs)
1165 {
1166 static_cast<void>(fence);
1167 static_cast<void>(timeoutNs);
1168 return true;
1169 }
1170
1171 void GuDevice::SetupInitialState()
1172 {
1173 _blending = BlendingState();
1174 _depthTest = DepthTestState();
1175 _cullFace = CullFaceState();
1176 _scissor = ScissorState();
1177 }
1178
1179 // ------------------------------------------------------------------ extensions
1180
1181 void GuDevice::BindProgram(GuShaderProgram* program) { _currentProgram = program; }
1182 GuShaderProgram* GuDevice::CurrentProgram() { return _currentProgram; }
1183
1184 void GuDevice::BindTexture(std::uint32_t unit, const GuTexture* texture)
1185 {
1186 if (unit < MaxTextureUnits) {
1187 _boundTextures[unit] = texture;
1188 }
1189 }
1190
1191 void GuDevice::UnbindTexture(const GuTexture* texture)
1192 {
1193 for (std::uint32_t i = 0; i < MaxTextureUnits; i++) {
1194 if (_boundTextures[i] == texture) {
1195 _boundTextures[i] = nullptr;
1196 }
1197 }
1198 if (_paletteTexture == texture) {
1199 _paletteTexture = nullptr;
1200 }
1201 // A destroyed texture's store must not stay referenced by an open batch. Anything already submitted
1202 // is safe: resources are only ever destroyed between frames (level loads, menu transitions), and
1203 // PresentFrame() has synced the previous frame's list by then.
1204 FlushBatch();
1205 if (appliedStateValid && appliedState.TextureData != nullptr) {
1206 appliedStateValid = false;
1207 }
1208 // Drop CLUT copies built from the destroyed palette so a stale pointer can never match
1209 for (std::int32_t i = 0; i < clutCacheCount; i++) {
1210 if (clutCache[i].Palette == texture) {
1211 clutCache[i].Palette = nullptr;
1212 }
1213 }
1214 }
1215
1216 const GuTexture* GuDevice::GetBoundTexture(std::uint32_t unit)
1217 {
1218 return (unit < MaxTextureUnits ? _boundTextures[unit] : nullptr);
1219 }
1220
1221 void GuDevice::BindUniformRange(std::uint32_t index, const std::uint8_t* data, std::uint32_t size)
1222 {
1223 if (index < MaxUniformBindings) {
1224 _boundUniformRanges[index].Data = data;
1225 _boundUniformRanges[index].Size = size;
1226 }
1227 }
1228
1229 void GuDevice::SetRenderTarget(GuRenderTarget* renderTarget)
1230 {
1231 // The draw path reacts lazily at the next draw or clear (ApplyDrawTarget), which is also where the
1232 // open batch is closed - it belongs to the previous surface
1233 _currentRenderTarget = renderTarget;
1234 }
1235
1236 void GuDevice::UnbindRenderTarget(const GuRenderTarget* renderTarget)
1237 {
1238 if (_currentRenderTarget == renderTarget) {
1239 _currentRenderTarget = nullptr;
1240 }
1241 if (appliedTarget == renderTarget) {
1242 FlushBatch();
1243 appliedTargetValid = false;
1244 appliedTarget = nullptr;
1245 }
1246 }
1247
1248 // ------------------------------------------------------------------ palette CLUTs
1249
1250 void GuDevice::RegisterPaletteTexture(GuTexture* texture)
1251 {
1252 _paletteTexture = texture;
1253 NotifyPaletteTextureChanged(texture, 0, texture != nullptr ? texture->GetHeight() : 0);
1254 }
1255
1256 void GuDevice::NotifyPaletteTextureChanged(GuTexture* texture, std::int32_t firstRow, std::int32_t rowCount)
1257 {
1258 if (texture != _paletteTexture) {
1259 return;
1260 }
1261 _paletteGeneration++;
1262 for (std::int32_t i = 0; i < clutCacheCount; i++) {
1263 if (clutCache[i].Palette == texture && clutCache[i].Offset >= (firstRow - 1) * 256 &&
1264 clutCache[i].Offset < (firstRow + rowCount) * 256) {
1265 clutCache[i].Palette = nullptr;
1266 }
1267 }
1268 }
1269
1270 namespace
1271 {
1272 /**
1273 @brief Returns the frame's CLUT copy of one palette row, loading it into the frame arena if needed
1274
1275 The offset is a flat index into the palette texture and does not need to be row-aligned (the gem
1276 gradients pack two palettes into a single 256-entry row). Keyed exactly like the PowerVR's palette
1277 banks, so every draw of a row after the first one costs a pointer comparison.
1278 */
1279 const std::uint32_t* AcquireClutForRow(const GuTexture* palette, std::int32_t paletteOffset,
1280 std::uint32_t version)
1281 {
1282 const std::int32_t maxOffset = (palette != nullptr
1283 ? palette->GetWidth() * palette->GetHeight() - 256 : 0);
1284 if (palette == nullptr || palette->GetPixels() == nullptr ||
1285 paletteOffset < 0 || paletteOffset > maxOffset) {
1286 return nullptr;
1287 }
1288
1289 for (std::int32_t i = 0; i < clutCacheCount; i++) {
1290 if (clutCache[i].Palette == palette && clutCache[i].Offset == paletteOffset &&
1291 clutCache[i].Version == version) {
1292 return clutCache[i].Data;
1293 }
1294 }
1295
1296 // The GE reads the table when it executes the load command, which is behind the CPU, so every
1297 // distinct row of the frame needs its own copy rather than one shared scratch buffer
1298 std::uint32_t* data = static_cast<std::uint32_t*>(AllocFrameData(256 * sizeof(std::uint32_t), 16));
1299 if (data == nullptr) {
1300 return nullptr;
1301 }
1302 // A palette entry is an RGBA8 value with red in the lowest byte, which is byte for byte what
1303 // GU_PSM_8888 expects - unlike the PowerVR and the GX, no channel reordering is needed
1304 std::memcpy(data, reinterpret_cast<const std::uint32_t*>(palette->GetPixels()) + paletteOffset,
1305 256 * sizeof(std::uint32_t));
1306 sceKernelDcacheWritebackRange(data, 256 * sizeof(std::uint32_t));
1307
1308 if (clutCacheCount < MaxClutCacheEntries) {
1309 clutCache[clutCacheCount++] = { palette, paletteOffset, version, data };
1310 }
1311 return data;
1312 }
1313
1314 /** @brief Points the draw state at one page of a texture */
1315 void ApplyPageToState(DrawState& state, const GuTexture* texture, const GuTexture::Page& page)
1316 {
1317 state.TextureData = page.Data;
1318 state.TexturePsm = texture->GetGuPixelFormat();
1319 state.TextureWidth = page.PaddedWidth;
1320 state.TextureHeight = page.PaddedHeight;
1321 state.TextureStride = page.PaddedWidth;
1322 state.TextureSwizzled = page.Swizzled;
1323 }
1324
1325 /**
1326 @brief Resolves the texture state of one draw: the page a texture rectangle samples, and its CLUT
1327
1328 @p texRect is the instance's (uSpan, uOffset, vSpan, vOffset). Through-mode texture coordinates
1329 are texel indices, so the returned scale is simply the source size and the bias is the page
1330 origin - a single-page texture (everything up to 512x512) biases by zero.
1331 */
1332 bool ResolveTextureState(DrawState& state, GuTexture* texture, const float* texRect,
1333 float& uvScaleU, float& uvScaleV, float& uvBiasU, float& uvBiasV)
1334 {
1335 const float u0 = texRect[1] * float(texture->GetWidth());
1336 const float u1 = (texRect[1] + texRect[0]) * float(texture->GetWidth());
1337 const float v0 = texRect[3] * float(texture->GetHeight());
1338 const float v1 = (texRect[3] + texRect[2]) * float(texture->GetHeight());
1339 const GuTexture::Page* page = texture->AcquirePage(std::int32_t(std::min(u0, u1)),
1340 std::int32_t(std::min(v0, v1)));
1341 if (page == nullptr || page->Data == nullptr) {
1342 return false;
1343 }
1344 if (texture->GetPageCountX() > 1 || texture->GetPageCountY() > 1) {
1345 // A primitive samples one frame rect of an atlas, so it practically never straddles a page
1346 // boundary; when it does, the containing page is used and the overhang is clamped by the
1347 // hardware, which is a visibly wrong edge rather than a missing sprite
1348 const float maxU = std::max(u0, u1), maxV = std::max(v0, v1);
1349 if (maxU > float(page->OriginX + page->Width) + 0.5f ||
1350 maxV > float(page->OriginY + page->Height) + 0.5f) {
1351 static bool warnedStraddle = false;
1352 if (!warnedStraddle) {
1353 warnedStraddle = true;
1354 LOGW("A primitive samples across a GE texture page boundary; its edge will be clamped");
1355 }
1356 }
1357 }
1358
1359 ApplyPageToState(state, texture, *page);
1360 state.Filter = (texture->GetMagFilter() == nCine::SamplerFilter::Linear ? GU_LINEAR : GU_NEAREST);
1361 state.WrapU = MapWrapGu(texture->GetWrapS());
1362 state.WrapV = MapWrapGu(texture->GetWrapT());
1363 uvScaleU = float(texture->GetWidth());
1364 uvScaleV = float(texture->GetHeight());
1365 uvBiasU = float(page->OriginX);
1366 uvBiasV = float(page->OriginY);
1367 return true;
1368 }
1369 }
1370
1371 // ------------------------------------------------------------------ lighting hook
1372
1373 void GuDevice::SetPendingSoftwareLighting(const float* lightmap, std::int32_t lmW, std::int32_t lmH, std::int32_t scale,
1374 std::int32_t vpX, std::int32_t vpY, std::int32_t vpW, std::int32_t vpH, float ambR, float ambG, float ambB,
1375 bool waterActive, float waterLevelPx, float waterTime, float waterCamY)
1376 {
1377 PendingSoftwareLight light;
1378 light.Lightmap = lightmap;
1379 light.LmW = lmW;
1380 light.LmH = lmH;
1381 light.Scale = (scale > 0 ? scale : 1);
1382 light.VpX = vpX;
1383 light.VpY = vpY;
1384 light.VpW = vpW;
1385 light.VpH = vpH;
1386 light.AmbR = ambR;
1387 light.AmbG = ambG;
1388 light.AmbB = ambB;
1389 light.WaterActive = waterActive;
1390 light.WaterLevelPx = waterLevelPx;
1391 light.WaterTime = waterTime;
1392 light.WaterCamY = waterCamY;
1393 _pendingSoftwareLights.push_back(light);
1394 }
1395
1396 void GuDevice::EndFrame()
1397 {
1398 if (!_pendingSoftwareLights.empty()) {
1399 static bool warnedLeftoverLights = false;
1400 if (!warnedLeftoverLights) {
1401 warnedLeftoverLights = true;
1402 LOGW("Dropping {} unconsumed software-lighting entries", _pendingSoftwareLights.size());
1403 }
1404 _pendingSoftwareLights.clear();
1405 }
1406 }
1407
1408 void GuDevice::ApplyPendingSoftwareLighting()
1409 {
1410 if (_pendingSoftwareLights.empty()) {
1411 return;
1412 }
1413 const PendingSoftwareLight light = _pendingSoftwareLights.front();
1414 _pendingSoftwareLights.erase(_pendingSoftwareLights.begin());
1415
1416 const bool hasLighting = (light.Lightmap != nullptr && light.LmW > 0 && light.LmH > 0);
1417 const bool hasWater = light.WaterActive;
1418 if (!hasLighting && !hasWater) {
1419 return;
1420 }
1421
1422 EnsureList();
1423 ApplyDrawTarget();
1424 ApplyScissor();
1425
1426 float scaleX, scaleY;
1427 GetTargetScale(scaleX, scaleY);
1428 const float vpX = float(light.VpX) * scaleX, vpY = float(light.VpY) * scaleY;
1429 const float vpW = float(light.VpW) * scaleX, vpH = float(light.VpH) * scaleY;
1430
1431 if (hasLighting) {
1432 // Multiply factor from the CPU lightmap: out ~= scene * (r*(1+g) + amb*(1-r)) per channel (the
1433 // multiply-only approximation shared with the GX and PVR backends), as a 4444 texture drawn with
1434 // a dst * src blend over the viewport. The texture is generated into the frame arena, which is
1435 // exactly the lifetime it needs - the GE consumes it within this frame and it is gone at present.
1436 std::int32_t texW = 8, texH = 8;
1437 while (texW < light.LmW && texW < GuTexture::MaxPageDimension) texW <<= 1;
1438 while (texH < light.LmH && texH < GuTexture::MaxPageDimension) texH <<= 1;
1439 const std::size_t size = std::size_t(texW) * std::size_t(texH) * 2;
1440 std::uint16_t* const surface = static_cast<std::uint16_t*>(AllocFrameData(size, 16));
1441 if (surface != nullptr) {
1442 for (std::int32_t y = 0; y < light.LmH; y++) {
1443 const float* DEATH_RESTRICT src = light.Lightmap + std::size_t(y) * light.LmW * 2;
1444 std::uint16_t* DEATH_RESTRICT dst = surface + std::size_t(y) * texW;
1445 // Unlit runs repeat the same pair of factors across long spans, so remembering the last
1446 // converted texel turns most of the surface into a compare and a store
1447 float prevR = -1.0f, prevG = -1.0f;
1448 std::uint16_t prevTexel = 0;
1449 for (std::int32_t x = 0; x < light.LmW; x++) {
1450 const float rawR = src[x * 2];
1451 const float rawG = src[x * 2 + 1];
1452 if (rawR == prevR && rawG == prevG) {
1453 dst[x] = prevTexel;
1454 continue;
1455 }
1456 prevR = rawR;
1457 prevG = rawG;
1458 const float r = (rawR < 0.0f ? 0.0f : (rawR > 1.0f ? 1.0f : rawR));
1459 const float g = (rawG < 0.0f ? 0.0f : (rawG > 1.0f ? 1.0f : rawG));
1460 const float lit = r * (1.0f + g);
1461 const float inv = 1.0f - r;
1462 const std::uint32_t fr = Quantize4Bit(lit + light.AmbR * inv);
1463 const std::uint32_t fg = Quantize4Bit(lit + light.AmbG * inv);
1464 const std::uint32_t fb = Quantize4Bit(lit + light.AmbB * inv);
1465 prevTexel = std::uint16_t(0xF000 | (fb << 8) | (fg << 4) | fr);
1466 dst[x] = prevTexel;
1467 }
1468 // The padding columns are reached by the bilinear tap at the last texel
1469 for (std::int32_t x = light.LmW; x < texW; x++) {
1470 dst[x] = prevTexel;
1471 }
1472 }
1473 for (std::int32_t y = light.LmH; y < texH; y++) {
1474 std::memcpy(surface + std::size_t(y) * texW, surface + std::size_t(light.LmH - 1) * texW,
1475 std::size_t(texW) * 2);
1476 }
1477 sceKernelDcacheWritebackRange(surface, size);
1478
1479 DrawState state;
1480 state.TextureData = surface;
1481 state.TexturePsm = GU_PSM_4444;
1482 state.TextureWidth = texW;
1483 state.TextureHeight = texH;
1484 state.TextureStride = texW;
1485 state.TextureSwizzled = false;
1486 state.Filter = GU_LINEAR;
1487 state.Tfx = GU_TFX_MODULATE;
1488 state.Tcc = GU_TCC_RGB;
1489 // out = dst * src: the source factor is "the other side's colour", the destination factor zero
1490 state.BlendEnabled = true;
1491 state.BlendOp = GU_ADD;
1492 state.BlendSrc = GU_OTHER_COLOR;
1493 state.BlendDst = GU_FIX;
1494 state.BlendDstFix = 0x000000;
1495
1496 // The lightmap's row 0 corresponds to the bottom of the displayed viewport (the software
1497 // buffer convention), so V runs used -> 0 top -> bottom
1498 const float px[4] = { vpX + vpW, vpX + vpW, vpX, vpX };
1499 const float py[4] = { vpY, vpY + vpH, vpY, vpY + vpH };
1500 const float pu[4] = { float(light.LmW), float(light.LmW), 0.0f, 0.0f };
1501 const float pv[4] = { float(light.LmH), 0.0f, float(light.LmH), 0.0f };
1502 SubmitQuadPrimitive(state, px, py, pu, pv, PackAbgr(255, 255, 255, 255));
1503 }
1504 }
1505
1506 if (hasWater) {
1507 // Water v1: constant underwater tint band + above-deep-water darkening (shared with GX/PVR)
1508 DrawState state;
1509 state.BlendEnabled = true;
1510 state.BlendOp = GU_ADD;
1511 state.BlendSrc = GU_SRC_ALPHA;
1512 state.BlendDst = GU_ONE_MINUS_SRC_ALPHA;
1513
1514 const float waterTop = vpY + light.WaterLevelPx * scaleY;
1515 const float uv[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
1516 if (waterTop < vpY + vpH) {
1517 const float px[4] = { vpX + vpW, vpX + vpW, vpX, vpX };
1518 const float py[4] = { waterTop, vpY + vpH, waterTop, vpY + vpH };
1519 SubmitQuadPrimitive(state, px, py, uv, uv, PackAbgr(102, 153, 204, 102));
1520 }
1521 const float waterLevelNorm = (light.VpH > 0 ? light.WaterLevelPx / float(light.VpH) : 1.0f);
1522 if (waterLevelNorm < 0.4f && waterTop > vpY) {
1523 const std::uint8_t a = QuantizeChannel(0.4f - waterLevelNorm);
1524 const float px[4] = { vpX + vpW, vpX + vpW, vpX, vpX };
1525 const float py[4] = { vpY, waterTop, vpY, waterTop };
1526 SubmitQuadPrimitive(state, px, py, uv, uv,
1527 PackAbgr(QuantizeChannel(light.AmbR), QuantizeChannel(light.AmbG), QuantizeChannel(light.AmbB), a));
1528 }
1529 }
1530 }
1531
1532 // ------------------------------------------------------------------ draw dispatch
1533
1534 void GuDevice::DispatchTileMesh(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices)
1535 {
1536 // A tile-layer mesh is a plain triangle list of 8-float vertices (position.xy, texcoords.uv,
1537 // color.rgba) - the layout TileMap::AppendTileQuad() writes and TileMapVs.inc declares. It is a
1538 // hard contract of this shader family exactly like the std140 instance block is of the sprite one.
1539 constexpr std::int32_t FloatsPerVertex = 8;
1540 if (primitive != PrimitiveType::Triangles || numVertices < 3) {
1541 return;
1542 }
1543
1544 const GuBuffer* vbo = _currentProgram->GetBoundVbo();
1545 if (vbo == nullptr) {
1546 return;
1547 }
1548 const std::size_t firstFloat = (std::size_t(_currentProgram->GetBoundVboOffset()) / sizeof(float)) +
1549 std::size_t(firstVertex) * FloatsPerVertex;
1550 const std::size_t floatCount = std::size_t(numVertices) * FloatsPerVertex;
1551 if ((firstFloat + floatCount) * sizeof(float) > vbo->GetSize()) {
1552 return;
1553 }
1554 const float* DEATH_RESTRICT vertices = reinterpret_cast<const float*>(vbo->HostData()) + firstFloat;
1555
1556 const GuUniformBlock* block = _currentProgram->FindBlock("InstanceBlock");
1557 if (block == nullptr) {
1558 return;
1559 }
1560 std::int32_t binding = block->GetBindingIndex();
1561 if (binding < 0 || std::uint32_t(binding) >= MaxUniformBindings) {
1562 binding = 0;
1563 }
1564 const std::uint8_t* blockData = _boundUniformRanges[binding].Data;
1565 if (blockData == nullptr) {
1566 return;
1567 }
1568
1569 GuTexture* texture = const_cast<GuTexture*>(_boundTextures[0]);
1570 if (texture == nullptr) {
1571 return;
1572 }
1573
1574 const std::uint8_t* projBytes = _currentProgram->GetResolvedProjection();
1575 const std::uint8_t* viewBytes = _currentProgram->GetResolvedView();
1576 const float* projMat = (projBytes != nullptr ? reinterpret_cast<const float*>(projBytes) : IdentityMatrix);
1577 const float* viewMat = (viewBytes != nullptr ? reinterpret_cast<const float*>(viewBytes) : IdentityMatrix);
1578 float pv[16];
1579 Mat4Mul(projMat, viewMat, pv);
1580 Transform2D mvp;
1581 Mat4MulTransform2D(pv, reinterpret_cast<const float*>(blockData + kModelMatrixOffset), mvp);
1582
1583 // The layer tint modulates every vertex colour, which already carries the per-tile alpha
1584 float layerColor[4];
1585 std::memcpy(layerColor, blockData + kColorOffset, sizeof(layerColor));
1586
1587 // The palette to remap with is whatever the material bound to the palette sampler; the registered
1588 // global palette is the fallback (mirrors the sprite path). TileMapMeshPalette binds uTexturePalette
1589 // in its reflection, which is exactly what UsesPalette() reports.
1590 const bool isPaletteRemap = _currentProgram->UsesPalette();
1591 const GuTexture* paletteTex = nullptr;
1592 if (isPaletteRemap || texture->IsIndexed() || texture->NeedsPaletteBake()) {
1593 paletteTex = _boundTextures[1];
1594 if (paletteTex == nullptr || paletteTex == texture) {
1595 paletteTex = _paletteTexture;
1596 }
1597 }
1598
1599 // Unlike a sprite batch, the whole mesh shares one texture and one palette offset, so the residency,
1600 // the CLUT and the GE state are resolved once for the entire layer
1601 std::int32_t paletteOffset = 0;
1602 if (isPaletteRemap) {
1603 float palOffset = 0.0f;
1604 std::memcpy(&palOffset, blockData + kPaletteOffsetOffset, sizeof(palOffset));
1605 paletteOffset = std::int32_t(palOffset + 0.5f);
1606 }
1607 const std::uint32_t paletteVersion = (paletteTex == _paletteTexture
1608 ? _paletteGeneration : (paletteTex != nullptr ? paletteTex->GetContentVersion() : 0));
1609
1610 DrawState state;
1611 if (texture->NeedsPaletteBake()) {
1612 if (paletteTex == nullptr || paletteTex->GetPixels() == nullptr) {
1613 return;
1614 }
1615 const std::uint32_t* entries = reinterpret_cast<const std::uint32_t*>(paletteTex->GetPixels())
1616 + paletteOffset;
1617 if (!texture->EnsureBakedStore(entries, std::uint32_t(paletteOffset), paletteVersion, paletteTex)) {
1618 return;
1619 }
1620 } else if (texture->IsIndexed()) {
1621 state.Clut = AcquireClutForRow(paletteTex, paletteOffset, paletteVersion);
1622 if (state.Clut == nullptr) {
1623 return;
1624 }
1625 }
1626
1627 const float texRect[4] = { 1.0f, 0.0f, 1.0f, 0.0f };
1628 float uvScaleU = 1.0f, uvScaleV = 1.0f, uvBiasU = 0.0f, uvBiasV = 0.0f;
1629 if (!ResolveTextureState(state, texture, texRect, uvScaleU, uvScaleV, uvBiasU, uvBiasV)) {
1630 return;
1631 }
1632 std::uint32_t srcFix = 0, dstFix = 0;
1633 state.BlendEnabled = _blending.Enabled;
1634 state.BlendOp = GU_ADD;
1635 state.BlendSrc = MapBlendGu(_blending.SrcRgb, srcFix);
1636 state.BlendDst = MapBlendGu(_blending.DstRgb, dstFix);
1637 state.BlendSrcFix = srcFix;
1638 state.BlendDstFix = dstFix;
1639
1640 EnsureList();
1641 ApplyDrawTarget();
1642 ApplyScissor();
1643
1644 const Recti viewport = (_viewport.W > 0 && _viewport.H > 0)
1645 ? _viewport : Recti(0, 0, _logicalWidth, _logicalHeight);
1646 float scaleX, scaleY;
1647 GetTargetScale(scaleX, scaleY);
1648 const bool screenPass = (_currentRenderTarget == nullptr);
1649
1650 // The NDC-to-raster mapping is affine and constant for the whole mesh, so it is folded into the
1651 // transform once instead of being reapplied per vertex. A screen pass mirrors NDC, which is just the
1652 // sign of the Y scale.
1653 const float rasterScaleX = 0.5f * float(viewport.W) * scaleX;
1654 const float rasterBiasX = rasterScaleX + float(viewport.X) * scaleX;
1655 const float rasterScaleY = 0.5f * float(viewport.H) * scaleY * (screenPass ? 1.0f : -1.0f);
1656 const float rasterBiasY = 0.5f * float(viewport.H) * scaleY + float(viewport.Y) * scaleY;
1657 const Transform2D raster = {
1658 mvp.Xx * rasterScaleX, mvp.Xy * rasterScaleY,
1659 mvp.Yx * rasterScaleX, mvp.Yy * rasterScaleY,
1660 mvp.Tx * rasterScaleX + rasterBiasX, mvp.Ty * rasterScaleY + rasterBiasY
1661 };
1662
1663 // A tileset atlas wider or taller than one GE page is split into several, and different tiles of the
1664 // same layer then live in different pages - so the page is chosen per primitive rather than once for
1665 // the mesh. Single-page atlases (the common case: a 10-tile-wide sheet is a 340 px atlas) skip all of
1666 // this and keep one state for the whole layer.
1667 const bool pagedTexture = (texture->GetPageCountX() > 1 || texture->GetPageCountY() > 1);
1668 auto project = [&](const float* v, float& outX, float& outY, float& outU, float& outV) {
1669 outX = raster.Xx * v[0] + raster.Yx * v[1] + raster.Tx;
1670 outY = raster.Xy * v[0] + raster.Yy * v[1] + raster.Ty;
1671 outU = v[2] * uvScaleU - uvBiasU;
1672 outV = v[3] * uvScaleV - uvBiasV;
1673 };
1674 // Repoints the state at the page a primitive's texture coordinates fall into and rebases them onto it
1675 auto selectPage = [&](DrawState& target, float* pu, float* pvv, std::int32_t count) {
1676 float minU = pu[0], minV = pvv[0];
1677 for (std::int32_t i = 1; i < count; i++) {
1678 minU = std::min(minU, pu[i]);
1679 minV = std::min(minV, pvv[i]);
1680 }
1681 const GuTexture::Page* page = texture->AcquirePage(std::int32_t(minU), std::int32_t(minV));
1682 if (page == nullptr || page->Data == nullptr) {
1683 return false;
1684 }
1685 ApplyPageToState(target, texture, *page);
1686 for (std::int32_t i = 0; i < count; i++) {
1687 pu[i] -= float(page->OriginX);
1688 pvv[i] -= float(page->OriginY);
1689 }
1690 return true;
1691 };
1692
1693 const std::int32_t triangleCount = numVertices / 3;
1694 std::int32_t triangle = 0;
1695 // Virtually every tile of a layer carries the same colour (white at the layer's alpha), so the four
1696 // clamp+float-to-int quantizations run once per change instead of once per tile
1697 float lastColor[4] = { -1.0f, -1.0f, -1.0f, -1.0f };
1698 std::uint32_t lastAbgr = 0;
1699 while (triangle < triangleCount) {
1700 // Tiles reach here as the six vertices of two triangles, of which the third and fourth repeat the
1701 // first and third. Recognizing that pattern lets a tile go out as one quad - and, since tile
1702 // quads are axis-aligned, as a two-vertex GE rectangle rather than six triangle vertices.
1703 const float* group = vertices + std::size_t(triangle) * 3 * FloatsPerVertex;
1704 const bool isQuad = (triangle + 2 <= triangleCount &&
1705 group[3 * FloatsPerVertex + 0] == group[0] && group[3 * FloatsPerVertex + 1] == group[1] &&
1706 group[4 * FloatsPerVertex + 0] == group[2 * FloatsPerVertex + 0] &&
1707 group[4 * FloatsPerVertex + 1] == group[2 * FloatsPerVertex + 1]);
1708
1709 float px[4], py[4], pu[4], pvv[4];
1710 if (group[4] != lastColor[0] || group[5] != lastColor[1] || group[6] != lastColor[2] || group[7] != lastColor[3]) {
1711 lastColor[0] = group[4]; lastColor[1] = group[5]; lastColor[2] = group[6]; lastColor[3] = group[7];
1712 lastAbgr = PackAbgr(QuantizeChannel(group[4] * layerColor[0]),
1713 QuantizeChannel(group[5] * layerColor[1]), QuantizeChannel(group[6] * layerColor[2]),
1714 QuantizeChannel(group[7] * layerColor[3]));
1715 }
1716
1717 if (isQuad) {
1718 // Corner order of the sprite strip (v0, v1, v2, v3): vertices 1, 2, 0 and 5 of the tile's six
1719 static const std::int32_t QuadOrder[4] = { 1, 2, 0, 5 };
1720 for (std::int32_t i = 0; i < 4; i++) {
1721 project(group + std::size_t(QuadOrder[i]) * FloatsPerVertex, px[i], py[i], pu[i], pvv[i]);
1722 }
1723 DrawState quadState = state;
1724 if (!pagedTexture || selectPage(quadState, pu, pvv, 4)) {
1725 SubmitQuadPrimitive(quadState, px, py, pu, pvv, lastAbgr);
1726 }
1727 triangle += 2;
1728 } else {
1729 for (std::int32_t i = 0; i < 3; i++) {
1730 project(group + std::size_t(i) * FloatsPerVertex, px[i], py[i], pu[i], pvv[i]);
1731 }
1732 DrawState triState = state;
1733 triState.Prim = GU_TRIANGLES;
1734 if (!pagedTexture || selectPage(triState, pu, pvv, 3)) {
1735 Vertex2D* v = AllocVertices(triState, 3);
1736 if (v == nullptr) {
1737 return;
1738 }
1739 for (std::int32_t i = 0; i < 3; i++) {
1740 v[i] = { pu[i], pvv[i], lastAbgr, px[i], py[i], 0.0f };
1741 }
1742 }
1743 triangle++;
1744 }
1745 }
1746 }
1747
1748 void GuDevice::DispatchLineStrip(std::int32_t firstVertex, std::int32_t numVertices)
1749 {
1750 // The weapon wheel arrives as a textured line strip of 4-float vertices (position.xy, texcoords.uv)
1751 // - the layout the MeshSprite shader's attributes declare. The GE has a native single-pixel line
1752 // primitive, so unlike the PowerVR (which expands every segment into a thin quad) the strip goes out
1753 // as it is, in one draw call.
1754 constexpr std::int32_t FloatsPerVertex = 4;
1755 if (numVertices < 2) {
1756 return;
1757 }
1758
1759 const GuBuffer* vbo = _currentProgram->GetBoundVbo();
1760 if (vbo == nullptr) {
1761 return;
1762 }
1763 const std::size_t firstFloat = (std::size_t(_currentProgram->GetBoundVboOffset()) / sizeof(float)) +
1764 std::size_t(firstVertex) * FloatsPerVertex;
1765 const std::size_t floatCount = std::size_t(numVertices) * FloatsPerVertex;
1766 if ((firstFloat + floatCount) * sizeof(float) > vbo->GetSize()) {
1767 return;
1768 }
1769 const float* DEATH_RESTRICT vertices = reinterpret_cast<const float*>(vbo->HostData()) + firstFloat;
1770
1771 const GuUniformBlock* block = _currentProgram->FindBlock("InstanceBlock");
1772 if (block == nullptr) {
1773 return;
1774 }
1775 std::int32_t binding = block->GetBindingIndex();
1776 if (binding < 0 || std::uint32_t(binding) >= MaxUniformBindings) {
1777 binding = 0;
1778 }
1779 const std::uint8_t* blockData = _boundUniformRanges[binding].Data;
1780 if (blockData == nullptr) {
1781 return;
1782 }
1783
1784 GuTexture* texture = const_cast<GuTexture*>(_boundTextures[0]);
1785 if (texture == nullptr) {
1786 return;
1787 }
1788
1789 const std::uint8_t* projBytes = _currentProgram->GetResolvedProjection();
1790 const std::uint8_t* viewBytes = _currentProgram->GetResolvedView();
1791 const float* projMat = (projBytes != nullptr ? reinterpret_cast<const float*>(projBytes) : IdentityMatrix);
1792 const float* viewMat = (viewBytes != nullptr ? reinterpret_cast<const float*>(viewBytes) : IdentityMatrix);
1793 float pvMat[16];
1794 Mat4Mul(projMat, viewMat, pvMat);
1795 Transform2D mvp;
1796 Mat4MulTransform2D(pvMat, reinterpret_cast<const float*>(blockData + kModelMatrixOffset), mvp);
1797
1798 // Every vertex of the strip carries the instance colour, so it is packed once
1799 float color[4];
1800 std::memcpy(color, blockData + kColorOffset, sizeof(color));
1801 const std::uint32_t abgr = PackAbgr(QuantizeChannel(color[0]), QuantizeChannel(color[1]),
1802 QuantizeChannel(color[2]), QuantizeChannel(color[3]));
1803
1804 DrawState state;
1805 const std::uint32_t paletteVersion = _paletteGeneration;
1806 if (texture->NeedsPaletteBake()) {
1807 const GuTexture* paletteTex = _boundTextures[1];
1808 if (paletteTex == nullptr || paletteTex == texture) {
1809 paletteTex = _paletteTexture;
1810 }
1811 if (paletteTex == nullptr || paletteTex->GetPixels() == nullptr ||
1812 !texture->EnsureBakedStore(reinterpret_cast<const std::uint32_t*>(paletteTex->GetPixels()), 0,
1813 paletteVersion, paletteTex)) {
1814 return;
1815 }
1816 } else if (texture->IsIndexed()) {
1817 const GuTexture* paletteTex = _boundTextures[1];
1818 if (paletteTex == nullptr || paletteTex == texture) {
1819 paletteTex = _paletteTexture;
1820 }
1821 state.Clut = AcquireClutForRow(paletteTex, 0, paletteVersion);
1822 if (state.Clut == nullptr) {
1823 return;
1824 }
1825 }
1826
1827 const float texRect[4] = { 1.0f, 0.0f, 1.0f, 0.0f };
1828 float uvScaleU = 1.0f, uvScaleV = 1.0f, uvBiasU = 0.0f, uvBiasV = 0.0f;
1829 if (!ResolveTextureState(state, texture, texRect, uvScaleU, uvScaleV, uvBiasU, uvBiasV)) {
1830 return;
1831 }
1832 std::uint32_t srcFix = 0, dstFix = 0;
1833 state.BlendEnabled = _blending.Enabled;
1834 state.BlendOp = GU_ADD;
1835 state.BlendSrc = MapBlendGu(_blending.SrcRgb, srcFix);
1836 state.BlendDst = MapBlendGu(_blending.DstRgb, dstFix);
1837 state.BlendSrcFix = srcFix;
1838 state.BlendDstFix = dstFix;
1839 state.Prim = GU_LINE_STRIP;
1840
1841 EnsureList();
1842 ApplyDrawTarget();
1843 ApplyScissor();
1844
1845 const Recti viewport = (_viewport.W > 0 && _viewport.H > 0)
1846 ? _viewport : Recti(0, 0, _logicalWidth, _logicalHeight);
1847 float scaleX, scaleY;
1848 GetTargetScale(scaleX, scaleY);
1849 const bool screenPass = (_currentRenderTarget == nullptr);
1850
1851 const float rasterScaleX = 0.5f * float(viewport.W) * scaleX;
1852 const float rasterBiasX = rasterScaleX + float(viewport.X) * scaleX;
1853 const float rasterScaleY = 0.5f * float(viewport.H) * scaleY * (screenPass ? 1.0f : -1.0f);
1854 const float rasterBiasY = 0.5f * float(viewport.H) * scaleY + float(viewport.Y) * scaleY;
1855 const Transform2D raster = {
1856 mvp.Xx * rasterScaleX, mvp.Xy * rasterScaleY,
1857 mvp.Yx * rasterScaleX, mvp.Yy * rasterScaleY,
1858 mvp.Tx * rasterScaleX + rasterBiasX, mvp.Ty * rasterScaleY + rasterBiasY
1859 };
1860
1861 // A line strip is one primitive, so it gets its own draw call
1862 FlushBatch();
1863 Vertex2D* v = AllocVertices(state, numVertices);
1864 if (v == nullptr) {
1865 return;
1866 }
1867 for (std::int32_t i = 0; i < numVertices; i++) {
1868 const float* src = vertices + std::size_t(i) * FloatsPerVertex;
1869 v[i].U = src[2] * uvScaleU - uvBiasU;
1870 v[i].V = src[3] * uvScaleV - uvBiasV;
1871 v[i].Color = abgr;
1872 v[i].X = raster.Xx * src[0] + raster.Yx * src[1] + raster.Tx;
1873 v[i].Y = raster.Xy * src[0] + raster.Yy * src[1] + raster.Ty;
1874 v[i].Z = 0.0f;
1875 }
1876 FlushBatch();
1877 }
1878
1879 void GuDevice::Dispatch(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices)
1880 {
1881 if (_currentProgram == nullptr || numVertices <= 0 || !_guInitialized) {
1882 return;
1883 }
1884
1885 // The program's whole console identity is its effect-table entry, resolved at load from the true
1886 // (program, variant) the loaders plumbed in - a program without an entry has no fixed_function block
1887 // in its .shader file (Lighting, Blur, the Resize* family, runtime-compiled shaders, ...) and keeps
1888 // the logged, skipped draw
1889 const FixedFunctionGeneratedEffect* generated = _currentProgram->GetGeneratedEffect();
1890 if (generated == nullptr) {
1891 frameSkippedDraws++;
1892 if (!_currentProgram->FetchUnsupportedWarned()) {
1893 LOGW("Skipping draws of program \"{}\": No fixed_function effect declared by the shader", _currentProgram->GetObjectLabel());
1894 }
1895 return;
1896 }
1897 const FixedFunctionIntrinsic intrinsic = generated->Intrinsic;
1898
1899 // The Combine draw is the direct-tier lighting hook (see the software backend)
1900 if (intrinsic == FixedFunctionIntrinsic::LightingCombine) {
1901 ApplyPendingSoftwareLighting();
1902 return;
1903 }
1904
1905 // A whole tile layer arrives as one mesh instead of one command per tile
1906 if (intrinsic == FixedFunctionIntrinsic::TileMapMesh) {
1907 DispatchTileMesh(primitive, firstVertex, numVertices);
1908 return;
1909 }
1910
1911 // The weapon wheel is the one vertex-fed mesh on this tier, a textured line strip
1912 if (intrinsic == FixedFunctionIntrinsic::LineStripMesh) {
1913 if (primitive == PrimitiveType::LineStrip) {
1914 DispatchLineStrip(firstVertex, numVertices);
1915 } else if (!_currentProgram->FetchUnsupportedWarned()) {
1916 LOGW("Skipping draws of program \"{}\": Only the line-strip form of the mesh pipeline is supported by the GU dispatch", _currentProgram->GetObjectLabel());
1917 }
1918 return;
1919 }
1920
1921 // Everything else is the procedural sprite-quad family
1922 const bool isQuadFamily = (generated->Fn != nullptr);
1923 if (!isQuadFamily || (primitive != PrimitiveType::TriangleStrip && primitive != PrimitiveType::Triangles)) {
1924 frameSkippedDraws++;
1925 if (!_currentProgram->FetchUnsupportedWarned()) {
1926 LOGW("Skipping draws of program \"{}\": Effect not supported by the GU dispatch", _currentProgram->GetObjectLabel());
1927 }
1928 return;
1929 }
1930
1931 const std::uint8_t* projBytes = _currentProgram->GetResolvedProjection();
1932 const std::uint8_t* viewBytes = _currentProgram->GetResolvedView();
1933 const float* projMat = (projBytes != nullptr ? reinterpret_cast<const float*>(projBytes) : IdentityMatrix);
1934 const float* viewMat = (viewBytes != nullptr ? reinterpret_cast<const float*>(viewBytes) : IdentityMatrix);
1935
1936 const GuUniformBlock* block = _currentProgram->FindBlock("InstanceBlock");
1937 if (block == nullptr) {
1938 block = _currentProgram->FindBlock("InstancesBlock");
1939 }
1940 if (block == nullptr) {
1941 return;
1942 }
1943 std::int32_t binding = block->GetBindingIndex();
1944 if (binding < 0 || std::uint32_t(binding) >= MaxUniformBindings) {
1945 binding = 0;
1946 }
1947 const std::uint8_t* blockData = _boundUniformRanges[binding].Data;
1948 if (blockData == nullptr) {
1949 return;
1950 }
1951
1952 const ShaderCompiler::ProgramVariant* reflection = _currentProgram->GetReflection();
1953 auto samplerUnit = [reflection](const char* name, std::int32_t def) -> std::int32_t {
1954 if (reflection != nullptr) {
1955 for (std::size_t i = 0; i < reflection->TextureCount; i++) {
1956 if (std::strcmp(reflection->Textures[i].Name, name) == 0) {
1957 return (reflection->Textures[i].Unit >= 0 ? reflection->Textures[i].Unit : def);
1958 }
1959 }
1960 }
1961 return def;
1962 };
1963 std::uint32_t instanceStride = 0;
1964 if (reflection != nullptr) {
1965 for (std::size_t i = 0; i < reflection->BlockCount; i++) {
1966 if (reflection->Blocks[i].InstanceStride > 0) {
1967 instanceStride = reflection->Blocks[i].InstanceStride;
1968 break;
1969 }
1970 }
1971 }
1972
1973 float pv[16];
1974 Mat4Mul(projMat, viewMat, pv);
1975
1976 // Batched programs are exactly the ones whose reflection declares a BATCH_SIZE-strided
1977 // InstancesBlock (non-batched programs use a flat InstanceBlock with no stride), so the reflected
1978 // stride IS the batching signal - no per-program identity needed
1979 const bool batched = (instanceStride > 0);
1980 std::int32_t numInstances = 1;
1981 if (batched) {
1982 numInstances = numVertices / 6;
1983 if (numInstances < 1) {
1984 numInstances = 1;
1985 }
1986 }
1987
1988 // A program samples the sprite texture exactly when its reflection binds uTexture
1989 bool hasTexture = false;
1990 if (reflection != nullptr) {
1991 for (std::size_t i = 0; i < reflection->TextureCount; i++) {
1992 if (std::strcmp(reflection->Textures[i].Name, "uTexture") == 0) {
1993 hasTexture = true;
1994 break;
1995 }
1996 }
1997 }
1998 // The instance layout follows the block's own reflected declaration rather than any effect identity:
1999 // a block that declares texRect uses the textured member offsets whether or not the program samples
2000 // a texture (the Transition carries texRect but samples nothing)
2001 bool texturedLayout = hasTexture;
2002 if (!texturedLayout && reflection != nullptr) {
2003 for (std::size_t i = 0; i < reflection->BlockCount && !texturedLayout; i++) {
2004 const ShaderCompiler::UniformBlock& b = reflection->Blocks[i];
2005 for (std::size_t j = 0; j < b.MemberCount; j++) {
2006 if (std::strcmp(b.Members[j].Name, "texRect") == 0) {
2007 texturedLayout = true;
2008 break;
2009 }
2010 }
2011 }
2012 }
2013 // Every effect that samples indexed sprites through the palette texture binds uTexturePalette in its
2014 // reflection, which is what UsesPalette() reports
2015 const bool isPaletteRemap = _currentProgram->UsesPalette();
2016
2017 const FixedFunctionRequirements reqs = generated->Requirements;
2018 const bool needsTexelStep = ((reqs & FixedFunctionRequirements::NeedsTexelStep) == FixedFunctionRequirements::NeedsTexelStep);
2019 const bool needsUniforms = ((reqs & FixedFunctionRequirements::NeedsUniforms) == FixedFunctionRequirements::NeedsUniforms);
2020 const bool needsStripBuilder = ((reqs & FixedFunctionRequirements::NeedsStripBuilder) == FixedFunctionRequirements::NeedsStripBuilder);
2021 const bool needsQuadAxes = ((reqs & FixedFunctionRequirements::NeedsQuadAxes) == FixedFunctionRequirements::NeedsQuadAxes);
2022 const std::int32_t textureUnit = samplerUnit("uTexture", 0);
2023 GuTexture* texture = const_cast<GuTexture*>(hasTexture
2024 ? _boundTextures[std::uint32_t(textureUnit) < MaxTextureUnits ? textureUnit : 0] : nullptr);
2025 if (hasTexture && texture == nullptr) {
2026 return;
2027 }
2028
2029 // The palette to resolve indices with is whatever the material bound to the palette sampler (e.g.
2030 // the recolored preview palettes of the profile menu); the registered global palette is the fallback
2031 const GuTexture* paletteTex = nullptr;
2032 if (isPaletteRemap || (texture != nullptr && (texture->IsIndexed() || texture->NeedsPaletteBake()))) {
2033 const std::int32_t paletteUnit = samplerUnit("uTexturePalette", 1);
2034 paletteTex = (std::uint32_t(paletteUnit) < MaxTextureUnits ? _boundTextures[paletteUnit] : nullptr);
2035 if (paletteTex == nullptr || paletteTex == texture) {
2036 paletteTex = _paletteTexture;
2037 }
2038 }
2039 const std::uint32_t paletteVersion = (paletteTex == _paletteTexture
2040 ? _paletteGeneration : (paletteTex != nullptr ? paletteTex->GetContentVersion() : 0));
2041
2042 EnsureList();
2043 ApplyDrawTarget();
2044 ApplyScissor();
2045
2046 // Bounds guard, mirroring the software device
2047 const std::uint32_t rangeSize = _boundUniformRanges[binding].Size;
2048 if (batched && rangeSize > 0 && std::uint32_t(numInstances) * instanceStride > rangeSize) {
2049 numInstances = std::int32_t(rangeSize / instanceStride);
2050 }
2051
2052 const Recti viewport = (_viewport.W > 0 && _viewport.H > 0)
2053 ? _viewport : Recti(0, 0, _logicalWidth, _logicalHeight);
2054 float scaleX, scaleY;
2055 GetTargetScale(scaleX, scaleY);
2056
2057 // The material's own blending, shared by every instance of the draw
2058 DrawState material;
2059 {
2060 std::uint32_t srcFix = 0, dstFix = 0;
2061 material.BlendEnabled = _blending.Enabled;
2062 material.BlendOp = GU_ADD;
2063 material.BlendSrc = MapBlendGu(_blending.SrcRgb, srcFix);
2064 material.BlendDst = MapBlendGu(_blending.DstRgb, dstFix);
2065 material.BlendSrcFix = srcFix;
2066 material.BlendDstFix = dstFix;
2067 }
2068
2069 // Texel sizes of the sprite texture in texture space (part of the EffectContext contract), derived
2070 // only for effects flagged with the texel-size facility
2071 const float texelWidth = (needsTexelStep && hasTexture && texture->GetWidth() > 0 ? 1.0f / float(texture->GetWidth()) : 0.0f);
2072 const float texelHeight = (needsTexelStep && hasTexture && texture->GetHeight() > 0 ? 1.0f / float(texture->GetHeight()) : 0.0f);
2073
2074 // The engine's NDC orientation matches the software backend, whose top-down raster is flipped at
2075 // present time; the GE scans out its buffer top-down directly, so screen passes mirror NDC here
2076 // instead (+1 = bottom row). Render-to-texture passes keep the unmirrored top-down store, which is
2077 // what the sampling passes already expect - which is just the sign of the raster Y scale below.
2078 const bool screenPass = (_currentRenderTarget == nullptr);
2079
2080 // Constant NDC-to-raster mapping, folded in once rather than reapplied for every sprite corner
2081 const float rasterScaleX = 0.5f * float(viewport.W) * scaleX;
2082 const float rasterBiasX = rasterScaleX + float(viewport.X) * scaleX;
2083 const float rasterScaleY = 0.5f * float(viewport.H) * scaleY * (screenPass ? 1.0f : -1.0f);
2084 const float rasterBiasY = 0.5f * float(viewport.H) * scaleY + float(viewport.Y) * scaleY;
2085
2086 for (std::int32_t k = 0; k < numInstances; k++) {
2087 const std::uint8_t* inst = blockData + std::size_t(k) * (batched ? instanceStride : 0);
2088
2089 Transform2D mvp;
2090 Mat4MulTransform2D(pv, reinterpret_cast<const float*>(inst + kModelMatrixOffset), mvp);
2091 float color[4];
2092 std::memcpy(color, inst + kColorOffset, sizeof(color));
2093 float texRect[4] = { 0.0f, 0.0f, 1.0f, 1.0f };
2094 float spriteSize[2];
2095 if (texturedLayout) {
2096 std::memcpy(texRect, inst + kTexRectOffset, sizeof(texRect));
2097 std::memcpy(spriteSize, inst + kSpriteSizeOffset, sizeof(spriteSize));
2098 } else {
2099 std::memcpy(spriteSize, inst + kSpriteSizeNoTexOffset, sizeof(spriteSize));
2100 }
2101
2102 // Select this instance's texture page (and CLUT or bake) - through-mode texture coordinates are
2103 // texel indices of the bound page, so the conversion also carries the page origin
2104 DrawState state = material;
2105 float uvScaleU = 1.0f, uvScaleV = 1.0f, uvBiasU = 0.0f, uvBiasV = 0.0f;
2106 if (hasTexture) {
2107 std::int32_t paletteOffset = 0;
2108 if (isPaletteRemap) {
2109 float palOffset = 0.0f;
2110 std::memcpy(&palOffset, inst + kPaletteOffsetOffset, sizeof(palOffset));
2111 paletteOffset = std::int32_t(palOffset + 0.5f);
2112 }
2113 if (texture->NeedsPaletteBake()) {
2114 // Index + per-pixel alpha has no paletted form: a CPU bake through the palette row is
2115 // what the other consoles do too
2116 if (paletteTex == nullptr || paletteTex->GetPixels() == nullptr) {
2117 continue;
2118 }
2119 const std::uint32_t* entries = reinterpret_cast<const std::uint32_t*>(paletteTex->GetPixels())
2120 + paletteOffset;
2121 if (!texture->EnsureBakedStore(entries, std::uint32_t(paletteOffset), paletteVersion, paletteTex)) {
2122 continue;
2123 }
2124 } else if (texture->IsIndexed()) {
2125 // An 8bpp store can only be read through a CLUT, whatever it is being drawn with - the
2126 // lookup belongs to the texture read rather than to the effect. An effect that remaps
2127 // takes the row from the instance; anything else (the fonts) uses the base row.
2128 state.Clut = AcquireClutForRow(paletteTex, paletteOffset, paletteVersion);
2129 if (state.Clut == nullptr) {
2130 continue;
2131 }
2132 }
2133 if (!ResolveTextureState(state, texture, texRect, uvScaleU, uvScaleV, uvBiasU, uvBiasV)) {
2134 continue;
2135 }
2136 }
2137
2138 // Synthesize the four sprite corners exactly like the software FetchVertex, with the constant
2139 // NDC-to-raster mapping folded into the transform so a corner costs one multiply-add per axis.
2140 // The corner weights are 0 or 1, so the sprite's extent in raster space is just the transformed
2141 // axes scaled by its size, and the corners are sums of those.
2142 const float originX = mvp.Tx * rasterScaleX + rasterBiasX;
2143 const float originY = mvp.Ty * rasterScaleY + rasterBiasY;
2144 const float spanXx = mvp.Xx * rasterScaleX * spriteSize[0];
2145 const float spanXy = mvp.Xy * rasterScaleY * spriteSize[0];
2146 const float spanYx = mvp.Yx * rasterScaleX * spriteSize[1];
2147 const float spanYy = mvp.Yy * rasterScaleY * spriteSize[1];
2148 float px[4], py[4], pu[4], pvv[4];
2149 for (std::int32_t i = 0; i < 4; i++) {
2150 const float ax = ((i & ~1) == 0) ? 1.0f : 0.0f;
2151 const float ay = (i & 1) ? 1.0f : 0.0f;
2152 px[i] = originX + ax * spanXx + ay * spanYx;
2153 py[i] = originY + ax * spanXy + ay * spanYy;
2154 pu[i] = (ax * texRect[0] + texRect[1]) * uvScaleU - uvBiasU;
2155 pvv[i] = (ay * texRect[2] + texRect[3]) * uvScaleV - uvBiasV;
2156 }
2157
2158 // Nothing is clipped geometrically - the GE has a real raster scissor and it is already
2159 // programmed - but a quad that cannot touch the surface at all is worth not submitting
2160 {
2161 const float minX = std::min(std::min(px[0], px[1]), std::min(px[2], px[3]));
2162 const float maxX = std::max(std::max(px[0], px[1]), std::max(px[2], px[3]));
2163 const float minY = std::min(std::min(py[0], py[1]), std::min(py[2], py[3]));
2164 const float maxY = std::max(std::max(py[0], py[1]), std::max(py[2], py[3]));
2165 if (maxX <= float(appliedScissor[0]) || minX >= float(appliedScissor[0] + appliedScissor[2]) ||
2166 maxY <= float(appliedScissor[1]) || minY >= float(appliedScissor[1] + appliedScissor[3])) {
2167 continue;
2168 }
2169 }
2170
2171 // The pass descriptors the per-effect functions declare are mapped onto this instance's corners
2172 // and the resolved GE state through the context
2173 EffectContext ctx;
2174 ctx.InstanceColor = color;
2175 ctx.TexelW = texelWidth;
2176 ctx.TexelH = texelHeight;
2177 ctx.Batched = batched;
2178 ctx.Material = &state;
2179 ctx.Px = px;
2180 ctx.Py = py;
2181 ctx.Pu = pu;
2182 ctx.Pv = pvv;
2183 ctx.TexRect = texRect;
2184 // The optional context facilities are only wired up for effects whose static analysis says they
2185 // can call them; members of an unused facility are simply never read
2186 if (needsQuadAxes) {
2187 ctx.OriginX = originX;
2188 ctx.OriginY = originY;
2189 ctx.AxisXx = spanXx;
2190 ctx.AxisXy = spanXy;
2191 ctx.AxisYx = spanYx;
2192 ctx.AxisYy = spanYy;
2193 }
2194 ctx.Program = (needsUniforms ? _currentProgram : nullptr);
2195 if (needsStripBuilder) {
2196 ctx.UvScaleU = uvScaleU;
2197 ctx.UvScaleV = uvScaleV;
2198 ctx.UvBiasU = uvBiasU;
2199 ctx.UvBiasV = uvBiasV;
2200 }
2201
2202 generated->Fn(ctx);
2203 }
2204 }
2205 }