Debian Codegraph @

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

raw
1 #include "PvrDevice.h"
2 #include "PvrBuffer.h"
3 #include "PvrShaderProgram.h"
4 #include "PvrRenderTarget.h"
5 #include "PvrTexture.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 <dc/sq.h>
16
17 namespace nCine::RHI::PVR
18 {
19 namespace
20 {
21 // The DefaultSprite / DefaultBatchedSprites instance layout is a hard contract of the shader family
22 // (std140 offsets within the InstanceBlock / each batched Instance) - identical to the software
23 // backend's decode (see SwDevice.cpp)
24 constexpr std::uint32_t kModelMatrixOffset = 0;
25 constexpr std::uint32_t kColorOffset = 64;
26 constexpr std::uint32_t kTexRectOffset = 80;
27 constexpr std::uint32_t kSpriteSizeOffset = 96;
28 constexpr std::uint32_t kPaletteOffsetOffset = 104;
29 constexpr std::uint32_t kSpriteSizeNoTexOffset = 80;
30
31 const float IdentityMatrix[16] = {
32 1, 0, 0, 0,
33 0, 1, 0, 0,
34 0, 0, 1, 0,
35 0, 0, 0, 1
36 };
37
38 // Column-major 4x4 multiply, out = a * b (matches the software device)
39 void Mat4Mul(const float* DEATH_RESTRICT a, const float* DEATH_RESTRICT b, float* DEATH_RESTRICT out)
40 {
41 for (std::int32_t col = 0; col < 4; col++) {
42 for (std::int32_t row = 0; row < 4; row++) {
43 out[col * 4 + row] =
44 a[0 * 4 + row] * b[col * 4 + 0] +
45 a[1 * 4 + row] * b[col * 4 + 1] +
46 a[2 * 4 + row] * b[col * 4 + 2] +
47 a[3 * 4 + row] * b[col * 4 + 3];
48 }
49 }
50 }
51
52 // Both draw paths only ever transform points of the form (x, y, 0, 1), so just six of the sixteen
53 // products of projection*view*model are ever read back. Sprites pay this per instance, which made
54 // the full 4x4 multiply the most expensive step of the per-instance loop.
55 struct Transform2D
56 {
57 float Xx, Xy; // Column 0, rows 0 and 1
58 float Yx, Yy; // Column 1, rows 0 and 1
59 float Tx, Ty; // Column 3, rows 0 and 1
60 };
61
62 void Mat4MulTransform2D(const float* DEATH_RESTRICT pv, const float* DEATH_RESTRICT model, Transform2D& out)
63 {
64 out.Xx = pv[0] * model[0] + pv[4] * model[1] + pv[8] * model[2] + pv[12] * model[3];
65 out.Xy = pv[1] * model[0] + pv[5] * model[1] + pv[9] * model[2] + pv[13] * model[3];
66 out.Yx = pv[0] * model[4] + pv[4] * model[5] + pv[8] * model[6] + pv[12] * model[7];
67 out.Yy = pv[1] * model[4] + pv[5] * model[5] + pv[9] * model[6] + pv[13] * model[7];
68 out.Tx = pv[0] * model[12] + pv[4] * model[13] + pv[8] * model[14] + pv[12] * model[15];
69 out.Ty = pv[1] * model[12] + pv[5] * model[13] + pv[9] * model[14] + pv[13] * model[15];
70 }
71
72 // Maps a pipeline-neutral blend factor onto the PVR factor set
73 std::int32_t MapBlendPvr(nCine::BlendingFactor factor)
74 {
75 switch (factor) {
76 case nCine::BlendingFactor::Zero: return PVR_BLEND_ZERO;
77 case nCine::BlendingFactor::One: return PVR_BLEND_ONE;
78 case nCine::BlendingFactor::SrcColor: return PVR_BLEND_DESTCOLOR; // Valid as a dst factor only; the src slot maps below
79 case nCine::BlendingFactor::OneMinusSrcColor: return PVR_BLEND_INVDESTCOLOR;
80 case nCine::BlendingFactor::DstColor: return PVR_BLEND_DESTCOLOR;
81 case nCine::BlendingFactor::OneMinusDstColor: return PVR_BLEND_INVDESTCOLOR;
82 case nCine::BlendingFactor::SrcAlpha: return PVR_BLEND_SRCALPHA;
83 case nCine::BlendingFactor::OneMinusSrcAlpha: return PVR_BLEND_INVSRCALPHA;
84 case nCine::BlendingFactor::DstAlpha: return PVR_BLEND_DESTALPHA;
85 case nCine::BlendingFactor::OneMinusDstAlpha: return PVR_BLEND_INVDESTALPHA;
86 default: return PVR_BLEND_ONE;
87 }
88 }
89
90 inline std::uint8_t QuantizeChannel(float v)
91 {
92 v = (v < 0.0f ? 0.0f : (v > 1.0f ? 1.0f : v));
93 return std::uint8_t(v * 255.0f + 0.5f);
94 }
95
96 // Straight to the 4 bits an ARGB4444 channel actually keeps, skipping the round trip through 8 bits
97 inline std::uint32_t Quantize4Bit(float v)
98 {
99 v = (v < 0.0f ? 0.0f : (v > 1.0f ? 1.0f : v));
100 return std::uint32_t(v * 15.0f + 0.5f);
101 }
102
103 inline std::uint32_t PackArgb(std::uint8_t r, std::uint8_t g, std::uint8_t b, std::uint8_t a)
104 {
105 return (std::uint32_t(a) << 24) | (std::uint32_t(r) << 16) | (std::uint32_t(g) << 8) | std::uint32_t(b);
106 }
107
108 // Clamps one screen-space quad edge pair (a..b with linearly mapped texture coordinates ua..ub)
109 // into [lo, hi]; returns false when the whole span lies outside. Works for either edge direction.
110 bool ClipQuadEdge(float& a, float& b, float& ua, float& ub, float lo, float hi)
111 {
112 if ((a <= lo && b <= lo) || (a >= hi && b >= hi)) {
113 return false;
114 }
115 const float d = b - a;
116 if (d != 0.0f) {
117 const float du = (ub - ua) / d;
118 const float na = (a < lo ? lo : (a > hi ? hi : a));
119 const float nb = (b < lo ? lo : (b > hi ? hi : b));
120 ua += (na - a) * du;
121 ub += (nb - b) * du;
122 a = na;
123 b = nb;
124 }
125 return true;
126 }
127
128 // The tile accelerator is a state machine: a polygon header stays in effect for every strip that
129 // follows it within the open list, so a header identical to the last submitted one does not have
130 // to go out again - it is 32 of the 160 bytes of a typical quad, and batches reuse one header for
131 // hundreds of primitives. Cleared whenever a new list opens (see InvalidateSubmittedHeader()).
132 std::uint32_t lastHeaderWords[8];
133 bool lastHeaderValid = false;
134
135 void InvalidateSubmittedHeader()
136 {
137 lastHeaderValid = false;
138 }
139
140 // Writes the header into the store queues only when it differs from the last submitted one, and
141 // returns the queue pointer for the vertices that follow
142 DEATH_ALWAYS_INLINE std::uint32_t* SubmitHeaderIfChanged(const pvr_poly_hdr_t& hdr)
143 {
144 std::uint32_t* DEATH_RESTRICT sq = SQ_MASK_DEST(PVR_TA_INPUT);
145 const std::uint32_t* DEATH_RESTRICT header = reinterpret_cast<const std::uint32_t*>(&hdr);
146 if (lastHeaderValid &&
147 lastHeaderWords[0] == header[0] && lastHeaderWords[1] == header[1] &&
148 lastHeaderWords[2] == header[2] && lastHeaderWords[3] == header[3] &&
149 lastHeaderWords[4] == header[4] && lastHeaderWords[5] == header[5] &&
150 lastHeaderWords[6] == header[6] && lastHeaderWords[7] == header[7]) {
151 return sq;
152 }
153 sq[0] = lastHeaderWords[0] = header[0]; sq[1] = lastHeaderWords[1] = header[1];
154 sq[2] = lastHeaderWords[2] = header[2]; sq[3] = lastHeaderWords[3] = header[3];
155 sq[4] = lastHeaderWords[4] = header[4]; sq[5] = lastHeaderWords[5] = header[5];
156 sq[6] = lastHeaderWords[6] = header[6]; sq[7] = lastHeaderWords[7] = header[7];
157 lastHeaderValid = true;
158 sq_flush(sq);
159 return sq + 8;
160 }
161
162 // Submits one strip of `count` vertices (3 = a single triangle, 4 = a quad) under the given header
163 // to the open translucent list. The corner order matches the procedural sprite strip (v0, v1, v2,
164 // v3) exactly like the software FetchVertex synthesizes it. The offset colour is added after
165 // texturing (only when the polygon enables it), which is how the actor state effects brighten or
166 // tint the sprite - see the effect handling in Dispatch.
167 //
168 // The primitives are written straight into the store queues rather than assembled in main memory
169 // and handed to pvr_prim(): that path copies every 32-byte primitive a second time on its way out,
170 // which at four vertices per sprite and per tile was a large part of the submission cost. The queue
171 // pointer advances a block at a time exactly as sq_cpy() does, which alternates the two hardware
172 // banks so a bank is never rewritten while its write-back is still in flight. The PVR driver has
173 // already pointed the queues at the TA FIFO (pvr_prim() itself relies on that), so no lock is taken.
174 void SubmitStrip(const pvr_poly_hdr_t& hdr, const float* px, const float* py, const float* pu, const float* pv,
175 std::int32_t count, std::uint32_t argb, std::uint32_t oargb = 0, float dx = 0.0f, float dy = 0.0f)
176 {
177 static_assert(sizeof(pvr_vertex_t) == 32 && sizeof(pvr_poly_hdr_t) == 32,
178 "The store queues submit whole 32 byte blocks");
179
180 std::uint32_t* DEATH_RESTRICT sq = SubmitHeaderIfChanged(hdr);
181
182 for (std::int32_t i = 0; i < count; i++) {
183 sq[0] = (i == count - 1 ? PVR_CMD_VERTEX_EOL : PVR_CMD_VERTEX);
184 reinterpret_cast<float*>(sq)[1] = px[i] + dx;
185 reinterpret_cast<float*>(sq)[2] = py[i] + dy;
186 reinterpret_cast<float*>(sq)[3] = 1.0f;
187 reinterpret_cast<float*>(sq)[4] = pu[i];
188 reinterpret_cast<float*>(sq)[5] = pv[i];
189 sq[6] = argb;
190 sq[7] = oargb;
191 sq_flush(sq);
192 sq += 8;
193 }
194 }
195
196 void SubmitQuad(const pvr_poly_hdr_t& hdr, const float* px, const float* py, const float* pu, const float* pv,
197 std::uint32_t argb, std::uint32_t oargb = 0, float dx = 0.0f, float dy = 0.0f)
198 {
199 SubmitStrip(hdr, px, py, pu, pv, 4, argb, oargb, dx, dy);
200 }
201
202 // As SubmitStrip(), but each vertex carries its own colour so the rasterizer interpolates it across
203 // the primitive - which is how a gradient is expressed without a fragment shader
204 void SubmitStripShaded(const pvr_poly_hdr_t& hdr, const float* px, const float* py, std::int32_t count,
205 const std::uint32_t* argb)
206 {
207 std::uint32_t* DEATH_RESTRICT sq = SubmitHeaderIfChanged(hdr);
208
209 for (std::int32_t i = 0; i < count; i++) {
210 sq[0] = (i == count - 1 ? PVR_CMD_VERTEX_EOL : PVR_CMD_VERTEX);
211 reinterpret_cast<float*>(sq)[1] = px[i];
212 reinterpret_cast<float*>(sq)[2] = py[i];
213 reinterpret_cast<float*>(sq)[3] = 1.0f;
214 reinterpret_cast<float*>(sq)[4] = 0.0f;
215 reinterpret_cast<float*>(sq)[5] = 0.0f;
216 sq[6] = argb[i];
217 sq[7] = 0;
218 sq_flush(sq);
219 sq += 8;
220 }
221 }
222
223 }
224
225 // EffectContext deliberately has EXTERNAL linkage (namespace scope, though it is still
226 // defined only in this translation unit): the generated table struct below is itself at
227 // namespace scope - so the backend's ShaderProgram can forward-declare it and hold a typed
228 // entry pointer - and names EffectContext in a member type; the console toolchain's GCC
229 // ICEs when such an external struct member references an internal-linkage type.
230 // ---------------------------------------------------------- fixed-function quad effects
231 //
232 // The quad-family effects are expressed as FixedFunctionPass descriptors handed to this
233 // EffectContext - the structural contract documented in FixedFunctionPass.h. The per-effect
234 // functions live in the shaders' fixed_function blocks and are transpiled by the
235 // ShaderCompiler into Shaders/Generated/PvrGeneratedEffects.h, included below against this
236 // concrete context (see Docs/FixedFunctionShaderDesign.md); only the submission machinery
237 // stays here.
238
239 struct EffectContext
240 {
241 // The strip builder is deliberately small: every geometry effect submits trapezoid or fan
242 // pieces of at most 4 vertices, and a bigger scratch would only grow the per-instance stack
243 static constexpr std::int32_t MaxStripVertices = 8;
244
245 // Decoded instance data of the draw being dispatched (the documented contract)
246 const float* InstanceColor;
247 float TexelW;
248 float TexelH;
249 bool Batched;
250
251 // Backend internals the pass state maps onto: the compiled base material header, its
252 // build context (for deriving blend twins on demand) and the current instance's
253 // post-clip corner arrays
254 const pvr_poly_hdr_t* Hdr;
255 pvr_poly_cxt_t* BaseCxt;
256 pvr_poly_hdr_t* HdrAdditive;
257 bool* HdrAdditiveValid;
258 pvr_poly_hdr_t* HdrOpaque;
259 bool* HdrOpaqueValid;
260 pvr_poly_hdr_t* HdrAlpha;
261 bool* HdrAlphaValid;
262 const float* Px;
263 const float* Py;
264 const float* Pu;
265 const float* Pv;
266 const float* TexRect;
267
268 // Pre-clip quad geometry (the quad_origin/quad_axis_* built-ins), the program (for resolved
269 // uniforms), the material blend factors (the shaded-strip Material twin cannot read them
270 // back from BaseCxt - the blend twins above mutate its blend fields) and the UV scale of the
271 // padded texture store (folded into strip UVs exactly like the quad corner synthesis)
272 float OriginX, OriginY;
273 float AxisXx, AxisXy;
274 float AxisYx, AxisYy;
275 const PvrShaderProgram* Program;
276 std::int32_t MaterialBlendSrc;
277 std::int32_t MaterialBlendDst;
278 float UvScaleU, UvScaleV;
279
280 // Colour-polygon twins for shaded strips, one per BlendMode, compiled lazily per draw (see
281 // SubmitStripShaded); they do not depend on the instance's texture variant, so they are
282 // never invalidated within a draw
283 pvr_poly_hdr_t* HdrShaded;
284 bool* HdrShadedValid;
285
286 // The strip builder scratch; colours are packed at set time (same quantization as the quad
287 // path, so identical float inputs produce identical vertex words)
288 float StripX[MaxStripVertices];
289 float StripY[MaxStripVertices];
290 float StripU[MaxStripVertices];
291 float StripV[MaxStripVertices];
292 std::uint32_t StripArgb[MaxStripVertices];
293
294 const float* Color() const { return InstanceColor; }
295 float TexelWidth() const { return TexelW; }
296 float TexelHeight() const { return TexelH; }
297 bool IsBatched() const { return Batched; }
298
299 float QuadOriginX() const { return OriginX; }
300 float QuadOriginY() const { return OriginY; }
301 float QuadAxisXx() const { return AxisXx; }
302 float QuadAxisXy() const { return AxisXy; }
303 float QuadAxisYx() const { return AxisYx; }
304 float QuadAxisYy() const { return AxisYy; }
305
306 bool HasUniform(const char* name) const
307 {
308 return (Program->ResolveUniform(name) != nullptr);
309 }
310 void LoadUniform(const char* name, float* out, std::int32_t floatCount) const
311 {
312 // An unresolved name leaves the caller's zeros in place - blocks guard with
313 // has_uniform() exactly like the handwritten code null-checked the pointers
314 const std::uint8_t* bytes = Program->ResolveUniform(name);
315 if (bytes != nullptr) {
316 std::memcpy(out, bytes, std::size_t(floatCount) * sizeof(float));
317 }
318 }
319
320 void SetStripVertexPosition(std::int32_t i, float x, float y)
321 {
322 if (std::uint32_t(i) < std::uint32_t(MaxStripVertices)) {
323 StripX[i] = x;
324 StripY[i] = y;
325 }
326 }
327 void SetStripVertexUv(std::int32_t i, float u, float v)
328 {
329 if (std::uint32_t(i) < std::uint32_t(MaxStripVertices)) {
330 StripU[i] = u * UvScaleU;
331 StripV[i] = v * UvScaleV;
332 }
333 }
334 void SetStripVertexColor(std::int32_t i, float r, float g, float b, float a)
335 {
336 if (std::uint32_t(i) < std::uint32_t(MaxStripVertices)) {
337 StripArgb[i] = PackArgb(QuantizeChannel(r), QuantizeChannel(g), QuantizeChannel(b), QuantizeChannel(a));
338 }
339 }
340
341 // Whether a UV span can be mapped onto the screen at all (a zero texRect has no scale)
342 bool HasTexelStep() const { return TexRect[0] != 0.0f && TexRect[2] != 0.0f; }
343 // Maps a span in the sprite's UV space onto the quad's on-screen extent - the texel step
344 // the Outline ring taps use. The corners are already in raster space, so the result is a
345 // raster displacement (the padding scale applies to both the texel size and the quad's
346 // span, so it cancels out).
347 float TexelToScreenX(float uvSpan) const { return (Px[0] - Px[2]) * (uvSpan / TexRect[0]); }
348 float TexelToScreenY(float uvSpan) const { return (Py[1] - Py[0]) * (uvSpan / TexRect[2]); }
349 // The documented texel_size() built-in of the fixed_function contract: the Outline shader
350 // family carries the sprite's UV-space texel size in its instance color.xy (exactly like
351 // the GLSL derives its tap offsets), folded through the raster-space conversion above
352 float TexelStepX() const { return TexelToScreenX(InstanceColor[0]); }
353 float TexelStepY() const { return TexelToScreenY(InstanceColor[1]); }
354
355 // The material header (or its lazily compiled blend twin) a pass's blend mode maps onto -
356 // shared by the quad and the textured-strip submissions
357 const pvr_poly_hdr_t* MaterialHeaderFor(FixedFunctionPass::BlendMode blend)
358 {
359 switch (blend) {
360 case FixedFunctionPass::BlendMode::Additive:
361 // Deliberately SRCALPHA rather than a literal ONE source factor: it is the
362 // additive mechanism Colorized has always used, and its split-multiplier
363 // passes rely on the source alpha scaling each contribution
364 if (!*HdrAdditiveValid) {
365 BaseCxt->blend.src = PVR_BLEND_SRCALPHA;
366 BaseCxt->blend.dst = PVR_BLEND_ONE;
367 pvr_poly_compile(HdrAdditive, BaseCxt);
368 *HdrAdditiveValid = true;
369 }
370 return HdrAdditive;
371 case FixedFunctionPass::BlendMode::Opaque:
372 if (!*HdrOpaqueValid) {
373 BaseCxt->blend.src = PVR_BLEND_ONE;
374 BaseCxt->blend.dst = PVR_BLEND_ZERO;
375 pvr_poly_compile(HdrOpaque, BaseCxt);
376 *HdrOpaqueValid = true;
377 }
378 return HdrOpaque;
379 case FixedFunctionPass::BlendMode::Alpha:
380 if (!*HdrAlphaValid) {
381 BaseCxt->blend.src = PVR_BLEND_SRCALPHA;
382 BaseCxt->blend.dst = PVR_BLEND_INVSRCALPHA;
383 pvr_poly_compile(HdrAlpha, BaseCxt);
384 *HdrAlphaValid = true;
385 }
386 return HdrAlpha;
387 default:
388 return Hdr;
389 }
390 }
391
392 // The packed offset colour of a pass: added after texturing only on polygons compiled with
393 // specular enabled (a per-effect property of the base material, see usesOffsetColor in
394 // Dispatch); a pass without one submits 0, which is also what specular-enabled polygons
395 // expect for "no offset"
396 std::uint32_t PackOffsetColor(const FixedFunctionPass& pass) const
397 {
398 return (pass.HasOffsetColor
399 ? PackArgb(QuantizeChannel(pass.OffsetColor[0]), QuantizeChannel(pass.OffsetColor[1]),
400 QuantizeChannel(pass.OffsetColor[2]), 0)
401 : 0);
402 }
403
404 void SubmitQuad(const FixedFunctionPass& pass)
405 {
406 const pvr_poly_hdr_t* hdr = MaterialHeaderFor(pass.Blend);
407 const std::uint32_t argb = PackArgb(QuantizeChannel(pass.Color[0]), QuantizeChannel(pass.Color[1]),
408 QuantizeChannel(pass.Color[2]), QuantizeChannel(pass.Color[3]));
409 // Qualified: the SubmitStrip member above hides the free helper of the same name
410 nCine::RHI::PVR::SubmitStrip(*hdr, Px, Py, Pu, Pv, 4, argb, PackOffsetColor(pass),
411 pass.ScreenOffset[0], pass.ScreenOffset[1]);
412 }
413
414 // Textured strip out of the builder scratch: the pass's flat colour over the material state
415 // (the warp's band pieces). Qualified call - the free SubmitStrip helper would otherwise be
416 // hidden by this member's own name.
417 void SubmitStrip(const FixedFunctionPass& pass, std::int32_t count)
418 {
419 if (count > MaxStripVertices) {
420 count = MaxStripVertices;
421 }
422 if (count < 3) {
423 return;
424 }
425 const pvr_poly_hdr_t* hdr = MaterialHeaderFor(pass.Blend);
426 const std::uint32_t argb = PackArgb(QuantizeChannel(pass.Color[0]), QuantizeChannel(pass.Color[1]),
427 QuantizeChannel(pass.Color[2]), QuantizeChannel(pass.Color[3]));
428 nCine::RHI::PVR::SubmitStrip(*hdr, StripX, StripY, StripU, StripV, count, argb,
429 PackOffsetColor(pass), pass.ScreenOffset[0], pass.ScreenOffset[1]);
430 }
431
432 // Shaded (per-vertex-colour) strip out of the builder scratch: always an UNTEXTURED colour
433 // polygon - a gradient has no texture to modulate - whose blend comes from the pass. For an
434 // untextured material the Material twin compiles to the exact words of the base header, so
435 // the TA header dedup keeps the submitted stream identical to reusing the base (which is
436 // what the handwritten iris did).
437 void SubmitStripShaded(const FixedFunctionPass& pass, std::int32_t count)
438 {
439 if (count > MaxStripVertices) {
440 count = MaxStripVertices;
441 }
442 if (count < 3) {
443 return;
444 }
445 std::int32_t mode = std::int32_t(pass.Blend);
446 if (std::uint32_t(mode) > std::uint32_t(FixedFunctionPass::BlendMode::Alpha)) {
447 mode = 0;
448 }
449 if (!HdrShadedValid[mode]) {
450 pvr_poly_cxt_t scxt;
451 pvr_poly_cxt_col(&scxt, PVR_LIST_TR_POLY);
452 scxt.gen.culling = PVR_CULLING_NONE;
453 scxt.depth.comparison = PVR_DEPTHCMP_ALWAYS;
454 scxt.depth.write = PVR_DEPTHWRITE_DISABLE;
455 switch (FixedFunctionPass::BlendMode(mode)) {
456 case FixedFunctionPass::BlendMode::Additive:
457 scxt.blend.src = PVR_BLEND_SRCALPHA;
458 scxt.blend.dst = PVR_BLEND_ONE;
459 break;
460 case FixedFunctionPass::BlendMode::Opaque:
461 scxt.blend.src = PVR_BLEND_ONE;
462 scxt.blend.dst = PVR_BLEND_ZERO;
463 break;
464 case FixedFunctionPass::BlendMode::Alpha:
465 scxt.blend.src = PVR_BLEND_SRCALPHA;
466 scxt.blend.dst = PVR_BLEND_INVSRCALPHA;
467 break;
468 default:
469 scxt.blend.src = pvr_blend_mode_t(MaterialBlendSrc);
470 scxt.blend.dst = pvr_blend_mode_t(MaterialBlendDst);
471 break;
472 }
473 pvr_poly_compile(&HdrShaded[mode], &scxt);
474 HdrShadedValid[mode] = true;
475 }
476 nCine::RHI::PVR::SubmitStripShaded(HdrShaded[mode], StripX, StripY, count, StripArgb);
477 }
478 };
479 }
480
481 // The per-effect functions themselves are GENERATED: the ShaderCompiler transpiles each shader's
482 // fixed_function block into C++ over the EffectContext defined above (the type name itself is the
483 // "using EffectContext = ...;" alias the header expects - the anonymous namespace above is the same
484 // namespace the header's payload reopens within this translation unit). Included at global scope
485 // because the header opens nCine::RHI::PVR itself.
486 #include "../../../../Shaders/Generated/PvrGeneratedEffects.h"
487
488 namespace nCine::RHI::PVR
489 {
490 const FixedFunctionGeneratedEffect* PvrDevice::FindGeneratedEffect(const char* program, const char* variant)
491 {
492 // A linear scan is fine - the lookup runs once per program load, not per draw
493 for (std::size_t i = 0; i < FixedFunctionGeneratedEffectCount; i++) {
494 const FixedFunctionGeneratedEffect& e = FixedFunctionGeneratedEffects[i];
495 if (std::strcmp(e.Program, program) == 0 && std::strcmp(e.Variant, variant) == 0) {
496 return &e;
497 }
498 }
499 return nullptr;
500 }
501
502 PvrDevice::BlendingState PvrDevice::_blending;
503 PvrDevice::DepthTestState PvrDevice::_depthTest;
504 PvrDevice::CullFaceState PvrDevice::_cullFace;
505 PvrDevice::ScissorState PvrDevice::_scissor;
506 Recti PvrDevice::_viewport(0, 0, 0, 0);
507 Colorf PvrDevice::_clearColor(0.0f, 0.0f, 0.0f, 1.0f);
508
509 PvrShaderProgram* PvrDevice::_currentProgram = nullptr;
510 const PvrTexture* PvrDevice::_boundTextures[PvrDevice::MaxTextureUnits] = {};
511 PvrDevice::UniformRange PvrDevice::_boundUniformRanges[PvrDevice::MaxUniformBindings] = {};
512 PvrRenderTarget* PvrDevice::_currentRenderTarget = nullptr;
513
514 bool PvrDevice::_pvrInitialized = false;
515 std::int32_t PvrDevice::_logicalWidth = 640;
516 std::int32_t PvrDevice::_logicalHeight = 480;
517 PvrDevice::SceneTarget PvrDevice::_sceneTarget = PvrDevice::SceneTarget::None;
518 std::uint32_t PvrDevice::_sceneCounter = 0;
519 PvrRenderTarget* PvrDevice::_sceneRenderTarget = nullptr;
520
521 PvrTexture* PvrDevice::_paletteTexture = nullptr;
522 std::uint32_t PvrDevice::_paletteGeneration = 1;
523 PvrDevice::PaletteBank PvrDevice::_paletteBanks[PvrDevice::MaxPaletteBanks] = {};
524 std::uint32_t PvrDevice::_paletteUseCounter = 0;
525
526 std::vector<PvrDevice::PendingSoftwareLight> PvrDevice::_pendingSoftwareLights;
527
528 pvr_ptr_t PvrDevice::_lightmapVram = nullptr;
529 std::size_t PvrDevice::_lightmapVramSize = 0;
530 std::int32_t PvrDevice::_lightmapW = 0;
531 std::int32_t PvrDevice::_lightmapH = 0;
532
533 // ------------------------------------------------------------------ session
534
535 void PvrDevice::InitializePvr()
536 {
537 if (_pvrInitialized) {
538 return;
539 }
540
541 // Everything renders through the translucent list with autosort DISABLED, so the list preserves
542 // submission order - the engine's painter's-order queue maps 1:1. Splitting cutout sprites into
543 // the punch-through list was evaluated and REJECTED: the CLX2 renders PT in its own per-tile
544 // phase BEFORE the translucent pass, so a PT sprite would fall under every TR draw regardless
545 // of submission order (the background layers alone are TR quads under all sprites), and with
546 // depth compare ALWAYS / writes off there is no Z to arbitrate - see the ordering analysis in
547 // Docs/FixedFunctionShaderDesign.md section 5.
548 pvr_init_params_t params = {
549 // Opaque, opaque modifier, translucent, translucent modifier, punch-through
550 { PVR_BINSIZE_0, PVR_BINSIZE_0, PVR_BINSIZE_32, PVR_BINSIZE_0, PVR_BINSIZE_0 },
551 512 * 1024, // Vertex buffer size
552 0, // DMA disabled (store-queue submission)
553 0, // No FSAA
554 1, // Autosort DISABLED (submission order = draw order)
555 2 // Extra OPB overflow buffers
556 };
557 pvr_init(&params);
558 pvr_set_bg_color(0.0f, 0.0f, 0.0f);
559 pvr_set_pal_format(PVR_PAL_ARGB8888);
560
561 _pvrInitialized = true;
562 }
563
564 void PvrDevice::EnsureScene()
565 {
566 const SceneTarget wanted = (_currentRenderTarget != nullptr ? SceneTarget::RenderTexture : SceneTarget::Screen);
567 if (_sceneTarget == wanted && (wanted != SceneTarget::RenderTexture || _sceneRenderTarget == _currentRenderTarget)) {
568 return;
569 }
570 FinishScene();
571
572 pvr_wait_ready();
573 if (wanted == SceneTarget::RenderTexture) {
574 PvrTexture* texture = _currentRenderTarget->GetColorTexture(0);
575 if (texture == nullptr || texture->GetVramPointer() == nullptr) {
576 return; // No surface to render into; draws will be skipped
577 }
578 // Render-to-texture scene into the target's RGB565 surface. Deliberately not through
579 // pvr_scene_begin_txr(): that wrapper is deprecated, and it forwards the *screen* dimensions as
580 // the render size while using the width it is given only as the stride. For any target narrower
581 // than the display that trips the "stride < width" check inside pvr_scene_begin_rtt(), which
582 // then returns without starting a scene at all - so nothing was ever rendered and the target
583 // kept whatever its memory held.
584 const std::uint32_t renderWidth = std::uint32_t(texture->GetPaddedWidth());
585 const std::uint32_t renderHeight = std::uint32_t(texture->GetPaddedHeight());
586 if (pvr_scene_begin_rtt(texture->GetVramPointer(), renderWidth, renderHeight, renderWidth) < 0) {
587 LOGE("Cannot start a render-to-texture scene for a {}x{} target", renderWidth, renderHeight);
588 return;
589 }
590 _sceneRenderTarget = _currentRenderTarget;
591 } else {
592 pvr_scene_begin();
593 _sceneRenderTarget = nullptr;
594 }
595 pvr_list_begin(PVR_LIST_TR_POLY);
596 // A new list starts with no polygon-header state in the tile accelerator
597 InvalidateSubmittedHeader();
598 _sceneTarget = wanted;
599 }
600
601 void PvrDevice::FinishScene()
602 {
603 if (_sceneTarget == SceneTarget::None) {
604 return;
605 }
606 pvr_list_finish();
607 pvr_scene_finish();
608 _sceneTarget = SceneTarget::None;
609 _sceneRenderTarget = nullptr;
610 _sceneCounter++;
611 }
612
613 void PvrDevice::PresentFrame()
614 {
615 if (!_pvrInitialized) {
616 return;
617 }
618 if (_sceneTarget == SceneTarget::None) {
619 // Nothing was drawn this frame; run an empty scene to keep the display pacing
620 pvr_wait_ready();
621 pvr_scene_begin();
622 pvr_list_begin(PVR_LIST_TR_POLY);
623 InvalidateSubmittedHeader();
624 _sceneTarget = SceneTarget::Screen;
625 }
626 FinishScene();
627 }
628
629 void PvrDevice::ResizeScreenFramebuffer(std::int32_t width, std::int32_t height)
630 {
631 if (width > 0 && height > 0) {
632 _logicalWidth = width;
633 _logicalHeight = height;
634 }
635 }
636
637 void PvrDevice::GetTargetScale(float& scaleX, float& scaleY, float& offsetX, float& offsetY)
638 {
639 offsetX = 0.0f;
640 offsetY = 0.0f;
641 if (_currentRenderTarget != nullptr) {
642 // Render-to-texture scenes render 1:1 into the target surface
643 scaleX = 1.0f;
644 scaleY = 1.0f;
645 } else {
646 scaleX = (_logicalWidth > 0 ? 640.0f / float(_logicalWidth) : 1.0f);
647 scaleY = (_logicalHeight > 0 ? 480.0f / float(_logicalHeight) : 1.0f);
648 }
649 }
650
651 // ------------------------------------------------------------------ state
652
653 void PvrDevice::SetBlendingEnabled(bool enabled) { _blending.Enabled = enabled; }
654 void PvrDevice::SetBlendingFactors(nCine::BlendingFactor srcRgb, nCine::BlendingFactor dstRgb, nCine::BlendingFactor srcAlpha, nCine::BlendingFactor dstAlpha)
655 {
656 _blending.SrcRgb = srcRgb;
657 _blending.DstRgb = dstRgb;
658 _blending.SrcAlpha = srcAlpha;
659 _blending.DstAlpha = dstAlpha;
660 }
661 PvrDevice::BlendingState PvrDevice::GetBlendingState() { return _blending; }
662 void PvrDevice::SetBlendingState(const BlendingState& state) { _blending = state; }
663
664 void PvrDevice::SetDepthTestEnabled(bool enabled) { _depthTest.TestEnabled = enabled; }
665 void PvrDevice::SetDepthMaskEnabled(bool enabled) { _depthTest.MaskEnabled = enabled; }
666 PvrDevice::DepthTestState PvrDevice::GetDepthTestState() { return _depthTest; }
667 void PvrDevice::SetDepthTestState(const DepthTestState& state) { _depthTest = state; }
668
669 void PvrDevice::SetCullFaceEnabled(bool enabled) { _cullFace.Enabled = enabled; }
670 PvrDevice::CullFaceState PvrDevice::GetCullFaceState() { return _cullFace; }
671 void PvrDevice::SetCullFaceState(const CullFaceState& state) { _cullFace = state; }
672
673 PvrDevice::ScissorState PvrDevice::GetScissorState() { return _scissor; }
674 void PvrDevice::SetScissorState(const ScissorState& state) { _scissor = state; }
675 void PvrDevice::SetScissor(const Recti& rect)
676 {
677 // Same contract as the GL device: setting a rect also enables the test (callers like
678 // RenderCommand and Viewport rely on it and restore via SetScissorState afterwards)
679 _scissor.Enabled = true;
680 _scissor.Rect = rect;
681 }
682 void PvrDevice::SetScissorTestEnabled(bool enabled) { _scissor.Enabled = enabled; }
683
684 Recti PvrDevice::GetViewport() { return _viewport; }
685 void PvrDevice::SetViewport(const Recti& rect) { _viewport = rect; }
686 void PvrDevice::InitViewport(std::int32_t x, std::int32_t y, std::int32_t width, std::int32_t height)
687 {
688 _viewport = Recti(x, y, width, height);
689 }
690
691 Colorf PvrDevice::GetClearColor() { return _clearColor; }
692 void PvrDevice::SetClearColor(const Colorf& color)
693 {
694 _clearColor = color;
695 if (_pvrInitialized) {
696 pvr_set_bg_color(color.R, color.G, color.B);
697 }
698 }
699
700 void PvrDevice::Clear(ClearFlags flags)
701 {
702 static_cast<void>(flags);
703 if (!_pvrInitialized) {
704 return;
705 }
706 if (_currentRenderTarget == nullptr && _sceneTarget == SceneTarget::None) {
707 // The first clear of a screen frame is provided for free by the scene background plane -
708 // pushing ~300k blended pixels through the translucent pipe for it again would be one of
709 // the most expensive draws of the whole frame. Only mid-scene clears (and render targets,
710 // which have no reliable background plane) paint the quad below.
711 pvr_set_bg_color(_clearColor.R, _clearColor.G, _clearColor.B);
712 return;
713 }
714 // The scene background provides the frame clear; an explicit mid-scene clear draws a flat quad
715 EnsureScene();
716 if (_sceneTarget == SceneTarget::None) {
717 return;
718 }
719 float scaleX, scaleY, offsetX, offsetY;
720 GetTargetScale(scaleX, scaleY, offsetX, offsetY);
721 const float w = float(_currentRenderTarget != nullptr ? _viewport.W : _logicalWidth) * scaleX;
722 const float h = float(_currentRenderTarget != nullptr ? _viewport.H : _logicalHeight) * scaleY;
723
724 pvr_poly_cxt_t cxt;
725 pvr_poly_cxt_col(&cxt, PVR_LIST_TR_POLY);
726 cxt.gen.culling = PVR_CULLING_NONE;
727 cxt.depth.comparison = PVR_DEPTHCMP_ALWAYS;
728 cxt.depth.write = PVR_DEPTHWRITE_DISABLE;
729 cxt.blend.src = PVR_BLEND_ONE;
730 cxt.blend.dst = PVR_BLEND_ZERO;
731 pvr_poly_hdr_t hdr;
732 pvr_poly_compile(&hdr, &cxt);
733
734 const std::uint32_t argb = PackArgb(QuantizeChannel(_clearColor.R), QuantizeChannel(_clearColor.G),
735 QuantizeChannel(_clearColor.B), QuantizeChannel(_clearColor.A));
736 const float px[4] = { w, w, 0.0f, 0.0f };
737 const float py[4] = { 0.0f, h, 0.0f, h };
738 const float uv[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
739 SubmitQuad(hdr, px, py, uv, uv, argb);
740 }
741
742 // ------------------------------------------------------------------ draw entry points
743
744 void PvrDevice::DrawArrays(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices)
745 {
746 Dispatch(primitive, firstVertex, numVertices);
747 }
748 void PvrDevice::DrawArraysInstanced(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices, std::int32_t numInstances)
749 {
750 static_cast<void>(numInstances);
751 Dispatch(primitive, firstVertex, numVertices);
752 }
753 void PvrDevice::DrawElements(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t baseVertex)
754 {
755 static_cast<void>(indexFormat);
756 static_cast<void>(indexOffset);
757 Dispatch(primitive, baseVertex, std::int32_t(numIndices));
758 }
759 void PvrDevice::DrawElementsInstanced(PrimitiveType primitive, std::uint32_t numIndices, IndexFormat indexFormat, std::uintptr_t indexOffset, std::int32_t numInstances, std::int32_t baseVertex)
760 {
761 static_cast<void>(indexFormat);
762 static_cast<void>(indexOffset);
763 static_cast<void>(numInstances);
764 Dispatch(primitive, baseVertex, std::int32_t(numIndices));
765 }
766
767 FenceHandle PvrDevice::InsertFence()
768 {
769 return reinterpret_cast<FenceHandle>(std::uintptr_t(1));
770 }
771 void PvrDevice::DeleteFence(FenceHandle& fence)
772 {
773 fence = nullptr;
774 }
775 bool PvrDevice::ClientWaitFence(FenceHandle fence, std::uint64_t timeoutNs)
776 {
777 static_cast<void>(fence);
778 static_cast<void>(timeoutNs);
779 return true;
780 }
781
782 void PvrDevice::SetupInitialState()
783 {
784 _blending = BlendingState();
785 _depthTest = DepthTestState();
786 _cullFace = CullFaceState();
787 _scissor = ScissorState();
788 }
789
790 // ------------------------------------------------------------------ extensions
791
792 void PvrDevice::BindProgram(PvrShaderProgram* program) { _currentProgram = program; }
793 PvrShaderProgram* PvrDevice::CurrentProgram() { return _currentProgram; }
794
795 void PvrDevice::BindTexture(std::uint32_t unit, const PvrTexture* texture)
796 {
797 if (unit < MaxTextureUnits) {
798 _boundTextures[unit] = texture;
799 }
800 }
801
802 void PvrDevice::UnbindTexture(const PvrTexture* texture)
803 {
804 for (std::uint32_t i = 0; i < MaxTextureUnits; i++) {
805 if (_boundTextures[i] == texture) {
806 _boundTextures[i] = nullptr;
807 }
808 }
809 if (_paletteTexture == texture) {
810 _paletteTexture = nullptr;
811 }
812 // Drop palette banks built from the destroyed palette so a stale pointer can never match
813 for (std::uint32_t i = 0; i < MaxPaletteBanks; i++) {
814 if (_paletteBanks[i].Palette == texture) {
815 _paletteBanks[i].PaletteOffset = -1;
816 _paletteBanks[i].Palette = nullptr;
817 }
818 }
819 }
820
821 const PvrTexture* PvrDevice::GetBoundTexture(std::uint32_t unit)
822 {
823 return (unit < MaxTextureUnits ? _boundTextures[unit] : nullptr);
824 }
825
826 void PvrDevice::BindUniformRange(std::uint32_t index, const std::uint8_t* data, std::uint32_t size)
827 {
828 if (index < MaxUniformBindings) {
829 _boundUniformRanges[index].Data = data;
830 _boundUniformRanges[index].Size = size;
831 }
832 }
833
834 void PvrDevice::SetRenderTarget(PvrRenderTarget* renderTarget)
835 {
836 // The scene state machine reacts lazily at the next draw (EnsureScene); an in-flight scene for a
837 // different target is finished there
838 _currentRenderTarget = renderTarget;
839 }
840
841 void PvrDevice::UnbindRenderTarget(const PvrRenderTarget* renderTarget)
842 {
843 if (_currentRenderTarget == renderTarget) {
844 _currentRenderTarget = nullptr;
845 }
846 if (_sceneRenderTarget == renderTarget) {
847 FinishScene();
848 }
849 }
850
851 // ------------------------------------------------------------------ palette banks
852
853 void PvrDevice::RegisterPaletteTexture(PvrTexture* texture)
854 {
855 _paletteTexture = texture;
856 NotifyPaletteTextureChanged(texture, 0, texture != nullptr ? texture->GetHeight() : 0);
857 }
858
859 void PvrDevice::NotifyPaletteTextureChanged(PvrTexture* texture, std::int32_t firstRow, std::int32_t rowCount)
860 {
861 if (texture != _paletteTexture) {
862 return;
863 }
864 _paletteGeneration++;
865 for (std::uint32_t i = 0; i < MaxPaletteBanks; i++) {
866 if (_paletteBanks[i].PaletteOffset >= (firstRow - 1) * 256 && _paletteBanks[i].PaletteOffset < (firstRow + rowCount) * 256) {
867 _paletteBanks[i].PaletteOffset = -1;
868 }
869 }
870 }
871
872 std::int32_t PvrDevice::AcquirePaletteBankForRow(const PvrTexture* palette, std::int32_t paletteOffset)
873 {
874 // The offset is a flat index into the palette texture and does not need to be row-aligned
875 // (e.g. the gem gradients pack two palettes into a single 256-entry row). The palette is usually
876 // the registered global one, but effects like the profile character previews bind their own
877 // recolored palette texture instead.
878 const std::int32_t maxOffset = palette != nullptr
879 ? palette->GetWidth() * palette->GetHeight() - 256 : 0;
880 if (palette == nullptr || palette->GetPixels() == nullptr ||
881 paletteOffset < 0 || paletteOffset > maxOffset) {
882 return -1;
883 }
884
885 return AcquirePaletteBank(palette, paletteOffset, palette->GetContentVersion(),
886 reinterpret_cast<const std::uint32_t*>(palette->GetPixels()) + paletteOffset);
887 }
888
889 std::int32_t PvrDevice::AcquirePaletteBank(const PvrTexture* palette, std::int32_t paletteOffset,
890 std::uint32_t version, const std::uint32_t* entries)
891 {
892 if (palette == nullptr || entries == nullptr) {
893 return -1;
894 }
895
896 _paletteUseCounter++;
897
898 std::int32_t bank = -1;
899 std::uint32_t oldestUse = UINT32_MAX;
900 std::int32_t oldestBank = 0;
901 for (std::uint32_t i = 0; i < MaxPaletteBanks; i++) {
902 if (_paletteBanks[i].PaletteOffset == paletteOffset && _paletteBanks[i].Palette == palette &&
903 _paletteBanks[i].PaletteVersion == version) {
904 bank = std::int32_t(i);
905 break;
906 }
907 if (_paletteBanks[i].LastUse < oldestUse) {
908 oldestUse = _paletteBanks[i].LastUse;
909 oldestBank = std::int32_t(i);
910 }
911 }
912
913 if (bank < 0) {
914 bank = oldestBank;
915 for (std::int32_t i = 0; i < 256; i++) {
916 const std::uint32_t rgba = entries[i];
917 pvr_set_pal_entry(std::uint32_t(bank) * 256 + std::uint32_t(i),
918 PackArgb(std::uint8_t(rgba & 0xFF), std::uint8_t((rgba >> 8) & 0xFF),
919 std::uint8_t((rgba >> 16) & 0xFF), std::uint8_t((rgba >> 24) & 0xFF)));
920 }
921 _paletteBanks[bank].PaletteOffset = paletteOffset;
922 _paletteBanks[bank].Palette = palette;
923 _paletteBanks[bank].PaletteVersion = version;
924 }
925
926 _paletteBanks[bank].LastUse = _paletteUseCounter;
927 return bank;
928 }
929
930 // ------------------------------------------------------------------ lighting hook
931
932 void PvrDevice::SetPendingSoftwareLighting(const float* lightmap, std::int32_t lmW, std::int32_t lmH, std::int32_t scale,
933 std::int32_t vpX, std::int32_t vpY, std::int32_t vpW, std::int32_t vpH, float ambR, float ambG, float ambB,
934 bool waterActive, float waterLevelPx, float waterTime, float waterCamY)
935 {
936 PendingSoftwareLight light;
937 light.Lightmap = lightmap;
938 light.LmW = lmW;
939 light.LmH = lmH;
940 light.Scale = (scale > 0 ? scale : 1);
941 light.VpX = vpX;
942 light.VpY = vpY;
943 light.VpW = vpW;
944 light.VpH = vpH;
945 light.AmbR = ambR;
946 light.AmbG = ambG;
947 light.AmbB = ambB;
948 light.WaterActive = waterActive;
949 light.WaterLevelPx = waterLevelPx;
950 light.WaterTime = waterTime;
951 light.WaterCamY = waterCamY;
952 _pendingSoftwareLights.push_back(light);
953 }
954
955 void PvrDevice::EndFrame()
956 {
957 if (!_pendingSoftwareLights.empty()) {
958 static bool warnedLeftoverLights = false;
959 if (!warnedLeftoverLights) {
960 warnedLeftoverLights = true;
961 LOGW("Dropping {} unconsumed software-lighting entries", _pendingSoftwareLights.size());
962 }
963 _pendingSoftwareLights.clear();
964 }
965 }
966
967 void PvrDevice::ApplyPendingSoftwareLighting()
968 {
969 if (_pendingSoftwareLights.empty()) {
970 return;
971 }
972 const PendingSoftwareLight light = _pendingSoftwareLights.front();
973 _pendingSoftwareLights.erase(_pendingSoftwareLights.begin());
974
975 const bool hasLighting = (light.Lightmap != nullptr && light.LmW > 0 && light.LmH > 0);
976 const bool hasWater = light.WaterActive;
977 if (!hasLighting && !hasWater) {
978 return;
979 }
980
981 EnsureScene();
982 if (_sceneTarget == SceneTarget::None) {
983 return;
984 }
985 float scaleX, scaleY, offsetX, offsetY;
986 GetTargetScale(scaleX, scaleY, offsetX, offsetY);
987 const float vpX = float(light.VpX) * scaleX, vpY = float(light.VpY) * scaleY;
988 const float vpW = float(light.VpW) * scaleX, vpH = float(light.VpH) * scaleY;
989
990 if (hasLighting) {
991 // Multiply factor from the CPU lightmap: out ≈ scene * (r*(1+g) + amb*(1-r)) per channel (the
992 // multiply-only approximation shared with the GX backend), as an ARGB4444 texture drawn with a
993 // dst * src blend over the viewport
994 std::int32_t texW = 8, texH = 8;
995 while (texW < light.LmW && texW < 1024) texW <<= 1;
996 while (texH < light.LmH && texH < 1024) texH <<= 1;
997 const std::size_t size = std::size_t(texW) * std::size_t(texH) * 2;
998 bool layoutChanged = (_lightmapW != texW || _lightmapH != texH);
999 if (_lightmapVram == nullptr || _lightmapVramSize < size) {
1000 if (_lightmapVram != nullptr) {
1001 pvr_mem_free(_lightmapVram);
1002 }
1003 _lightmapVram = pvr_mem_malloc(size);
1004 _lightmapVramSize = size;
1005 layoutChanged = true;
1006 }
1007 if (_lightmapVram != nullptr) {
1008 _lightmapW = texW;
1009 _lightmapH = texH;
1010 // The factors are written straight into video memory as a non-twiddled surface. This is a
1011 // single screen-aligned quad, so the interleaved texel order would buy nothing at sampling
1012 // time while costing a full twiddling pass (plus a same-sized staging copy) every frame -
1013 // the same trade-off the sprite uploads make in PvrTexture::RefreshVramStore().
1014 std::uint16_t* const surface = static_cast<std::uint16_t*>(_lightmapVram);
1015 if (layoutChanged) {
1016 // Only the used LmW x LmH region is rewritten per frame; the padding is sampled through
1017 // the compensated texture coordinates only at the very edge, and is filled just once.
1018 // Spelled out as word stores - video memory only takes 16/32-bit accesses, and libc
1019 // memset does not guarantee that (the size is always a multiple of four here)
1020 std::uint32_t* DEATH_RESTRICT fill = reinterpret_cast<std::uint32_t*>(surface);
1021 for (std::size_t i = 0, n = size / 4; i < n; i++) {
1022 fill[i] = 0xFFFFFFFFu;
1023 }
1024 }
1025 for (std::int32_t y = 0; y < light.LmH; y++) {
1026 const float* DEATH_RESTRICT src = light.Lightmap + std::size_t(y) * light.LmW * 2;
1027 std::uint16_t* DEATH_RESTRICT dst = surface + std::size_t(y) * texW;
1028 // Unlit runs repeat the same pair of factors across long spans, so remembering the last
1029 // converted texel turns most of the surface into a compare and a store
1030 float prevR = -1.0f, prevG = -1.0f;
1031 std::uint16_t prevTexel = 0;
1032 for (std::int32_t x = 0; x < light.LmW; x++) {
1033 const float rawR = src[x * 2];
1034 const float rawG = src[x * 2 + 1];
1035 if (rawR == prevR && rawG == prevG) {
1036 dst[x] = prevTexel;
1037 continue;
1038 }
1039 prevR = rawR;
1040 prevG = rawG;
1041 const float r = (rawR < 0.0f ? 0.0f : (rawR > 1.0f ? 1.0f : rawR));
1042 const float g = (rawG < 0.0f ? 0.0f : (rawG > 1.0f ? 1.0f : rawG));
1043 const float lit = r * (1.0f + g);
1044 const float inv = 1.0f - r;
1045 const std::uint32_t fr = Quantize4Bit(lit + light.AmbR * inv);
1046 const std::uint32_t fg = Quantize4Bit(lit + light.AmbG * inv);
1047 const std::uint32_t fb = Quantize4Bit(lit + light.AmbB * inv);
1048 prevTexel = std::uint16_t(0xF000 | (fr << 8) | (fg << 4) | fb);
1049 dst[x] = prevTexel;
1050 }
1051 }
1052
1053 pvr_poly_cxt_t cxt;
1054 pvr_poly_cxt_txr(&cxt, PVR_LIST_TR_POLY, PVR_TXRFMT_ARGB4444 | PVR_TXRFMT_NONTWIDDLED,
1055 texW, texH, _lightmapVram, PVR_FILTER_BILINEAR);
1056 cxt.gen.culling = PVR_CULLING_NONE;
1057 cxt.depth.comparison = PVR_DEPTHCMP_ALWAYS;
1058 cxt.depth.write = PVR_DEPTHWRITE_DISABLE;
1059 cxt.blend.src = PVR_BLEND_DESTCOLOR; // out = dst * src
1060 cxt.blend.dst = PVR_BLEND_ZERO;
1061 pvr_poly_hdr_t hdr;
1062 pvr_poly_compile(&hdr, &cxt);
1063
1064 // The lightmap's row 0 corresponds to the bottom of the displayed viewport (the software
1065 // buffer convention), so V runs (used/texH) -> 0 top -> bottom
1066 const float uMax = float(light.LmW) / float(texW);
1067 const float vMax = float(light.LmH) / float(texH);
1068 const float px[4] = { vpX + vpW, vpX + vpW, vpX, vpX };
1069 const float py[4] = { vpY, vpY + vpH, vpY, vpY + vpH };
1070 const float pu[4] = { uMax, uMax, 0.0f, 0.0f };
1071 const float pv[4] = { vMax, 0.0f, vMax, 0.0f };
1072 SubmitQuad(hdr, px, py, pu, pv, PackArgb(255, 255, 255, 255));
1073 }
1074 }
1075
1076 if (hasWater) {
1077 // Water v1: constant underwater tint band + above-deep-water darkening (shared with GX)
1078 pvr_poly_cxt_t cxt;
1079 pvr_poly_cxt_col(&cxt, PVR_LIST_TR_POLY);
1080 cxt.gen.culling = PVR_CULLING_NONE;
1081 cxt.depth.comparison = PVR_DEPTHCMP_ALWAYS;
1082 cxt.depth.write = PVR_DEPTHWRITE_DISABLE;
1083 cxt.blend.src = PVR_BLEND_SRCALPHA;
1084 cxt.blend.dst = PVR_BLEND_INVSRCALPHA;
1085 pvr_poly_hdr_t hdr;
1086 pvr_poly_compile(&hdr, &cxt);
1087
1088 const float waterTop = vpY + light.WaterLevelPx * scaleY;
1089 const float uv[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
1090 if (waterTop < vpY + vpH) {
1091 const float px[4] = { vpX + vpW, vpX + vpW, vpX, vpX };
1092 const float py[4] = { waterTop, vpY + vpH, waterTop, vpY + vpH };
1093 SubmitQuad(hdr, px, py, uv, uv, PackArgb(102, 153, 204, 102));
1094 }
1095 const float waterLevelNorm = (light.VpH > 0 ? light.WaterLevelPx / float(light.VpH) : 1.0f);
1096 if (waterLevelNorm < 0.4f && waterTop > vpY) {
1097 const std::uint8_t a = QuantizeChannel(0.4f - waterLevelNorm);
1098 const float px[4] = { vpX + vpW, vpX + vpW, vpX, vpX };
1099 const float py[4] = { vpY, waterTop, vpY, waterTop };
1100 SubmitQuad(hdr, px, py, uv, uv,
1101 PackArgb(QuantizeChannel(light.AmbR), QuantizeChannel(light.AmbG), QuantizeChannel(light.AmbB), a));
1102 }
1103 }
1104 }
1105
1106 // ------------------------------------------------------------------ draw dispatch
1107
1108 void PvrDevice::DispatchTileMesh(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices)
1109 {
1110 // A tile-layer mesh is a plain triangle list of 8-float vertices (position.xy, texcoords.uv,
1111 // color.rgba) - the layout TileMap::AppendTileQuad() writes and TileMapVs.inc declares. It is a
1112 // hard contract of this shader family exactly like the std140 instance block is of the sprite one.
1113 constexpr std::int32_t FloatsPerVertex = 8;
1114 if (primitive != PrimitiveType::Triangles || numVertices < 3) {
1115 return;
1116 }
1117
1118 const PvrBuffer* vbo = _currentProgram->GetBoundVbo();
1119 if (vbo == nullptr) {
1120 return;
1121 }
1122 const std::size_t firstFloat = (std::size_t(_currentProgram->GetBoundVboOffset()) / sizeof(float)) +
1123 std::size_t(firstVertex) * FloatsPerVertex;
1124 const std::size_t floatCount = std::size_t(numVertices) * FloatsPerVertex;
1125 if ((firstFloat + floatCount) * sizeof(float) > vbo->GetSize()) {
1126 return;
1127 }
1128 const float* DEATH_RESTRICT vertices = reinterpret_cast<const float*>(vbo->HostData()) + firstFloat;
1129
1130 const PvrUniformBlock* block = _currentProgram->FindBlock("InstanceBlock");
1131 if (block == nullptr) {
1132 return;
1133 }
1134 std::int32_t binding = block->GetBindingIndex();
1135 if (binding < 0 || std::uint32_t(binding) >= MaxUniformBindings) {
1136 binding = 0;
1137 }
1138 const std::uint8_t* blockData = _boundUniformRanges[binding].Data;
1139 if (blockData == nullptr) {
1140 return;
1141 }
1142
1143 PvrTexture* texture = const_cast<PvrTexture*>(_boundTextures[0]);
1144 if (texture == nullptr) {
1145 return;
1146 }
1147
1148 const std::uint8_t* projBytes = _currentProgram->GetResolvedProjection();
1149 const std::uint8_t* viewBytes = _currentProgram->GetResolvedView();
1150 const float* projMat = (projBytes != nullptr ? reinterpret_cast<const float*>(projBytes) : IdentityMatrix);
1151 const float* viewMat = (viewBytes != nullptr ? reinterpret_cast<const float*>(viewBytes) : IdentityMatrix);
1152 float pv[16];
1153 Mat4Mul(projMat, viewMat, pv);
1154 Transform2D mvp;
1155 Mat4MulTransform2D(pv, reinterpret_cast<const float*>(blockData + kModelMatrixOffset), mvp);
1156
1157 // The layer tint modulates every vertex colour, which already carries the per-tile alpha
1158 float layerColor[4];
1159 std::memcpy(layerColor, blockData + kColorOffset, sizeof(layerColor));
1160
1161 // The palette to remap with is whatever the material bound to the palette sampler; the registered
1162 // global palette is the fallback (mirrors the sprite path). TileMapMeshPalette binds
1163 // uTexturePalette in its reflection, which is exactly what UsesPalette() reports - the remap
1164 // intent needs no effect identity of its own.
1165 const bool isPaletteRemap = _currentProgram->UsesPalette();
1166 const PvrTexture* paletteTex = nullptr;
1167 if (isPaletteRemap || texture->IsIndexed()) {
1168 paletteTex = _boundTextures[1];
1169 if (paletteTex == nullptr || paletteTex == texture) {
1170 paletteTex = _paletteTexture;
1171 }
1172 }
1173
1174 // Unlike a sprite batch, the whole mesh shares one texture and one palette offset, so the texture
1175 // residency, the palette bank and the polygon header are resolved once for the entire layer
1176 pvr_ptr_t vram = nullptr;
1177 std::uint32_t format = 0;
1178 if (texture->IsIndexed()) {
1179 // An 8bpp store can only be read through a palette, whatever it is being drawn with - the lookup
1180 // belongs to the texture read rather than to the effect. An effect that remaps takes the row from
1181 // the instance; anything else (the fonts, which are palette indices too) uses the base row.
1182 std::int32_t paletteOffset = 0;
1183 if (isPaletteRemap) {
1184 float palOffset = 0.0f;
1185 std::memcpy(&palOffset, blockData + kPaletteOffsetOffset, sizeof(palOffset));
1186 paletteOffset = std::int32_t(palOffset + 0.5f);
1187 }
1188 std::int32_t bank = AcquirePaletteBankForRow(paletteTex, paletteOffset);
1189 if (bank < 0) {
1190 bank = 0;
1191 }
1192 vram = texture->AcquireVramPointer();
1193 format = texture->GetVramFormat() | PVR_TXRFMT_8BPP_PAL(std::uint32_t(bank));
1194 } else if (isPaletteRemap && texture->NeedsPaletteBake() && paletteTex != nullptr && paletteTex->GetPixels() != nullptr) {
1195 float palOffset = 0.0f;
1196 std::memcpy(&palOffset, blockData + kPaletteOffsetOffset, sizeof(palOffset));
1197 const std::uint32_t paletteOffset = std::uint32_t(std::int32_t(palOffset + 0.5f));
1198 const std::uint32_t* entries = reinterpret_cast<const std::uint32_t*>(paletteTex->GetPixels()) + paletteOffset;
1199 vram = texture->EnsureBakedArgb4444(entries, paletteOffset,
1200 (paletteTex == _paletteTexture ? _paletteGeneration : paletteTex->GetContentVersion()), paletteTex);
1201 format = PVR_TXRFMT_ARGB4444 | PVR_TXRFMT_TWIDDLED;
1202 } else {
1203 vram = texture->AcquireVramPointer();
1204 format = texture->GetVramFormat();
1205 }
1206 if (vram == nullptr) {
1207 return;
1208 }
1209
1210 EnsureScene();
1211 if (_sceneTarget == SceneTarget::None) {
1212 return;
1213 }
1214
1215 const Recti viewport = (_viewport.W > 0 && _viewport.H > 0)
1216 ? _viewport : Recti(0, 0, _logicalWidth, _logicalHeight);
1217 float scaleX, scaleY, offsetX, offsetY;
1218 GetTargetScale(scaleX, scaleY, offsetX, offsetY);
1219 const bool screenPass = (_currentRenderTarget == nullptr);
1220 const float uvScaleU = texture->GetUScale();
1221 const float uvScaleV = texture->GetVScale();
1222
1223 pvr_poly_cxt_t cxt;
1224 pvr_poly_cxt_txr(&cxt, PVR_LIST_TR_POLY, int(format), texture->GetPaddedWidth(), texture->GetPaddedHeight(),
1225 vram, (texture->GetMagFilter() == nCine::SamplerFilter::Linear ? PVR_FILTER_BILINEAR : PVR_FILTER_NEAREST));
1226 cxt.gen.culling = PVR_CULLING_NONE;
1227 cxt.depth.comparison = PVR_DEPTHCMP_ALWAYS;
1228 cxt.depth.write = PVR_DEPTHWRITE_DISABLE;
1229 cxt.blend.src = (_blending.Enabled ? pvr_blend_mode_t(MapBlendPvr(_blending.SrcRgb)) : PVR_BLEND_ONE);
1230 cxt.blend.dst = (_blending.Enabled ? pvr_blend_mode_t(MapBlendPvr(_blending.DstRgb)) : PVR_BLEND_ZERO);
1231 cxt.txr.env = PVR_TXRENV_MODULATEALPHA;
1232 pvr_poly_hdr_t hdr;
1233 pvr_poly_compile(&hdr, &cxt);
1234
1235 const bool clipActive = (_scissor.Enabled && screenPass);
1236 float clipX0 = 0.0f, clipY0 = 0.0f, clipX1 = 0.0f, clipY1 = 0.0f;
1237 if (clipActive) {
1238 clipX0 = float(_scissor.Rect.X) * scaleX + offsetX;
1239 clipY0 = float(_scissor.Rect.Y) * scaleY + offsetY;
1240 clipX1 = float(_scissor.Rect.X + _scissor.Rect.W) * scaleX + offsetX;
1241 clipY1 = float(_scissor.Rect.Y + _scissor.Rect.H) * scaleY + offsetY;
1242 }
1243
1244 // Projects one mesh vertex into raster space, matching the sprite path's corner synthesis
1245 // The NDC-to-raster mapping is affine and constant for the whole mesh, so it is folded into the
1246 // transform once instead of being reapplied per vertex - every vertex then costs one multiply-add
1247 // per axis. A screen pass mirrors NDC, which is just the sign of the Y scale (see below).
1248 const float rasterScaleX = 0.5f * float(viewport.W) * scaleX;
1249 const float rasterBiasX = rasterScaleX + float(viewport.X) * scaleX + offsetX;
1250 const float rasterScaleY = 0.5f * float(viewport.H) * scaleY * (screenPass ? 1.0f : -1.0f);
1251 const float rasterBiasY = 0.5f * float(viewport.H) * scaleY + float(viewport.Y) * scaleY + offsetY;
1252 const Transform2D raster = {
1253 mvp.Xx * rasterScaleX, mvp.Xy * rasterScaleY,
1254 mvp.Yx * rasterScaleX, mvp.Yy * rasterScaleY,
1255 mvp.Tx * rasterScaleX + rasterBiasX, mvp.Ty * rasterScaleY + rasterBiasY
1256 };
1257
1258 auto project = [&](const float* v, float& outX, float& outY, float& outU, float& outV) {
1259 outX = raster.Xx * v[0] + raster.Yx * v[1] + raster.Tx;
1260 outY = raster.Xy * v[0] + raster.Yy * v[1] + raster.Ty;
1261 outU = v[2] * uvScaleU;
1262 outV = v[3] * uvScaleV;
1263 };
1264
1265 const std::int32_t triangleCount = numVertices / 3;
1266 std::int32_t triangle = 0;
1267 // Virtually every tile of a layer carries the same colour (white at the layer's alpha), so the
1268 // four clamp+float-to-int quantizations run once per change instead of once per tile
1269 float lastColor[4] = { -1.0f, -1.0f, -1.0f, -1.0f };
1270 std::uint32_t lastArgb = 0;
1271 while (triangle < triangleCount) {
1272 // Tiles reach here as the six vertices of two triangles, of which the third and fourth repeat
1273 // the first and third. Recognizing that pattern lets a tile go out as a single four-vertex
1274 // strip rather than two three-vertex ones, which is a third less vertex traffic and half the
1275 // polygon headers. Anything that doesn't match is emitted as plain triangles.
1276 const float* group = vertices + std::size_t(triangle) * 3 * FloatsPerVertex;
1277 const bool isQuad = (triangle + 2 <= triangleCount &&
1278 group[3 * FloatsPerVertex + 0] == group[0] && group[3 * FloatsPerVertex + 1] == group[1] &&
1279 group[4 * FloatsPerVertex + 0] == group[2 * FloatsPerVertex + 0] &&
1280 group[4 * FloatsPerVertex + 1] == group[2 * FloatsPerVertex + 1]);
1281
1282 float px[4], py[4], pu[4], pvv[4];
1283 std::int32_t cornerCount;
1284 if (isQuad) {
1285 // Strip order (see SubmitQuad): the two corners of one edge, then the two of the opposite
1286 // one - vertices 1, 2, 0 and 5 of the tile's six
1287 static const std::int32_t QuadOrder[4] = { 1, 2, 0, 5 };
1288 for (std::int32_t i = 0; i < 4; i++) {
1289 project(group + std::size_t(QuadOrder[i]) * FloatsPerVertex, px[i], py[i], pu[i], pvv[i]);
1290 }
1291 cornerCount = 4;
1292 triangle += 2;
1293 } else {
1294 for (std::int32_t i = 0; i < 3; i++) {
1295 project(group + std::size_t(i) * FloatsPerVertex, px[i], py[i], pu[i], pvv[i]);
1296 }
1297 cornerCount = 3;
1298 triangle++;
1299 }
1300
1301 if (clipActive) {
1302 // The bounding-box reject is exact for the fully outside case
1303 float minX = px[0], maxX = px[0], minY = py[0], maxY = py[0];
1304 for (std::int32_t i = 1; i < cornerCount; i++) {
1305 minX = std::min(minX, px[i]); maxX = std::max(maxX, px[i]);
1306 minY = std::min(minY, py[i]); maxY = std::max(maxY, py[i]);
1307 }
1308 if (maxX <= clipX0 || minX >= clipX1 || maxY <= clipY0 || minY >= clipY1) {
1309 continue;
1310 }
1311 // A tile straddling the scissor edge is clipped exactly like the sprite path clips its
1312 // axis-aligned quads: there is no hardware scissor on this tier, and on the splitscreen
1313 // boundary an unclipped tile would draw up to a full tile into the other player's viewport.
1314 // The corner-sharing test mirrors the sprite path; anything else (the raw-triangle fallback,
1315 // a rotated layer) keeps the conservative bounding-box reject above.
1316 if (cornerCount == 4 && px[0] == px[1] && px[2] == px[3] && py[0] == py[2] && py[1] == py[3]) {
1317 float xA = px[2], xB = px[0], uA = pu[2], uB = pu[0];
1318 if (!ClipQuadEdge(xA, xB, uA, uB, clipX0, clipX1)) {
1319 continue;
1320 }
1321 px[2] = px[3] = xA; px[0] = px[1] = xB;
1322 pu[2] = pu[3] = uA; pu[0] = pu[1] = uB;
1323 float yA = py[0], yB = py[1], vA = pvv[0], vB = pvv[1];
1324 if (!ClipQuadEdge(yA, yB, vA, vB, clipY0, clipY1)) {
1325 continue;
1326 }
1327 py[0] = py[2] = yA; py[1] = py[3] = yB;
1328 pvv[0] = pvv[2] = vA; pvv[1] = pvv[3] = vB;
1329 }
1330 }
1331
1332 // Every vertex of a tile carries the same colour, so it only has to be packed once per change
1333 if (group[4] != lastColor[0] || group[5] != lastColor[1] || group[6] != lastColor[2] || group[7] != lastColor[3]) {
1334 lastColor[0] = group[4]; lastColor[1] = group[5]; lastColor[2] = group[6]; lastColor[3] = group[7];
1335 lastArgb = PackArgb(QuantizeChannel(group[4] * layerColor[0]),
1336 QuantizeChannel(group[5] * layerColor[1]), QuantizeChannel(group[6] * layerColor[2]),
1337 QuantizeChannel(group[7] * layerColor[3]));
1338 }
1339 SubmitStrip(hdr, px, py, pu, pvv, cornerCount, lastArgb);
1340 }
1341 }
1342
1343 void PvrDevice::DispatchLineStrip(std::int32_t firstVertex, std::int32_t numVertices)
1344 {
1345 // The weapon wheel arrives as a textured line strip of 4-float vertices (position.xy,
1346 // texcoords.uv) - the layout the MeshSprite shader's attributes declare. The tile accelerator
1347 // has no line primitive, so every segment goes out as a quad half a pixel to each side of the
1348 // line, which is what the 1-wide GL lines this stands in for rasterize to.
1349 constexpr std::int32_t FloatsPerVertex = 4;
1350 if (numVertices < 2) {
1351 return;
1352 }
1353
1354 const PvrBuffer* vbo = _currentProgram->GetBoundVbo();
1355 if (vbo == nullptr) {
1356 return;
1357 }
1358 const std::size_t firstFloat = (std::size_t(_currentProgram->GetBoundVboOffset()) / sizeof(float)) +
1359 std::size_t(firstVertex) * FloatsPerVertex;
1360 const std::size_t floatCount = std::size_t(numVertices) * FloatsPerVertex;
1361 if ((firstFloat + floatCount) * sizeof(float) > vbo->GetSize()) {
1362 return;
1363 }
1364 const float* DEATH_RESTRICT vertices = reinterpret_cast<const float*>(vbo->HostData()) + firstFloat;
1365
1366 const PvrUniformBlock* block = _currentProgram->FindBlock("InstanceBlock");
1367 if (block == nullptr) {
1368 return;
1369 }
1370 std::int32_t binding = block->GetBindingIndex();
1371 if (binding < 0 || std::uint32_t(binding) >= MaxUniformBindings) {
1372 binding = 0;
1373 }
1374 const std::uint8_t* blockData = _boundUniformRanges[binding].Data;
1375 if (blockData == nullptr) {
1376 return;
1377 }
1378
1379 PvrTexture* texture = const_cast<PvrTexture*>(_boundTextures[0]);
1380 if (texture == nullptr) {
1381 return;
1382 }
1383
1384 const std::uint8_t* projBytes = _currentProgram->GetResolvedProjection();
1385 const std::uint8_t* viewBytes = _currentProgram->GetResolvedView();
1386 const float* projMat = (projBytes != nullptr ? reinterpret_cast<const float*>(projBytes) : IdentityMatrix);
1387 const float* viewMat = (viewBytes != nullptr ? reinterpret_cast<const float*>(viewBytes) : IdentityMatrix);
1388 float pv[16];
1389 Mat4Mul(projMat, viewMat, pv);
1390 Transform2D mvp;
1391 Mat4MulTransform2D(pv, reinterpret_cast<const float*>(blockData + kModelMatrixOffset), mvp);
1392
1393 // Every vertex of the strip carries the instance colour, so it is packed once
1394 float color[4];
1395 std::memcpy(color, blockData + kColorOffset, sizeof(color));
1396 const std::uint32_t argb = PackArgb(QuantizeChannel(color[0]), QuantizeChannel(color[1]),
1397 QuantizeChannel(color[2]), QuantizeChannel(color[3]));
1398
1399 // The strip shares one texture, so residency (with the palette bank for indexed assets, which
1400 // use the base row like the fonts do) and the polygon header are resolved once
1401 pvr_ptr_t vram = nullptr;
1402 std::uint32_t format = 0;
1403 if (texture->IsIndexed()) {
1404 const PvrTexture* paletteTex = _boundTextures[1];
1405 if (paletteTex == nullptr || paletteTex == texture) {
1406 paletteTex = _paletteTexture;
1407 }
1408 std::int32_t bank = AcquirePaletteBankForRow(paletteTex, 0);
1409 if (bank < 0) {
1410 bank = 0;
1411 }
1412 vram = texture->AcquireVramPointer();
1413 format = texture->GetVramFormat() | PVR_TXRFMT_8BPP_PAL(std::uint32_t(bank));
1414 } else {
1415 vram = texture->AcquireVramPointer();
1416 format = texture->GetVramFormat();
1417 }
1418 if (vram == nullptr) {
1419 return;
1420 }
1421
1422 EnsureScene();
1423 if (_sceneTarget == SceneTarget::None) {
1424 return;
1425 }
1426
1427 const Recti viewport = (_viewport.W > 0 && _viewport.H > 0)
1428 ? _viewport : Recti(0, 0, _logicalWidth, _logicalHeight);
1429 float scaleX, scaleY, offsetX, offsetY;
1430 GetTargetScale(scaleX, scaleY, offsetX, offsetY);
1431 const bool screenPass = (_currentRenderTarget == nullptr);
1432 const float uvScaleU = texture->GetUScale();
1433 const float uvScaleV = texture->GetVScale();
1434
1435 pvr_poly_cxt_t cxt;
1436 pvr_poly_cxt_txr(&cxt, PVR_LIST_TR_POLY, int(format), texture->GetPaddedWidth(), texture->GetPaddedHeight(),
1437 vram, (texture->GetMagFilter() == nCine::SamplerFilter::Linear ? PVR_FILTER_BILINEAR : PVR_FILTER_NEAREST));
1438 cxt.gen.culling = PVR_CULLING_NONE;
1439 cxt.depth.comparison = PVR_DEPTHCMP_ALWAYS;
1440 cxt.depth.write = PVR_DEPTHWRITE_DISABLE;
1441 cxt.blend.src = (_blending.Enabled ? pvr_blend_mode_t(MapBlendPvr(_blending.SrcRgb)) : PVR_BLEND_ONE);
1442 cxt.blend.dst = (_blending.Enabled ? pvr_blend_mode_t(MapBlendPvr(_blending.DstRgb)) : PVR_BLEND_ZERO);
1443 cxt.txr.env = PVR_TXRENV_MODULATEALPHA;
1444 // Match the desktop sampler's ClampToEdge (the engine's texture default): with the KOS default
1445 // wrap mode, the strip's V=0 bilinear fetch on the power-of-two-padded texture blends row 0
1446 // half-and-half with the zeroed bottom padding row, halving both the colour and the alpha of
1447 // the whole line (the weapon-wheel gradient is a 400x1 image padded to 512x8)
1448 cxt.txr.uv_clamp = PVR_UVCLAMP_UV;
1449 pvr_poly_hdr_t hdr;
1450 pvr_poly_compile(&hdr, &cxt);
1451
1452 const bool clipActive = (_scissor.Enabled && screenPass);
1453 float clipX0 = 0.0f, clipY0 = 0.0f, clipX1 = 0.0f, clipY1 = 0.0f;
1454 if (clipActive) {
1455 clipX0 = float(_scissor.Rect.X) * scaleX + offsetX;
1456 clipY0 = float(_scissor.Rect.Y) * scaleY + offsetY;
1457 clipX1 = float(_scissor.Rect.X + _scissor.Rect.W) * scaleX + offsetX;
1458 clipY1 = float(_scissor.Rect.Y + _scissor.Rect.H) * scaleY + offsetY;
1459 }
1460
1461 // The NDC-to-raster mapping is folded into the transform once, like the other mesh paths
1462 const float rasterScaleX = 0.5f * float(viewport.W) * scaleX;
1463 const float rasterBiasX = rasterScaleX + float(viewport.X) * scaleX + offsetX;
1464 const float rasterScaleY = 0.5f * float(viewport.H) * scaleY * (screenPass ? 1.0f : -1.0f);
1465 const float rasterBiasY = 0.5f * float(viewport.H) * scaleY + float(viewport.Y) * scaleY + offsetY;
1466 const Transform2D raster = {
1467 mvp.Xx * rasterScaleX, mvp.Xy * rasterScaleY,
1468 mvp.Yx * rasterScaleX, mvp.Yy * rasterScaleY,
1469 mvp.Tx * rasterScaleX + rasterBiasX, mvp.Ty * rasterScaleY + rasterBiasY
1470 };
1471
1472 const float pixelScale = std::max(scaleX, scaleY);
1473
1474 float prevX = raster.Xx * vertices[0] + raster.Yx * vertices[1] + raster.Tx;
1475 float prevY = raster.Xy * vertices[0] + raster.Yy * vertices[1] + raster.Ty;
1476 float prevU = vertices[2] * uvScaleU;
1477 float prevV = vertices[3] * uvScaleV;
1478 for (std::int32_t i = 1; i < numVertices; i++) {
1479 const float* v = vertices + std::size_t(i) * FloatsPerVertex;
1480 const float curX = raster.Xx * v[0] + raster.Yx * v[1] + raster.Tx;
1481 const float curY = raster.Xy * v[0] + raster.Yy * v[1] + raster.Ty;
1482 const float curU = v[2] * uvScaleU;
1483 const float curV = v[3] * uvScaleV;
1484
1485 const float dx = curX - prevX, dy = curY - prevY;
1486 const float len2 = dx * dx + dy * dy;
1487 if (len2 > 0.000001f) {
1488 const float len = std::sqrt(len2);
1489 // GL's line rasterization guarantees an unbroken one-pixel chain whatever the slope; a
1490 // quad exactly one pixel wide covers too few pixel centres on diagonals and the line
1491 // comes out dashed and dimmer. Widening by the slope's Manhattan factor (1 for axis
1492 // aligned, sqrt(2) at 45 degrees) restores the same continuous coverage.
1493 const float halfWidth = 0.5f * pixelScale * (std::abs(dx) + std::abs(dy)) / len;
1494 bool visible = true;
1495 if (clipActive) {
1496 // Segments are about a pixel wide, so a conservative reject is enough - exact
1497 // clipping could never make a visible difference
1498 const float minX = std::min(prevX, curX) - halfWidth, maxX = std::max(prevX, curX) + halfWidth;
1499 const float minY = std::min(prevY, curY) - halfWidth, maxY = std::max(prevY, curY) + halfWidth;
1500 visible = !(maxX <= clipX0 || minX >= clipX1 || maxY <= clipY0 || minY >= clipY1);
1501 }
1502 if (visible) {
1503 // Perpendicular of the segment, half a (slope-compensated) pixel long
1504 const float invLen = halfWidth / len;
1505 const float nx = -dy * invLen;
1506 const float ny = dx * invLen;
1507
1508 const float px[4] = { prevX + nx, prevX - nx, curX + nx, curX - nx };
1509 const float py[4] = { prevY + ny, prevY - ny, curY + ny, curY - ny };
1510 const float pu[4] = { prevU, prevU, curU, curU };
1511 const float pvv[4] = { prevV, prevV, curV, curV };
1512 SubmitQuad(hdr, px, py, pu, pvv, argb);
1513 }
1514 }
1515
1516 prevX = curX; prevY = curY; prevU = curU; prevV = curV;
1517 }
1518 }
1519
1520 void PvrDevice::Dispatch(PrimitiveType primitive, std::int32_t firstVertex, std::int32_t numVertices)
1521 {
1522 static_cast<void>(firstVertex);
1523 if (_currentProgram == nullptr || numVertices <= 0 || !_pvrInitialized) {
1524 return;
1525 }
1526
1527 // The program's whole console identity is its generated-table entry, resolved at load from the
1528 // true (program, variant) the loaders plumbed in - a program without an entry has no
1529 // fixed_function block in its .shader file (LightingMesh, Blur, the Resize* family,
1530 // runtime-compiled shaders, ...) and keeps the logged, skipped draw.
1531 const FixedFunctionGeneratedEffect* generated = _currentProgram->GetGeneratedEffect();
1532 if (generated == nullptr) {
1533 if (!_currentProgram->FetchUnsupportedWarned()) {
1534 LOGW("Skipping draws of program \"{}\": No fixed_function effect declared by the shader", _currentProgram->GetObjectLabel());
1535 }
1536 return;
1537 }
1538 const FixedFunctionIntrinsic intrinsic = generated->Intrinsic;
1539
1540 // The Combine draw is the direct-tier lighting hook (see the software backend)
1541 if (intrinsic == FixedFunctionIntrinsic::LightingCombine) {
1542 ApplyPendingSoftwareLighting();
1543 return;
1544 }
1545
1546 // A whole tile layer arrives as one mesh instead of one command per tile
1547 if (intrinsic == FixedFunctionIntrinsic::TileMapMesh) {
1548 DispatchTileMesh(primitive, firstVertex, numVertices);
1549 return;
1550 }
1551
1552 // The weapon wheel is the one vertex-fed mesh on this tier, a textured line strip
1553 if (intrinsic == FixedFunctionIntrinsic::LineStripMesh) {
1554 if (primitive == PrimitiveType::LineStrip) {
1555 DispatchLineStrip(firstVertex, numVertices);
1556 } else if (!_currentProgram->FetchUnsupportedWarned()) {
1557 LOGW("Skipping draws of program \"{}\": Only the line-strip form of the mesh pipeline is supported by the PVR dispatch", _currentProgram->GetObjectLabel());
1558 }
1559 return;
1560 }
1561
1562 // Everything else is the procedural sprite-quad family: a transpiled effect function
1563 // (geometry synthesis included - the iris and the warp are ordinary blocks since phase 4)
1564 const bool isQuadFamily = (generated->Fn != nullptr);
1565 if (!isQuadFamily || (primitive != PrimitiveType::TriangleStrip && primitive != PrimitiveType::Triangles)) {
1566 if (!_currentProgram->FetchUnsupportedWarned()) {
1567 LOGW("Skipping draws of program \"{}\": Effect not supported by the PVR dispatch", _currentProgram->GetObjectLabel());
1568 }
1569 return;
1570 }
1571
1572 const std::uint8_t* projBytes = _currentProgram->GetResolvedProjection();
1573 const std::uint8_t* viewBytes = _currentProgram->GetResolvedView();
1574 const float* projMat = (projBytes != nullptr ? reinterpret_cast<const float*>(projBytes) : IdentityMatrix);
1575 const float* viewMat = (viewBytes != nullptr ? reinterpret_cast<const float*>(viewBytes) : IdentityMatrix);
1576
1577 const PvrUniformBlock* block = _currentProgram->FindBlock("InstanceBlock");
1578 if (block == nullptr) {
1579 block = _currentProgram->FindBlock("InstancesBlock");
1580 }
1581 if (block == nullptr) {
1582 return;
1583 }
1584 std::int32_t binding = block->GetBindingIndex();
1585 if (binding < 0 || std::uint32_t(binding) >= MaxUniformBindings) {
1586 binding = 0;
1587 }
1588 const std::uint8_t* blockData = _boundUniformRanges[binding].Data;
1589 if (blockData == nullptr) {
1590 return;
1591 }
1592
1593 const ShaderCompiler::ProgramVariant* reflection = _currentProgram->GetReflection();
1594 auto samplerUnit = [reflection](const char* name, std::int32_t def) -> std::int32_t {
1595 if (reflection != nullptr) {
1596 for (std::size_t i = 0; i < reflection->TextureCount; i++) {
1597 if (std::strcmp(reflection->Textures[i].Name, name) == 0) {
1598 return (reflection->Textures[i].Unit >= 0 ? reflection->Textures[i].Unit : def);
1599 }
1600 }
1601 }
1602 return def;
1603 };
1604 std::uint32_t instanceStride = 0;
1605 if (reflection != nullptr) {
1606 for (std::size_t i = 0; i < reflection->BlockCount; i++) {
1607 if (reflection->Blocks[i].InstanceStride > 0) {
1608 instanceStride = reflection->Blocks[i].InstanceStride;
1609 break;
1610 }
1611 }
1612 }
1613
1614 float pv[16];
1615 Mat4Mul(projMat, viewMat, pv);
1616
1617 // Batched programs are exactly the ones whose reflection declares a BATCH_SIZE-strided
1618 // InstancesBlock (non-batched programs use a flat InstanceBlock with no stride), so the
1619 // reflected stride IS the batching signal - no per-program identity needed
1620 const bool batched = (instanceStride > 0);
1621 std::int32_t numInstances = 1;
1622 if (batched) {
1623 numInstances = numVertices / 6;
1624 if (numInstances < 1) {
1625 numInstances = 1;
1626 }
1627 if (instanceStride == 0) {
1628 instanceStride = 112;
1629 }
1630 }
1631
1632 // A program samples the sprite texture exactly when its reflection binds uTexture - the
1633 // no-texture sprite programs and the Transition (which carries texRect in its block but
1634 // samples nothing, hence the separate layout flag) simply do not declare it
1635 bool hasTexture = false;
1636 if (reflection != nullptr) {
1637 for (std::size_t i = 0; i < reflection->TextureCount; i++) {
1638 if (std::strcmp(reflection->Textures[i].Name, "uTexture") == 0) {
1639 hasTexture = true;
1640 break;
1641 }
1642 }
1643 }
1644 // The instance layout follows the block's own reflected declaration rather than any effect
1645 // identity: a block that declares texRect uses the textured member offsets whether or not
1646 // the program samples a texture (the Transition carries texRect but samples nothing)
1647 bool texturedLayout = hasTexture;
1648 if (!texturedLayout && reflection != nullptr) {
1649 for (std::size_t i = 0; i < reflection->BlockCount && !texturedLayout; i++) {
1650 const ShaderCompiler::UniformBlock& b = reflection->Blocks[i];
1651 for (std::size_t j = 0; j < b.MemberCount; j++) {
1652 if (std::strcmp(b.Members[j].Name, "texRect") == 0) {
1653 texturedLayout = true;
1654 break;
1655 }
1656 }
1657 }
1658 }
1659 // Every effect that samples indexed sprites through the palette texture binds uTexturePalette
1660 // in its reflection, which is what UsesPalette() reports (PaletteRemap and the "...Palette"
1661 // variants of the actor state effects alike)
1662 const bool isPaletteRemap = _currentProgram->UsesPalette();
1663
1664 // The offset colour is added after texturing only on polygons compiled with specular enabled,
1665 // which is a per-program property of the base material - so it comes from the generated
1666 // table's static analysis (does any pass of the effect write p.offset_color?), not from a pass
1667 const bool usesOffsetColor = generated->UsesOffsetColor;
1668 // Same static analysis, for the optional context facilities: the flags record exactly which
1669 // builtin families the transpiled function calls, so the setup that only feeds an uncalled
1670 // facility is skipped below. Skipping is invisible to the effect by construction - it cannot
1671 // read what it never calls - so every submitted primitive stays bit-identical.
1672 const FixedFunctionRequirements reqs = generated->Requirements;
1673 const bool needsTexelStep = ((reqs & FixedFunctionRequirements::NeedsTexelStep) == FixedFunctionRequirements::NeedsTexelStep);
1674 const bool needsUniforms = ((reqs & FixedFunctionRequirements::NeedsUniforms) == FixedFunctionRequirements::NeedsUniforms);
1675 const bool needsStripBuilder = ((reqs & FixedFunctionRequirements::NeedsStripBuilder) == FixedFunctionRequirements::NeedsStripBuilder);
1676 const bool needsQuadAxes = ((reqs & FixedFunctionRequirements::NeedsQuadAxes) == FixedFunctionRequirements::NeedsQuadAxes);
1677 const std::int32_t textureUnit = samplerUnit("uTexture", 0);
1678 PvrTexture* texture = const_cast<PvrTexture*>(hasTexture
1679 ? _boundTextures[std::uint32_t(textureUnit) < MaxTextureUnits ? textureUnit : 0] : nullptr);
1680 if (hasTexture && texture == nullptr) {
1681 return;
1682 }
1683
1684 // The palette to remap with is whatever the material bound to the palette sampler (e.g. the
1685 // recolored preview palettes of the profile menu); the registered global palette is the fallback
1686 const PvrTexture* paletteTex = nullptr;
1687 if (isPaletteRemap || (texture != nullptr && texture->IsIndexed())) {
1688 const std::int32_t paletteUnit = samplerUnit("uTexturePalette", 1);
1689 paletteTex = (std::uint32_t(paletteUnit) < MaxTextureUnits ? _boundTextures[paletteUnit] : nullptr);
1690 if (paletteTex == nullptr || paletteTex == texture) {
1691 paletteTex = _paletteTexture;
1692 }
1693 }
1694
1695 EnsureScene();
1696 if (_sceneTarget == SceneTarget::None) {
1697 return;
1698 }
1699
1700 // Bounds guard, mirroring the software device
1701 const std::uint32_t rangeSize = _boundUniformRanges[binding].Size;
1702 if (batched && rangeSize > 0 && std::uint32_t(numInstances) * instanceStride > rangeSize) {
1703 numInstances = std::int32_t(rangeSize / instanceStride);
1704 }
1705
1706 const Recti viewport = (_viewport.W > 0 && _viewport.H > 0)
1707 ? _viewport : Recti(0, 0, _logicalWidth, _logicalHeight);
1708 float scaleX, scaleY, offsetX, offsetY;
1709 GetTargetScale(scaleX, scaleY, offsetX, offsetY);
1710
1711 const std::int32_t blendSrc = (_blending.Enabled ? MapBlendPvr(_blending.SrcRgb) : PVR_BLEND_ONE);
1712 const std::int32_t blendDst = (_blending.Enabled ? MapBlendPvr(_blending.DstRgb) : PVR_BLEND_ZERO);
1713 const std::int32_t filter = (hasTexture && texture->GetMagFilter() == nCine::SamplerFilter::Linear
1714 ? PVR_FILTER_BILINEAR : PVR_FILTER_NEAREST);
1715
1716 // The build context outlives the compile so EffectContext::SubmitQuad can derive blend twins
1717 // (the additive passes of Colorized, an opaque pass) from the compiled base state on demand
1718 pvr_poly_cxt_t cxt;
1719 pvr_poly_hdr_t hdr;
1720 bool hdrValid = false;
1721 pvr_ptr_t lastVram = nullptr;
1722 std::int32_t lastBank = -2;
1723 // Blend twins of the same polygon, compiled lazily for effects that build their result out
1724 // of several differently blended passes
1725 pvr_poly_hdr_t hdrAdditive;
1726 bool hdrAdditiveValid = false;
1727 pvr_poly_hdr_t hdrOpaque;
1728 bool hdrOpaqueValid = false;
1729 pvr_poly_hdr_t hdrAlpha;
1730 bool hdrAlphaValid = false;
1731 // Colour-polygon twins for shaded strips, one per BlendMode; they depend only on the
1732 // material blend factors (constant across the draw), so they are compiled at most once per
1733 // draw and never invalidated by texture-variant changes
1734 pvr_poly_hdr_t hdrShaded[4];
1735 bool hdrShadedValid[4] = { false, false, false, false };
1736
1737 // Texel sizes of the sprite texture in texture space (part of the EffectContext contract;
1738 // the effects that need an on-screen texel step derive it from the instance colour instead,
1739 // exactly like their GLSL does). Derived only for effects flagged with the texel-size
1740 // facility - everything else gets deterministic zeros without the divides.
1741 const float texelWidth = (needsTexelStep && hasTexture && texture->GetWidth() > 0 ? 1.0f / float(texture->GetWidth()) : 0.0f);
1742 const float texelHeight = (needsTexelStep && hasTexture && texture->GetHeight() > 0 ? 1.0f / float(texture->GetHeight()) : 0.0f);
1743
1744 // The engine's NDC orientation matches the software backend, whose top-down raster is flipped at
1745 // present time; the PVR scans out its buffer top-down directly, so screen passes mirror NDC here
1746 // instead (+1 = bottom row). Render-to-texture passes keep the unmirrored top-down store, which is
1747 // what the sampling passes already expect - which is just the sign of the raster Y scale below.
1748 const bool screenPass = (_currentRenderTarget == nullptr);
1749
1750 // Constant NDC-to-raster mapping, folded in once rather than reapplied for every sprite corner
1751 const float rasterScaleX = 0.5f * float(viewport.W) * scaleX;
1752 const float rasterBiasX = rasterScaleX + float(viewport.X) * scaleX + offsetX;
1753 const float rasterScaleY = 0.5f * float(viewport.H) * scaleY * (screenPass ? 1.0f : -1.0f);
1754 const float rasterBiasY = 0.5f * float(viewport.H) * scaleY + float(viewport.Y) * scaleY + offsetY;
1755
1756 // The PVR rasterizer has no scissor for the general case, so scissored quads are clipped
1757 // geometrically. The rect maps to raster coordinates the same way the vertices do (screen passes
1758 // mirror NDC, so the engine rect's Y addresses raster rows directly - see the GX device); only
1759 // screen passes are clipped, which covers every scissor user on this tier (menu clipping,
1760 // splitscreen viewports)
1761 const bool clipActive = (_scissor.Enabled && screenPass);
1762 float clipX0 = 0.0f, clipY0 = 0.0f, clipX1 = 0.0f, clipY1 = 0.0f;
1763 if (clipActive) {
1764 clipX0 = float(_scissor.Rect.X) * scaleX + offsetX;
1765 clipY0 = float(_scissor.Rect.Y) * scaleY + offsetY;
1766 clipX1 = float(_scissor.Rect.X + _scissor.Rect.W) * scaleX + offsetX;
1767 clipY1 = float(_scissor.Rect.Y + _scissor.Rect.H) * scaleY + offsetY;
1768 }
1769
1770 for (std::int32_t k = 0; k < numInstances; k++) {
1771 const std::uint8_t* inst = blockData + std::size_t(k) * (batched ? instanceStride : 0);
1772
1773 Transform2D mvp;
1774 Mat4MulTransform2D(pv, reinterpret_cast<const float*>(inst + kModelMatrixOffset), mvp);
1775 float color[4];
1776 std::memcpy(color, inst + kColorOffset, sizeof(color));
1777 float texRect[4] = { 0.0f, 0.0f, 1.0f, 1.0f };
1778 float spriteSize[2];
1779 if (texturedLayout) {
1780 std::memcpy(texRect, inst + kTexRectOffset, sizeof(texRect));
1781 std::memcpy(spriteSize, inst + kSpriteSizeOffset, sizeof(spriteSize));
1782 } else {
1783 std::memcpy(spriteSize, inst + kSpriteSizeNoTexOffset, sizeof(spriteSize));
1784 }
1785
1786 // Select this instance's texture variant and (re)compile the poly header when it changes
1787 float uvScaleU = 1.0f, uvScaleV = 1.0f;
1788 if (hasTexture) {
1789 pvr_ptr_t vram = nullptr;
1790 std::uint32_t format = 0;
1791 std::int32_t bank = -1;
1792 if (texture->IsIndexed()) {
1793 // See the mesh path: a paletted store needs a bank selected under every effect
1794 std::int32_t paletteOffset = 0;
1795 if (isPaletteRemap) {
1796 float palOffset = 0.0f;
1797 std::memcpy(&palOffset, inst + kPaletteOffsetOffset, sizeof(palOffset));
1798 paletteOffset = std::int32_t(palOffset + 0.5f);
1799 }
1800 bank = AcquirePaletteBankForRow(paletteTex, paletteOffset);
1801 if (bank < 0) {
1802 bank = 0;
1803 }
1804 vram = texture->AcquireVramPointer();
1805 format = texture->GetVramFormat() | PVR_TXRFMT_8BPP_PAL(std::uint32_t(bank));
1806 } else if (isPaletteRemap && texture->NeedsPaletteBake() && paletteTex != nullptr && paletteTex->GetPixels() != nullptr) {
1807 float palOffset = 0.0f;
1808 std::memcpy(&palOffset, inst + kPaletteOffsetOffset, sizeof(palOffset));
1809 const std::uint32_t paletteOffset = std::uint32_t(std::int32_t(palOffset + 0.5f));
1810 const std::uint32_t* entries = reinterpret_cast<const std::uint32_t*>(
1811 paletteTex->GetPixels()) + paletteOffset;
1812 vram = texture->EnsureBakedArgb4444(entries, paletteOffset,
1813 (paletteTex == _paletteTexture ? _paletteGeneration : paletteTex->GetContentVersion()), paletteTex);
1814 format = PVR_TXRFMT_ARGB4444 | PVR_TXRFMT_TWIDDLED;
1815 } else {
1816 vram = texture->AcquireVramPointer();
1817 format = texture->GetVramFormat();
1818 }
1819 if (vram == nullptr) {
1820 continue;
1821 }
1822 uvScaleU = texture->GetUScale();
1823 uvScaleV = texture->GetVScale();
1824 if (!hdrValid || vram != lastVram || bank != lastBank) {
1825 pvr_poly_cxt_txr(&cxt, PVR_LIST_TR_POLY, int(format),
1826 texture->GetPaddedWidth(), texture->GetPaddedHeight(), vram, pvr_filter_mode_t(filter));
1827 cxt.gen.culling = PVR_CULLING_NONE;
1828 cxt.depth.comparison = PVR_DEPTHCMP_ALWAYS;
1829 cxt.depth.write = PVR_DEPTHWRITE_DISABLE;
1830 cxt.blend.src = pvr_blend_mode_t(blendSrc);
1831 cxt.blend.dst = pvr_blend_mode_t(blendDst);
1832 cxt.txr.env = PVR_TXRENV_MODULATEALPHA;
1833 // The offset colour is added to the texturing result, which is how the actor state
1834 // effects brighten and tint the sprite (see the generated effect functions)
1835 if (usesOffsetColor) {
1836 cxt.gen.specular = PVR_SPECULAR_ENABLE;
1837 }
1838 pvr_poly_compile(&hdr, &cxt);
1839 // The compiled base changed, so any blend twins derived from it are stale
1840 hdrAdditiveValid = false;
1841 hdrOpaqueValid = false;
1842 hdrAlphaValid = false;
1843 hdrValid = true;
1844 lastVram = vram;
1845 lastBank = bank;
1846 }
1847 } else if (!hdrValid) {
1848 pvr_poly_cxt_col(&cxt, PVR_LIST_TR_POLY);
1849 cxt.gen.culling = PVR_CULLING_NONE;
1850 cxt.depth.comparison = PVR_DEPTHCMP_ALWAYS;
1851 cxt.depth.write = PVR_DEPTHWRITE_DISABLE;
1852 cxt.blend.src = pvr_blend_mode_t(blendSrc);
1853 cxt.blend.dst = pvr_blend_mode_t(blendDst);
1854 pvr_poly_compile(&hdr, &cxt);
1855 hdrValid = true;
1856 }
1857
1858 // Synthesize the four sprite corners exactly like the software FetchVertex, with the constant
1859 // NDC-to-raster mapping folded into the transform (see DispatchTileMesh) so a corner costs one
1860 // multiply-add per axis. The corner weights are 0 or 1, so the sprite's extent in raster space
1861 // is just the transformed axes scaled by its size, and the corners are sums of those.
1862 const float originX = mvp.Tx * rasterScaleX + rasterBiasX;
1863 const float originY = mvp.Ty * rasterScaleY + rasterBiasY;
1864 const float spanXx = mvp.Xx * rasterScaleX * spriteSize[0];
1865 const float spanXy = mvp.Xy * rasterScaleY * spriteSize[0];
1866 const float spanYx = mvp.Yx * rasterScaleX * spriteSize[1];
1867 const float spanYy = mvp.Yy * rasterScaleY * spriteSize[1];
1868 float px[4], py[4], pu[4], pvv[4];
1869 for (std::int32_t i = 0; i < 4; i++) {
1870 const float ax = ((i & ~1) == 0) ? 1.0f : 0.0f;
1871 const float ay = (i & 1) ? 1.0f : 0.0f;
1872 px[i] = originX + ax * spanXx + ay * spanYx;
1873 py[i] = originY + ax * spanXy + ay * spanYy;
1874 pu[i] = (ax * texRect[0] + texRect[1]) * uvScaleU;
1875 pvv[i] = (ay * texRect[2] + texRect[3]) * uvScaleV;
1876 }
1877
1878 if (clipActive) {
1879 // Corners 2/3 share the left edge and 0/1 the right one (ax); 0/2 share the top edge and
1880 // 1/3 the bottom one (ay) - see the corner synthesis above
1881 const bool axisAligned = (px[0] == px[1] && px[2] == px[3] && py[0] == py[2] && py[1] == py[3]);
1882 if (axisAligned) {
1883 float xA = px[2], xB = px[0], uA = pu[2], uB = pu[0];
1884 if (!ClipQuadEdge(xA, xB, uA, uB, clipX0, clipX1)) {
1885 continue;
1886 }
1887 px[2] = px[3] = xA; px[0] = px[1] = xB;
1888 pu[2] = pu[3] = uA; pu[0] = pu[1] = uB;
1889 float yA = py[0], yB = py[1], vA = pvv[0], vB = pvv[1];
1890 if (!ClipQuadEdge(yA, yB, vA, vB, clipY0, clipY1)) {
1891 continue;
1892 }
1893 py[0] = py[2] = yA; py[1] = py[3] = yB;
1894 pvv[0] = pvv[2] = vA; pvv[1] = pvv[3] = vB;
1895 } else {
1896 // Rotated quad: conservative bounding-box reject only (exact clipping of rotated
1897 // sprites is not worth it for the scissor users on this tier)
1898 const float minX = std::min(std::min(px[0], px[1]), std::min(px[2], px[3]));
1899 const float maxX = std::max(std::max(px[0], px[1]), std::max(px[2], px[3]));
1900 const float minY = std::min(std::min(py[0], py[1]), std::min(py[2], py[3]));
1901 const float maxY = std::max(std::max(py[0], py[1]), std::max(py[2], py[3]));
1902 if (maxX <= clipX0 || minX >= clipX1 || maxY <= clipY0 || minY >= clipY1) {
1903 continue;
1904 }
1905 }
1906 }
1907
1908 // The pass descriptors the per-effect functions declare are mapped onto this instance's
1909 // corners and the compiled material state through the context
1910 EffectContext ctx;
1911 ctx.InstanceColor = color;
1912 ctx.TexelW = texelWidth;
1913 ctx.TexelH = texelHeight;
1914 ctx.Batched = batched;
1915 ctx.Hdr = &hdr;
1916 ctx.BaseCxt = &cxt;
1917 ctx.HdrAdditive = &hdrAdditive;
1918 ctx.HdrAdditiveValid = &hdrAdditiveValid;
1919 ctx.HdrOpaque = &hdrOpaque;
1920 ctx.HdrOpaqueValid = &hdrOpaqueValid;
1921 ctx.HdrAlpha = &hdrAlpha;
1922 ctx.HdrAlphaValid = &hdrAlphaValid;
1923 ctx.Px = px;
1924 ctx.Py = py;
1925 ctx.Pu = pu;
1926 ctx.Pv = pvv;
1927 ctx.TexRect = texRect;
1928 // The optional context facilities are only wired up for effects whose static analysis
1929 // says they can call them (see reqs above); the loop-invariant conditions predict
1930 // perfectly, and members of an unused facility are simply never read
1931 if (needsQuadAxes) {
1932 ctx.OriginX = originX;
1933 ctx.OriginY = originY;
1934 ctx.AxisXx = spanXx;
1935 ctx.AxisXy = spanXy;
1936 ctx.AxisYx = spanYx;
1937 ctx.AxisYy = spanYy;
1938 }
1939 // Resolved uniforms are the only thing the context needs the program for, so effects
1940 // without the facility get no program plumbed at all (no resolution can ever run)
1941 ctx.Program = (needsUniforms ? _currentProgram : nullptr);
1942 if (needsStripBuilder) {
1943 // The shaded-strip Material twin and the strip UV scale exist only for the strip
1944 // builder; the material blend factors feed that twin's compilation
1945 ctx.MaterialBlendSrc = blendSrc;
1946 ctx.MaterialBlendDst = blendDst;
1947 ctx.UvScaleU = uvScaleU;
1948 ctx.UvScaleV = uvScaleV;
1949 ctx.HdrShaded = hdrShaded;
1950 ctx.HdrShadedValid = hdrShadedValid;
1951 }
1952
1953 // Every quad-family effect is the transpiled form of its shader's fixed_function block
1954 // (masks, outline, shields, colorized, palette remap, the default sprites - batched
1955 // twins and palette variants included - and the geometry-synthesized iris and warp)
1956 generated->Fn(ctx);
1957 }
1958 }
1959 }