Debian Codegraph @

Sources/nCine/Graphics/RHI/Software/SwTileRasterizer.cpp

raw
1 #if defined(WITH_RHI_SOFTWARE)
2
3 #include "SwTileRenderer.h"
4 #include "SwScanlineOps.h"
5
6 #include <algorithm>
7 #include <cmath>
8 #include <cstddef>
9 #include <cstring>
10
11 using namespace Death::Containers;
12
13 namespace nCine::RHI::Software
14 {
15 // The sampler/filter enums live in the parent nCine namespace; pull them in so the ported rasterizer
16 // bodies can name them unqualified (this TU never sees any legacy shadow of the same names)
17 using nCine::SamplerFilter;
18 using nCine::SamplerWrapping;
19
20 // Per-tile rasterization, called from SwTileRenderer::ProcessTile. All the sampling / blend / vertex
21 // helpers below are file-local (internal linkage) copies of the immediate rasterizer's math kept in
22 // SwRaster.cpp — the tile path is standalone, so nothing crosses the TU boundary except
23 // RenderCommandToTile (external linkage), which SwTileRenderer.cpp forward-declares and calls.
24 namespace TileInternal
25 {
26 // =====================================================================
27 // Fixed-point / integer texel wrapping helpers
28 // =====================================================================
29
30 static inline std::int32_t WrapTexelFix(std::int32_t coordFix, std::int32_t texDim, SamplerWrapping mode)
31 {
32 std::int32_t idx = coordFix >> 16;
33 switch (mode) {
34 case SamplerWrapping::Repeat:
35 idx = idx % texDim;
36 if (idx < 0) idx += texDim;
37 return idx;
38 case SamplerWrapping::MirroredRepeat: {
39 std::int32_t period = texDim * 2;
40 idx = idx % period;
41 if (idx < 0) idx += period;
42 if (idx >= texDim) idx = period - 1 - idx;
43 return idx;
44 }
45 default:
46 if (idx < 0) return 0;
47 if (idx >= texDim) return texDim - 1;
48 return idx;
49 }
50 }
51
52 static inline std::int32_t NormalizeRepeatFix(std::int32_t coordFix, std::int32_t texDimFix)
53 {
54 coordFix = coordFix % texDimFix;
55 if (coordFix < 0) coordFix += texDimFix;
56 return coordFix;
57 }
58
59 static inline std::int32_t AdvanceRepeatFix(std::int32_t coordFix, std::int32_t step, std::int32_t texDimFix)
60 {
61 coordFix += step;
62 if (coordFix >= texDimFix) coordFix -= texDimFix;
63 else if (coordFix < 0) coordFix += texDimFix;
64 return coordFix;
65 }
66
67 static inline std::int32_t WrapTexelCoord(std::int32_t idx, std::int32_t texDim, SamplerWrapping mode)
68 {
69 switch (mode) {
70 case SamplerWrapping::Repeat:
71 idx = idx % texDim;
72 if (idx < 0) idx += texDim;
73 return idx;
74 case SamplerWrapping::MirroredRepeat: {
75 std::int32_t period = texDim * 2;
76 idx = idx % period;
77 if (idx < 0) idx += period;
78 if (idx >= texDim) idx = period - 1 - idx;
79 return idx;
80 }
81 default:
82 if (idx < 0) return 0;
83 if (idx >= texDim) return texDim - 1;
84 return idx;
85 }
86 }
87
88 // Float UV wrap for the generic triangle path - a verbatim copy of SwRaster.cpp's WrapUV so a
89 // deferred triangle samples exactly like an immediate one (the two paths must stay bit-identical:
90 // the same draw may take either depending on the deferral queue's state).
91 static inline float WrapUV(float t, SamplerWrapping mode)
92 {
93 switch (mode) {
94 case SamplerWrapping::Repeat:
95 t -= std::floor(t);
96 return t;
97 case SamplerWrapping::MirroredRepeat: {
98 float f = std::floor(t);
99 t -= f;
100 if (static_cast<std::int32_t>(f) & 1) t = 1.0f - t;
101 return t;
102 }
103 default: // ClampToEdge
104 if (t < 0.0f) return 0.0f;
105 if (t > 1.0f) return 1.0f;
106 return t;
107 }
108 }
109
110 // =====================================================================
111 // Bilinear sampling from 16.16 fixed-point UV coordinates
112 // =====================================================================
113
114 struct BilinearRowCtx
115 {
116 const std::uint8_t* row0;
117 const std::uint8_t* row1;
118 std::int32_t ify;
119 std::int32_t fy;
120 };
121
122 static inline BilinearRowCtx PrepareBilinearRow(const std::uint8_t* texPixels, std::int32_t texW, std::int32_t texH, std::int32_t texBpp,
123 std::int32_t vFix, SamplerWrapping wrapT)
124 {
125 const std::int32_t vf = vFix - (1 << 15);
126 std::int32_t y0 = vf >> 16;
127 const std::int32_t fy = (vf & 0xFFFF) >> 8;
128 std::int32_t y1 = WrapTexelCoord(y0 + 1, texH, wrapT);
129 y0 = WrapTexelCoord(y0, texH, wrapT);
130 return {
131 texPixels + static_cast<std::size_t>(y0) * texW * texBpp,
132 texPixels + static_cast<std::size_t>(y1) * texW * texBpp,
133 255 - fy, fy
134 };
135 }
136
137 static inline void SampleBilinearFixRow(const BilinearRowCtx& row, std::int32_t texW, std::int32_t texBpp,
138 std::int32_t uFix, SamplerWrapping wrapS,
139 std::uint8_t* out)
140 {
141 const std::int32_t uf = uFix - (1 << 15);
142 std::int32_t x0 = uf >> 16;
143 const std::int32_t fx = (uf & 0xFFFF) >> 8;
144 std::int32_t x1 = WrapTexelCoord(x0 + 1, texW, wrapS);
145 x0 = WrapTexelCoord(x0, texW, wrapS);
146
147 const std::uint8_t* c00 = row.row0 + x0 * texBpp;
148 const std::uint8_t* c10 = row.row0 + x1 * texBpp;
149 const std::uint8_t* c01 = row.row1 + x0 * texBpp;
150 const std::uint8_t* c11 = row.row1 + x1 * texBpp;
151 std::uint8_t e00[4], e10[4], e01[4], e11[4];
152 if DEATH_UNLIKELY(texBpp != 4) {
153 SwExpandTexel(e00, c00, texBpp); c00 = e00;
154 SwExpandTexel(e10, c10, texBpp); c10 = e10;
155 SwExpandTexel(e01, c01, texBpp); c01 = e01;
156 SwExpandTexel(e11, c11, texBpp); c11 = e11;
157 }
158
159 const std::int32_t ifx = 255 - fx;
160 const std::int32_t w00 = ifx * row.ify;
161 const std::int32_t w10 = fx * row.ify;
162 const std::int32_t w01 = ifx * row.fy;
163 const std::int32_t w11 = fx * row.fy;
164
165 out[0] = static_cast<std::uint8_t>((c00[0] * w00 + c10[0] * w10 + c01[0] * w01 + c11[0] * w11) >> 16);
166 out[1] = static_cast<std::uint8_t>((c00[1] * w00 + c10[1] * w10 + c01[1] * w01 + c11[1] * w11) >> 16);
167 out[2] = static_cast<std::uint8_t>((c00[2] * w00 + c10[2] * w10 + c01[2] * w01 + c11[2] * w11) >> 16);
168 out[3] = static_cast<std::uint8_t>((c00[3] * w00 + c10[3] * w10 + c01[3] * w01 + c11[3] * w11) >> 16);
169 }
170
171 // Float-coordinate bilinear sample for the generic triangle path - a verbatim copy of
172 // SwRaster.cpp's SampleBilinearFloat (see WrapUV above for why the copies must match).
173 static inline void SampleBilinearFloat(const std::uint8_t* texPixels, std::int32_t texW, std::int32_t texH, std::int32_t texBpp,
174 float u, float v,
175 SamplerWrapping wrapS, SamplerWrapping wrapT,
176 std::uint8_t* out)
177 {
178 const float uf = u * texW - 0.5f;
179 const float vf = v * texH - 0.5f;
180
181 std::int32_t x0 = static_cast<std::int32_t>(std::floor(uf));
182 std::int32_t y0 = static_cast<std::int32_t>(std::floor(vf));
183
184 std::int32_t fx = static_cast<std::int32_t>((uf - x0) * 255.0f + 0.5f);
185 std::int32_t fy = static_cast<std::int32_t>((vf - y0) * 255.0f + 0.5f);
186 if (fx < 0) fx = 0; if (fx > 255) fx = 255;
187 if (fy < 0) fy = 0; if (fy > 255) fy = 255;
188
189 std::int32_t x1 = WrapTexelCoord(x0 + 1, texW, wrapS);
190 std::int32_t y1 = WrapTexelCoord(y0 + 1, texH, wrapT);
191 x0 = WrapTexelCoord(x0, texW, wrapS);
192 y0 = WrapTexelCoord(y0, texH, wrapT);
193
194 const std::uint8_t* c00 = texPixels + (static_cast<std::size_t>(y0) * texW + x0) * texBpp;
195 const std::uint8_t* c10 = texPixels + (static_cast<std::size_t>(y0) * texW + x1) * texBpp;
196 const std::uint8_t* c01 = texPixels + (static_cast<std::size_t>(y1) * texW + x0) * texBpp;
197 const std::uint8_t* c11 = texPixels + (static_cast<std::size_t>(y1) * texW + x1) * texBpp;
198 std::uint8_t e00[4], e10[4], e01[4], e11[4];
199 if DEATH_UNLIKELY(texBpp != 4) {
200 SwExpandTexel(e00, c00, texBpp); c00 = e00;
201 SwExpandTexel(e10, c10, texBpp); c10 = e10;
202 SwExpandTexel(e01, c01, texBpp); c01 = e01;
203 SwExpandTexel(e11, c11, texBpp); c11 = e11;
204 }
205
206 const std::int32_t ifx = 255 - fx;
207 const std::int32_t ify = 255 - fy;
208 const std::int32_t w00 = ifx * ify;
209 const std::int32_t w10 = fx * ify;
210 const std::int32_t w01 = ifx * fy;
211 const std::int32_t w11 = fx * fy;
212
213 out[0] = static_cast<std::uint8_t>((c00[0] * w00 + c10[0] * w10 + c01[0] * w01 + c11[0] * w11) >> 16);
214 out[1] = static_cast<std::uint8_t>((c00[1] * w00 + c10[1] * w10 + c01[1] * w01 + c11[1] * w11) >> 16);
215 out[2] = static_cast<std::uint8_t>((c00[2] * w00 + c10[2] * w10 + c01[2] * w01 + c11[2] * w11) >> 16);
216 out[3] = static_cast<std::uint8_t>((c00[3] * w00 + c10[3] * w10 + c01[3] * w01 + c11[3] * w11) >> 16);
217 }
218
219 static inline void SampleBilinearFix(const std::uint8_t* texPixels, std::int32_t texW, std::int32_t texH, std::int32_t texBpp,
220 std::int32_t uFix, std::int32_t vFix,
221 SamplerWrapping wrapS, SamplerWrapping wrapT,
222 std::uint8_t* out)
223 {
224 const std::int32_t uf = uFix - (1 << 15);
225 const std::int32_t vf = vFix - (1 << 15);
226 std::int32_t x0 = uf >> 16;
227 std::int32_t y0 = vf >> 16;
228 const std::int32_t fx = (uf & 0xFFFF) >> 8;
229 const std::int32_t fy = (vf & 0xFFFF) >> 8;
230 std::int32_t x1 = WrapTexelCoord(x0 + 1, texW, wrapS);
231 std::int32_t y1 = WrapTexelCoord(y0 + 1, texH, wrapT);
232 x0 = WrapTexelCoord(x0, texW, wrapS);
233 y0 = WrapTexelCoord(y0, texH, wrapT);
234
235 const std::uint8_t* c00 = texPixels + (static_cast<std::size_t>(y0) * texW + x0) * texBpp;
236 const std::uint8_t* c10 = texPixels + (static_cast<std::size_t>(y0) * texW + x1) * texBpp;
237 const std::uint8_t* c01 = texPixels + (static_cast<std::size_t>(y1) * texW + x0) * texBpp;
238 const std::uint8_t* c11 = texPixels + (static_cast<std::size_t>(y1) * texW + x1) * texBpp;
239 std::uint8_t f00[4], f10[4], f01[4], f11[4];
240 if DEATH_UNLIKELY(texBpp != 4) {
241 SwExpandTexel(f00, c00, texBpp); c00 = f00;
242 SwExpandTexel(f10, c10, texBpp); c10 = f10;
243 SwExpandTexel(f01, c01, texBpp); c01 = f01;
244 SwExpandTexel(f11, c11, texBpp); c11 = f11;
245 }
246
247 const std::int32_t ifx = 255 - fx;
248 const std::int32_t ify = 255 - fy;
249 const std::int32_t w00 = ifx * ify;
250 const std::int32_t w10 = fx * ify;
251 const std::int32_t w01 = ifx * fy;
252 const std::int32_t w11 = fx * fy;
253
254 out[0] = static_cast<std::uint8_t>((c00[0] * w00 + c10[0] * w10 + c01[0] * w01 + c11[0] * w11) >> 16);
255 out[1] = static_cast<std::uint8_t>((c00[1] * w00 + c10[1] * w10 + c01[1] * w01 + c11[1] * w11) >> 16);
256 out[2] = static_cast<std::uint8_t>((c00[2] * w00 + c10[2] * w10 + c01[2] * w01 + c11[2] * w11) >> 16);
257 out[3] = static_cast<std::uint8_t>((c00[3] * w00 + c10[3] * w10 + c01[3] * w01 + c11[3] * w11) >> 16);
258 }
259
260 // Scanline blending and tinting use the CPU-dispatched implementations shared with the immediate
261 // rasterizer (SwScanlineOps.h): the previous per-TU copies here were NEON-or-scalar, which left the
262 // x86 desktop build running the hottest inner loops scalar while SwRaster.cpp's SSE2/AVX2 code idled.
263
264 // =====================================================================
265 // PaletteRemap LUT fast path
266 // Applies the per-command table SwTileRenderer::SubmitCommand baked (ctx.paletteLut) in place of
267 // the transpiled fragment: the whole palette + tint math collapses to indexing by the raw texel's
268 // index byte. Output is bit-identical to the fragment (the table replicates its float math).
269 // =====================================================================
270
271 static inline void ApplyPaletteLutPixel(const SwPaletteLut& lut, std::uint8_t* px)
272 {
273 // Read both source bytes before writing: the index/alpha offsets may address any of the four
274 const std::uint8_t* entry = lut.packed[px[lut.indexByteOffset]];
275 if (lut.alphaByteOffset >= 0) {
276 // Per-pixel source alpha (RG8 index textures: swizzle maps .a to the texel's alpha byte).
277 // The 255 / 0 shortcuts are exact: 255/255 == 1.0 is the factor baked into entry[3], and a
278 // zero source alpha multiplies through to a quantized 0.
279 const std::uint8_t alphaByte = px[lut.alphaByteOffset];
280 const std::uint8_t idx = px[lut.indexByteOffset];
281 px[0] = entry[0];
282 px[1] = entry[1];
283 px[2] = entry[2];
284 if (alphaByte == 255) {
285 px[3] = entry[3];
286 } else if (alphaByte == 0) {
287 px[3] = 0;
288 } else {
289 // Exactly the fragment's (palette.a * src.a) * tint.a, quantized like packColor
290 const float palA = lut.palAlphaByte[idx] / 255.0f;
291 const float srcA = alphaByte / 255.0f;
292 px[3] = SwQuantizeColor((palA * srcA) * lut.tintAlpha);
293 }
294 } else {
295 // Constant source alpha: the entire output pixel is the 4-byte table entry
296 px[0] = entry[0];
297 px[1] = entry[1];
298 px[2] = entry[2];
299 px[3] = entry[3];
300 }
301 }
302
303 static void ApplyPaletteLutScanline(const SwPaletteLut& lut, std::uint8_t* scanBuf, std::int32_t width)
304 {
305 if (lut.alphaByteOffset < 0) {
306 const std::int32_t indexByteOffset = lut.indexByteOffset;
307 for (std::int32_t i = 0; i < width; i++) {
308 std::uint8_t* px = &scanBuf[i * 4];
309 std::memcpy(px, lut.packed[px[indexByteOffset]], 4);
310 }
311 } else {
312 for (std::int32_t i = 0; i < width; i++) {
313 ApplyPaletteLutPixel(lut, &scanBuf[i * 4]);
314 }
315 }
316 }
317
318 // Fused gather + palette LUT for one texel of a nearest-sampled PaletteRemap draw: reads the index
319 // (and source-alpha) byte straight from the texture STORE and writes the final LUT'd pixel, skipping
320 // the intermediate 4-byte expansion the two-pass gather-then-ApplyPaletteLut pair produced. The
321 // store-byte selection mirrors SwExpandTexel exactly (a LUT byte offset beyond the store width reads
322 // the constant 255 fill), so the output is bit-identical to the two-pass path for every store width.
323 static DEATH_ALWAYS_INLINE void FusedPaletteLutTexel(const SwPaletteLut& lut, const std::uint8_t* DEATH_RESTRICT src,
324 std::int32_t texBpp, std::uint8_t* DEATH_RESTRICT dst)
325 {
326 const std::uint8_t idx = (lut.indexByteOffset < texBpp ? src[lut.indexByteOffset] : std::uint8_t(255));
327 const std::uint8_t* entry = lut.packed[idx];
328 if (lut.alphaByteOffset < 0) {
329 // Constant source alpha: the entire output pixel is the 4-byte table entry
330 std::memcpy(dst, entry, 4);
331 } else {
332 const std::uint8_t alphaByte = (lut.alphaByteOffset < texBpp ? src[lut.alphaByteOffset] : std::uint8_t(255));
333 dst[0] = entry[0];
334 dst[1] = entry[1];
335 dst[2] = entry[2];
336 if (alphaByte == 255) {
337 dst[3] = entry[3];
338 } else if (alphaByte == 0) {
339 dst[3] = 0;
340 } else {
341 // Exactly the fragment's (palette.a * src.a) * tint.a, quantized like packColor
342 const float palA = lut.palAlphaByte[idx] / 255.0f;
343 const float srcA = alphaByte / 255.0f;
344 dst[3] = SwQuantizeColor((palA * srcA) * lut.tintAlpha);
345 }
346 }
347 }
348
349 // Fused gather + palette LUT + fast blend for one texel: FusedPaletteLutTexel's output blended
350 // straight over the destination pixel with the SrcAlpha / OneMinusSrcAlpha pair (or stored as-is
351 // when blending is off), replacing the scanline staging + BlendScanlineSrcAlpha pass. The blend
352 // math and its 0 / 255 alpha shortcuts are byte-for-byte the scalar reference of the SIMD scanline
353 // blenders (see SwRaster.cpp's quantization contract), so the result is bit-identical to the
354 // two-pass form - and a transparent texel never touches the destination at all.
355 static DEATH_ALWAYS_INLINE void FusedPaletteLutBlendTexel(const SwPaletteLut& lut, const std::uint8_t* DEATH_RESTRICT src,
356 std::int32_t texBpp, std::uint8_t* DEATH_RESTRICT dst, bool useFastBlend)
357 {
358 if (!useFastBlend) {
359 // Blending disabled: the LUT output is the final pixel
360 FusedPaletteLutTexel(lut, src, texBpp, dst);
361 return;
362 }
363 const std::uint8_t idx = (lut.indexByteOffset < texBpp ? src[lut.indexByteOffset] : std::uint8_t(255));
364 const std::uint8_t* entry = lut.packed[idx];
365 std::int32_t sA;
366 if (lut.alphaByteOffset < 0) {
367 sA = entry[3];
368 } else {
369 const std::uint8_t alphaByte = (lut.alphaByteOffset < texBpp ? src[lut.alphaByteOffset] : std::uint8_t(255));
370 if (alphaByte == 255) {
371 sA = entry[3];
372 } else if (alphaByte == 0) {
373 sA = 0;
374 } else {
375 // Exactly the fragment's (palette.a * src.a) * tint.a, quantized like packColor
376 const float palA = lut.palAlphaByte[idx] / 255.0f;
377 const float srcA = alphaByte / 255.0f;
378 sA = SwQuantizeColor((palA * srcA) * lut.tintAlpha);
379 }
380 }
381 if (sA == 0) {
382 return;
383 }
384 if (sA >= 255) {
385 dst[0] = entry[0];
386 dst[1] = entry[1];
387 dst[2] = entry[2];
388 dst[3] = std::uint8_t(sA);
389 return;
390 }
391 const std::int32_t inv = 255 - sA;
392 dst[0] = static_cast<std::uint8_t>((entry[0] * sA + dst[0] * inv) >> 8);
393 dst[1] = static_cast<std::uint8_t>((entry[1] * sA + dst[1] * inv) >> 8);
394 dst[2] = static_cast<std::uint8_t>((entry[2] * sA + dst[2] * inv) >> 8);
395 dst[3] = static_cast<std::uint8_t>((sA * 255 + dst[3] * inv) >> 8);
396 }
397
398 // =====================================================================
399 // Vertex fetch — identical transform to SwRaster::FetchVertex (procedural sprite quad or interleaved
400 // clip-space vertices), only parameterized on the viewport so it stays thread-safe during a flush.
401 // =====================================================================
402 static Vertex2D FetchVertex(const DrawContext& ctx, std::int32_t index,
403 std::int32_t viewportX, std::int32_t viewportY,
404 std::int32_t viewportW, std::int32_t viewportH)
405 {
406 Vertex2D out = { 0, 0, 0, 0, 1, 1, 1, 1 };
407
408 if DEATH_LIKELY(ctx.vertexData == nullptr) {
409 const float ax = ((index & ~1) == 0) ? 1.0f : 0.0f;
410 const float ay = (index & 1) ? 1.0f : 0.0f;
411
412 const float wx = ax * ctx.ff.spriteSize[0];
413 const float wy = ay * ctx.ff.spriteSize[1];
414
415 const float* m = ctx.ff.mvpMatrix;
416 out.x = m[0] * wx + m[4] * wy + m[12];
417 out.y = m[1] * wx + m[5] * wy + m[13];
418
419 out.u = ax * ctx.ff.texRect[0] + ctx.ff.texRect[1];
420 out.v = ay * ctx.ff.texRect[2] + ctx.ff.texRect[3];
421
422 out.r = ctx.ff.color[0];
423 out.g = ctx.ff.color[1];
424 out.b = ctx.ff.color[2];
425 out.a = ctx.ff.color[3];
426 } else {
427 // General path: interleaved clip-space vertices [x, y, u, v] (device pre-transforms positions)
428 std::int32_t stride = ctx.vertexStride;
429 if DEATH_UNLIKELY(stride <= 0) stride = 4 * static_cast<std::int32_t>(sizeof(float));
430 const std::uint8_t* base = static_cast<const std::uint8_t*>(ctx.vertexData);
431 const float* f = reinterpret_cast<const float*>(base + static_cast<std::size_t>(index) * stride);
432 out.x = f[0];
433 out.y = f[1];
434 out.u = f[2];
435 out.v = f[3];
436
437 out.r = ctx.ff.color[0];
438 out.g = ctx.ff.color[1];
439 out.b = ctx.ff.color[2];
440 out.a = ctx.ff.color[3];
441 }
442
443 // Viewport transform: NDC [-1,+1] → screen pixel coordinates
444 out.x = (out.x + 1.0f) * 0.5f * static_cast<float>(viewportW) + static_cast<float>(viewportX);
445 out.y = (1.0f - out.y) * 0.5f * static_cast<float>(viewportH) + static_cast<float>(viewportY);
446
447 // Snap to the pixel grid when within epsilon of an integer (matches the immediate path)
448 constexpr float SnapEps = 1.0f / 128.0f;
449 float rxSnap = std::round(out.x);
450 float rySnap = std::round(out.y);
451 if (std::fabs(out.x - rxSnap) < SnapEps) out.x = rxSnap;
452 if (std::fabs(out.y - rySnap) < SnapEps) out.y = rySnap;
453
454 return out;
455 }
456
457 // =====================================================================
458 // Submit-time preparation of a procedural quad command (see PreparedQuad in SwTileRenderer.h)
459 // Runs everything the tile rasterizers used to re-derive per binned tile - the four FetchVertex
460 // transforms, the texture / tint / blend derivation and the axis-aligned / affine setup - exactly
461 // once per command, with the identical expressions so the per-tile rasterization is bit-identical.
462 // Leaves prep.valid == false for a quad the rasterizers would reject as a no-op, so SubmitCommand
463 // can discard the command without binning it.
464 // =====================================================================
465 void PrepareQuad(const DrawContext& ctx, std::int32_t viewportX, std::int32_t viewportY,
466 std::int32_t viewportW, std::int32_t viewportH, SwTileRenderer::PreparedQuad& prep)
467 {
468 prep.valid = false;
469 prep.constantFill = false;
470
471 const Vertex2D v0 = FetchVertex(ctx, 0, viewportX, viewportY, viewportW, viewportH);
472 const Vertex2D v1 = FetchVertex(ctx, 1, viewportX, viewportY, viewportW, viewportH);
473 const Vertex2D v2 = FetchVertex(ctx, 2, viewportX, viewportY, viewportW, viewportH);
474 const Vertex2D v3 = FetchVertex(ctx, 3, viewportX, viewportY, viewportW, viewportH);
475 prep.v[0] = v0;
476 prep.v[1] = v1;
477 prep.v[2] = v2;
478 prep.v[3] = v3;
479
480 // Check axis-aligned (same tolerance as the immediate path)
481 prep.axisAligned = (std::fabs(v0.x - v1.x) < 0.5f && std::fabs(v2.x - v3.x) < 0.5f &&
482 std::fabs(v0.y - v2.y) < 0.5f && std::fabs(v1.y - v3.y) < 0.5f);
483
484 // Screen-space bounding box (the axis-aligned setup and both tile clips read it)
485 prep.fxMin = std::min({v0.x, v1.x, v2.x, v3.x});
486 prep.fxMax = std::max({v0.x, v1.x, v2.x, v3.x});
487 prep.fyMin = std::min({v0.y, v1.y, v2.y, v3.y});
488 prep.fyMax = std::max({v0.y, v1.y, v2.y, v3.y});
489
490 // Texture info
491 const SwTexture* tex = (ctx.ff.hasTexture && ctx.ff.textureUnit < static_cast<std::int32_t>(MaxTextureUnits)
492 ? ctx.textures[ctx.ff.textureUnit] : nullptr);
493 prep.texPixels = (tex != nullptr ? tex->GetPixels(0) : nullptr);
494 prep.texW = (tex != nullptr ? tex->GetWidth() : 0);
495 prep.texH = (tex != nullptr ? tex->GetHeight() : 0);
496 prep.texBpp = (tex != nullptr ? tex->GetBytesPerPixel() : 4);
497 prep.wrapS = (tex != nullptr ? tex->GetWrapS() : SamplerWrapping::ClampToEdge);
498 prep.wrapT = (tex != nullptr ? tex->GetWrapT() : SamplerWrapping::ClampToEdge);
499 prep.useLinear = (tex != nullptr && tex->GetMagFilter() == SamplerFilter::Linear && prep.texW > 1 && prep.texH > 1);
500
501 // PARANOID GUARD (was per tile): a zero-dimension texture causes % 0 (division by zero) in
502 // WrapTexelFix / NormalizeRepeatFix, which kills the worker thread on ARM.
503 if DEATH_UNLIKELY(prep.texPixels != nullptr && (prep.texW <= 0 || prep.texH <= 0)) {
504 return; // malformed texture — skip the entire draw call
505 }
506
507 // Tint color
508 prep.tR = static_cast<std::int32_t>(std::min(1.0f, ctx.ff.color[0]) * 255.0f + 0.5f);
509 prep.tG = static_cast<std::int32_t>(std::min(1.0f, ctx.ff.color[1]) * 255.0f + 0.5f);
510 prep.tB = static_cast<std::int32_t>(std::min(1.0f, ctx.ff.color[2]) * 255.0f + 0.5f);
511 prep.tA = static_cast<std::int32_t>(std::min(1.0f, ctx.ff.color[3]) * 255.0f + 0.5f);
512 prep.whiteTint = (prep.tR >= 255 && prep.tG >= 255 && prep.tB >= 255 && prep.tA >= 255);
513
514 prep.useBlend = ctx.blendingEnabled;
515 prep.useFastBlend = (prep.useBlend &&
516 ctx.blendSrc == SwBlendFactor::SrcAlpha &&
517 ctx.blendDst == SwBlendFactor::OneMinusSrcAlpha);
518
519 // Constant-color solid fill: the hint promises the fragment writes packColor(vColor) regardless
520 // of position or texel, so evaluate it exactly once here (bit-identical by construction) and let
521 // the rasterizers fill / blend the constant instead of calling it per pixel
522 if DEATH_UNLIKELY(ctx.constantColorHint && prep.texPixels == nullptr && ctx.fragmentShader != nullptr) {
523 std::uint8_t px4[4] = { 255, 255, 255, 255 };
524 FragmentShaderInput fsInput;
525 fsInput.rgba = px4;
526 fsInput.u = 0.0f;
527 fsInput.v = 0.0f;
528 fsInput.x = 0;
529 fsInput.y = 0;
530 fsInput.texWidth = prep.texW;
531 fsInput.texHeight = prep.texH;
532 fsInput.textures = ctx.textures;
533 fsInput.color = ctx.ff.color;
534 fsInput.userData = ctx.fragmentShaderUserData;
535 ctx.fragmentShader(fsInput);
536 std::memcpy(prep.constColor, px4, sizeof(prep.constColor));
537 prep.constantFill = true;
538 }
539
540 if (prep.axisAligned) {
541 prep.fullW = prep.fxMax - prep.fxMin;
542 prep.fullH = prep.fyMax - prep.fyMin;
543 if (prep.fullW < 0.5f || prep.fullH < 0.5f) {
544 return; // degenerate — the axis-aligned rasterizer draws nothing
545 }
546
547 // UV corners
548 prep.uLeft = (v2.x <= v0.x) ? v2.u : v0.u;
549 prep.uRight = (v2.x <= v0.x) ? v0.u : v2.u;
550 prep.vTop = (v0.y <= v1.y) ? v0.v : v1.v;
551 prep.vBot = (v0.y <= v1.y) ? v1.v : v0.v;
552
553 // Fixed-point UV setup
554 prep.texWFix = prep.texW << 16;
555 prep.dtxFix = (prep.texPixels != nullptr ? static_cast<std::int32_t>((prep.uRight - prep.uLeft) * prep.texW * 65536.0f / prep.fullW) : 0);
556 prep.dtyFix = (prep.texPixels != nullptr ? static_cast<std::int32_t>((prep.vBot - prep.vTop) * prep.texH * 65536.0f / prep.fullH) : 0);
557
558 prep.useRepeatS = (prep.wrapS == SamplerWrapping::Repeat);
559 prep.useRepeatT = (prep.wrapT == SamplerWrapping::Repeat);
560 prep.useClampS = (prep.wrapS == SamplerWrapping::ClampToEdge);
561 prep.useScanBuf = ((prep.useFastBlend || !prep.useBlend) && prep.texPixels != nullptr);
562 } else {
563 // Compute affine UV mapping from the first triangle (v0, v1, v2)
564 const float e1x = v2.x - v0.x, e1y = v2.y - v0.y;
565 const float e2x = v1.x - v0.x, e2y = v1.y - v0.y;
566 const float det = e1x * e2y - e1y * e2x;
567 if (std::fabs(det) < 1e-6f) {
568 return; // degenerate — the affine rasterizer draws nothing
569 }
570 const float invDet = 1.0f / det;
571
572 const float du_s = v2.u - v0.u, du_t = v1.u - v0.u;
573 const float dv_s = v2.v - v0.v, dv_t = v1.v - v0.v;
574
575 const float ds_dx = e2y * invDet, ds_dy = -e2x * invDet;
576 const float dt_dx = -e1y * invDet, dt_dy = e1x * invDet;
577
578 prep.dudx = du_s * ds_dx + du_t * dt_dx;
579 prep.dudy = du_s * ds_dy + du_t * dt_dy;
580 prep.dvdx = dv_s * ds_dx + dv_t * dt_dx;
581 prep.dvdy = dv_s * ds_dy + dv_t * dt_dy;
582
583 // Edge functions for coverage testing (two triangles forming the quad)
584 prep.t1w0dx = v1.y - v2.y;
585 prep.t1w1dx = v2.y - v0.y;
586 prep.t1w2dx = v0.y - v1.y;
587 const float area1 = (v2.x - v1.x) * (v0.y - v1.y) - (v2.y - v1.y) * (v0.x - v1.x);
588
589 prep.t2w0dx = v1.y - v3.y;
590 prep.t2w1dx = v3.y - v2.y;
591 prep.t2w2dx = v2.y - v1.y;
592 const float area2 = (v3.x - v1.x) * (v2.y - v1.y) - (v3.y - v1.y) * (v2.x - v1.x);
593
594 if (std::fabs(area1) < 1e-6f && std::fabs(area2) < 1e-6f) {
595 return; // degenerate — the affine rasterizer draws nothing
596 }
597 prep.tri1Valid = (std::fabs(area1) >= 1e-6f);
598 prep.tri2Valid = (std::fabs(area2) >= 1e-6f);
599 prep.sign1 = (area1 > 0.0f);
600 prep.sign2 = (area2 > 0.0f);
601
602 prep.dudxFix = (prep.texPixels != nullptr ? static_cast<std::int32_t>(prep.dudx * prep.texW * 65536.0f) : 0);
603 prep.dvdxFix = (prep.texPixels != nullptr ? static_cast<std::int32_t>(prep.dvdx * prep.texH * 65536.0f) : 0);
604 }
605
606 prep.valid = true;
607 }
608
609 // =====================================================================
610 // Tile-local axis-aligned quad rasterizer
611 // Renders only the portion of the quad that intersects the tile. The destination buffer is the tile
612 // (TileSize stride), not the full framebuffer. The per-command state (vertices, texture / tint /
613 // blend derivation, fixed-point UV steps) comes precomputed in `prep` (see PrepareQuad); only the
614 // tile clip and the row walk remain per-tile, evaluated with the identical expressions.
615 // =====================================================================
616 static void DrawAxisAlignedQuadTile(const DrawContext& ctx, const SwTileRenderer::PreparedQuad& prep,
617 std::uint8_t* tileBuf, std::int32_t tileX, std::int32_t tileY,
618 std::int32_t tileW, std::int32_t tileH)
619 {
620 // Clip to tile bounds (in framebuffer coordinates)
621 std::int32_t xMin = std::max(tileX, static_cast<std::int32_t>(prep.fxMin));
622 std::int32_t xMax = std::min(tileX + tileW - 1, static_cast<std::int32_t>(prep.fxMax - 0.5f));
623 std::int32_t yMin = std::max(tileY, static_cast<std::int32_t>(prep.fyMin));
624 std::int32_t yMax = std::min(tileY + tileH - 1, static_cast<std::int32_t>(prep.fyMax - 0.5f));
625
626 // Also apply scissor (scissorRect.Y is already stored top-down by SubmitCommand)
627 if DEATH_UNLIKELY(ctx.scissorEnabled) {
628 xMin = std::max(xMin, ctx.scissorRect.X);
629 xMax = std::min(xMax, ctx.scissorRect.X + ctx.scissorRect.W - 1);
630 yMin = std::max(yMin, ctx.scissorRect.Y);
631 yMax = std::min(yMax, ctx.scissorRect.Y + ctx.scissorRect.H - 1);
632 }
633 if DEATH_UNLIKELY(xMin > xMax || yMin > yMax) return;
634
635 // Precomputed per-command state (local names kept so the loops below stay verbatim)
636 const std::uint8_t* texPixels = prep.texPixels;
637 const std::int32_t texW = prep.texW;
638 const std::int32_t texH = prep.texH;
639 const std::int32_t texBpp = prep.texBpp;
640 const SamplerWrapping wrapS = prep.wrapS;
641 const SamplerWrapping wrapT = prep.wrapT;
642 const bool useLinear = prep.useLinear;
643 const std::int32_t tR = prep.tR, tG = prep.tG, tB = prep.tB, tA = prep.tA;
644 const bool whiteTint = prep.whiteTint;
645 const bool useBlend = prep.useBlend;
646 const bool useFastBlend = prep.useFastBlend;
647 const std::int32_t texWFix = prep.texWFix;
648 const std::int32_t dtxFix = prep.dtxFix;
649 const std::int32_t dtyFix = prep.dtyFix;
650 const bool useRepeatS = prep.useRepeatS;
651 const bool useRepeatT = prep.useRepeatT;
652
653 const std::int32_t txBase = (texPixels != nullptr ? static_cast<std::int32_t>((prep.uLeft + (xMin + 0.5f - prep.fxMin) * (prep.uRight - prep.uLeft) / prep.fullW) * texW * 65536.0f) : 0);
654 std::int32_t tyFix = (texPixels != nullptr ? static_cast<std::int32_t>((prep.vTop + (yMin + 0.5f - prep.fyMin) * (prep.vBot - prep.vTop) / prep.fullH) * texH * 65536.0f) : 0);
655
656 const bool uvSafeX = (prep.useClampS && txBase >= 0 && (txBase + dtxFix * (xMax - xMin)) >= 0 &&
657 (txBase >> 16) < texW && ((txBase + dtxFix * (xMax - xMin)) >> 16) < texW);
658
659 const std::int32_t scanWidth = xMax - xMin + 1;
660
661 // Constant-color solid fill (no texture): the fragment output is the per-command constant
662 // prep.constColor, so skip per-pixel work entirely - a plain 32-bit pattern fill when the write
663 // is opaque, the constant-source SIMD blend otherwise (both bit-identical to the per-pixel
664 // path, including its destination-alpha convention). Generic (non-fast) blend factors fall
665 // through to the per-pixel loop below, which consumes the constant in place of the fragment.
666 if DEATH_UNLIKELY(prep.constantFill && (useFastBlend || !useBlend)) {
667 if (useFastBlend && prep.constColor[3] == 0) {
668 return; // Fully transparent: the per-pixel path would skip every pixel
669 }
670 const bool opaqueFill = (!useBlend || prep.constColor[3] >= 255);
671 std::uint32_t pattern;
672 std::memcpy(&pattern, prep.constColor, sizeof(pattern));
673 for (std::int32_t py = yMin; py <= yMax; py++) {
674 const std::int32_t localRow = py - tileY;
675 const std::int32_t localCol = xMin - tileX;
676 // PARANOID: float→int rounding can push these just outside the tile
677 if DEATH_UNLIKELY(localRow < 0 || localRow >= tileH || localCol < 0 || localCol >= tileW) continue;
678 std::uint8_t* dstRow = tileBuf + (localRow * SwTileRenderer::TileSize + localCol) * 4;
679 if (opaqueFill) {
680 std::uint32_t* dst32 = reinterpret_cast<std::uint32_t*>(dstRow);
681 for (std::int32_t i = 0; i < scanWidth; i++) {
682 dst32[i] = pattern;
683 }
684 } else {
685 BlendScanlineConstSrcAlpha(dstRow, scanWidth, prep.constColor);
686 }
687 }
688 return;
689 }
690
691 // Scanline buffer for tint+blend (fits within the tile width = max 32 pixels)
692 alignas(16) std::uint8_t scanBuf[SwTileRenderer::TileSize * 4];
693 const bool useScanBuf = prep.useScanBuf;
694
695 // Cache ctx.fragmentShader into a local to defeat compiler aliasing pessimism (fsInput.textures
696 // aliases with ctx through FragmentShaderInput). Flush() already waits on workersActive before
697 // returning, so ctx is guaranteed not to be overwritten while workers run.
698 const FragmentShaderFn cachedShader = ctx.fragmentShader;
699
700 for (std::int32_t py = yMin; py <= yMax; py++, tyFix += dtyFix) {
701 // Tile-local row offset
702 const std::int32_t localRow = py - tileY;
703 const std::int32_t localCol = xMin - tileX;
704 // PARANOID: float→int rounding can push these just outside the tile
705 if DEATH_UNLIKELY(localRow < 0 || localRow >= tileH || localCol < 0 || localCol >= tileW) continue;
706 std::uint8_t* dstRow = tileBuf + (localRow * SwTileRenderer::TileSize + localCol) * 4;
707
708 // Get source Y
709 std::int32_t srcY = 0;
710 if (texPixels != nullptr) {
711 srcY = (useRepeatT)
712 ? WrapTexelFix(tyFix, texH, SamplerWrapping::Repeat)
713 : WrapTexelFix(tyFix, texH, wrapT);
714 }
715 const std::uint8_t* texRow = (texPixels != nullptr ? texPixels + static_cast<std::size_t>(srcY) * texW * texBpp : nullptr);
716
717 #if defined(DEATH_TARGET_ARM)
718 // Prefetch the next texture row
719 if (texPixels != nullptr) {
720 __builtin_prefetch(texPixels + static_cast<std::size_t>(WrapTexelFix(tyFix + dtyFix, texH, wrapT)) * texW * texBpp, 0, 1);
721 }
722 #endif
723
724 if (useScanBuf) {
725 std::int32_t txFix = txBase;
726 if (useRepeatS && !useLinear) {
727 txFix = NormalizeRepeatFix(txFix, texWFix);
728 }
729
730 // All phases fused for PaletteRemap: gather the index byte straight from the store, look
731 // the final pixel up in the LUT and blend (or store) it straight into the destination
732 // row - a native R8 index draw (tile layers, most sprites) reads 1 byte and conditionally
733 // writes 4 per pixel, with no staging round trip (the former form staged 4 bytes per
734 // pixel here and re-read them in a separate scanline blend pass), and a transparent texel
735 // never touches the destination. useScanBuf guarantees the blend is the fast pair or off.
736 // AcquirePaletteLut guarantees the guards (nearest sampling, a bound non-empty texture),
737 // they are re-checked only so an impossible state falls back to the generic path.
738 if DEATH_UNLIKELY(ctx.paletteLut != nullptr && texRow != nullptr && !useLinear) {
739 const SwPaletteLut& lut = *ctx.paletteLut;
740 if (uvSafeX && dtxFix == 65536) {
741 // uvSafeX guarantees (srcX + scanWidth - 1) < texW, so the full scanline is in-bounds
742 const std::int32_t srcX = std::max(0, std::min(texW - 1, txFix >> 16));
743 const std::uint8_t* src = &texRow[srcX * texBpp];
744 if (useFastBlend && texBpp == 1 && lut.indexByteOffset == 0 && lut.alphaByteOffset < 0) {
745 // The dominant draw (1:1 R8 indices, constant source alpha, fast blend) runs
746 // through the CPU-dispatched scanline op - AVX2 gathers 8 LUT entries per step
747 FusedLutBlendScanline(dstRow, src, scanWidth, lut.packed);
748 } else {
749 for (std::int32_t i = 0; i < scanWidth; i++) {
750 FusedPaletteLutBlendTexel(lut, src + i * texBpp, texBpp, &dstRow[i * 4], useFastBlend);
751 }
752 }
753 } else if (uvSafeX) {
754 for (std::int32_t i = 0; i < scanWidth; i++) {
755 const std::int32_t srcX = std::max(0, std::min(texW - 1, txFix >> 16));
756 FusedPaletteLutBlendTexel(lut, &texRow[srcX * texBpp], texBpp, &dstRow[i * 4], useFastBlend);
757 txFix += dtxFix;
758 }
759 } else if (useRepeatS) {
760 for (std::int32_t i = 0; i < scanWidth; i++) {
761 const std::int32_t srcX = txFix >> 16;
762 FusedPaletteLutBlendTexel(lut, &texRow[srcX * texBpp], texBpp, &dstRow[i * 4], useFastBlend);
763 txFix = AdvanceRepeatFix(txFix, dtxFix, texWFix);
764 }
765 } else {
766 for (std::int32_t i = 0; i < scanWidth; i++) {
767 const std::int32_t srcX = WrapTexelFix(txFix, texW, wrapS);
768 FusedPaletteLutBlendTexel(lut, &texRow[srcX * texBpp], texBpp, &dstRow[i * 4], useFastBlend);
769 txFix += dtxFix;
770 }
771 }
772 continue; // The destination row is final - phases 2 and 3 have nothing left to do
773 }
774
775 // Phase 1: gather texels (narrow native stores expand to the 4-byte working form here)
776 if (useLinear) {
777 const BilinearRowCtx brow = PrepareBilinearRow(texPixels, texW, texH, texBpp, tyFix, wrapT);
778 for (std::int32_t i = 0; i < scanWidth; ++i) {
779 SampleBilinearFixRow(brow, texW, texBpp, txFix, wrapS, &scanBuf[i * 4]);
780 txFix += dtxFix;
781 }
782 } else if (texRow != nullptr) {
783 if (uvSafeX && dtxFix == 65536) {
784 // uvSafeX guarantees (srcX + scanWidth - 1) < texW, so the full scanline is
785 // in-bounds; direct memcpy (4-byte stores) or a SIMD expand run
786 const std::int32_t srcX = std::max(0, std::min(texW - 1, txFix >> 16));
787 SwExpandTexelRun(scanBuf, &texRow[srcX * texBpp], scanWidth, texBpp);
788 } else if (uvSafeX) {
789 for (std::int32_t i = 0; i < scanWidth; i++) {
790 const std::int32_t srcX = std::max(0, std::min(texW - 1, txFix >> 16));
791 SwExpandTexel(&scanBuf[i * 4], &texRow[srcX * texBpp], texBpp);
792 txFix += dtxFix;
793 }
794 } else if (useRepeatS) {
795 for (std::int32_t i = 0; i < scanWidth; i++) {
796 const std::int32_t srcX = txFix >> 16;
797 SwExpandTexel(&scanBuf[i * 4], &texRow[srcX * texBpp], texBpp);
798 txFix = AdvanceRepeatFix(txFix, dtxFix, texWFix);
799 }
800 } else {
801 for (std::int32_t i = 0; i < scanWidth; i++) {
802 const std::int32_t srcX = WrapTexelFix(txFix, texW, wrapS);
803 SwExpandTexel(&scanBuf[i * 4], &texRow[srcX * texBpp], texBpp);
804 txFix += dtxFix;
805 }
806 }
807 }
808
809 // Phase 2: palette LUT, fragment shader or tint
810 if DEATH_UNLIKELY(ctx.paletteLut != nullptr) {
811 // PaletteRemap fallback for states the fused path above declined (it cannot occur for
812 // a LUT the submit-time validation accepted; kept so the two-pass result is always
813 // available): the gather already fetched the expanded texels, each pixel is a lookup.
814 ApplyPaletteLutScanline(*ctx.paletteLut, scanBuf, scanWidth);
815 } else if DEATH_UNLIKELY(cachedShader != nullptr) {
816 FragmentShaderInput fsInput;
817 fsInput.v = tyFix / 65536.0f / static_cast<float>(texH > 0 ? texH : 1);
818 fsInput.texWidth = texW;
819 fsInput.texHeight = texH;
820 fsInput.textures = ctx.textures;
821 fsInput.color = ctx.ff.color;
822 fsInput.userData = ctx.fragmentShaderUserData;
823 const float invTexW = 1.0f / static_cast<float>(texW > 0 ? texW : 1);
824 std::int32_t txFixShader = txBase;
825 for (std::int32_t i = 0; i < scanWidth; i++) {
826 fsInput.rgba = &scanBuf[i * 4];
827 fsInput.u = txFixShader / 65536.0f * invTexW;
828 fsInput.x = xMin + i;
829 fsInput.y = py;
830 cachedShader(fsInput);
831 txFixShader += dtxFix;
832 }
833 } else if DEATH_UNLIKELY(!whiteTint) {
834 TintScanline(scanBuf, scanWidth, tR, tG, tB, tA);
835 }
836
837 // Phase 3: blend or copy
838 if (useFastBlend) {
839 BlendScanlineSrcAlpha(dstRow, scanBuf, scanWidth);
840 } else {
841 std::memcpy(dstRow, scanBuf, static_cast<std::size_t>(scanWidth) * 4);
842 }
843 } else {
844 // Per-pixel path
845 std::int32_t txFix = txBase;
846 if (useRepeatS && texPixels != nullptr && !useLinear) {
847 txFix = NormalizeRepeatFix(txFix, texWFix);
848 }
849
850 for (std::int32_t px = xMin; px <= xMax; px++, dstRow += 4) {
851 std::int32_t sR, sG, sB, sA;
852 if (useLinear && texPixels != nullptr) {
853 std::uint8_t raw[4];
854 SampleBilinearFix(texPixels, texW, texH, texBpp, txFix, tyFix, wrapS, wrapT, raw);
855 txFix += dtxFix;
856 sR = raw[0]; sG = raw[1]; sB = raw[2]; sA = raw[3];
857 } else if (texRow != nullptr) {
858 std::int32_t srcX;
859 if (useRepeatS) {
860 srcX = txFix >> 16;
861 txFix = AdvanceRepeatFix(txFix, dtxFix, texWFix);
862 } else if (uvSafeX) {
863 srcX = txFix >> 16;
864 txFix += dtxFix;
865 } else {
866 srcX = WrapTexelFix(txFix, texW, wrapS);
867 txFix += dtxFix;
868 }
869 std::uint8_t raw[4];
870 SwExpandTexel(raw, &texRow[srcX * texBpp], texBpp);
871 sR = raw[0]; sG = raw[1]; sB = raw[2]; sA = raw[3];
872 } else {
873 sR = 255; sG = 255; sB = 255; sA = 255;
874 txFix += dtxFix;
875 }
876
877 if DEATH_UNLIKELY(ctx.paletteLut != nullptr) {
878 // PaletteRemap fast path (see the scanline variant above)
879 std::uint8_t px4[4] = {
880 static_cast<std::uint8_t>(sR), static_cast<std::uint8_t>(sG),
881 static_cast<std::uint8_t>(sB), static_cast<std::uint8_t>(sA)
882 };
883 ApplyPaletteLutPixel(*ctx.paletteLut, px4);
884 sR = px4[0]; sG = px4[1]; sB = px4[2]; sA = px4[3];
885 } else if DEATH_UNLIKELY(prep.constantFill) {
886 // Solid fill under generic blend factors: consume the precomputed constant
887 // (identical to what the fragment would write) instead of calling it per pixel
888 sR = prep.constColor[0]; sG = prep.constColor[1]; sB = prep.constColor[2]; sA = prep.constColor[3];
889 } else if DEATH_UNLIKELY(cachedShader != nullptr) {
890 std::uint8_t px4[4] = {
891 static_cast<std::uint8_t>(sR), static_cast<std::uint8_t>(sG),
892 static_cast<std::uint8_t>(sB), static_cast<std::uint8_t>(sA)
893 };
894 FragmentShaderInput fsInput;
895 fsInput.rgba = px4;
896 fsInput.u = (txFix - dtxFix) / 65536.0f / static_cast<float>(texW > 0 ? texW : 1);
897 fsInput.v = tyFix / 65536.0f / static_cast<float>(texH > 0 ? texH : 1);
898 fsInput.x = px;
899 fsInput.y = py;
900 fsInput.texWidth = texW;
901 fsInput.texHeight = texH;
902 fsInput.textures = ctx.textures;
903 fsInput.color = ctx.ff.color;
904 fsInput.userData = ctx.fragmentShaderUserData;
905 cachedShader(fsInput);
906 sR = px4[0]; sG = px4[1]; sB = px4[2]; sA = px4[3];
907 } else if (!whiteTint) {
908 sR = (sR * tR) >> 8;
909 sG = (sG * tG) >> 8;
910 sB = (sB * tB) >> 8;
911 sA = (sA * tA) >> 8;
912 }
913
914 if (useBlend) {
915 if (sA == 0) continue;
916 if (useFastBlend) {
917 if (sA >= 255) {
918 dstRow[0] = static_cast<std::uint8_t>(sR);
919 dstRow[1] = static_cast<std::uint8_t>(sG);
920 dstRow[2] = static_cast<std::uint8_t>(sB);
921 dstRow[3] = static_cast<std::uint8_t>(sA);
922 } else {
923 const std::int32_t inv = 255 - sA;
924 dstRow[0] = static_cast<std::uint8_t>((sR * sA + dstRow[0] * inv) >> 8);
925 dstRow[1] = static_cast<std::uint8_t>((sG * sA + dstRow[1] * inv) >> 8);
926 dstRow[2] = static_cast<std::uint8_t>((sB * sA + dstRow[2] * inv) >> 8);
927 dstRow[3] = static_cast<std::uint8_t>((sA * 255 + dstRow[3] * inv) >> 8);
928 }
929 } else {
930 // Generic blend
931 const float srcRf = sR / 255.0f, srcGf = sG / 255.0f, srcBf = sB / 255.0f, srcAf = sA / 255.0f;
932 const float dstRf = dstRow[0] / 255.0f, dstGf = dstRow[1] / 255.0f, dstBf = dstRow[2] / 255.0f, dstAf = dstRow[3] / 255.0f;
933 auto bf = [&](SwBlendFactor f, float c) -> float {
934 switch (f) {
935 case SwBlendFactor::Zero: return 0.0f;
936 case SwBlendFactor::One: return c;
937 case SwBlendFactor::SrcAlpha: return c * srcAf;
938 case SwBlendFactor::OneMinusSrcAlpha: return c * (1.0f - srcAf);
939 case SwBlendFactor::DstAlpha: return c * dstAf;
940 case SwBlendFactor::OneMinusDstAlpha: return c * (1.0f - dstAf);
941 default: return c;
942 }
943 };
944 auto clamp01 = [](float v) { return v < 0.0f ? 0.0f : (v > 1.0f ? 1.0f : v); };
945 dstRow[0] = static_cast<std::uint8_t>(clamp01(bf(ctx.blendSrc, srcRf) + bf(ctx.blendDst, dstRf)) * 255.0f);
946 dstRow[1] = static_cast<std::uint8_t>(clamp01(bf(ctx.blendSrc, srcGf) + bf(ctx.blendDst, dstGf)) * 255.0f);
947 dstRow[2] = static_cast<std::uint8_t>(clamp01(bf(ctx.blendSrc, srcBf) + bf(ctx.blendDst, dstBf)) * 255.0f);
948 dstRow[3] = static_cast<std::uint8_t>(clamp01(bf(ctx.blendSrc, srcAf) + bf(ctx.blendDst, dstAf)) * 255.0f);
949 }
950 } else {
951 dstRow[0] = static_cast<std::uint8_t>(sR);
952 dstRow[1] = static_cast<std::uint8_t>(sG);
953 dstRow[2] = static_cast<std::uint8_t>(sB);
954 dstRow[3] = static_cast<std::uint8_t>(sA);
955 }
956 }
957 }
958 }
959 }
960
961 // =====================================================================
962 // Tile-local affine quad rasterizer (rotated/scaled sprites)
963 // The per-command state (vertices, UV gradients, edge-function increments, texture / tint / blend
964 // derivation) comes precomputed in `prep` (see PrepareQuad); only the tile clip and the row walk
965 // remain per-tile, evaluated with the identical expressions.
966 // =====================================================================
967 static void DrawAffineQuadTile(const DrawContext& ctx, const SwTileRenderer::PreparedQuad& prep,
968 std::uint8_t* tileBuf, std::int32_t tileX, std::int32_t tileY,
969 std::int32_t tileW, std::int32_t tileH)
970 {
971 // Precomputed per-command state (local names kept so the loops below stay verbatim)
972 const Vertex2D v0 = prep.v[0], v1 = prep.v[1], v2 = prep.v[2], v3 = prep.v[3];
973 const float dudx = prep.dudx, dudy = prep.dudy;
974 const float dvdx = prep.dvdx, dvdy = prep.dvdy;
975 const float t1_w0_dx = prep.t1w0dx, t1_w1_dx = prep.t1w1dx, t1_w2_dx = prep.t1w2dx;
976 const float t2_w0_dx = prep.t2w0dx, t2_w1_dx = prep.t2w1dx, t2_w2_dx = prep.t2w2dx;
977 const bool sign1 = prep.sign1;
978 const bool sign2 = prep.sign2;
979
980 // Clip to tile bounds
981 std::int32_t xMin = tileX, xMax = tileX + tileW - 1;
982 std::int32_t yMin = tileY, yMax = tileY + tileH - 1;
983
984 // Also clip to the quad bounding box
985 xMin = std::max(xMin, static_cast<std::int32_t>(prep.fxMin));
986 xMax = std::min(xMax, static_cast<std::int32_t>(prep.fxMax));
987 yMin = std::max(yMin, static_cast<std::int32_t>(prep.fyMin));
988 yMax = std::min(yMax, static_cast<std::int32_t>(prep.fyMax));
989
990 if (ctx.scissorEnabled) {
991 xMin = std::max(xMin, ctx.scissorRect.X);
992 xMax = std::min(xMax, ctx.scissorRect.X + ctx.scissorRect.W - 1);
993 yMin = std::max(yMin, ctx.scissorRect.Y);
994 yMax = std::min(yMax, ctx.scissorRect.Y + ctx.scissorRect.H - 1);
995 }
996 if (xMin > xMax || yMin > yMax) return;
997
998 const std::uint8_t* texPixels = prep.texPixels;
999 const std::int32_t texW = prep.texW;
1000 const std::int32_t texH = prep.texH;
1001 const std::int32_t texBpp = prep.texBpp;
1002 const SamplerWrapping wrapS = prep.wrapS;
1003 const SamplerWrapping wrapT = prep.wrapT;
1004 const bool useLinear = prep.useLinear;
1005 const std::int32_t tR = prep.tR, tG = prep.tG, tB = prep.tB, tA = prep.tA;
1006 const bool whiteTint = prep.whiteTint;
1007 const bool useBlend = prep.useBlend;
1008 const bool useFastBlend = prep.useFastBlend;
1009 const std::int32_t dudxFix = prep.dudxFix;
1010 const std::int32_t dvdxFix = prep.dvdxFix;
1011
1012 const FragmentShaderFn cachedShader = ctx.fragmentShader;
1013
1014 // Fully transparent solid fill under the fast blend: every pixel would be skipped
1015 if DEATH_UNLIKELY(prep.constantFill && useFastBlend && prep.constColor[3] == 0) {
1016 return;
1017 }
1018
1019 for (std::int32_t py = yMin; py <= yMax; py++) {
1020 const float pyCtr = py + 0.5f;
1021 const std::int32_t localRow = py - tileY;
1022
1023 // Edge functions at start of row
1024 float px0f = xMin + 0.5f;
1025 float t1_w0 = (v2.x - v1.x) * (pyCtr - v1.y) - (v2.y - v1.y) * (px0f - v1.x);
1026 float t1_w1 = (v0.x - v2.x) * (pyCtr - v2.y) - (v0.y - v2.y) * (px0f - v2.x);
1027 float t1_w2 = (v1.x - v0.x) * (pyCtr - v0.y) - (v1.y - v0.y) * (px0f - v0.x);
1028 float t2_w0 = (v3.x - v1.x) * (pyCtr - v1.y) - (v3.y - v1.y) * (px0f - v1.x);
1029 float t2_w1 = (v2.x - v3.x) * (pyCtr - v3.y) - (v2.y - v3.y) * (px0f - v3.x);
1030 float t2_w2 = (v1.x - v2.x) * (pyCtr - v2.y) - (v1.y - v2.y) * (px0f - v2.x);
1031
1032 // UV at start of row
1033 float relX = px0f - v0.x;
1034 float relY = pyCtr - v0.y;
1035 float uStart = v0.u + dudx * relX + dudy * relY;
1036 float vStart = v0.v + dvdx * relX + dvdy * relY;
1037
1038 std::int32_t uFix = (texPixels != nullptr ? static_cast<std::int32_t>(uStart * texW * 65536.0f) : 0);
1039 std::int32_t vFix = (texPixels != nullptr ? static_cast<std::int32_t>(vStart * texH * 65536.0f) : 0);
1040
1041 for (std::int32_t px = xMin; px <= xMax; px++) {
1042 bool in1 = prep.tri1Valid &&
1043 ((t1_w0 >= 0.0f) == sign1) && ((t1_w1 >= 0.0f) == sign1) && ((t1_w2 >= 0.0f) == sign1);
1044 bool in2 = prep.tri2Valid &&
1045 ((t2_w0 >= 0.0f) == sign2) && ((t2_w1 >= 0.0f) == sign2) && ((t2_w2 >= 0.0f) == sign2);
1046
1047 if (in1 || in2) {
1048 const std::int32_t localCol = px - tileX;
1049 // PARANOID: float→int rounding can push these just outside the tile
1050 if DEATH_UNLIKELY(localRow < 0 || localRow >= tileH || localCol < 0 || localCol >= tileW) goto NextPixel;
1051 {
1052 std::uint8_t* dstPx = tileBuf + (localRow * SwTileRenderer::TileSize + localCol) * 4;
1053
1054 std::int32_t sR, sG, sB, sA;
1055 if (texPixels != nullptr) {
1056 if (useLinear) {
1057 std::uint8_t raw[4];
1058 SampleBilinearFix(texPixels, texW, texH, texBpp, uFix, vFix, wrapS, wrapT, raw);
1059 sR = raw[0]; sG = raw[1]; sB = raw[2]; sA = raw[3];
1060 } else {
1061 std::int32_t srcX = std::max(0, std::min(texW - 1, WrapTexelFix(uFix, texW, wrapS)));
1062 std::int32_t srcY = std::max(0, std::min(texH - 1, WrapTexelFix(vFix, texH, wrapT)));
1063 std::uint8_t raw[4];
1064 SwExpandTexel(raw, texPixels + (static_cast<std::size_t>(srcY) * texW + srcX) * texBpp, texBpp);
1065 sR = raw[0]; sG = raw[1]; sB = raw[2]; sA = raw[3];
1066 }
1067 } else {
1068 sR = 255; sG = 255; sB = 255; sA = 255;
1069 }
1070
1071 // Palette LUT, constant fill, tint or shader
1072 if DEATH_UNLIKELY(ctx.paletteLut != nullptr) {
1073 // PaletteRemap fast path (see the scanline variant above); rotated palette
1074 // sprites land here
1075 std::uint8_t px4[4] = {
1076 static_cast<std::uint8_t>(sR), static_cast<std::uint8_t>(sG),
1077 static_cast<std::uint8_t>(sB), static_cast<std::uint8_t>(sA)
1078 };
1079 ApplyPaletteLutPixel(*ctx.paletteLut, px4);
1080 sR = px4[0]; sG = px4[1]; sB = px4[2]; sA = px4[3];
1081 } else if DEATH_UNLIKELY(prep.constantFill) {
1082 // Rotated solid fill: consume the precomputed constant (identical to what
1083 // the fragment would write) instead of calling it per pixel
1084 sR = prep.constColor[0]; sG = prep.constColor[1]; sB = prep.constColor[2]; sA = prep.constColor[3];
1085 } else if DEATH_UNLIKELY(cachedShader != nullptr) {
1086 std::uint8_t px4[4] = {
1087 static_cast<std::uint8_t>(sR), static_cast<std::uint8_t>(sG),
1088 static_cast<std::uint8_t>(sB), static_cast<std::uint8_t>(sA)
1089 };
1090 FragmentShaderInput fsInput;
1091 fsInput.rgba = px4;
1092 fsInput.u = uFix / 65536.0f / static_cast<float>(texW > 0 ? texW : 1);
1093 fsInput.v = vFix / 65536.0f / static_cast<float>(texH > 0 ? texH : 1);
1094 fsInput.x = px;
1095 fsInput.y = py;
1096 fsInput.texWidth = texW;
1097 fsInput.texHeight = texH;
1098 fsInput.textures = ctx.textures;
1099 fsInput.color = ctx.ff.color;
1100 fsInput.userData = ctx.fragmentShaderUserData;
1101 cachedShader(fsInput);
1102 sR = px4[0]; sG = px4[1]; sB = px4[2]; sA = px4[3];
1103 } else if DEATH_UNLIKELY(!whiteTint) {
1104 sR = (sR * tR) >> 8;
1105 sG = (sG * tG) >> 8;
1106 sB = (sB * tB) >> 8;
1107 sA = (sA * tA) >> 8;
1108 }
1109
1110 // Blend
1111 if (useBlend) {
1112 if (sA == 0) goto NextPixel;
1113 if (useFastBlend) {
1114 if (sA >= 255) {
1115 dstPx[0] = static_cast<std::uint8_t>(sR);
1116 dstPx[1] = static_cast<std::uint8_t>(sG);
1117 dstPx[2] = static_cast<std::uint8_t>(sB);
1118 dstPx[3] = static_cast<std::uint8_t>(sA);
1119 } else {
1120 const std::int32_t inv = 255 - sA;
1121 dstPx[0] = static_cast<std::uint8_t>((sR * sA + dstPx[0] * inv) >> 8);
1122 dstPx[1] = static_cast<std::uint8_t>((sG * sA + dstPx[1] * inv) >> 8);
1123 dstPx[2] = static_cast<std::uint8_t>((sB * sA + dstPx[2] * inv) >> 8);
1124 dstPx[3] = static_cast<std::uint8_t>((sA * 255 + dstPx[3] * inv) >> 8);
1125 }
1126 } else {
1127 const float srcRf = sR / 255.0f, srcGf = sG / 255.0f, srcBf = sB / 255.0f, srcAf = sA / 255.0f;
1128 const float dstRf = dstPx[0] / 255.0f, dstGf = dstPx[1] / 255.0f, dstBf = dstPx[2] / 255.0f, dstAf = dstPx[3] / 255.0f;
1129 auto bf = [&](SwBlendFactor f, float c) -> float {
1130 switch (f) {
1131 case SwBlendFactor::Zero: return 0.0f;
1132 case SwBlendFactor::One: return c;
1133 case SwBlendFactor::SrcAlpha: return c * srcAf;
1134 case SwBlendFactor::OneMinusSrcAlpha: return c * (1.0f - srcAf);
1135 case SwBlendFactor::DstAlpha: return c * dstAf;
1136 case SwBlendFactor::OneMinusDstAlpha: return c * (1.0f - dstAf);
1137 default: return c;
1138 }
1139 };
1140 auto clamp01 = [](float v) { return v < 0.0f ? 0.0f : (v > 1.0f ? 1.0f : v); };
1141 dstPx[0] = static_cast<std::uint8_t>(clamp01(bf(ctx.blendSrc, srcRf) + bf(ctx.blendDst, dstRf)) * 255.0f);
1142 dstPx[1] = static_cast<std::uint8_t>(clamp01(bf(ctx.blendSrc, srcGf) + bf(ctx.blendDst, dstGf)) * 255.0f);
1143 dstPx[2] = static_cast<std::uint8_t>(clamp01(bf(ctx.blendSrc, srcBf) + bf(ctx.blendDst, dstBf)) * 255.0f);
1144 dstPx[3] = static_cast<std::uint8_t>(clamp01(bf(ctx.blendSrc, srcAf) + bf(ctx.blendDst, dstAf)) * 255.0f);
1145 }
1146 } else {
1147 dstPx[0] = static_cast<std::uint8_t>(sR);
1148 dstPx[1] = static_cast<std::uint8_t>(sG);
1149 dstPx[2] = static_cast<std::uint8_t>(sB);
1150 dstPx[3] = static_cast<std::uint8_t>(sA);
1151 }
1152 }
1153 }
1154
1155 NextPixel:
1156 t1_w0 += t1_w0_dx; t1_w1 += t1_w1_dx; t1_w2 += t1_w2_dx;
1157 t2_w0 += t2_w0_dx; t2_w1 += t2_w1_dx; t2_w2 += t2_w2_dx;
1158 uFix += dudxFix; vFix += dvdxFix;
1159 }
1160 }
1161 }
1162
1163 // =====================================================================
1164 // Main entry point: render a single command into the tile buffer
1165 // =====================================================================
1166 void RenderCommandToTile(const DrawContext& ctx, const SwTileRenderer::PreparedQuad* prep,
1167 PrimitiveType type,
1168 std::int32_t firstVertex, std::int32_t count,
1169 std::uint8_t* tileBuffer, std::int32_t tileX, std::int32_t tileY,
1170 std::int32_t tileW, std::int32_t tileH,
1171 std::int32_t viewportX, std::int32_t viewportY,
1172 std::int32_t viewportW, std::int32_t viewportH)
1173 {
1174 // Fast path: procedural 4-vertex quad (most common case). SubmitCommand prepared the vertices
1175 // and derived state once per command; a caller without a prepared command derives one locally.
1176 if DEATH_LIKELY(type == PrimitiveType::TriangleStrip && count == 4 && firstVertex == 0 &&
1177 ctx.vertexData == nullptr) {
1178 SwTileRenderer::PreparedQuad localPrep;
1179 if DEATH_UNLIKELY(prep == nullptr) {
1180 PrepareQuad(ctx, viewportX, viewportY, viewportW, viewportH, localPrep);
1181 prep = &localPrep;
1182 }
1183 if DEATH_UNLIKELY(!prep->valid) {
1184 return; // degenerate quad — draws nothing on any path
1185 }
1186 if (prep->axisAligned) {
1187 DrawAxisAlignedQuadTile(ctx, *prep, tileBuffer, tileX, tileY, tileW, tileH);
1188 } else {
1189 DrawAffineQuadTile(ctx, *prep, tileBuffer, tileX, tileY, tileW, tileH);
1190 }
1191 return;
1192 }
1193
1194 // Generic triangle rasterization path (per-pixel, tile-clipped)
1195 SmallVector<std::int32_t, 6> indices;
1196 if (type == PrimitiveType::TriangleStrip || type == PrimitiveType::Triangles || type == PrimitiveType::TriangleFan) {
1197 indices.resize(static_cast<std::size_t>(count));
1198 for (std::int32_t i = 0; i < count; ++i) {
1199 indices[i] = firstVertex + i;
1200 }
1201 }
1202
1203 auto rasterTri = [&](Vertex2D va, Vertex2D vb, Vertex2D vc) {
1204 // Simplified triangle rasterizer clipped to the tile
1205 float w0_dx = vb.y - vc.y, w0_dy = vc.x - vb.x;
1206 float w1_dx = vc.y - va.y, w1_dy = va.x - vc.x;
1207 float w2_dx = va.y - vb.y, w2_dy = vb.x - va.x;
1208 float area = (vc.x - vb.x) * (va.y - vb.y) - (vc.y - vb.y) * (va.x - vb.x);
1209 if DEATH_UNLIKELY(std::fabs(area) < 1e-6f) {
1210 return;
1211 }
1212 // Orientation-normalize so the interior is positive for every winding, then decide the
1213 // exact w == 0 edge pixels with a top-left fill rule (include when the normalized edge
1214 // gradient points right, or straight down for horizontal edges). Two strip triangles
1215 // sharing a diagonal then cover each of its pixels exactly once - the previous symmetric
1216 // ">= vs sign" rule made both triangles exclude (or both include) the shared edge,
1217 // leaving a one-pixel crack (or a double-blend seam) across mesh strips.
1218 const float orient = (area > 0.0f ? 1.0f : -1.0f);
1219 area *= orient;
1220 w0_dx *= orient; w0_dy *= orient;
1221 w1_dx *= orient; w1_dy *= orient;
1222 w2_dx *= orient; w2_dy *= orient;
1223 const float invArea = 1.0f / area;
1224 const bool incl0 = (w0_dx > 0.0f || (w0_dx == 0.0f && w0_dy > 0.0f));
1225 const bool incl1 = (w1_dx > 0.0f || (w1_dx == 0.0f && w1_dy > 0.0f));
1226 const bool incl2 = (w2_dx > 0.0f || (w2_dx == 0.0f && w2_dy > 0.0f));
1227
1228 std::int32_t minX = std::max(tileX, static_cast<std::int32_t>(std::min({va.x, vb.x, vc.x})));
1229 std::int32_t maxX = std::min(tileX + tileW - 1, static_cast<std::int32_t>(std::max({va.x, vb.x, vc.x})));
1230 std::int32_t minY = std::max(tileY, static_cast<std::int32_t>(std::min({va.y, vb.y, vc.y})));
1231 std::int32_t maxY = std::min(tileY + tileH - 1, static_cast<std::int32_t>(std::max({va.y, vb.y, vc.y})));
1232
1233 if DEATH_UNLIKELY(ctx.scissorEnabled) {
1234 minX = std::max(minX, ctx.scissorRect.X);
1235 maxX = std::min(maxX, ctx.scissorRect.X + ctx.scissorRect.W - 1);
1236 minY = std::max(minY, ctx.scissorRect.Y);
1237 maxY = std::min(maxY, ctx.scissorRect.Y + ctx.scissorRect.H - 1);
1238 }
1239 if DEATH_UNLIKELY(minX > maxX || minY > maxY) {
1240 return;
1241 }
1242
1243 const SwTexture* tex = (ctx.ff.hasTexture && ctx.ff.textureUnit < static_cast<std::int32_t>(MaxTextureUnits)
1244 ? ctx.textures[ctx.ff.textureUnit] : nullptr);
1245 const std::uint8_t* texPixels = (tex != nullptr ? tex->GetPixels(0) : nullptr);
1246 const std::int32_t texW = (tex != nullptr ? tex->GetWidth() : 0);
1247 const std::int32_t texH = (tex != nullptr ? tex->GetHeight() : 0);
1248 const std::int32_t texBpp = (tex != nullptr ? tex->GetBytesPerPixel() : 4);
1249 if DEATH_UNLIKELY(texPixels != nullptr && (texW <= 0 || texH <= 0)) {
1250 texPixels = nullptr; // Malformed texture - treat as untextured (see PrepareQuad's guard)
1251 }
1252 const SamplerWrapping wrapS = (tex != nullptr ? tex->GetWrapS() : SamplerWrapping::ClampToEdge);
1253 const SamplerWrapping wrapT = (tex != nullptr ? tex->GetWrapT() : SamplerWrapping::ClampToEdge);
1254 const bool useLinear = (tex != nullptr && tex->GetMagFilter() == SamplerFilter::Linear && texW > 1 && texH > 1);
1255
1256 const std::int32_t tR = static_cast<std::int32_t>(std::min(1.0f, ctx.ff.color[0]) * 255.0f + 0.5f);
1257 const std::int32_t tG = static_cast<std::int32_t>(std::min(1.0f, ctx.ff.color[1]) * 255.0f + 0.5f);
1258 const std::int32_t tB = static_cast<std::int32_t>(std::min(1.0f, ctx.ff.color[2]) * 255.0f + 0.5f);
1259 const std::int32_t tA = static_cast<std::int32_t>(std::min(1.0f, ctx.ff.color[3]) * 255.0f + 0.5f);
1260 const bool useBlend = ctx.blendingEnabled;
1261 const bool useFastBlend = (useBlend && ctx.blendSrc == SwBlendFactor::SrcAlpha && ctx.blendDst == SwBlendFactor::OneMinusSrcAlpha);
1262 const FragmentShaderFn cachedShader = ctx.fragmentShader;
1263
1264 const float px0f = minX + 0.5f, py0f = minY + 0.5f;
1265 float w0_row = orient * ((vc.x - vb.x) * (py0f - vb.y) - (vc.y - vb.y) * (px0f - vb.x));
1266 float w1_row = orient * ((va.x - vc.x) * (py0f - vc.y) - (va.y - vc.y) * (px0f - vc.x));
1267 float w2_row = orient * ((vb.x - va.x) * (py0f - va.y) - (vb.y - va.y) * (px0f - va.x));
1268
1269 for (std::int32_t py = minY; py <= maxY; py++) {
1270 float w0 = w0_row, w1 = w1_row, w2 = w2_row;
1271 for (std::int32_t px = minX; px <= maxX; ++px, w0 += w0_dx, w1 += w1_dx, w2 += w2_dx) {
1272 if ((w0 < 0.0f || (w0 == 0.0f && !incl0)) ||
1273 (w1 < 0.0f || (w1 == 0.0f && !incl1)) ||
1274 (w2 < 0.0f || (w2 == 0.0f && !incl2))) {
1275 continue;
1276 }
1277
1278 const float b0 = w0 * invArea, b1 = w1 * invArea, b2 = w2 * invArea;
1279 float u = b0 * va.u + b1 * vb.u + b2 * vc.u;
1280 float vv = b0 * va.v + b1 * vb.v + b2 * vc.v;
1281
1282 // The sampling below is a verbatim copy of the immediate path's RasterizeTriangle
1283 // (SwRaster.cpp) so a deferred triangle produces the same bytes as an immediate one
1284 std::int32_t sR, sG, sB, sA;
1285 if (texPixels != nullptr && useLinear) {
1286 u = WrapUV(u, wrapS);
1287 vv = WrapUV(vv, wrapT);
1288 std::uint8_t raw[4];
1289 SampleBilinearFloat(texPixels, texW, texH, texBpp, u, vv, wrapS, wrapT, raw);
1290 sR = raw[0]; sG = raw[1]; sB = raw[2]; sA = raw[3];
1291 } else if (texPixels != nullptr) {
1292 u = WrapUV(u, wrapS);
1293 vv = WrapUV(vv, wrapT);
1294 const std::int32_t srcX = std::max(0, std::min(texW - 1, static_cast<std::int32_t>(u * (texW - 1) + 0.5f)));
1295 const std::int32_t srcY = std::max(0, std::min(texH - 1, static_cast<std::int32_t>(vv * (texH - 1) + 0.5f)));
1296 std::uint8_t raw[4];
1297 SwExpandTexel(raw, texPixels + (srcY * texW + srcX) * texBpp, texBpp);
1298 sR = raw[0]; sG = raw[1]; sB = raw[2]; sA = raw[3];
1299 } else {
1300 sR = 255; sG = 255; sB = 255; sA = 255;
1301 }
1302
1303 // Apply the transpiled fragment or the vertex-color tint (same as the immediate path)
1304 if DEATH_UNLIKELY(cachedShader != nullptr) {
1305 std::uint8_t px4[4] = {
1306 static_cast<std::uint8_t>(sR), static_cast<std::uint8_t>(sG),
1307 static_cast<std::uint8_t>(sB), static_cast<std::uint8_t>(sA)
1308 };
1309 FragmentShaderInput fsInput;
1310 fsInput.rgba = px4;
1311 fsInput.u = u;
1312 fsInput.v = vv;
1313 fsInput.x = px;
1314 fsInput.y = py;
1315 fsInput.texWidth = texW;
1316 fsInput.texHeight = texH;
1317 fsInput.textures = ctx.textures;
1318 fsInput.color = ctx.ff.color;
1319 fsInput.userData = ctx.fragmentShaderUserData;
1320 cachedShader(fsInput);
1321 sR = px4[0]; sG = px4[1]; sB = px4[2]; sA = px4[3];
1322 } else {
1323 sR = (sR * tR) >> 8; sG = (sG * tG) >> 8;
1324 sB = (sB * tB) >> 8; sA = (sA * tA) >> 8;
1325 }
1326
1327 const std::int32_t localRow = py - tileY;
1328 const std::int32_t localCol = px - tileX;
1329 std::uint8_t* dstPx = tileBuffer + (localRow * SwTileRenderer::TileSize + localCol) * 4;
1330
1331 if (useBlend) {
1332 if (sA == 0) continue;
1333 if (useFastBlend) {
1334 if (sA >= 255) {
1335 dstPx[0] = static_cast<std::uint8_t>(sR); dstPx[1] = static_cast<std::uint8_t>(sG);
1336 dstPx[2] = static_cast<std::uint8_t>(sB); dstPx[3] = static_cast<std::uint8_t>(sA);
1337 } else {
1338 const std::int32_t inv = 255 - sA;
1339 dstPx[0] = static_cast<std::uint8_t>((sR * sA + dstPx[0] * inv) >> 8);
1340 dstPx[1] = static_cast<std::uint8_t>((sG * sA + dstPx[1] * inv) >> 8);
1341 dstPx[2] = static_cast<std::uint8_t>((sB * sA + dstPx[2] * inv) >> 8);
1342 dstPx[3] = static_cast<std::uint8_t>((sA * 255 + dstPx[3] * inv) >> 8);
1343 }
1344 } else {
1345 // Generic blend (same float math as the affine tile rasterizer above)
1346 const float srcRf = sR / 255.0f, srcGf = sG / 255.0f, srcBf = sB / 255.0f, srcAf = sA / 255.0f;
1347 const float dstRf = dstPx[0] / 255.0f, dstGf = dstPx[1] / 255.0f, dstBf = dstPx[2] / 255.0f, dstAf = dstPx[3] / 255.0f;
1348 auto bf = [&](SwBlendFactor f, float c) -> float {
1349 switch (f) {
1350 case SwBlendFactor::Zero: return 0.0f;
1351 case SwBlendFactor::One: return c;
1352 case SwBlendFactor::SrcAlpha: return c * srcAf;
1353 case SwBlendFactor::OneMinusSrcAlpha: return c * (1.0f - srcAf);
1354 case SwBlendFactor::DstAlpha: return c * dstAf;
1355 case SwBlendFactor::OneMinusDstAlpha: return c * (1.0f - dstAf);
1356 default: return c;
1357 }
1358 };
1359 auto clamp01 = [](float v) { return v < 0.0f ? 0.0f : (v > 1.0f ? 1.0f : v); };
1360 dstPx[0] = static_cast<std::uint8_t>(clamp01(bf(ctx.blendSrc, srcRf) + bf(ctx.blendDst, dstRf)) * 255.0f);
1361 dstPx[1] = static_cast<std::uint8_t>(clamp01(bf(ctx.blendSrc, srcGf) + bf(ctx.blendDst, dstGf)) * 255.0f);
1362 dstPx[2] = static_cast<std::uint8_t>(clamp01(bf(ctx.blendSrc, srcBf) + bf(ctx.blendDst, dstBf)) * 255.0f);
1363 dstPx[3] = static_cast<std::uint8_t>(clamp01(bf(ctx.blendSrc, srcAf) + bf(ctx.blendDst, dstAf)) * 255.0f);
1364 }
1365 } else {
1366 dstPx[0] = static_cast<std::uint8_t>(sR); dstPx[1] = static_cast<std::uint8_t>(sG);
1367 dstPx[2] = static_cast<std::uint8_t>(sB); dstPx[3] = static_cast<std::uint8_t>(sA);
1368 }
1369 }
1370 w0_row += w0_dy; w1_row += w1_dy; w2_row += w2_dy;
1371 }
1372 };
1373
1374 // Dispatch based on primitive type
1375 switch (type) {
1376 case PrimitiveType::Triangles:
1377 for (std::size_t i = 0; i + 2 < indices.size(); i += 3) {
1378 rasterTri(FetchVertex(ctx, indices[i], viewportX, viewportY, viewportW, viewportH),
1379 FetchVertex(ctx, indices[i + 1], viewportX, viewportY, viewportW, viewportH),
1380 FetchVertex(ctx, indices[i + 2], viewportX, viewportY, viewportW, viewportH));
1381 }
1382 break;
1383 case PrimitiveType::TriangleStrip:
1384 for (std::size_t i = 0; i + 2 < indices.size(); i++) {
1385 if (i & 1) {
1386 rasterTri(FetchVertex(ctx, indices[i], viewportX, viewportY, viewportW, viewportH),
1387 FetchVertex(ctx, indices[i + 2], viewportX, viewportY, viewportW, viewportH),
1388 FetchVertex(ctx, indices[i + 1], viewportX, viewportY, viewportW, viewportH));
1389 } else {
1390 rasterTri(FetchVertex(ctx, indices[i], viewportX, viewportY, viewportW, viewportH),
1391 FetchVertex(ctx, indices[i + 1], viewportX, viewportY, viewportW, viewportH),
1392 FetchVertex(ctx, indices[i + 2], viewportX, viewportY, viewportW, viewportH));
1393 }
1394 }
1395 break;
1396 case PrimitiveType::TriangleFan:
1397 for (std::size_t i = 1; i + 1 < indices.size(); i++) {
1398 rasterTri(FetchVertex(ctx, indices[0], viewportX, viewportY, viewportW, viewportH),
1399 FetchVertex(ctx, indices[i], viewportX, viewportY, viewportW, viewportH),
1400 FetchVertex(ctx, indices[i + 1], viewportX, viewportY, viewportW, viewportH));
1401 }
1402 break;
1403 default:
1404 break;
1405 }
1406 }
1407 }
1408 }
1409
1410 #endif