core: route DITHERING through the batch UBO

First refactor of the batch-matrix variant-shrinking arc. Lifts
the dithering bit out of compile-time #define territory and into
the per-batch cbuffer slot that already carries u_resolution_scale
/ u_true_color / u_scaled_dithering, on the same pattern as the
prior 7b575a3-line work. The PSX GP0(E1).dither_enable bit flips
constantly mid-frame in real games (interior vs exterior in MGS,
overhead vs gameplay in Crash, mode transitions everywhere) - the
former #if DITHERING / #else / #endif in the FS body would have
required a different DXBC per dithering value, which is exactly
the kind of per-frame churn pre-bake is supposed to make
disappear.

Shape:

* WriteBatchUniformBuffer: replace the u_pad0 trailing slot with
  uint u_dithering. Same cbuffer footprint (48 bytes / three
  16-byte rows); the trailing row is now
  (u_resolution_scale, u_true_color, u_scaled_dithering,
  u_dithering) with no padding.

* GenerateBatchFragmentShader: drop
  DefineMacro(ss, "DITHERING", dithering). The `dithering`
  function parameter stays in the signature for now so the four
  backends (D3D11, D3D12, Vulkan, OpenGL) and their matrix
  dimensions don't need touching in this commit - the value is
  simply ignored when generating source. Follow-up commits per
  backend can drop the dim from m_batch_pipelines /
  m_batch_fragment_shader_blobs once the runtime callers stop
  caring.

* Three #if DITHERING / #else / #endif body blocks become
  if (u_dithering != 0u) / else runtime branches:
    - The textured /  u_true_color = 1 / !RAW_TEXTURE branch
      (ApplyDithering vs min-clamp to 255)
    - The textured /  u_true_color = 0 / !RAW_TEXTURE branch
      (ApplyDithering vs >>3 clamp to 31)
    - The untextured branch (ApplyDithering vs the u_true_color
      shift)
  All three are uniform-control-flow branches - u_dithering is
  a cbuffer scalar so every SIMD lane reads the same value and
  no divergence penalty applies. ApplyDithering's body is
  ~10 instructions of integer math; the branch costs are
  negligible compared to the texture sample + palette lookup
  that dominates the textured branch anyway.

* BatchUBOData: u_pad0 renamed to u_dithering. The struct's
  layout is byte-for-byte unchanged (uint32_t at offset 44 in
  the 48-byte struct), so the existing FlushRender upload path
  picks up the new value without any size or alignment work.

* SetDrawMode (where m_batch.dithering is set per-batch): also
  set m_batch_ubo_data.u_dithering, conditional dirty-bit
  toggle so the UBO upload only runs when the value actually
  changes. The flush condition at line 1369 that triggers a
  FlushRender on dithering_enable != m_batch.dithering stays;
  it's no longer required for shader correctness (same DXBC
  serves both values), but the existing batch-state-change
  flush model is preserved for this commit to avoid changing
  two things at once. Follow-up could drop it for a small
  per-frame save.

Visible behaviour: zero. The DXBC produced for any single
(dithering_enable, *) configuration is now identical to what
the previous DXBC for (dithering_enable=N, *) would have been
for the matching N - the if/else picks the same code path the
#if/#else would have picked, with the same operands and the
same outputs. The only observable difference is the timing of
when dithering settings flip - previously a compile, now a
cbuffer write.

Cost matrix delta (D3D12):
  PSX GP0(E1).dither_enable flip (mid-frame, very common):
    ~50 ms D3DCompile + ~10 ms PSO -> ~4 byte UBO write.
  Disk-cache-warm version of the same:
    ~1 ms shader-cache hit -> ~4 byte UBO write.

The matrix-dim cleanup for D3D12 (drop the [dithering] axis
from m_batch_pipelines<2, 2, 5, 9, 4, 2, 7> and
m_batch_fragment_shader_blobs<2, 2, 9, 4, 7>, and the dithering
parameter from GetBatchFragmentShader / GetBatchPipeline /
DrawBatchVertices, and the precompile worker's outer loop) is
a separate commit because it touches the .h's DimensionalArray
templates, all the call sites, and the bg-thread enumeration
loop - none of that is required for the source-side correctness
of the cbuffer routing. Doing the dim collapse and the source
refactor together in one commit would conflate two unrelated
concerns and make the bisect window bigger if a regression shows
up.

The other three backends (D3D11, OpenGL, Vulkan) still pass
`dithering` to GenerateBatchFragmentShader and key their batch
matrices by it. They benefit from the cbuffer routing too -
the dithering toggle no longer triggers a shader recompile in
any of them - they just hold redundant dim-0 / dim-1 slots in
their matrices that compile to identical DXBC. Same follow-up
shape per backend.

Test:
  - Build: D3D12 backend compiles, links, runs.
  - Default rendering: any PSX title boots and renders correctly.
    Dithering is on by default in most games' default render
    state so this exercises the u_dithering = 1 branch
    immediately.
  - Toggle "True Color" off (which is what makes dithering
    visible): the dither pattern must appear in the output for
    any non-RAW_TEXTURE polygon. FF7 backgrounds, MGS interiors,
    Crash Bandicoot overhead views are good test signals - all
    have visible smooth-gradient surfaces that show dither
    pattern in lo-bit mode.
  - Toggle "True Color" on: the dithering branch still runs in
    the shader (u_dithering may still be 1 from the game's
    register state) but ApplyDithering produces visually
    indistinguishable output at high bit-depth.
  - Toggle "True Color" mid-game: no shader recompile should
    happen (was already true post-7b575a3); same expectation
    holds post-this-commit.
  - Mid-frame dither flip from a game that toggles register
    state: any game that does this (most do) should continue
    to render correctly. Previously: a flush + PSO swap; now:
    a flush + cbuffer write. Same visual output, less work.

Follow-ups in this arc (in rough order of effort):
  - Drop the [dithering] dim from D3D12 batch matrices.
  - Route INTERLACING macro through u_interlacing cbuffer slot
    (same shape, smaller blast radius - one #if in the FS, no
    register-bit-bit-flip-mid-frame considerations).
  - Route PGXP_DEPTH_VS through cbuffer (VS body branch only).
  - Decide whether to route PGXP_DEPTH_FS (requires always-emit
    SV_Depth - perf-tradeoff worth measuring).
  - Route UV_LIMITS through cbuffer (largest of the four;
    requires per-vertex buffer layout change).
  - Pre-bake the resulting reduced FS matrix.
This commit is contained in:
LibretroAdmin 2026-05-18 22:47:27 +00:00 • committed by U-DESKTOP-SPFP6AQ\twistedtechre
commit 3af8e0247a
3 changed files with 43 additions and 14 deletions

View file

@ -1409,6 +1409,16 @@ void GPU_HW::DispatchRenderCommand()
m_batch.texture_mode = texture_mode;
m_batch.transparency_mode = transparency_mode;
m_batch.dithering = dithering_enable;
// Push the new dithering bit to the batch UBO so the next
// FlushRender's shader sees it. Was a compile-time #define
// baked into the FS source (driving a dim of the batch FS / PSO
// matrix); now a runtime branch on u_dithering. Toggling this
// mid-frame - which happens on every PSX GP0(E1).dither_enable
// write - is a single 4-byte cbuffer write, no shader recompile
// and no PSO churn.
const uint32_t new_dithering = dithering_enable ? 1u : 0u;
m_batch_ubo_dirty |= (m_batch_ubo_data.u_dithering != new_dithering);
m_batch_ubo_data.u_dithering = new_dithering;
if (m_draw_mode.IsTextureWindowChanged())
{

View file

@ -129,7 +129,14 @@ protected:
uint32_t u_resolution_scale;
uint32_t u_true_color;
uint32_t u_scaled_dithering;
uint32_t u_pad0; // pad to 16-byte cbuffer row
// u_dithering: per-batch ordered dithering toggle (the PSX
// GP0(E1).dither_enable bit). Used to live in the shader source
// as a compile-time DITHERING macro and as a dim in the batch
// FS / PSO matrices; now a runtime branch on the cbuffer field.
// Set in SetDrawMode alongside m_batch.dithering. Mirror of
// u_scaled_dithering's per-session shape, but the per-batch
// granularity matches the underlying register write rate.
uint32_t u_dithering;
};
struct VRAMFillUBOData

View file

@ -84,7 +84,7 @@ void GPU_HW_ShaderGen::WriteBatchUniformBuffer(std::stringstream& ss)
{"uint2 u_texture_window_and", "uint2 u_texture_window_or", "float u_src_alpha_factor",
"float u_dst_alpha_factor", "uint u_interlaced_displayed_field",
"bool u_set_mask_while_drawing", "uint u_resolution_scale", "uint u_true_color",
"uint u_scaled_dithering", "uint u_pad0"},
"uint u_scaled_dithering", "uint u_dithering"},
false);
// Alias the historical compile-time constants to their cbuffer-
@ -731,7 +731,16 @@ std::string GPU_HW_ShaderGen::GenerateBatchFragmentShader(GPU_HW::BatchRenderMod
DefineMacro(ss, "PALETTE_4_BIT", actual_texture_mode == GPUTextureMode::Palette4Bit);
DefineMacro(ss, "PALETTE_8_BIT", actual_texture_mode == GPUTextureMode::Palette8Bit);
DefineMacro(ss, "RAW_TEXTURE", raw_texture);
DefineMacro(ss, "DITHERING", dithering);
// DITHERING used to live as a compile-time #define driving three
// #if/#else blocks in the FS body. It is now routed through the
// batch UBO (u_dithering) and the three former #if sites below
// are uniform-control-flow runtime branches. Toggling dithering
// (per-batch, owned by m_batch.dithering) is a single 4-byte
// cbuffer write picked up on the next FlushRender - no DXBC
// recompile and no PSO rebuild needed when the PSX
// GP0(E1).dither_enable bit flips mid-frame. Same shape as
// u_scaled_dithering above, just lifted from the per-call axis
// rather than per-session.
// DITHERING_SCALED and TRUE_COLOR used to live as compile-time
// #defines, baking a fresh shader compile for every flip of either.
// They are now routed through the batch UBO (u_scaled_dithering,
@ -928,18 +937,19 @@ float4 SampleFromVRAM(uint4 texpage, float2 coords)
// If not using true color, truncate the framebuffer colors to 5-bit.
// Runtime branch on u_true_color (was a compile-time #if). The
// inner RAW_TEXTURE / DITHERING #ifs stay compile-time because
// those are still structural in the shader matrix.
// inner RAW_TEXTURE #if stays compile-time because that is still
// structural in the shader matrix; the inner dithering choice
// is itself a runtime branch on u_dithering for the same
// cbuffer-routing reason as u_true_color above.
if (u_true_color != 0u)
{
icolor = uint3(texcol.rgb * float3(255.0, 255.0, 255.0));
#if !RAW_TEXTURE
icolor = (icolor * vertcol) >> 7;
#if DITHERING
if (u_dithering != 0u)
icolor = ApplyDithering(uint2(v_pos.xy), icolor);
#else
else
icolor = min(icolor, uint3(255u, 255u, 255u));
#endif
#endif
}
else
@ -947,11 +957,10 @@ float4 SampleFromVRAM(uint4 texpage, float2 coords)
icolor = uint3(texcol.rgb * float3(255.0, 255.0, 255.0)) >> 3;
#if !RAW_TEXTURE
icolor = (icolor * vertcol) >> 4;
#if DITHERING
if (u_dithering != 0u)
icolor = ApplyDithering(uint2(v_pos.xy), icolor);
#else
else
icolor = min(icolor >> 3, uint3(31u, 31u, 31u));
#endif
#endif
}
@ -963,12 +972,15 @@ float4 SampleFromVRAM(uint4 texpage, float2 coords)
icolor = vertcol;
ialpha = 1.0;
#if DITHERING
if (u_dithering != 0u)
{
icolor = ApplyDithering(uint2(v_pos.xy), icolor);
#else
}
else
{
if (u_true_color == 0u)
icolor >>= 3;
#endif
}
// However, the mask bit is cleared if set mask bit is false.
oalpha = float(u_set_mask_while_drawing);