Debian Codegraph @

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

raw
1 #if defined(WITH_RHI_SOFTWARE)
2
3 #include "SwTileRenderer.h"
4 #include "SwShaderRuntime.h" // sw::swTexture / sw::floor / sw::mod, replicated by the palette-LUT builder
5
6 #include <Containers/SmallVector.h>
7
8 #if defined(DEATH_ENABLE_NEON)
9 # include <arm_neon.h>
10 #endif
11
12 #include <algorithm>
13 #include <atomic>
14 #include <cfloat>
15 #include <cstring>
16
17 using namespace Death::Containers;
18
19 namespace nCine::RHI::Software
20 {
21 // Per-tile rasterization entry points, defined in SwTileRasterizer.cpp. Kept in this internal namespace
22 // so they have external linkage across the two translation units without leaking into the public API.
23 namespace TileInternal
24 {
25 void PrepareQuad(const DrawContext& ctx, std::int32_t viewportX, std::int32_t viewportY,
26 std::int32_t viewportW, std::int32_t viewportH, SwTileRenderer::PreparedQuad& prep);
27
28 void RenderCommandToTile(const DrawContext& ctx, const SwTileRenderer::PreparedQuad* prep,
29 PrimitiveType type,
30 std::int32_t firstVertex, std::int32_t count,
31 std::uint8_t* tileBuffer, std::int32_t tileX, std::int32_t tileY,
32 std::int32_t tileW, std::int32_t tileH,
33 std::int32_t viewportX, std::int32_t viewportY,
34 std::int32_t viewportW, std::int32_t viewportH);
35 }
36
37 namespace SwTileRenderer
38 {
39 // =====================================================================
40 // Internal state
41 // =====================================================================
42 namespace
43 {
44 // Cache key of one palette LUT within a flush window. Draws sharing the palette texture (and
45 // its content version), the palette row offset, the tint and the index-texture byte mapping
46 // produce identical tables - and one frame of tile-layer draws submits hundreds of such
47 // commands - so SubmitCommand reuses a pooled table instead of rebuilding 256 entries per draw.
48 struct PaletteLutKey
49 {
50 const SwTexture* palette;
51 std::uint32_t paletteVersion;
52 float paletteOffset;
53 float tint[4];
54 std::int32_t indexByteOffset;
55 std::int32_t alphaByteOffset;
56 };
57
58 struct TileState
59 {
60 bool initialized = false;
61 std::int32_t fbWidth = 0;
62 std::int32_t fbHeight = 0;
63 std::int32_t tilesX = 0;
64 std::int32_t tilesY = 0;
65 std::int32_t totalTiles = 0;
66
67 // Viewport snapshotted into each submitted command (mirrors SwRaster's viewport so the
68 // deferred vertex transform is identical to the immediate one)
69 std::int32_t viewportX = 0;
70 std::int32_t viewportY = 0;
71 std::int32_t viewportW = 0;
72 std::int32_t viewportH = 0;
73
74 // Command arena: grows on demand up to MaxCommands and keeps both its capacity and each
75 // slot's heap allocations (vertexStorage) across frames, so steady state allocates nothing -
76 // exactly like the former fixed array, minus the ~3.6 MB worst-case static footprint. Slots
77 // [0, commandCount) are live; growth may MOVE live slots, which is safe because the
78 // self-referential ctx pointers (fragmentShaderUserData, vertexData) are fixed up in Flush.
79 SmallVector<DeferredCommand, 0> commands;
80 std::int32_t commandCount = 0;
81
82 // Per-tile command index lists for binning (uint16_t indices into the commands arena), sized
83 // by SetTargetBuffer to the actual destination's tile count (kept at the largest seen)
84 SmallVector<SmallVector<std::uint16_t, 64>, 0> tileBins;
85
86 // Palette-LUT pool of the current flush window (parallel arrays; commands store indices,
87 // resolved to pointers by Flush once the pool stops growing). Reset by DiscardPending.
88 SmallVector<SwPaletteLut, 0> paletteLuts;
89 SmallVector<PaletteLutKey, 0> paletteLutKeys;
90
91 // Current render target buffer
92 std::uint8_t* targetBuffer = nullptr;
93 bool isFboTarget = false;
94 #if defined(RHI_USE_FB16)
95 // Whether targetBuffer is the RGB565 screen framebuffer (tiles are rasterized in RGBA8
96 // scratch either way; only the tile <-> framebuffer copies convert)
97 bool is16Bit = false;
98 #endif
99
100 // Worker threads for parallel tile processing
101 #if defined(WITH_THREADS)
102 // Upper bound on worker threads; the runtime count leaves CPU headroom (see Initialize) so
103 // the main thread (which also processes tiles) keeps a core and background threads (audio
104 // decode/mixer, OS, other processes) don't preempt a tile worker mid-flush. PS Vita is
105 // pinned to 3 workers below.
106 static constexpr std::int32_t MaxWorkers = 15;
107 Thread workers[MaxWorkers];
108 Mutex mutex;
109 CondVariable workReady;
110 CondVariable workDone;
111 std::atomic<std::int32_t> workersActive{0};
112 std::int32_t numSpawnedWorkers = 0; // Actual threads created — may be < MaxWorkers if spawn fails
113 bool shutdownRequested = false;
114
115 // Work distribution
116 std::atomic<std::int32_t> nextTileIndex{0};
117 std::int32_t flushGeneration = 0; // Incremented each Flush to prevent worker re-entry
118 std::int32_t workerGeneration[MaxWorkers] = {}; // Last generation each worker processed
119
120 // Signal and join the workers before this object's mutex / condition variables are destroyed
121 // at static teardown, so they are never left blocked on a destroyed primitive (the renderer
122 // keeps the pool alive for the whole process and has no explicit Shutdown() call site).
123 ~TileState()
124 {
125 if (!initialized) {
126 return;
127 }
128 mutex.Lock();
129 shutdownRequested = true;
130 workReady.Broadcast();
131 mutex.Unlock();
132 for (std::int32_t i = 0; i < MaxWorkers; i++) {
133 if (static_cast<bool>(workers[i])) {
134 workers[i].Join();
135 }
136 }
137 }
138 #endif
139 };
140
141 TileState g_tile;
142
143 // =====================================================================
144 // Palette-LUT builder for the PaletteRemap fast path (see SwPaletteLut in SwRaster.h)
145 // =====================================================================
146
147 // Maps a sampling-swizzle source channel to its byte offset in the gathered (4-byte expanded) texel, or a
148 // negative value for the non-byte sources (Zero / One)
149 inline std::int32_t SwizzleChannelByte(SwizzleChannel channel)
150 {
151 switch (channel) {
152 case SwizzleChannel::Red: return 0;
153 case SwizzleChannel::Green: return 1;
154 case SwizzleChannel::Blue: return 2;
155 case SwizzleChannel::Alpha: return 3;
156 default: return -3;
157 }
158 }
159
160 // Validates the fast-path constraints for a PaletteRemap draw (ctx.paletteRemapHint) and returns
161 // the index of a pooled SwPaletteLut for it, building one when no cached table matches. Returns -1
162 // when any constraint fails - the draw then keeps the generic transpiled fragment, so the LUT is a
163 // pure optimization. `ctx` must be the command's own snapshot (its userData already repointed).
164 std::int32_t AcquirePaletteLut(const DrawContext& ctx)
165 {
166 // The parameter block is the transpiled fragment's single vPaletteOffset float
167 if (ctx.fragmentShader == nullptr || ctx.fragmentShaderUserData == nullptr ||
168 ctx.fragmentShaderUserDataSize < sizeof(float)) {
169 return -1;
170 }
171 if (!ctx.ff.hasTexture || ctx.ff.textureUnit < 0 || ctx.ff.textureUnit >= std::int32_t(MaxTextureUnits)) {
172 return -1;
173 }
174 const SwTexture* indexTex = ctx.textures[ctx.ff.textureUnit];
175 if (indexTex == nullptr || indexTex->GetPixels(0) == nullptr ||
176 indexTex->GetWidth() <= 0 || indexTex->GetHeight() <= 0) {
177 return -1;
178 }
179 // The rasterizer's gather phases fetch raw (unswizzled) texel bytes, which the LUT indexes by.
180 // A bilinear gather would average palette indices - something the fragment's own nearest
181 // re-sample never sees - so the fast path requires nearest sampling. The condition mirrors
182 // the quad rasterizers' useLinear exactly.
183 if (indexTex->GetMagFilter() == nCine::SamplerFilter::Linear && indexTex->GetWidth() > 1 && indexTex->GetHeight() > 1) {
184 return -1;
185 }
186 // The fragment reads the index through the texture's sampling swizzle: `.r` selects the index
187 // byte and `.a` the source-alpha byte. The offsets index the gathered, 4-byte EXPANDED texel
188 // (SwTexture stores R8/RG8 natively; every gather expands with 255 fill): an R8 index texture
189 // keeps the identity swizzle (the expanded texel is [index,255,255,255], so `.a` reads the
190 // constant 255 = opaque); an RG8 one maps `.a` to green ([index,alpha,255,255]). Zero / One
191 // in `.a` fold to a constant.
192 const SwizzleChannel* swizzle = indexTex->GetSwizzle();
193 const std::int32_t indexByteOffset = SwizzleChannelByte(swizzle[0]);
194 if (indexByteOffset < 0) {
195 return -1;
196 }
197 std::int32_t alphaByteOffset = SwizzleChannelByte(swizzle[3]);
198 if (alphaByteOffset < 0) {
199 if (swizzle[3] == SwizzleChannel::One) {
200 alphaByteOffset = -1; // Constant 1.0 source alpha
201 } else if (swizzle[3] == SwizzleChannel::Zero) {
202 alphaByteOffset = -2; // Constant 0.0 source alpha
203 } else {
204 return -1;
205 }
206 }
207 // The fragment samples the palette on unit 1 (PaletteRemap.shader: texture_unit(1)). A missing
208 // palette is fine (swTexture yields transparent black, baked below the same way), but a
209 // CPU-rendered target could change without a content-version bump, so it stays generic.
210 const SwTexture* palette = ctx.textures[1];
211 if (palette != nullptr && palette->IsRenderTarget()) {
212 return -1;
213 }
214
215 PaletteLutKey key;
216 key.palette = palette;
217 key.paletteVersion = (palette != nullptr ? palette->GetContentVersion() : 0);
218 key.paletteOffset = *reinterpret_cast<const float*>(ctx.fragmentShaderUserData);
219 key.tint[0] = ctx.ff.color[0];
220 key.tint[1] = ctx.ff.color[1];
221 key.tint[2] = ctx.ff.color[2];
222 key.tint[3] = ctx.ff.color[3];
223 key.indexByteOffset = indexByteOffset;
224 key.alphaByteOffset = alphaByteOffset;
225
226 // Most draws of a window share one palette / tint (tile layers submit runs of hundreds), so a
227 // most-recent-first linear scan almost always hits its first entry
228 for (std::int32_t i = std::int32_t(g_tile.paletteLutKeys.size()) - 1; i >= 0; i--) {
229 const PaletteLutKey& k = g_tile.paletteLutKeys[i];
230 if (k.palette == key.palette && k.paletteVersion == key.paletteVersion &&
231 k.paletteOffset == key.paletteOffset &&
232 k.tint[0] == key.tint[0] && k.tint[1] == key.tint[1] &&
233 k.tint[2] == key.tint[2] && k.tint[3] == key.tint[3] &&
234 k.indexByteOffset == key.indexByteOffset && k.alphaByteOffset == key.alphaByteOffset) {
235 return i;
236 }
237 }
238
239 // Build a new table by replicating the transpiled PaletteRemap fragment for each of the 256
240 // index bytes, with the identical float operations in the identical order so the results are
241 // bit-exact. floor(src.r * 255 + 0.5) recovers the index byte exactly (src.r is idx / 255), so
242 // per index everything but the per-pixel source-alpha factor collapses to constants.
243 g_tile.paletteLutKeys.push_back(key);
244 SwPaletteLut& lut = g_tile.paletteLuts.emplace_back();
245 lut.tintAlpha = ctx.ff.color[3];
246 lut.indexByteOffset = indexByteOffset;
247 lut.alphaByteOffset = alphaByteOffset;
248 lut.allOpaque = true;
249
250 FragmentShaderInput paletteInput = {};
251 paletteInput.textures = ctx.textures;
252 // The constant source alpha baked into packed[][3]: 1.0 both for the swizzle-One case and for
253 // the per-pixel case's alpha-byte-255 shortcut (255/255 == 1.0 exactly); 0.0 for swizzle-Zero
254 const float bakedSrcAlpha = (alphaByteOffset == -2 ? 0.0f : 1.0f);
255 for (std::int32_t i = 0; i < 256; i++) {
256 const float srcR = i / 255.0f;
257 const float palIndex = sw::floor(key.paletteOffset + 0.5f) + sw::floor(srcR * 255.0f + 0.5f);
258 const float palX = (sw::mod(palIndex, 256.0f) + 0.5f) / 256.0f;
259 const float palY = (sw::floor(palIndex / 256.0f) + 0.5f) / 256.0f;
260 const sw::vec4 color = sw::swTexture(paletteInput, 1, sw::vec2(palX, palY));
261 lut.packed[i][0] = SwQuantizeColor(color.r * ctx.ff.color[0]);
262 lut.packed[i][1] = SwQuantizeColor(color.g * ctx.ff.color[1]);
263 lut.packed[i][2] = SwQuantizeColor(color.b * ctx.ff.color[2]);
264 lut.packed[i][3] = SwQuantizeColor((color.a * bakedSrcAlpha) * lut.tintAlpha);
265 if (lut.packed[i][3] != 255) {
266 lut.allOpaque = false;
267 }
268 // color.a always originates from a byte (or the exact 0.0 / 1.0 of a Zero / One swizzle),
269 // so this recovers it losslessly; dividing it by 255 at apply time reproduces the exact
270 // float the fragment's own sample would produce
271 lut.palAlphaByte[i] = std::uint8_t(std::int32_t(color.a * 255.0f + 0.5f));
272 }
273 return std::int32_t(g_tile.paletteLuts.size()) - 1;
274 }
275
276 // Per-tile scratch buffer (each worker uses its own slice; slot 0 belongs to the main thread,
277 // slots 1..MaxWorkers to the workers): 32x32x4 = 4096 bytes per slice, so each slice also starts
278 // on its own cache line
279 #if defined(WITH_THREADS)
280 alignas(64) std::uint8_t g_tileScratch[TileState::MaxWorkers + 1][TileSize * TileSize * 4];
281 #else
282 alignas(64) std::uint8_t g_tileScratch[1][TileSize * TileSize * 4];
283 #endif
284
285 // =====================================================================
286 // Tile clear
287 // =====================================================================
288 inline void ClearTileBuffer(std::uint8_t* tile, std::int32_t pixelCount, std::uint32_t clearColor)
289 {
290 #if defined(DEATH_ENABLE_NEON)
291 uint32x4_t pattern = vdupq_n_u32(clearColor);
292 std::int32_t i = 0;
293 std::uint32_t* dst32 = reinterpret_cast<std::uint32_t*>(tile);
294 for (; i + 16 <= pixelCount; i += 16) {
295 vst1q_u32(dst32 + i, pattern);
296 vst1q_u32(dst32 + i + 4, pattern);
297 vst1q_u32(dst32 + i + 8, pattern);
298 vst1q_u32(dst32 + i + 12, pattern);
299 }
300 for (; i + 4 <= pixelCount; i += 4) {
301 vst1q_u32(dst32 + i, pattern);
302 }
303 for (; i < pixelCount; i++) {
304 dst32[i] = clearColor;
305 }
306 #else
307 std::uint32_t* dst32 = reinterpret_cast<std::uint32_t*>(tile);
308 for (std::int32_t i = 0; i < pixelCount; i++) {
309 dst32[i] = clearColor;
310 }
311 #endif
312 }
313
314 // =====================================================================
315 // Copy tile buffer back to framebuffer
316 // =====================================================================
317 inline void CopyTileToFramebuffer(const std::uint8_t* tile, std::uint8_t* fb,
318 std::int32_t tileX, std::int32_t tileY,
319 std::int32_t tileW, std::int32_t tileH,
320 std::int32_t fbWidth, std::int32_t fbHeight,
321 bool flipY)
322 {
323 const std::int32_t rowBytes = tileW * 4;
324 for (std::int32_t row = 0; row < tileH; row++) {
325 const std::uint8_t* src = tile + row * TileSize * 4;
326 const std::int32_t dstY = flipY ? (fbHeight - 1 - (tileY + row)) : (tileY + row);
327 if DEATH_UNLIKELY(dstY < 0 || dstY >= fbHeight) {
328 continue;
329 }
330 #if defined(RHI_USE_FB16)
331 if (g_tile.is16Bit) {
332 // Tiles are rasterized as RGBA8; the 565 conversion happens once here, per copied row
333 SwStoreFbSpan565(fb + (dstY * fbWidth + tileX) * 2, src, tileW);
334 continue;
335 }
336 #endif
337 std::uint8_t* dst = fb + (dstY * fbWidth + tileX) * 4;
338 std::memcpy(dst, src, rowBytes);
339 }
340 }
341
342 // =====================================================================
343 // Copy framebuffer region into tile buffer (for read-modify-write blending)
344 // =====================================================================
345 inline void CopyFramebufferToTile(std::uint8_t* tile, const std::uint8_t* fb,
346 std::int32_t tileX, std::int32_t tileY,
347 std::int32_t tileW, std::int32_t tileH,
348 std::int32_t fbWidth, std::int32_t fbHeight,
349 bool flipY)
350 {
351 const std::int32_t rowBytes = tileW * 4;
352 for (std::int32_t row = 0; row < tileH; row++) {
353 std::uint8_t* dst = tile + row * TileSize * 4;
354 const std::int32_t srcY = flipY ? (fbHeight - 1 - (tileY + row)) : (tileY + row);
355 if DEATH_UNLIKELY(srcY < 0 || srcY >= fbHeight) {
356 std::memset(dst, 0, rowBytes);
357 continue;
358 }
359 #if defined(RHI_USE_FB16)
360 if (g_tile.is16Bit) {
361 SwLoadFbSpan565(dst, fb + (srcY * fbWidth + tileX) * 2, tileW);
362 continue;
363 }
364 #endif
365 const std::uint8_t* src = fb + (srcY * fbWidth + tileX) * 4;
366 std::memcpy(dst, src, rowBytes);
367 }
368 }
369
370 // =====================================================================
371 // Process a single tile: read back if needed, render all binned commands, copy back
372 // =====================================================================
373 void ProcessTile(std::int32_t tileIndex, std::int32_t workerIndex)
374 {
375 const std::int32_t tileCol = tileIndex % g_tile.tilesX;
376 const std::int32_t tileRow = tileIndex / g_tile.tilesX;
377 const std::int32_t tileX = tileCol * TileSize;
378 const std::int32_t tileY = tileRow * TileSize;
379 const std::int32_t tileW = std::min(TileSize, g_tile.fbWidth - tileX);
380 const std::int32_t tileH = std::min(TileSize, g_tile.fbHeight - tileY);
381
382 if DEATH_UNLIKELY(tileW <= 0 || tileH <= 0) {
383 return;
384 }
385
386 const auto& bin = g_tile.tileBins[tileIndex];
387 if (bin.empty()) {
388 return; // No commands touch this tile - nothing to do
389 }
390
391 // Thread-local scratch buffer
392 std::uint8_t* tileBuf = g_tileScratch[workerIndex];
393
394 // Reverse-painter cull: the last command that overwrites this whole tile independent of the
395 // destination (opaqueOverwrite + full cover, see SwTileRenderer.h) makes everything before it
396 // invisible here - each earlier pixel is overwritten - so the walk starts at that command and
397 // the framebuffer read-back is skipped entirely. In a side-scroller this is the common tile:
398 // solid ground/foreground covers it and the parallax layers behind cost nothing. Subsumes the
399 // former first-command rule (a non-blended background covering the tile), which as a bonus
400 // wrongly fired for an affine quad - a rotated quad does not cover its bounding box, so the
401 // tile corners outside it kept stale scratch; opaqueOverwrite is axis-aligned only.
402 std::size_t firstCmd = 0;
403 bool needsReadBack = true;
404 for (std::size_t i = bin.size(); i > 0;) {
405 const DeferredCommand& cmd = g_tile.commands[bin[--i]];
406 if (cmd.opaqueOverwrite &&
407 cmd.coverMinX <= tileX && cmd.coverMinY <= tileY &&
408 cmd.coverMaxX >= tileX + tileW - 1 && cmd.coverMaxY >= tileY + tileH - 1) {
409 firstCmd = i;
410 needsReadBack = false;
411 break;
412 }
413 }
414
415 if (needsReadBack) {
416 // Initialize the tile with current framebuffer contents (needed for correct blending)
417 CopyFramebufferToTile(tileBuf, g_tile.targetBuffer,
418 tileX, tileY, tileW, tileH,
419 g_tile.fbWidth, g_tile.fbHeight, g_tile.isFboTarget);
420 }
421
422 // Render the visible suffix of the commands binned to this tile
423 for (std::size_t k = firstCmd; k < bin.size(); k++) {
424 const DeferredCommand& cmd = g_tile.commands[bin[k]];
425 TileInternal::RenderCommandToTile(
426 cmd.ctx, &cmd.prep, cmd.primType, cmd.firstVertex, cmd.count,
427 tileBuf, tileX, tileY, tileW, tileH,
428 cmd.viewportX, cmd.viewportY, cmd.viewportW, cmd.viewportH);
429 }
430
431 // Copy the tile back to the framebuffer
432 CopyTileToFramebuffer(tileBuf, g_tile.targetBuffer,
433 tileX, tileY, tileW, tileH,
434 g_tile.fbWidth, g_tile.fbHeight, g_tile.isFboTarget);
435 }
436
437 #if defined(WITH_THREADS)
438 // =====================================================================
439 // Worker thread function: process tiles from a shared atomic counter
440 // =====================================================================
441 void WorkerThreadFunc(void* arg)
442 {
443 const std::int32_t workerIndex = static_cast<std::int32_t>(reinterpret_cast<std::intptr_t>(arg));
444
445 while (true) {
446 // Wait for new work (generation must advance)
447 g_tile.mutex.Lock();
448 while (g_tile.workerGeneration[workerIndex] == g_tile.flushGeneration && !g_tile.shutdownRequested) {
449 g_tile.workReady.Wait(g_tile.mutex);
450 }
451 if DEATH_UNLIKELY(g_tile.shutdownRequested) {
452 g_tile.mutex.Unlock();
453 return;
454 }
455 g_tile.workerGeneration[workerIndex] = g_tile.flushGeneration;
456 g_tile.mutex.Unlock();
457
458 // Process tiles using an atomic counter (work-stealing pattern)
459 while (true) {
460 std::int32_t idx = g_tile.nextTileIndex.fetch_add(1, std::memory_order_relaxed);
461 if (idx >= g_tile.totalTiles) {
462 break;
463 }
464 ProcessTile(idx, workerIndex + 1); // +1 because the main thread uses slot 0
465 }
466
467 // Signal completion
468 std::atomic_thread_fence(std::memory_order_release); // Ensure all tile writes are pushed out
469 g_tile.mutex.Lock();
470 g_tile.workersActive--;
471 if (g_tile.workersActive == 0) {
472 g_tile.workDone.Signal();
473 }
474 g_tile.mutex.Unlock();
475 }
476 }
477 #endif
478 }
479
480 // =====================================================================
481 // Public API
482 // =====================================================================
483
484 void Initialize()
485 {
486 // Idempotent: the device calls this before every draw, so once the pool is up and the state is
487 // reset, subsequent calls must be true no-ops (resetting commandCount/targetBuffer here would
488 // discard the frame's batched draws and break batching).
489 if (g_tile.initialized) {
490 return;
491 }
492
493 #if defined(WITH_THREADS)
494 g_tile.shutdownRequested = false;
495 g_tile.workersActive = 0;
496 g_tile.numSpawnedWorkers = 0;
497 g_tile.flushGeneration = 0;
498 std::memset(g_tile.workerGeneration, 0, sizeof(g_tile.workerGeneration));
499
500 // Spawn worker threads
501 #if defined(DEATH_TARGET_VITA)
502 // Vita has 4 cores: core 0 (OS) + cores 1-3 (app). Force 3 workers.
503 const std::int32_t numWorkers = 3;
504 #else
505 // Leave scheduling headroom instead of saturating every logical CPU: the flush barrier waits
506 // for ALL workers, so with `workers + main == logical CPUs` any other runnable thread (audio
507 // decode/mixer, OS, a browser in the background) preempts one worker for a scheduler quantum
508 // and stalls the whole frame - measured on a 16-thread CPU as random 10-60 ms frame spikes
509 // several times per second. Reserving 1 logical CPU for the main thread (it rasterizes tiles
510 // too) plus a quarter of the CPUs (at least 2) for everything else eliminated the spikes with
511 // an unchanged median frame time (the extra workers bought nothing once the CPU was saturated).
512 // Small machines keep at least the 3 workers the tile renderer always used there.
513 const std::int32_t logicalCpus = static_cast<std::int32_t>(Thread::GetProcessorCount());
514 const std::int32_t reservedCpus = std::max(2, logicalCpus / 4);
515 const std::int32_t numWorkers = std::clamp(
516 logicalCpus - 1 - reservedCpus,
517 std::min(3, logicalCpus - 1),
518 static_cast<std::int32_t>(TileState::MaxWorkers));
519 #endif
520
521 for (std::int32_t i = 0; i < numWorkers; i++) {
522 g_tile.workers[i] = Thread(WorkerThreadFunc,
523 reinterpret_cast<void*>(static_cast<std::intptr_t>(i)));
524 // Only count workers that actually started
525 if (static_cast<bool>(g_tile.workers[i])) {
526 g_tile.numSpawnedWorkers++;
527 }
528 }
529 #endif
530 g_tile.initialized = true;
531 g_tile.fbWidth = 0;
532 g_tile.fbHeight = 0;
533 g_tile.totalTiles = 0;
534 g_tile.commandCount = 0;
535 g_tile.targetBuffer = nullptr;
536 }
537
538 void Shutdown()
539 {
540 if DEATH_UNLIKELY(!g_tile.initialized) {
541 return;
542 }
543
544 #if defined(WITH_THREADS)
545 // Signal workers to exit
546 g_tile.mutex.Lock();
547 g_tile.shutdownRequested = true;
548 g_tile.workReady.Broadcast();
549 g_tile.mutex.Unlock();
550
551 // Join all workers
552 for (std::int32_t i = 0; i < TileState::MaxWorkers; i++) {
553 if (static_cast<bool>(g_tile.workers[i])) {
554 g_tile.workers[i].Join();
555 }
556 }
557 // mutex/workReady/workDone are destroyed automatically by their destructors
558 #endif
559 g_tile.initialized = false;
560 }
561
562 bool IsActive()
563 {
564 return g_tile.initialized;
565 }
566
567 void SetViewport(std::int32_t x, std::int32_t y, std::int32_t width, std::int32_t height)
568 {
569 g_tile.viewportX = x;
570 g_tile.viewportY = y;
571 g_tile.viewportW = width;
572 g_tile.viewportH = height;
573 }
574
575 void SetTargetBuffer(std::uint8_t* buffer, std::int32_t width, std::int32_t height, bool isFboTarget)
576 {
577 if DEATH_UNLIKELY(!g_tile.initialized) {
578 return;
579 }
580
581 // The device sets the same target before every draw; do nothing (and never flush) when nothing
582 // changed so consecutive draws to the same surface keep batching into one flush.
583 if (buffer == g_tile.targetBuffer && width == g_tile.fbWidth &&
584 height == g_tile.fbHeight && isFboTarget == g_tile.isFboTarget) {
585 return;
586 }
587
588 // The target is actually changing: flush whatever is still queued for the old one first
589 if (g_tile.commandCount > 0) {
590 Flush();
591 }
592
593 // Sanity guard only (the bin table below is sized dynamically); a nonsensical target disables
594 // the layer until the next valid one
595 if DEATH_UNLIKELY(width > MaxSurfaceDimension || height > MaxSurfaceDimension || width <= 0 || height <= 0) {
596 g_tile.targetBuffer = nullptr;
597 g_tile.fbWidth = 0;
598 g_tile.fbHeight = 0;
599 g_tile.totalTiles = 0;
600 g_tile.isFboTarget = false;
601 return;
602 }
603
604 g_tile.targetBuffer = buffer;
605 g_tile.isFboTarget = isFboTarget;
606 #if defined(RHI_USE_FB16)
607 // On the software backend a non-FBO target IS the screen framebuffer - the only 16-bit surface
608 g_tile.is16Bit = !isFboTarget;
609 #endif
610 g_tile.fbWidth = width;
611 g_tile.fbHeight = height;
612 g_tile.tilesX = (width + TileSize - 1) >> TileSizeShift;
613 g_tile.tilesY = (height + TileSize - 1) >> TileSizeShift;
614 g_tile.totalTiles = g_tile.tilesX * g_tile.tilesY;
615 // Grow the bin table to the actual destination's tile count (never shrunk: bins keep their
616 // heap capacity so steady state allocates nothing; the largest target seen wins)
617 if (std::int32_t(g_tile.tileBins.size()) < g_tile.totalTiles) {
618 g_tile.tileBins.resize(g_tile.totalTiles);
619 }
620 }
621
622 bool SubmitCommand(const DrawContext& ctx, PrimitiveType type,
623 std::int32_t firstVertex, std::int32_t count)
624 {
625 if DEATH_UNLIKELY(!g_tile.initialized || g_tile.targetBuffer == nullptr) {
626 return false;
627 }
628
629 // Line and point primitives are rasterized only by the immediate path (SwRaster) - they are
630 // rare (the HUD weapon wheel's arcs) and a tile-clipped line walk is not worth its complexity
631 // here. Declining makes the caller flush the queue first, so the draw order is preserved.
632 if DEATH_UNLIKELY(type == PrimitiveType::Points || type == PrimitiveType::Lines ||
633 type == PrimitiveType::LineLoop || type == PrimitiveType::LineStrip) {
634 return false;
635 }
636
637 // An effect's fragment-callback parameter block (fragmentShaderUserData) lives on the caller's
638 // stack in SwDevice::Dispatch and dies when the draw returns, whereas a deferred draw outlives it.
639 // We snapshot the block into the command below (it is trivially copyable) to make the deferred
640 // draw self-contained; decline the draw — SwRaster then rasterizes it immediately — when the block
641 // can't be snapshotted (no declared size, or larger than the per-command storage).
642 if (ctx.fragmentShader != nullptr && ctx.fragmentShaderUserData != nullptr) {
643 if (ctx.fragmentShaderUserDataSize == 0 ||
644 ctx.fragmentShaderUserDataSize > MaxFragmentShaderUserDataSize) {
645 return false;
646 }
647 }
648
649 if DEATH_UNLIKELY(g_tile.commandCount >= MaxCommands) {
650 // Buffer full - flush and retry, or fall back to immediate
651 Flush();
652 if (g_tile.commandCount >= MaxCommands) return false;
653 }
654
655 // Use the viewport snapshot for the NDC→screen transform (mirrors SwRaster::SetViewport). Fall
656 // back to the full buffer when no explicit viewport was set (matches SwDevice::Dispatch).
657 std::int32_t vpX = g_tile.viewportX;
658 std::int32_t vpY = g_tile.viewportY;
659 std::int32_t vpW = g_tile.viewportW;
660 std::int32_t vpH = g_tile.viewportH;
661 if (vpW <= 0 || vpH <= 0) {
662 vpX = 0;
663 vpY = 0;
664 vpW = g_tile.fbWidth;
665 vpH = g_tile.fbHeight;
666 }
667
668 // Acquire a command slot, growing the arena on demand (geometric growth, capacity and each
669 // slot's heap allocations retained across frames). Growth may move the live slots below cmdIdx;
670 // that is safe because their self-referential ctx pointers are only fixed up (and dereferenced)
671 // at Flush. A discarded command simply never increments commandCount, so the slot is reused by
672 // the next submission.
673 const std::int32_t cmdIdx = g_tile.commandCount;
674 if (cmdIdx >= std::int32_t(g_tile.commands.size())) {
675 g_tile.commands.emplace_back();
676 }
677 DeferredCommand& cmd = g_tile.commands[cmdIdx];
678 cmd.ctx = ctx;
679 // Snapshot the fragment-callback parameter block into the command's own storage (ctx points at
680 // caller-stack memory, which is still alive here). cmd.ctx.fragmentShaderUserData keeps the
681 // caller pointer for the submit-time consumers below (PrepareQuad's constant-fill evaluation,
682 // AcquirePaletteLut); Flush repoints it at userDataStorage before any deferred dereference.
683 if (ctx.fragmentShader != nullptr && ctx.fragmentShaderUserData != nullptr) {
684 std::memcpy(cmd.userDataStorage, ctx.fragmentShaderUserData, ctx.fragmentShaderUserDataSize);
685 }
686 // Snapshot a general draw's vertices the same way: ctx.vertexData points into the device's
687 // per-draw scratch buffer, which the next draw overwrites, whereas the deferred draw outlives
688 // it. The repoint at vertexStorage likewise happens in Flush.
689 if (ctx.vertexData != nullptr) {
690 const std::int32_t strideFloats = (ctx.vertexStride > 0 ? ctx.vertexStride / std::int32_t(sizeof(float)) : 4);
691 const std::size_t floatCount = (std::size_t(firstVertex) + std::size_t(count)) * std::size_t(strideFloats);
692 const float* src = static_cast<const float*>(ctx.vertexData);
693 cmd.vertexStorage.assign(src, src + floatCount);
694 }
695 // scissorRect.Y is stored in top-down screen space so the tile rasterizer can use it directly as a
696 // pixel-row clip. ctx.scissorRect.Y is bottom-up (the RHI scissor convention), so flip it here.
697 if DEATH_UNLIKELY(ctx.scissorEnabled) {
698 cmd.ctx.scissorRect.Y = g_tile.fbHeight - ctx.scissorRect.Y - ctx.scissorRect.H;
699 }
700
701 // Compute the screen-space AABB from the draw command
702 std::int32_t screenMinX, screenMinY, screenMaxX, screenMaxY;
703 bool accurateBounds;
704
705 if DEATH_LIKELY(type == PrimitiveType::TriangleStrip && count == 4 && firstVertex == 0 && ctx.vertexData == nullptr) {
706 // Procedural sprite quad: run the submit-time preparation (the four FetchVertex transforms
707 // plus the texture / tint / blend / UV-step derivation the tile rasterizers used to redo per
708 // binned tile, see PreparedQuad) and take the binning bounds from the exact screen-space
709 // vertices the rasterizer will consume.
710 TileInternal::PrepareQuad(cmd.ctx, vpX, vpY, vpW, vpH, cmd.prep);
711 if DEATH_UNLIKELY(!cmd.prep.valid) {
712 return true; // Degenerate quad - accepted but discarded (it draws nothing on any path)
713 }
714 screenMinX = std::max(0, static_cast<std::int32_t>(cmd.prep.fxMin));
715 screenMinY = std::max(0, static_cast<std::int32_t>(cmd.prep.fyMin));
716 screenMaxX = std::min(g_tile.fbWidth - 1, static_cast<std::int32_t>(cmd.prep.fxMax));
717 screenMaxY = std::min(g_tile.fbHeight - 1, static_cast<std::int32_t>(cmd.prep.fyMax));
718 accurateBounds = true;
719 } else if (cmd.ctx.vertexData != nullptr) {
720 // General vertex-fed draw: bin by the transformed vertices' bounding box (the same NDC ->
721 // screen mapping the rasterizer's vertex fetch applies, padded a pixel for its snap).
722 // accurateBounds stays false - an AABB does not promise the geometry covers it, and the
723 // read-back-skip optimization must only fire for full-cover draws.
724 cmd.prep.valid = false;
725 const std::int32_t strideFloats = (cmd.ctx.vertexStride > 0 ? cmd.ctx.vertexStride / std::int32_t(sizeof(float)) : 4);
726 const float* v = static_cast<const float*>(cmd.ctx.vertexData) + std::size_t(firstVertex) * std::size_t(strideFloats);
727 float fxMin = FLT_MAX, fxMax = -FLT_MAX, fyMin = FLT_MAX, fyMax = -FLT_MAX;
728 for (std::int32_t i = 0; i < count; i++, v += strideFloats) {
729 const float sx = (v[0] + 1.0f) * 0.5f * static_cast<float>(vpW) + static_cast<float>(vpX);
730 const float sy = (1.0f - v[1]) * 0.5f * static_cast<float>(vpH) + static_cast<float>(vpY);
731 fxMin = std::min(fxMin, sx);
732 fxMax = std::max(fxMax, sx);
733 fyMin = std::min(fyMin, sy);
734 fyMax = std::max(fyMax, sy);
735 }
736 screenMinX = std::max(0, static_cast<std::int32_t>(fxMin) - 1);
737 screenMinY = std::max(0, static_cast<std::int32_t>(fyMin) - 1);
738 screenMaxX = std::min(g_tile.fbWidth - 1, static_cast<std::int32_t>(fxMax) + 1);
739 screenMaxY = std::min(g_tile.fbHeight - 1, static_cast<std::int32_t>(fyMax) + 1);
740 accurateBounds = false;
741 } else {
742 // For non-procedural quads, use full framebuffer bounds (conservative)
743 cmd.prep.valid = false;
744 screenMinX = 0;
745 screenMinY = 0;
746 screenMaxX = g_tile.fbWidth - 1;
747 screenMaxY = g_tile.fbHeight - 1;
748 accurateBounds = false;
749 }
750
751 // Scissor clip — Y always flipped for tile culling because tile rows are indexed top-down in
752 // screen space but the framebuffer stores rows bottom-up.
753 if DEATH_UNLIKELY(ctx.scissorEnabled) {
754 std::int32_t scY0 = g_tile.fbHeight - ctx.scissorRect.Y - ctx.scissorRect.H;
755 std::int32_t scY1 = g_tile.fbHeight - 1 - ctx.scissorRect.Y;
756 screenMinX = std::max(screenMinX, ctx.scissorRect.X);
757 screenMinY = std::max(screenMinY, scY0);
758 screenMaxX = std::min(screenMaxX, ctx.scissorRect.X + ctx.scissorRect.W - 1);
759 screenMaxY = std::min(screenMaxY, scY1);
760 }
761
762 if DEATH_UNLIKELY(screenMinX > screenMaxX || screenMinY > screenMaxY) {
763 return true; // Command is fully clipped - accepted but discarded
764 }
765
766 // PaletteRemap fast path: bake the command's palette row + tint into a pooled 256-entry LUT the
767 // tile rasterizer indexes instead of calling the transpiled fragment per pixel. -1 (constraint
768 // not met) keeps the generic fragment. Runs at submit time, while the caller's userData pointer
769 // is still alive.
770 cmd.paletteLutIndex = (ctx.paletteRemapHint ? AcquirePaletteLut(cmd.ctx) : -1);
771
772 // Classify a destination-independent full write (the reverse-painter cull's trigger, see the
773 // field in SwTileRenderer.h). Only an axis-aligned procedural quad qualifies - it writes every
774 // pixel of its drawn rectangle - and only when nothing it writes depends on the destination:
775 // blending off (whatever the source, the write replaces the pixel), or the fast blend pair with
776 // a source that is provably opaque everywhere (src-over with alpha 255 is the same replace).
777 cmd.opaqueOverwrite = false;
778 if (accurateBounds && cmd.prep.valid && cmd.prep.axisAligned) {
779 bool overwrites = !cmd.prep.useBlend;
780 if (!overwrites && cmd.prep.useFastBlend) {
781 if (cmd.prep.constantFill) {
782 overwrites = (cmd.prep.constColor[3] >= 255);
783 } else if (cmd.paletteLutIndex >= 0) {
784 // Every LUT entry opaque and the source alpha a constant 1 - each sampled texel,
785 // whatever its index, lands on an opaque entry
786 const SwPaletteLut& lut = g_tile.paletteLuts[cmd.paletteLutIndex];
787 overwrites = (lut.allOpaque && lut.alphaByteOffset == -1);
788 }
789 }
790 if (overwrites) {
791 // The axis-aligned rasterizer writes exactly [int(fxMin), int(fxMax - 0.5)] per axis
792 // (tile-clipped); the binning AABB above rounds the max edges up to int(fxMax), which may
793 // claim one pixel column/row the rasterizer never writes - fine for binning (conservative)
794 // but not for a cover test, so the cull gets its own exact rectangle
795 std::int32_t coverMinX = static_cast<std::int32_t>(cmd.prep.fxMin);
796 std::int32_t coverMaxX = static_cast<std::int32_t>(cmd.prep.fxMax - 0.5f);
797 std::int32_t coverMinY = static_cast<std::int32_t>(cmd.prep.fyMin);
798 std::int32_t coverMaxY = static_cast<std::int32_t>(cmd.prep.fyMax - 0.5f);
799 if DEATH_UNLIKELY(ctx.scissorEnabled) {
800 // cmd.ctx.scissorRect.Y was flipped to top-down above, matching tile coordinates
801 coverMinX = std::max(coverMinX, cmd.ctx.scissorRect.X);
802 coverMaxX = std::min(coverMaxX, cmd.ctx.scissorRect.X + cmd.ctx.scissorRect.W - 1);
803 coverMinY = std::max(coverMinY, cmd.ctx.scissorRect.Y);
804 coverMaxY = std::min(coverMaxY, cmd.ctx.scissorRect.Y + cmd.ctx.scissorRect.H - 1);
805 }
806 cmd.coverMinX = coverMinX;
807 cmd.coverMinY = coverMinY;
808 cmd.coverMaxX = coverMaxX;
809 cmd.coverMaxY = coverMaxY;
810 cmd.opaqueOverwrite = (coverMinX <= coverMaxX && coverMinY <= coverMaxY);
811 }
812 }
813
814 cmd.primType = type;
815 cmd.firstVertex = firstVertex;
816 cmd.count = count;
817 cmd.viewportX = vpX;
818 cmd.viewportY = vpY;
819 cmd.viewportW = vpW;
820 cmd.viewportH = vpH;
821 cmd.screenMinX = screenMinX;
822 cmd.screenMinY = screenMinY;
823 cmd.screenMaxX = screenMaxX;
824 cmd.screenMaxY = screenMaxY;
825 cmd.boundsAreAccurate = accurateBounds;
826 g_tile.commandCount++;
827
828 // Bin into overlapping tiles (clamp to the valid tile range)
829 const std::int32_t tileMinCol = std::max(0, screenMinX >> TileSizeShift);
830 const std::int32_t tileMaxCol = std::min(g_tile.tilesX - 1, screenMaxX >> TileSizeShift);
831 const std::int32_t tileMinRow = std::max(0, screenMinY >> TileSizeShift);
832 const std::int32_t tileMaxRow = std::min(g_tile.tilesY - 1, screenMaxY >> TileSizeShift);
833
834 for (std::int32_t row = tileMinRow; row <= tileMaxRow; row++) {
835 for (std::int32_t col = tileMinCol; col <= tileMaxCol; col++) {
836 const std::int32_t tileIdx = row * g_tile.tilesX + col;
837 g_tile.tileBins[tileIdx].push_back(static_cast<std::uint16_t>(cmdIdx));
838 }
839 }
840
841 return true;
842 }
843
844 void Flush()
845 {
846 if DEATH_UNLIKELY(!g_tile.initialized || g_tile.commandCount == 0) {
847 return;
848 }
849
850 // The target buffer must have been set via SetTargetBuffer()
851 if (g_tile.targetBuffer == nullptr || g_tile.totalTiles == 0) {
852 DiscardPending();
853 return;
854 }
855
856 // Fix up the per-command pointers now that submissions are done for this window and neither the
857 // command arena nor the LUT pool grows any further, so everything stays stable for every worker:
858 // - palette-LUT pool indices resolve into pointers
859 // - the self-referential ctx pointers (fragment userData, general-draw vertices) repoint at the
860 // command's own storage; they held the submit-time caller pointers (dead by now, but never
861 // dereferenced since) because arena growth may have MOVED the commands after submission
862 for (std::int32_t i = 0; i < g_tile.commandCount; i++) {
863 DeferredCommand& cmd = g_tile.commands[i];
864 cmd.ctx.paletteLut = (cmd.paletteLutIndex >= 0 ? &g_tile.paletteLuts[cmd.paletteLutIndex] : nullptr);
865 if (cmd.ctx.fragmentShader != nullptr && cmd.ctx.fragmentShaderUserData != nullptr) {
866 cmd.ctx.fragmentShaderUserData = cmd.userDataStorage;
867 }
868 if (cmd.ctx.vertexData != nullptr) {
869 cmd.ctx.vertexData = cmd.vertexStorage.data();
870 }
871 }
872
873 #if defined(WITH_THREADS)
874 // Multi-threaded tile processing using an atomic work counter
875 g_tile.nextTileIndex.store(0, std::memory_order_relaxed);
876
877 g_tile.mutex.Lock();
878 g_tile.flushGeneration++;
879 // Set the active count based on the successfully spawned threads
880 g_tile.workersActive.store(g_tile.numSpawnedWorkers, std::memory_order_release);
881 g_tile.workReady.Broadcast();
882 g_tile.mutex.Unlock();
883
884 // The main thread also processes tiles (worker slot 0)
885 while (true) {
886 std::int32_t idx = g_tile.nextTileIndex.fetch_add(1, std::memory_order_relaxed);
887 if (idx >= g_tile.totalTiles) break;
888 ProcessTile(idx, 0);
889 }
890
891 // Wait for all workers to finish
892 g_tile.mutex.Lock();
893 while (g_tile.workersActive.load(std::memory_order_acquire) > 0) {
894 g_tile.workDone.Wait(g_tile.mutex);
895 }
896 g_tile.mutex.Unlock();
897
898 // Ensure all worker pixel writes are globally visible before the engine moves on to
899 // DiscardPending or flipping buffers.
900 std::atomic_thread_fence(std::memory_order_acquire);
901 #else
902 // Single-threaded fallback: process tiles sequentially
903 for (std::int32_t i = 0; i < g_tile.totalTiles; i++) {
904 ProcessTile(i, 0);
905 }
906 #endif
907
908 // Reset for the next frame
909 DiscardPending();
910 }
911
912 void DiscardPending()
913 {
914 g_tile.commandCount = 0;
915 for (std::int32_t i = 0; i < g_tile.totalTiles; i++) {
916 g_tile.tileBins[i].clear();
917 }
918 // The palette LUTs belong to the discarded commands (keys include per-window texture versions)
919 g_tile.paletteLuts.clear();
920 g_tile.paletteLutKeys.clear();
921 }
922
923 std::int32_t GetPendingCommandCount()
924 {
925 return g_tile.commandCount;
926 }
927 }
928 }
929
930 #endif