Commit graph

12 commits

Author SHA1 Message Date
LibretroAdmin
80d0495145 core/d3d12: pre-bake the display pixel shader
The prize set. display_ps is the per-frame hot shader - every
frame goes through this on its way to the host display, so cold-
flip cost matters here more than anywhere else in the GPU
pipeline. This commit pre-bakes 54 variants covering the full
runtime configuration matrix and replaces the shadergen +
m_shader_cache.GetPixelShader path in GetDisplayPipeline with
indexed-lookup into two static arrays of D3D12_SHADER_BYTECODE.

Variant axes (4 axes, 54 unique blobs):

  * DEPTH_24BIT (2 values): 16-bit framebuffer (the common case;
    every game's standard scanout) vs 24-bit (FMV cutscenes,
    games that opt into true-colour framebuffers).

  * interlace_mode (3 values): InterlacedRenderMode enum from
    gpu_hw.h. Mapped to a (INTERLACED, INTERLEAVED) bool pair
    in the variant /D defines:
      i=0 (None):              (INTERLACED=0, INTERLEAVED=0)
      i=1 (InterleavedFields): (INTERLACED=1, INTERLEAVED=1)
      i=2 (SeparateFields):    (INTERLACED=1, INTERLEAVED=0)

  * SMOOTH_CHROMA (2 values): chroma-plane smoothing in the
    24-bit path. Heavy when active - SampleVRAM24Smoothed runs
    9 SampleVRAM24 calls per output pixel (1 centre + 4 x 2x2
    averages), each of which is 2 LoadVRAM calls. Dead code
    when DEPTH_24BIT=0; the variant table omits the c=1 entry
    for d=0 (54 = 18 + 36, not 72 = 2 x 3 x 2 x 6).

  * MULTISAMPLES (6 values: 1, 2, 4, 8, 16, 32): MSAA sample
    count. Same cardinality axis as vram_read_ps (21f4623).
    Composed multiplicatively with SMOOTH_CHROMA: at
    /DSMOOTH_CHROMA=1 /DMULTISAMPLES=32 the inner loop unrolls
    to 9 * 2 * 32 = 576 texture loads per pixel - the d1i?c1m32
    blobs are correspondingly the largest in the set (99 kB
    each).

Variant suffix convention: d{0,1}i{0,1,2}c{0,1}m{01,02,04,08,16,
32}. MULTISAMPLES padded to 2 digits so alphabetical .inc
filename ordering matches the natural nested-loop iteration
order. The d=0 set has 18 entries (one chroma value); d=1 has
36 (both chroma values).

Blob size distribution:
  smallest:  1276 B  d0i0c0m01  (16-bit, no interlace, no MSAA)
  median:   ~3500 B
  largest: 99152 B  d1i2c1m32  (24-bit, SeparateFields, smooth
                                chroma, 32x MSAA - 576 loads/px)
  total:    942 kB of DXBC across 54 .inc files
  on-disk: ~5.6 MB of .inc text (the hex-encoding overhead is
           ~6x vs the binary - "0xXX, " per byte - same shape
           as the vram_read note in 21f4623)

Runtime selection in GetDisplayPipeline:

  if (depth_24) -> k_display_d1[interlace_mode][chroma][ms_idx]
  else          -> k_display_d0[interlace_mode][ms_idx]

Two arrays rather than one ragged 4D, because the smooth_chroma
dimension is structurally absent on the d=0 path (SMOOTH_CHROMA
is dead code there; fxc /O3 would have produced identical DXBC
for c=0 and c=1 anyway, so we save 18 blobs / ~30 kB DXBC by
not baking them). ms_idx is log2(m_multisamples) computed by a
function-scope kMultisamplesIndex lambda - same predicate /
fallback shape as the vram_read pre-bake. The arrays are
function-scope static const so they initialise on first call
and the cost is amortised across the per-frame display PSO
stream for the rest of the session.

Files added:

* data/shaders/d3d12/display.ps.hlsl: standalone HLSL matching
  GenerateDisplayFragmentShader's D3D12 output post-e64fc28
  cbuffer routing. 24-byte cbuffer (u_vram_offset.xy,
  u_crop_left, u_field_offset, u_resolution_scale, u_pad0)
  layout-identical to the GPU_HW_D3D12::UpdateDisplay
  SetGraphicsRoot32BitConstants push. RGBA8ToRGBA5551,
  RGBToYUV, YUVToRGB, fixYCoord helpers all inlined.
  SampleVRAM24, SampleVRAMAverage2x2, SampleVRAM24Smoothed
  match the shadergen body byte-for-byte.

* src/common/d3d12/embedded_dxbc/display_ps_d{0,1}i{0,1,2}c{0,1}
  m{01,02,04,08,16,32}.inc: 54 DXBC blobs (with the
  smooth-chroma collapse on the d=0 path). All built with
  Microsoft fxc; full RDEF/ISGN/OSGN/SHEX/STAT chunk set; all
  54 stamped "Microsoft (R) HLSL Shader Compiler 10.1". Validator
  (check_microsoft_creator in tools/regen_d3d12_dxbc.py)
  passes all 54.

Files modified:

* tools/regen_d3d12_dxbc.py: TEMPLATE_VARIANTS gains the
  display.ps.hlsl entry with 54 rows. Comment explains the
  interlace_mode -> (INTERLACED, INTERLEAVED) mapping and the
  d=0 chroma collapse.

* src/common/d3d12/embedded_shaders.h: 108 extern declarations
  (54 array + 54 size_bytes). Header docblock explains the
  variant axis breakdown, the suffix convention, and the
  two-array runtime selection.

* src/common/d3d12/embedded_shaders.cpp: 54 #include lines for
  the new .inc files, inside namespace D3D12::EmbeddedShaders.

* src/core/gpu_hw_d3d12.cpp GetDisplayPipeline: shadergen call
  + m_shader_cache.GetPixelShader path replaced with the
  kMultisamplesIndex lambda + two static arrays + ternary
  indexed-lookup. The m_shadergen-not-yet-built check is
  dropped for this path since the embedded blobs are
  statically linked. Pipeline build downstream is unchanged
  (same root signature, RT format, blend/depth state).

Cost matrix delta (D3D12) for display_ps:
  Cold-flip multisamples toggle: ~50 ms x 6 D3DCompile +
                                 ~10 ms x 6 PSO
                                 -> ~10 ms x 6 PSO only.
  (Multisamples rebuild touches the full 2x3 display PSO
  matrix at the new sample count.)
  Cold-flip smooth_chroma toggle: ~50 ms x 2 D3DCompile +
                                  ~10 ms x 2 PSO
                                  -> ~10 ms x 2 PSO only.
  (Only the 2 d=1 PSOs are affected; d=0 PSOs are
  chroma-independent.)
  Disk-cache-warm: ~1 ms each -> 0 ms.
  Resolution scale toggle: 0 ms (cbuffer-routed via e64fc28).
  Per-frame PSO selection: previously a shader_cache hash
  lookup; now an array index. ~ns vs ~us delta - negligible.

The shadergen GenerateDisplayFragmentShader function is left
intact in gpu_hw_shadergen.cpp - the other three backends still
call it through their runtime shader-cache paths. Only D3D12
bypasses it now. This is the final shader on the non-batch
pre-bake roadmap.

Test:
  - Build: D3D12 backend links without unresolved symbols
    across all 54 new externs. Specific risk: a typo in any of
    the 108 extern names or 54 includes would surface here.
  - Runtime, default config (MSAA off, no chroma smoothing):
    every game must continue to scanout correctly. Failure
    modes if the d=0 path is wrong:
      * Garbled framebuffer / wrong colours on the per-frame
        display.
      * Interlace fields rendered wrong - test signal: any PSX
        game in interlaced output mode (most TV-target games).
        Wrong interlace mapping would manifest as field
        comb-tearing or half-height output.
  - Runtime, 24-bit colour: trigger any FMV. Standard test
    cases:
      * Sony intro bookend FMV - leaves no doubt the 24-bit
        path is hit.
      * In-game cutscene FMVs (FF7, MGS, Resident Evil).
    Failure mode if d=1 c=0 path wrong: FMV plays but colours
    are wrong (off hue, mismatched chroma).
  - Runtime, 24-bit + chroma smoothing: enable the "24-bit
    Chroma Smoothing" core option, then play FMV. Failure mode
    if d=1 c=1 path wrong: FMV plays with sharp chroma edges
    (the smoothing isn't happening) or with garbled output
    (variant table miswired).
  - MSAA at each level (2x/4x/8x/16x/32x): same screenshot
    tests at each. Failure mode for any individual blob:
    visible MSAA averaging artefacts in the displayed image.
    32x specifically validates that kMultisamplesIndex picks
    ms_idx=5 - wrong-side switch would index m16 (4) instead
    of m32 (5).
  - All combinations: display_ps is selected freshly each
    UpdateDisplay call, so the array indexing is exercised
    every frame. Any mis-indexed combo would be visually
    obvious.
  - Chroma toggle: flip "24-bit Chroma Smoothing" mid-FMV. The
    next display PSO selection picks blobs from k_display_d1
    [interlace_mode][1] instead of [0]. Failure mode: chroma
    smoothing doesn't toggle, or wrong PSO selected leading to
    garbled output.

If everything works, the only remaining pre-bake target is the
batch matrix - the ~1 min cold-flip prize, hundreds of variants.
That's the final arc of this whole sequence.
2026-05-19 00:22:35 +02:00
LibretroAdmin
21f46231f5 core/d3d12: pre-bake the VRAM read pixel shader
First MSAA-count cardinality variant. Where vram_update_depth_ps
(91f8c32) split on a binary MULTISAMPLING flag (Texture2D vs
Texture2DMS<float4>), vram_read_ps splits on the MULTISAMPLES
*count* itself - the [unroll] sample-resolve loop in the shader's
LoadVRAM helper unrolls a different number of times per variant.
Each power-of-2 sample count produces a distinct DXBC; the m1
blob takes the Texture2D path with a single Load, while m2..m32
all use Texture2DMS<float4> with different unroll counts in the
sample-averaging loop.

vram_read_ps is the upscaled-VRAM-to-native-16bpp encode pass
that backs screenshot capture, libretro readback, and save-state
staging. It's not in the per-frame hot path - it only runs when
the frontend explicitly requests VRAM contents - but every
MULTISAMPLES variant must be statically available because
m_multisamples can change between runs and pre-bake decisions
are made at link time.

Variant axis: MULTISAMPLES = 1, 2, 4, 8, 16, or 32 (6 blobs).
MULTISAMPLING is derived in-shader (#if MULTISAMPLES > 1) rather
than passed as a separate /D, since the binding type and the
unroll count are both functions of the same value.

Cbuffer is post-2980961 (24 bytes: u_base_coords, u_size,
u_resolution_scale, u_pad0), so RESOLUTION_SCALE is a runtime
cbuffer value and the box-filter loops in SampleVRAM remain
runtime loops (not [unroll]'d). Resolution scale therefore
doesn't multiply the variant count.

Blob sizes scale linearly with MULTISAMPLES because of the
[unroll] of the sample-resolve loop:

  vram_read_ps_m1.inc   3636 B  (Texture2D path, no loop)
  vram_read_ps_m2.inc   3996 B  (2 sample loads + averaging)
  vram_read_ps_m4.inc   4572 B  (4 sample loads)
  vram_read_ps_m8.inc   5724 B  (8 sample loads)
  vram_read_ps_m16.inc  8028 B  (16 sample loads)
  vram_read_ps_m32.inc 12636 B  (32 sample loads)

Total embedded bytecode footprint ~ 38 KB across the 6 blobs.
The .inc text-file sizes (22 KB - 77 KB) are larger than the
binary sizes by ~6x due to the hex-formatting overhead of the
.inc representation ("0xXX, " per byte) - this is invariant
across all pre-bakes and is reflected in the on-disk repo
footprint, not the runtime memory footprint.

Files added:

* data/shaders/d3d12/vram_read.ps.hlsl: standalone HLSL source
  matching GenerateVRAMReadFragmentShader's D3D12 output
  post-2980961. 24-byte cbuffer (u_base_coords.xy, u_size.xy,
  u_resolution_scale, u_pad0) layout-identical to the
  GPU_HW_D3D12::ReadVRAM SetGraphicsRoot32BitConstants push.
  RGBA8ToRGBA5551 helper inlined. LoadVRAM helper's MS-path
  loop is [unroll]'d (MULTISAMPLES is a compile-time /D);
  SampleVRAM's box-filter loops are runtime loops over
  u_resolution_scale.

* src/common/d3d12/embedded_dxbc/vram_read_ps_{m1,m2,m4,m8,m16,
  m32}.inc: 6 DXBC blobs, one per MULTISAMPLES value. All built
  with Microsoft fxc; full RDEF/ISGN/OSGN/SHEX/STAT chunk set;
  creator stamped "Microsoft (R) HLSL Shader Compiler 10.1".
  Validator (check_microsoft_creator in
  tools/regen_d3d12_dxbc.py) passes all 6.

Files modified:

* tools/regen_d3d12_dxbc.py: TEMPLATE_VARIANTS gains the
  vram_read.ps.hlsl entry with 6 rows (m1, m2, m4, m8, m16, m32).

* src/common/d3d12/embedded_shaders.h: 6 extern declarations
  added with their _size_bytes companions. Header docblock
  explains the cardinality-axis distinction vs the binary-axis
  variants above.

* src/common/d3d12/embedded_shaders.cpp: 6 #include lines.

* src/core/gpu_hw_d3d12.cpp GetVRAMReadbackPipeline: shadergen
  call + m_shader_cache.GetPixelShader path replaced with a
  switch on m_multisamples picking between the 6 blobs. Default
  case is a safety net that falls back to the m1 blob with a
  warn log - in practice every supported config falls into a
  named case because the libretro UI dropdown is restricted to
  the same 6 values the switch handles, and the GPU driver-
  capability detection in CreateResources only reports
  power-of-2 counts as supported. The
  m_shadergen-not-yet-built check is dropped for this path since
  the embedded blobs are statically linked.

Cost matrix delta (D3D12) for vram_read_ps:
  Cold-flip multisamples toggle: ~50 ms x N D3DCompile + ~10 ms
                                 x N PSO -> ~10 ms x N PSO only.
  (N = number of distinct MULTISAMPLES values cycled through in
  one session; typically 1-2 if the user picks one MSAA setting
  and keeps it.)
  Disk-cache-warm: ~1 ms each -> 0 ms.
  Resolution scale toggle: 0 ms (cbuffer-routed, no PSO change).

The shadergen GenerateVRAMReadFragmentShader function is left
intact in gpu_hw_shadergen.cpp - the other three backends still
call it through their runtime shader-cache paths. Only D3D12
bypasses it now.

Test:
  - Build: D3D12 backend links without unresolved symbols across
    all 6 new externs.
  - Runtime, MSAA disabled: trigger any readback path. Concrete
    cases:
      * RetroArch "Take Screenshot" hotkey - reads VRAM and
        encodes to PNG. Failure mode if m1 blob is wrong:
        garbled screenshot or wrong colours.
      * Save state - dumps VRAM into the savestate blob.
        Failure mode: load-state restores garbled VRAM.
  - Runtime, MSAA enabled at each level (2x/4x/8x/16x/32x):
    same screenshot / savestate tests. Failure mode: VRAM
    averaging incorrect; per-sample data not properly
    collapsed. Specifically:
      * Slightly off colours on edges of polygons (the MS
        averaging path is what makes upscaled VRAM look
        coherent vs the native 1024x512 readback).
      * 32x specifically tested for unroll-count correctness -
        if the runtime selects m16 by mistake when m_multisamples
        is 32, the readback would load 16 samples instead of 32
        and divide by 16 instead of 32, producing visibly darker
        readback output.
  - Resolution-scale toggle 1x <-> 8x: no PSO recompile (blob
    is scale-independent post-2980961); next readback uses the
    same PSO but different u_resolution_scale value through
    the cbuffer. SampleVRAM's box-filter loops scale at runtime.

Next per the same template now that cardinality-axis is
validated: display_ps (12 x M variants on depth_24 x
interlace_mode x smooth_chroma x MSAA). Largest blob set per
shader. After that the only remaining pre-bake target is the
batch matrix - the ~1 min cold-flip prize, hundreds of variants.
2026-05-18 23:42:30 +02:00
LibretroAdmin
91f8c32ef0 core/d3d12: pre-bake the VRAM update-depth pixel shader
First MSAA texture-binding variant pre-bake. Where vram_copy /
vram_write / vram_fill split on PGXP_DEPTH / WRAPPED / INTERLACED
which are body-branch flags only, vram_update_depth_ps splits on
MULTISAMPLING which changes the *binding type* of samp0
(Texture2D vs Texture2DMS<float4>) plus adds a conditional
SV_SampleIndex input to the entry-point signature. This exercises
the indexed-lookup runtime selection in territory that vram_read_ps
and display_ps will need too.

vram_update_depth runs the depth-only pass that propagates colour-
texture alpha (the PSX mask bit) into the depth buffer after every
CPU->VRAM upload. It's hit on every UpdateVRAM completion path in
games that toggle the mask bit, which means most native rendering
plus any title's transparency layer.

Variant axis: MULTISAMPLING on/off only (2 blobs). msaa0 is the
Texture2D path with .Load(int3(coords, mip)) form; msaa1 is the
Texture2DMS<float4> path with .Load(coords, sample) form and
SV_SampleIndex as an additional entry-point input. HLSL forces
per-sample shading on the msaa1 variant because SV_SampleIndex is
declared, so the PSO MSAA configuration (gpbuilder.SetMultisamples)
must match the shader's per-sample expectation - runtime selection
uses m_multisamples > 1 (same predicate as the shadergen
UsingMSAA() helper).

Files added:

* data/shaders/d3d12/vram_update_depth.ps.hlsl: standalone HLSL
  matching GenerateVRAMUpdateDepthFragmentShader's D3D12 output.
  No cbuffer - the shadergen function never calls
  DeclareUniformBuffer. v_tex0 declared but unused (matches the
  shadergen entry-point template which emits texcoord inputs
  unconditionally; the optimiser drops the dead read). #if
  MULTISAMPLING block switches both the binding and the body Load
  form; the SamplerState is declared for both variants to match
  shadergen byte-for-byte (Texture2DMS doesn't need a sampler for
  Load, but the dead binding is free at runtime).

* src/common/d3d12/embedded_dxbc/vram_update_depth_ps_msaa0.inc:
  DXBC for /DMULTISAMPLING=0 (Texture2D path). 672 bytes.
* src/common/d3d12/embedded_dxbc/vram_update_depth_ps_msaa1.inc:
  DXBC for /DMULTISAMPLING=1 (Texture2DMS<float4> path). 732
  bytes (60B larger for the per-sample shading flag in STAT plus
  the SV_SampleIndex input in ISGN).

Both built with Microsoft fxc; full RDEF/ISGN/OSGN/SHEX/STAT
chunk set; creator stamped "Microsoft (R) HLSL Shader Compiler
10.1". Validator (check_microsoft_creator in
tools/regen_d3d12_dxbc.py) passes both.

Files modified:

* tools/regen_d3d12_dxbc.py: TEMPLATE_VARIANTS gains the
  vram_update_depth.ps.hlsl entry with two rows (msaa0, msaa1).

* src/common/d3d12/embedded_shaders.h: 2 extern declarations
  added. Header docblock explains the MSAA binding-type difference
  vs the body-branch variants above.

* src/common/d3d12/embedded_shaders.cpp: 2 #include lines for
  the new .inc files.

* src/core/gpu_hw_d3d12.cpp GetVRAMUpdateDepthPipeline:
  shadergen call + m_shader_cache.GetPixelShader path replaced
  with a ternary on m_multisamples > 1 picking between the two
  D3D12_SHADER_BYTECODE structs. gpbuilder.SetMultisamples is
  unchanged - it drives the PSO MSAA state from m_multisamples
  directly. The m_shadergen-not-yet-built check is dropped for
  this path since the embedded blobs are statically linked.

The "match the PSO MSAA configuration to the shader expectation"
discipline is the load-bearing piece here. SV_SampleIndex in the
shader forces per-sample shading; the PSO must be configured with
matching MSAA sample count or the runtime will reject PSO creation
(D3D12 PSO validation does cross-check the rasterizer sample count
against the PS expectation). The pattern below scales naturally
to vram_read_ps and display_ps where M (the sample count itself)
also varies.

Cost matrix delta (D3D12) for vram_update_depth_ps:
  Cold-flip multisamples toggle: ~50 ms D3DCompile + ~10 ms PSO
                                 -> ~10 ms PSO only.
  Disk-cache-warm: ~1 ms -> 0 ms.
  Resolution scale toggle: 0 ms (no scale dependency).
  Note: the multisamples toggle itself triggers a much larger
  rebuild cascade (every MSAA-sensitive PSO across the GPU
  matrix), so vram_update_depth_ps's share is small in absolute
  terms - but it's the first proof point for the technique.

The shadergen GenerateVRAMUpdateDepthFragmentShader function is
left intact in gpu_hw_shadergen.cpp - OpenGL / Vulkan / D3D11
still call it through their runtime shader-cache paths. Only
D3D12 bypasses it now.

Test:
  - Build: D3D12 backend links without unresolved symbols.
    Specific risk: a typo in the MSAA-path entry signature would
    surface here (SV_SampleIndex semantic name, ordering vs
    SV_Position).
  - Runtime, MSAA disabled (default): every CPU->VRAM upload
    must continue to propagate mask bits correctly. Test signal:
    any game with mask-bit-using transparent sprites (FF7 spell
    effects, Tekken 3 ring-out smoke, MGS guard-search beams).
    Failure mode: transparency rendering wrong (sprites drawn at
    wrong depth, mask-bit-disabled pixels showing through layers
    that should occlude them).
  - Runtime, MSAA enabled (Multi-Sample Antialiasing core option
    set to 2x / 4x / 8x): same transparency tests, but per-sample
    depth propagation. The msaa1 blob is selected and the PS runs
    once per sample. Failure mode would be MSAA edges around
    transparent sprite boundaries flashing or disappearing because
    per-sample depth wasn't propagated.
  - MSAA toggle (1x -> 4x): triggers full PSO rebuild cascade as
    today. The vram_update_depth_ps portion now picks msaa1
    blob[1] instead of falling through D3DCompile. Cold-flip
    time drops by the D3DCompile share (~50 ms for this one
    shader).
  - Resolution scale toggle: no PSO recompile (blob is scale-
    independent); next UpdateVRAM completion uses the same PSO.

Next per the same template now that MSAA-binding is validated:
vram_read_ps (M MSAA variants on top of the 2980961 cbuffer
routing - first multi-axis MSAA-binding variant), then display_ps
(12xM variants - the prize set).
2026-05-18 23:27:45 +02:00
LibretroAdmin
22d18291e7 core/d3d12: pre-bake the VRAM fill pixel shader
First multi-axis pre-bake. Where vram_copy (cb4b443) and vram_write
(ba013aa) each had a single PGXP_DEPTH dimension and 2 blobs,
vram_fill is 3 axes (PGXP_DEPTH x WRAPPED x INTERLACED) for 8 blobs
total. Exercises the TEMPLATE_VARIANTS table for the first time
with a nested variant space and validates the indexed-lookup
runtime selection pattern that vram_update_depth / vram_read /
display will need for their MSAA splits.

vram_fill is hit on every screen-clear that the game submits, plus
FillVRAM operations from CPU DMA writes - common games that clear
every frame (most 3D titles) hit this constantly, but even
non-clearing-every-frame titles (2D scrollers, JRPG menus) hit it
on scene transitions. Pre-baking removes another D3DCompile from
cold-flips and another path exposed to shader-cache invalidation.

Variant axis breakdown:

  * PGXP_DEPTH: m_pgxp_depth_buffer runtime toggle. Controls how
    o_depth is written - u_fill_color.a (legacy alpha-as-depth) or
    constant 1.0 (PGXP-depth mode where depth is per-vertex from
    CPU projection).
  * WRAPPED: fill rect wraps past the VRAM edge. The runtime
    decides this per-call from the destination rect geometry via
    IsVRAMFillOversized at the call site (line 2194). When set,
    the shader does the same wrap-around discard logic as
    vram_copy / vram_write.
  * INTERLACED: skip every-other-row to preserve the field not
    currently being displayed. Set when the destination overlaps
    the active scanout region during interlaced output. The shader
    discards based on (dst_coords.y & 1) == u_interlaced_displayed_field.

No u_resolution_scale dependency in the shader body for D3D12
mode (fixYCoord is identity on HLSL; only the OpenGL backend's
GLSL body references VRAM_SIZE for the y-flip). No scale-refactor
was needed before pre-baking - the shadergen path's CONSTANT
RESOLUTION_SCALE emission would have been dead code.

Files added:

* data/shaders/d3d12/vram_fill.ps.hlsl: standalone HLSL source
  matching GenerateVRAMFillFragmentShader's D3D12 output.
  36-byte cbuffer member-for-member identical to VRAMFillUBOData
  (u_dst_coords, u_end_coords, u_fill_color, u_interlaced_-
  displayed_field). float4 u_fill_color forces 16-byte alignment
  so it lands at offset 16; the trailing uint sits at offset 32.
  Three #define switches at the top control body branches; v_pos
  is only read when INTERLACED || WRAPPED (the discard paths).

* src/common/d3d12/embedded_dxbc/vram_fill_ps_{p0w0i0,p0w0i1,
  p0w1i0,p0w1i1,p1w0i0,p1w0i1,p1w1i0,p1w1i1}.inc: 8 DXBC blobs,
  one per variant combo. Sizes scale predictably with feature
  complexity - 1016B for the minimal p1w0i0 (no wrap, no
  interlace, constant depth), 1380B for the maximal p0w1i1 (both
  discards plus the alpha-as-depth branch). All built with
  Microsoft fxc via Wine + d3dcompiler_47.dll; full
  RDEF/ISGN/OSGN/SHEX/STAT chunk set; creator string
  "Microsoft (R) HLSL Shader Compiler 10.1". Validator
  (check_microsoft_creator in tools/regen_d3d12_dxbc.py) passes
  all 8.

Files modified:

* tools/regen_d3d12_dxbc.py: TEMPLATE_VARIANTS gains the
  vram_fill.ps.hlsl entry with 8 rows. Variant suffix encodes
  the three flags as p{0,1}w{0,1}i{0,1} so the alphabetical
  ordering of the .inc files matches the natural nested-loop
  iteration order (pgxp outer, wrapped middle, interlaced
  inner). embedded_shaders.h externs and the GetVRAMFillPipeline
  call site mirror this naming convention exactly so a reader
  can grep p?w?i? across all three files and find consistent
  hits.

* src/common/d3d12/embedded_shaders.h: 8 extern declarations
  (one per variant) plus size constants. Header docblock
  explains the variant-axis breakdown and the indexed-lookup
  selection pattern.

* src/common/d3d12/embedded_shaders.cpp: 8 #include lines for
  the new .inc files, inside namespace D3D12::EmbeddedShaders.

* src/core/gpu_hw_d3d12.cpp GetVRAMFillPipeline: shadergen
  call + m_shader_cache.GetPixelShader path replaced with a
  function-scope static const D3D12_SHADER_BYTECODE
  [2][2][2] array indexed by [m_pgxp_depth_buffer ? 1 : 0]
  [wrapped & 1][interlaced & 1]. The static-const initializer
  runs once on first call (k_xxx externs and _size_bytes
  constants are linker-visible by then); subsequent calls are
  3 byte indexes. PSO build downstream is unchanged. The
  m_shadergen-not-yet-built check is dropped for this path
  since the embedded blobs are statically linked.

Cost matrix delta (D3D12) for vram_fill_ps:
  Cold-flip PGXP toggle: ~50ms x 4 D3DCompile + ~10ms x 4 PSO
                         -> ~10ms x 4 PSO only.
  (PGXP rebuilds the full wrapped x interlaced submatrix.)
  Disk-cache-warm: ~1 ms each -> 0 ms.
  Resolution scale toggle: 0 ms (no dependency in body).

The shadergen GenerateVRAMFillFragmentShader function is left
intact in gpu_hw_shadergen.cpp - the OpenGL / Vulkan / D3D11
backends still call it through their runtime shader-cache
paths. Only D3D12 bypasses it now.

Test:
  - Build: D3D12 backend links without unresolved symbols across
    all 8 new externs.
  - Runtime: every screen clear in every game must continue to
    render correctly. Concrete signals:
      * Most 3D titles clear every frame (test signal: any 3D
        title's gameplay, the screen-clear path is hit before
        every frame's draw queue). Failure mode: previous
        frame's content stays visible / smears between frames.
      * Tekken 3 round-start fades through a black clear before
        the round draw - if the wrong variant were selected,
        the fade would either not happen or leave stale pixels.
      * FF7 scene transitions (entering/leaving battle, world
        map -> field) clear the framebuffer; the transition
        flash would corrupt if the variant were wrong.
  - PGXP toggle: flip the "PGXP CPU mode" core option. First
    flip rebuilds all 4 (wrapped x interlaced) PSOs picking
    the p1??? variants instead of the p0??? variants. Subsequent
    same-direction flips hit the PSO cache.
  - Resolution scale toggle 1x <-> 8x: no PSO recompile (blobs
    are scale-independent); CPU side just updates the viewport
    and the next FillVRAM hits the same PSO.
  - Interlaced mode test: enable "Force Progressive Scan" off,
    play any title that runs in interlaced output (most PSX
    games do). The INTERLACED=1 path is hit when FillVRAM
    overlaps the active scanout - test signal: no flicker
    between fields during a fill operation.
  - Wrapped fill test: trigger any oversized FillVRAM (CPU
    writes a fill that crosses the right or bottom VRAM edge).
    Some games do this for the standby blackout overlay or for
    fullscreen depth-buffer clears that span multiple 256-tall
    VRAM strips. The WRAPPED=1 path is hit; failure mode would
    be the spillover region staying uncleared.

Next per the same template now that multi-axis is validated:
vram_update_depth_ps (2 MSAA variants - first MSAA texture-
binding variant exercise, Texture2D vs Texture2DMS<float4>),
then vram_read_ps (M MSAA variants on top of 2980961), then
display_ps (12xM variants - largest blob set per shader).
2026-05-18 23:16:38 +02:00
LibretroAdmin
ba013aa6de core/d3d12: pre-bake the VRAM write pixel shader
Same template as cb4b443 (vram_copy pre-bake), applied to vram_write_ps.
vram_write_ps is the CPU->VRAM upload path - hit on every game's
framebuffer streaming and FMV staging path, so it runs many times
per frame in practice. Pre-baking it removes another D3DCompile
from cold-flips and another path that's exposed to shader-cache
invalidation.

Variant axis: PGXP_DEPTH on/off only (2 blobs). The shadergen's
`use_ssbo` parameter is GLSL/Vulkan-only - the D3D12 caller at
GPU_HW_D3D12::GetVRAMWritePipeline always passes `false`, so the
use_ssbo dimension collapses to a single value for D3D12 and only
the texture-buffer source path (Buffer<uint4> samp0) gets pre-baked.

Files added:

* data/shaders/d3d12/vram_write.ps.hlsl: standalone HLSL source
  matching GenerateVRAMWriteFragmentShader(false)'s D3D12 output
  post-9d2b49d. 44-byte cbuffer member-for-member identical to
  VRAMWriteUBOData (u_base_coords, u_end_coords, u_size,
  u_buffer_base_offset, u_mask_or_bits, u_depth_value,
  u_resolution_scale, u_pad0). VRAM_SIZE / RESOLUTION_SCALE aliases
  inlined. RGBA5551ToRGBA8 helper inlined (no shadergen prelude
  available to standalone HLSL). PGXP_DEPTH branch in body controls
  the o_depth assignment.

* src/common/d3d12/embedded_dxbc/vram_write_ps_pgxp0.inc: DXBC for
  /DPGXP_DEPTH=0 (PGXP off, conditional o_depth). 2048 bytes.
* src/common/d3d12/embedded_dxbc/vram_write_ps_pgxp1.inc: DXBC for
  /DPGXP_DEPTH=1 (PGXP on, o_depth = 1.0). 2028 bytes.

Both built with Microsoft fxc via Wine + d3dcompiler_47.dll - full
RDEF/ISGN/OSGN/SHEX/STAT chunk set, creator stamped "Microsoft (R)
HLSL Shader Compiler 10.1". Validator (check_microsoft_creator in
tools/regen_d3d12_dxbc.py) passes both.

Files modified:

* tools/regen_d3d12_dxbc.py: TEMPLATE_VARIANTS gains the
  vram_write.ps.hlsl entry with two rows (pgxp0, pgxp1). Same
  shape as the vram_copy entry.

* src/common/d3d12/embedded_shaders.h: extern declarations added
  for the two new blobs and their size constants. Header docblock
  explains the use_ssbo collapse.

* src/common/d3d12/embedded_shaders.cpp: two #include lines for
  the new .inc files, inside namespace D3D12::EmbeddedShaders.

* src/core/gpu_hw_d3d12.cpp GetVRAMWritePipeline: shadergen call +
  m_shader_cache.GetPixelShader path replaced with an inline
  D3D12_SHADER_BYTECODE picked via m_pgxp_depth_buffer. PSO build
  downstream is unchanged (same root signature, MSAA, depth state,
  shader-cache PSO disk-cache via gpbuilder.Create). The
  m_shadergen-not-yet-built check is dropped for this path since
  the embedded blob is statically linked.

Cost matrix delta (D3D12) for vram_write_ps:
  Cold-flip PGXP toggle: ~50 ms x 2 D3DCompile + ~10 ms x 2 PSO
                         -> ~10 ms x 2 PSO only.
  Disk-cache-warm: ~1 ms each -> 0 ms.
  Resolution scale: 0 ms (already cbuffer-routed since 9d2b49d).

The shadergen GenerateVRAMWriteFragmentShader function is left
intact in gpu_hw_shadergen.cpp - the other three backends still
call it through their runtime shader-cache paths. Only D3D12
bypasses it now.

Test:
  - Build: D3D12 backend links without unresolved symbols.
  - Runtime: every VRAM upload that previously worked must still
    work. Concrete test: any game's pre-rendered backdrop streaming
    (FF7 entering new screens, MGS pre-rendered cutscene backdrops),
    any FMV playback (Sony intro bookend, in-game cutscenes), and
    any sprite-page reload (fighting-game character select). If
    the embedded blob were wrong, framebuffer uploads would land
    at wrong VRAM offsets and produce visible texture garble
    within seconds of any of those activities.
  - PGXP toggle: flip the "PGXP CPU mode" core option in RetroArch.
    First flip rebuilds PSOs picking blob[1] vs blob[0]; subsequent
    same-direction flips hit the PSO cache.
  - Resolution scale toggle 1x <-> 4x: no PSO recompile (blob is
    scale-independent post-9d2b49d); next CPU->VRAM upload pushes
    a different u_resolution_scale through the cbuffer.

Next per the same template now that the toolchain is trusted and
the pattern is established: vram_fill_ps (8 variants on PGXP x
WRAPPED x INTERLACED, no scale-refactor needed - body doesn't
reference RESOLUTION_SCALE for D3D12 mode), vram_update_depth_ps
(2 MSAA variants - first MSAA texture-binding variant exercise),
vram_read_ps (M MSAA variants - on top of the e64fc28-line
cbuffer routing already done).
2026-05-18 23:04:29 +02:00
LibretroAdmin
837f120ce4 core/d3d12: pre-bake the VRAM copy pixel shader (Microsoft fxc)
Second attempt at the cd971cd / da20f5b pre-bake, now with the
Microsoft fxc toolchain in place (09ca0dc). Same shadergen +
runtime changes as the reverted cd971cd; the only material
difference is that the .inc files are produced by Microsoft's
D3DCompile API instead of Wine's vkd3d-shader reimplementation,
which means the DXBC has the SHEX + STAT chunks that
CreateGraphicsPipelineState validation needs.

Output deltas vs the failed cd971cd attempt:

  vram_copy_ps_pgxp0.inc  3108B (vkd3d) -> 1908B (Microsoft)
  vram_copy_ps_pgxp1.inc  2984B (vkd3d) -> 1828B (Microsoft)

Microsoft's compiler produces smaller bytecode (better optimization
at /O3) and emits the full chunk set RDEF/ISGN/OSGN/SHEX/STAT,
where vkd3d-shader was emitting only ISGN/OSGN/RDEF/SHDR. The
SHEX chunk in particular is what changes here - it's the Shader
Model 5.0+ extended bytecode format that D3D12 PSO validation
expects for SM 5.0 shaders. SHDR is the older SM 4.0 format;
Microsoft D3D12 accepts SHDR for simple shaders by coincidence
of how the validator is structured, but rejects it for anything
with SV_Depth + discard + non-trivial cbuffer (the threshold
case cd971cd hit). SHEX-format output passes uniformly.

Validator confirmation:
  Both .inc files stamp creator string
  "Microsoft (R) HLSL Shader Compiler 10.1"; the
  check_microsoft_creator hook in tools/regen_d3d12_dxbc.py
  (ebd2300) passes them.

This restores the full set of changes that cd971cd shipped:

* data/shaders/d3d12/vram_copy.ps.hlsl - standalone HLSL source
  matching GenerateVRAMCopyFragmentShader's D3D12 output. Cbuffer
  layout member-for-member identical to VRAMCopyUBOData (48 bytes
  - u_src_coords, u_dst_coords, u_end_coords, u_size,
  u_set_mask_bit, u_depth_value, u_resolution_scale, u_pad0).
  VRAM_SIZE alias inlined. PGXP_DEPTH branch in body controls
  the o_depth assignment.

* tools/regen_d3d12_dxbc.py TEMPLATE_VARIANTS dict gains the
  vram_copy.ps.hlsl entry with two rows (pgxp0, pgxp1).

* src/common/d3d12/embedded_shaders.h gains extern declarations
  for k_vram_copy_ps_pgxp0[], _pgxp1[], and the matching
  _size_bytes constants.

* src/common/d3d12/embedded_shaders.cpp gains two #include
  lines inside namespace D3D12::EmbeddedShaders for the new
  .inc files.

* src/core/gpu_hw_d3d12.cpp GetVRAMCopyPipeline: shadergen call
  + m_shader_cache.GetPixelShader path replaced with an inline
  D3D12_SHADER_BYTECODE picked via m_pgxp_depth_buffer. PSO
  build downstream is unchanged. The m_shadergen-not-yet-built
  check is dropped for this path since the embedded blob is
  statically linked.

Variant axis: PGXP_DEPTH only (2 blobs, ~3.7 KB total). Resolution
scale is cbuffer-routed since e56d4d4 so it's not a variant; MSAA
isn't a variant since vram_copy never runs in MSAA mode (texture
binding conflict on the source view).

Cost matrix delta (D3D12 specifically) for vram_copy_ps:
  Cold-flip PGXP toggle: ~50 ms x 2 D3DCompile + ~10 ms x 2 PSO
                         -> ~10 ms x 2 PSO only.
  Disk-cache-warm: ~1 ms each -> 0 ms.
  Resolution scale: 0 ms (already cbuffer-routed).

Test:
  - Build: D3D12 backend links without unresolved symbols.
  - Runtime: FF7 menu navigation (heavy VRAM-copy traffic for
    menu sprite composition) and Tekken 3 round transitions
    (every-frame VRAM-copy splat for round number / TOTAL DMG
    text) render correctly. Failure mode if the .inc were wrong:
    visible sprite / text garble within a second of entering
    a menu or starting a round. Since cd971cd's failure mode
    was "D3D12 backend never inits", the success signal is
    simply that the backend comes up at all - the cd971cd
    log line "CreateGraphicsPipelineState failed: 80004005"
    no longer fires.
  - PGXP toggle: flip the "PGXP CPU mode" core option; the
    first flip rebuilds PSOs picking blob[1] vs blob[0] and
    renders correctly. Subsequent same-direction flips hit the
    PSO cache.
  - Resolution scale toggle 1x <-> 4x: no PSO recompile (the
    blob is scale-independent post-e56d4d4); CopyVRAM next
    frame pushes a different u_resolution_scale value through
    the cbuffer.

If this attempt also fails, the diff to look at is the .inc bytes
themselves (Microsoft-compiled, full chunk set) vs cd971cd's
.inc (vkd3d-shader-compiled, missing SHEX/STAT). Anything else
in the source is identical.

Next on the pre-bake side per the same template now that
the toolchain is trusted: vram_write_ps (4 variants: PGXP x
use_ssbo), vram_fill_ps (8 variants, no scale-refactor needed),
vram_update_depth_ps (2 MSAA variants - first MSAA texture-binding
variant exercise).
2026-05-18 22:57:57 +02:00
LibretroAdmin
ebd2300cde tools/d3d12: refuse non-Microsoft fxc output in the regen script
Post-mortem follow-up to cd971cd / da20f5b. The pre-bake attempt
failed because Wine's bundled d3dcompiler_47.dll (which is the
vkd3d-shader reimplementation, currently at version 1.10) produces
DXBC that's syntactically valid as a container but trips Microsoft
D3D12's CreateGraphicsPipelineState with E_FAIL for non-trivial
shaders. The vram_copy.ps.hlsl case crossed that threshold; the
simpler fullscreen_quad.vs.hlsl + copy.ps.hlsl cases happen to
work and are still in the repo, but they were also vkd3d-shader-
compiled and should be regenerated with Microsoft fxc when the
opportunity arises.

The fix is twofold: improve the SDK auto-detection so contributors
who have Microsoft fxc installed don't have to fight the script,
and add an output validator that refuses to write .inc files
produced by any compiler that isn't Microsoft fxc.

Auto-detection improvements (find_fxc):

* Wine prefix discovery widened. Previously the script only
  checked $WINEPREFIX/drive_c if WINEPREFIX was set. Now it also
  checks ~/.wine (the Wine default when WINEPREFIX is unset),
  and any prefix directory under ~/.local/share/wineprefixes/
  that has a drive_c subtree (PlayOnLinux / lutris-style layouts).
  Both /Program Files/ and /Program Files (x86)/ are searched in
  each prefix.
* Error message now points at the README's installation steps
  rather than telling the user to just install the SDK.
* Error message explicitly calls out that Wine's bundled
  d3dcompiler_47.dll is NOT a substitute and references
  da20f5b for context.

Output validator (extract_rdef_creator + check_microsoft_creator):

* extract_rdef_creator walks the DXBC container chunk index, finds
  the RDEF chunk, follows the creator_offset field at chunk body
  offset 24, and reads back the null-terminated ASCII creator
  string. The DXBC container layout (16-byte hash + version +
  total size + chunk count + chunk offsets) and the RDEF body
  layout (constant_buffer_count, constant_buffer_offset,
  resource_binding_count, resource_binding_offset, shader_version,
  compiler_flags, creator_offset) are documented in MSDN's old
  D3D11 reflection notes and in the wikitalk pages around DXBC;
  the implementation here uses fixed offsets that match what
  fxc.exe and vkd3d-shader both produce.
* check_microsoft_creator hooks into compile_one after the magic
  check. It refuses with a clear error message if the creator
  string doesn't contain "Microsoft". Microsoft fxc stamps
  something like "Microsoft (R) HLSL Shader Compiler 10.1";
  vkd3d-shader stamps "vkd3d-shader 1.10 (Wine bundled)". One
  substring check disambiguates.

What the validator does NOT do:

* It does not retroactively reject existing .inc files in the
  repo. The validator only fires on freshly-produced DXBC during
  a regen run. The vkd3d-shader-built fullscreen_quad_vs.inc and
  copy_ps.inc are unchanged by this commit; they'll get refreshed
  the next time a contributor with Microsoft fxc runs the regen
  script. Until then, they keep working because they're already
  in the repo and the build just compiles them as plain C++
  byte arrays - they never go through PSO validation (they're
  already valid DXBC).
* It does not lock the script to a specific fxc version. Any
  Microsoft fxc.exe (10.1, 10.5, the version that ships with the
  Windows 11 SDK, etc.) is accepted - they all stamp "Microsoft"
  in the creator string.
* It does not validate the binding layout vs the runtime root
  signature. That's a future enhancement - the runtime side
  expects specific (b0, t0, s0) layouts and the regen script
  could cross-check, but that's a much bigger feature.

README changes:

* New "Microsoft fxc.exe is required" section spells out why and
  cites the cd971cd / da20f5b failure as the worked example.
* "Installing Microsoft fxc.exe" subsection with separate
  Windows / Linux instructions. Linux gets two paths: install
  the SDK under a Wine prefix (auto-detected), or extract
  fxc.exe + d3dcompiler_47.dll directly from the MSI with
  msitools and pass --fxc. Both must live in the same dir so
  Wine's loader prefers Microsoft's d3dcompiler_47.dll over its
  bundled vkd3d-shader version.
* The auto-detection scope (WINEPREFIX, ~/.wine, ~/.local/share/
  wineprefixes/*) is now documented so contributors know where
  the script is looking.

This commit does NOT re-add the vram_copy.ps.hlsl source removed
by da20f5b. That comes back in a follow-up patch once a Microsoft
fxc-built .inc is available - same patch lands the .hlsl, the
.inc, and the call-site flip together (the dd54a73 lesson).

Test:
  - python3 -c 'import ast; ast.parse(open("tools/regen_d3d12_dxbc.py").read())'
    passes.
  - Loading the script as a module and feeding the EXISTING
    vkd3d-built copy_ps.inc into extract_rdef_creator returns
    'vkd3d-shader 1.10 (Wine bundled)'; the Microsoft substring
    check returns False. Confirms the validator would catch the
    cd971cd mistake if anyone tries to reproduce it.
  - find_fxc's broader Wine prefix scan is exercised by the
    standard test of running the script in an environment without
    Microsoft fxc; it now fails with the new pointed-at-README
    message instead of the old generic SDK message.
2026-05-18 22:16:18 +02:00
LibretroAdmin
da20f5b80e Revert "core/d3d12: pre-bake the VRAM copy pixel shader"
This reverts commit cd971cd. The pre-baked DXBC blob causes
CreateGraphicsPipelineState to fail with E_FAIL (0x80004005)
during D3D12 backend Initialize, falling back to software
renderer. Confirmed by Lib's screenshot + log output:

  [libretro INFO] [GPU_HW_D3D12] Max texture size: 16384x16384
  [libretro INFO] [GPU_HW_D3D12] Dual-source blend: supported
  [libretro INFO] [GPU_HW_D3D12] Per-sample shading: supported
  [libretro INFO] [GPU_HW_D3D12] Max multisamples: 8
  [libretro ERROR] [GetPipelineState] CreateGraphicsPipelineState failed: 80004005
  [libretro ERROR] [Initialize] Failed to compile pipelines

Root cause is in the wine + vkd3d-shader compilation path used to
produce vram_copy_ps_pgxp{0,1}.inc. Inspecting the DXBC reveals
vkd3d-shader (vkd3d-shader 1.10 Wine bundled) strips the
SamplerState samp0_ss declaration from the RDEF chunk because the
shader uses .Load() not .Sample() so samp0_ss is unused:

  copy_ps.inc RDEF: 3 bindings (samp0_ss, samp0, UBOBlock) - works
  vram_copy_ps_pgxp0.inc RDEF: 2 bindings (samp0, UBOBlock) - fails

This SHOULD be fine since D3D12 allows the shader to use a subset
of the root signature's resource bindings. But the Microsoft D3D12
runtime rejects this particular blob at PSO creation - likely
some other metadata mismatch (SHEX vs SHDR chunk format, missing
STAT chunk, or vkd3d-shader emitting SV_Depth / discard in a form
Microsoft's runtime won't accept). Without D3D12 debug-layer
messages it's hard to localize further.

copy_ps and fullscreen_quad_vs (both Wine-compiled) work in
production, so vkd3d-shader output is not universally
incompatible - it's specific to this shader's combination of
features (SV_Depth output + discard + larger cbuffer + bool
member + uint arithmetic).

For future pre-bakes of more complex shaders, the .inc files
should be regenerated using the Microsoft fxc.exe from a Windows
10/11 SDK (running natively on Windows or under Wine - Microsoft's
fxc.exe is an x86 PE binary that runs fine under Wine, no
vkd3d-shader reimplementation in the path). The current
fullscreen_quad_vs + copy_ps blobs landed with vkd3d-shader
because they're simple enough that the resulting bytecode passes
PSO validation; vram_copy_ps is the threshold case where it
doesn't.

Next pre-bake attempt should:
  1. Switch tools/regen_d3d12_dxbc.py to prefer Microsoft fxc.exe
     by default (Wine prefix lookup + WINEPREFIX environment),
     fall back to fxc_lite only when explicitly asked.
  2. Regenerate fullscreen_quad_vs + copy_ps with Microsoft fxc
     (to confirm byte-different output - and to lock in a known-
     working reference for diff comparison when adding new
     pre-baked shaders).
  3. Then redo vram_copy_ps with Microsoft fxc; expect to land
     it with no other changes needed.

The non-batch RESOLUTION_SCALE cbuffer refactor arc (e56d4d4,
9d2b49d, 2980961, e64fc28) is unaffected by this revert - those
commits don't touch any pre-baked blobs, just route u_resolution_scale
through cbuffers. The pre-bake follow-ups can resume once the
fxc.exe toolchain is in place.
2026-05-18 21:57:44 +02:00
LibretroAdmin
cd971cd1d2 core/d3d12: pre-bake the VRAM copy pixel shader
First multi-variant pre-bake, exercising the TEMPLATE_VARIANTS
infrastructure in tools/regen_d3d12_dxbc.py for the first time.
vram_copy_ps is the smallest cleanly-pre-bakeable non-batch shader
after the e56d4d4 RESOLUTION_SCALE refactor took it from
PGXP x N variants down to just PGXP (2 blobs). Pure body-branch
variant axis - no texture binding changes, no MSAA split, no
input-layout differences. Body is small (~30 lines) and the
runtime call site is one function (GetVRAMCopyPipeline) in one
backend.

Why pre-bake vram_copy_ps:

  * It's hit constantly during gameplay. Every PSX game uses
    VRAM-to-VRAM copies for sprite caching (Final Fantasy 7's
    pre-rendered backgrounds streaming sprites in, Tekken 3's
    text rendering between rounds, every fighting game's HUD
    composite, every JRPG's menu system).
  * After e56d4d4 the only variant axis is PGXP_DEPTH on/off, so
    2 blobs cover every (m_pgxp_depth_buffer, m_resolution_scale)
    combination - cleanest possible variant count.
  * It's the natural exercise for TEMPLATE_VARIANTS (which has
    sat empty since the regen tool was first scaffolded at
    ca8c9b0). Subsequent multi-variant pre-bakes (vram_write 4
    variants, vram_read M MSAA variants, display 12 x MSAA
    variants) reuse the same pattern.

Files added:

* data/shaders/d3d12/vram_copy.ps.hlsl: standalone HLSL source
  matching the GenerateVRAMCopyFragmentShader output for D3D12
  post-e56d4d4. The cbuffer layout matches VRAMCopyUBOData
  member-for-member (u_src_coords, u_dst_coords, u_end_coords,
  u_size, u_set_mask_bit, u_depth_value, u_resolution_scale,
  u_pad0 = 48 bytes). VRAM_SIZE alias inlined since the helper
  emission isn't accessible to standalone HLSL.
  PGXP_DEPTH variant is a single #if in the body controlling
  the o_depth assignment. MSAA path omitted entirely - vram_copy
  never runs in MSAA mode because the source texture is bound
  as both shader-resource AND framebuffer-output, which D3D12
  doesn't permit with an MSAA resource; the runtime uses the
  non-MSAA m_vram_read_texture shadow.

* src/common/d3d12/embedded_dxbc/vram_copy_ps_pgxp0.inc: DXBC
  blob for /DPGXP_DEPTH=0 (PGXP off, conditional o_depth).
  ~3.1 KB of bytecode.

* src/common/d3d12/embedded_dxbc/vram_copy_ps_pgxp1.inc: DXBC
  blob for /DPGXP_DEPTH=1 (PGXP on, o_depth = 1.0). ~3.0 KB.

Files modified:

* tools/regen_d3d12_dxbc.py: TEMPLATE_VARIANTS dict populated
  with the vram_copy.ps.hlsl entry. Two variant rows:
    ("pgxp0", ["PGXP_DEPTH=0"])
    ("pgxp1", ["PGXP_DEPTH=1"])
  The dispatch loop at line 232-238 (untouched, pre-existed
  from ca8c9b0) does the right thing: emit one .inc per row,
  identifier suffix from the variant_suffix string.

* src/common/d3d12/embedded_shaders.h: extern declarations
  added for the two new blobs (k_vram_copy_ps_pgxp0,
  k_vram_copy_ps_pgxp0_size_bytes, and pgxp1 pair). Each pair
  matches the regen tool's naming convention.

* src/common/d3d12/embedded_shaders.cpp: two #include lines
  added inside namespace D3D12::EmbeddedShaders, mirroring
  what was done for fullscreen_quad_vs + copy_ps. The .inc
  files define the storage; the prior extern declarations in
  the header give them external linkage.

* src/core/gpu_hw_d3d12.cpp GetVRAMCopyPipeline: dropped the
  shadergen-call + m_shader_cache.GetPixelShader path; replaced
  with an inline D3D12_SHADER_BYTECODE constructed from the
  embedded blob selected via m_pgxp_depth_buffer. Same PSO-
  creation flow downstream (gpbuilder, MSAA state, depth state,
  shader-cache PSO disk-cache via gpbuilder.Create). The
  m_shadergen-not-yet-constructed check is dropped for this
  path since the embedded blobs are statically linked - no
  ordering dependency on shadergen lifetime.

Toolchain confirmation:
  Built with Wine's d3dcompiler_47.dll via /tmp/fxc_lite/fxc_lite.exe
  on the contributor side (same tooling as 77b255f / 443a2a1).
  DXBC magic verified at regen time (the 'DXBC' signature in the
  first 4 bytes; the regen tool aborts the build if that doesn't
  match).

Cost matrix delta (D3D12 specifically):
  vram_copy_ps D3DCompile cost on cold-cache flip: ~50 ms each
  for the two PGXP variants -> 0 ms after this commit. The PSO
  compile itself still runs through gpbuilder.Create (~10 ms),
  so total cold-flip-of-PGXP cost drops by ~50 ms per variant.
  Disk-cache-warm cost was already in the noise (~1 ms cache
  lookup); now it's literally zero.

  Progress tracker: non_batch_progress_units stays at 17 - we
  still tick once per (depth_test) GetVRAMCopyPipeline call
  inside the precompile_sync loop. PSO compile is still the
  unit; we just stopped doing the D3DCompile half of that
  work.

Variant count after this commit, for the cold-flip cost matrix
columns we care about, for vram_copy specifically:
  * resolution_scale  : 0 ms (cbuffer-routed since e56d4d4)
  * pgxp_depth        : 0 ms D3DCompile + ~10 ms PSO compile
  * multisamples      : 0 (not a vram_copy variant axis)
  * filter / chroma   : 0 (no relationship to vram_copy)

The shadergen GenerateVRAMCopyFragmentShader function is left
intact in gpu_hw_shadergen.cpp - the other three backends
(D3D11, OpenGL, Vulkan) still call it through their runtime
shader-cache paths. Only the D3D12 backend bypasses it now.
Future per-backend pre-bake work could extend the pattern
to those backends too (Vulkan via SPIR-V pre-bake, OpenGL via
something else - GLSL doesn't have a comparable offline-
compiled bytecode format; SPIR-V cross would be the route).

Test:
  - Build: D3D12 backend should link without unresolved symbols.
    The shadergen->GenerateVRAMCopyFragmentShader path is no
    longer reachable through GetVRAMCopyPipeline on D3D12 but
    the function is still defined and used by other backends.
  - Runtime: every VRAM copy that previously worked must still
    work. Concrete test - FF7 menu navigation (uses VRAM copy
    for menu sprite composition heavily), Tekken 3 round-
    transition text rendering (VRAM copy each frame to splat
    the round number / TOTAL DMG sprites). If the embedded
    blob were wrong, sprites and menu text would garble within
    a second of entering a menu or starting a round.
  - PGXP toggle: flip the "PGXP CPU mode" option on and off
    in RetroArch's core options. The first flip recompiles
    PSOs; the embedded blob path picks blob[1] vs blob[0] and
    builds fresh PSOs. Subsequent same-direction flips hit the
    PSO cache.
  - Resolution scale toggle: 1x <-> 4x. No PSO recompile (since
    the blob is scale-independent now); CopyVRAM next frame
    just pushes a different u_resolution_scale value through
    the cbuffer.

This is the first non-batch FRAGMENT pre-bake on top of the
RESOLUTION_SCALE refactor. Following the same template:
vram_write_ps (4 variants: PGXP x use_ssbo), vram_fill_ps (8
variants: PGXP x wrapped x interlaced, no refactor needed
since the body doesn't reference RESOLUTION_SCALE), and
vram_update_depth_ps (2 MSAA variants, exercises MSAA
texture-binding variant for the first time).
2026-05-18 21:48:20 +02:00
LibretroAdmin
443a2a130b core/d3d12: pre-bake the copy/blit pixel shader
Next single-variant non-batch shader in the D3D12 pre-bake arc,
on top of fullscreen_quad_vs (dd54a73 + 77b255f). Picks the
copy/blit fragment shader (GenerateCopyFragmentShader -> bound
in GetCopyPipeline, used for full-frame blits during display
presentation / downscaling).

Why this one and not vram_copy / vram_update_depth / vram_fill /
vram_read / display - which were the other candidates on the
shortlist:

  * vram_update_depth: has an MSAA #ifdef split inside the body
    (LOAD_TEXTURE_MS vs LOAD_TEXTURE) plus a declare_sample_id
    in DeclareFragmentEntryPoint that depends on UsingMSAA(). So
    2 variants minimum, more once we account for the MSAA sample
    count.
  * vram_copy: has a PGXP_DEPTH define, plus uses VRAM_SIZE which
    is compile-time-baked from m_resolution_scale * VRAM_WIDTH/
    HEIGHT via the non-batch WriteCommonFunctions path. 2x
    pgxp_depth times ~5 resolution scale values minimum.
  * vram_fill: PGXP_DEPTH x wrapped x interlaced plus VRAM_SIZE
    via the same compile-time-bake path. 4x variants minimum,
    more after multiplying by resolution scale.
  * vram_read: VRAM_SIZE / RESOLUTION_SCALE bake-in via
    WriteCommonFunctions; the inner box-filter loop uses
    RESOLUTION_SCALE directly as the loop bound, so the variant
    count is one per scale value (5+).
  * display: depth_24bit x interlace_mode x smooth_chroma x
    UsingMSAA x RESOLUTION_SCALE - the multi-variant family with
    the biggest cost.

Each of the above hits one of two structural issues that the
infrastructure doesn't address yet:

  1. RESOLUTION_SCALE / VRAM_SIZE are baked in compile-time for
     non-batch shaders via WriteCommonFunctions's
     batch_uniform_buffer=false path. The cbuffer-routed batch
     path (post-7b575a3) only applies to batch shaders. Migrating
     a non-batch shader that references these constants requires
     either one .inc per resolution scale value, or a refactor
     that lets non-batch shaders read u_resolution_scale from the
     cbuffer too.
  2. The MSAA dimension multiplies every shader that calls
     LOAD_TEXTURE_MS in some branch.

ShaderGen::GenerateCopyFragmentShader (NOT
GPU_HW_ShaderGen::GenerateVRAMCopyFragmentShader - this is the
plain blit one declared in shadergen.h, not the VRAM-coords
copy in gpu_hw_shadergen.cpp) sidesteps all of this:

  * No WriteCommonFunctions call - so no RESOLUTION_SCALE, no
    VRAM_SIZE, no MULTISAMPLES bake-in.
  * No MSAA branch - takes a single Texture2D, not Texture2DMS.
  * No #define-controlled variants - the source string is
    identical on every call.
  * cbuffer-routed source rect (u_src_rect float4) - all runtime
    state lives in the UBO, none baked.

So one pre-baked variant covers every caller. Same shape as
fullscreen_quad_vs.

Files in this patch:

* data/shaders/d3d12/copy.ps.hlsl - standalone HLSL, ~16 lines,
  native HLSL syntax (no shadergen prelude, no aliases). cbuffer
  UBOBlock at register(b0), Texture2D samp0 at register(t0) +
  SamplerState samp0_ss at register(s0), one TEXCOORD0 input,
  one SV_Target0 output. Same source rect math as the original
  generated shader.

* src/common/d3d12/embedded_dxbc/copy_ps.inc - autogenerated by
  tools/regen_d3d12_dxbc.py /T ps_5_0 /E main /O3. Generated in
  this submission environment via Wine's d3dcompiler_47.dll
  through the fxc_lite shim (see 77b255f for the full toolchain
  setup). 808 bytes of valid DXBC (magic 0x43425844 / "DXBC",
  four chunks: ISGN / OSGN / SHEX / STAT).

* src/common/d3d12/embedded_shaders.h - extern declarations for
  k_copy_ps[] and k_copy_ps_size_bytes added below the existing
  fullscreen_quad_vs pair. Same comment format - documents the
  shader's role and the no-state-dependency rationale.

* src/common/d3d12/embedded_shaders.cpp - second #include line
  for embedded_dxbc/copy_ps.inc inside the namespace block.
  Pattern matches what subsequent migrations will follow.

* src/core/gpu_hw_d3d12.cpp - GetCopyPipeline body updated:
  - The ComPtr<ID3DBlob> fs = m_shader_cache.GetPixelShader(
    m_shadergen->GenerateCopyFragmentShader()) + null check
    replaced with a const D3D12_SHADER_BYTECODE fs = { ... }
    aggregate-init over the embedded blob.
  - The if (!m_shadergen) check is dropped - GetCopyPipeline
    no longer has any m_shadergen dependency. Other state
    (root signature, context, shader cache, mutex) was already
    initialised earlier than m_shadergen in the lifecycle, so
    removing the m_shadergen check doesn't open a 'called too
    early' window for this helper.
  - gpbuilder.SetPixelShader(fs.Get()) becomes
    gpbuilder.SetPixelShader(fs.pShaderBytecode,
                             static_cast<uint32_t>(fs.BytecodeLength))
    matching the existing SetVertexShader call form a few
    lines above. (Cleanup: a D3D12_SHADER_BYTECODE& overload
    on SetVertexShader / SetPixelShader in d3d12/util.h would
    elide the verbose unpack at all call sites - deferred to
    a follow-up patch so this one stays focused on the shader
    migration.)

Progress unit count unchanged. GetCopyPipeline still costs one
progress.Increment call in the precompile_sync block at the
'copy/blit (1)' entry of the 4 + 2 + 2 + 1 + 1 + 6 + 1 = 17
breakdown - the embedded shader removes the D3DCompile work,
but the ID3D12Device::CreateGraphicsPipelineState call (the
PSO compile) is what the progress tick actually corresponds to,
and that still happens.

Cost / behaviour:
  - Cold boot, shader_precompile_mode = Enabled: one fewer
    D3DCompile per first-touch of GetCopyPipeline (which is hit
    once per CompilePipelines pass). Combined with
    fullscreen_quad_vs, that's two non-batch shaders off the
    D3DCompile path. The bulk of the cold-boot ~1 min cost is
    still in the batch matrix (1164 cells) - this migration
    chips at a single non-batch unit, but it's the right next
    step structurally because it validates the .ps.hlsl side
    of the pipeline (fullscreen_quad_vs only validated .vs).
  - Lazy mode: same delta, on first lazy-fault of the copy
    pipeline.
  - Disabled: same delta, on first GetCopyPipeline call from
    the runloop (presentation copy / downscale).
  - Runtime: no behaviour change. The pre-baked DXBC binds at
    PSO creation; presentation copies / downscaling renders
    identically.

Failure modes to watch for:
  - If Wine's d3dcompiler produces semantically different DXBC
    from Microsoft's fxc.exe for this specific shader (very
    unlikely given the simplicity - one texture sample, no
    branching, no flow control), the blit would render
    incorrectly. Visible immediately as a wrong / blank
    presentation. Easy to spot.
  - If the .inc file gets out of sync with copy.ps.hlsl (e.g.
    someone edits the .hlsl without re-running the regen
    script), the embedded blob would compile against the old
    shader source. The autogen header comment in the .inc
    documents the source it was generated from, and the regen
    script is idempotent (re-running it on an unchanged .hlsl
    produces byte-identical output), so getting the two back
    in sync is just `python3 tools/regen_d3d12_dxbc.py`.

Test:
  - Build under USE_D3D12=1 succeeds.
  - Cold boot under shader_precompile_mode = Enabled. Progress
    bar reaches 100% at 17 non-batch units (unchanged). The
    copy/blit pipeline ticks the same as before; its PSO is
    built with the embedded PS blob.
  - Presentation / downscaling render correctly - GetCopyPipeline
    is called at presentation time from the host display layer.
    If the embedded PS is wrong, the framebuffer presents wrong
    on the first frame.
  - Toggle a non_dim setting (multisamples) to fire the full-
    flush branch. m_copy_pipeline is Reset() in DestroyPipelines;
    next CompilePipelines pass re-binds the embedded blob.
  - Toggle chroma_smoothing for the partial-flush branch -
    GetCopyPipeline isn't reached (only display pipelines clear),
    embedded blob undisturbed.

Next in the arc: a util.h cleanup adding a
SetVertexShader/SetPixelShader(D3D12_SHADER_BYTECODE&) overload
so the .pShaderBytecode + static_cast<uint32_t>(.BytecodeLength)
boilerplate disappears from call sites. After that, the
RESOLUTION_SCALE cbuffer refactor for non-batch shaders opens
up vram_copy / vram_update_depth / vram_fill / vram_read - the
last single-variant or near-single-variant non-batch shaders
before the batch matrix takes the rest of the arc.
2026-05-18 20:22:17 +02:00
LibretroAdmin
dd54a73809 core/d3d12: pre-bake the fullscreen-quad vertex shader
First end-to-end pre-bake migration off the runtime D3DCompile
path, on top of the scaffolding from ca8c9b0. Picks the smallest
possible target - a single-variant vertex shader with zero state
dependency, used by every non-batch pipeline (vram_fill /
vram_copy / vram_write / vram_update_depth / vram_readback /
display / copy/blit) - to validate the full pipeline before
larger migrations land.

Reasoning for starting here: the screen-quad VS emits a fullscreen
triangle from SV_VertexID via the standard bit-shift trick and
has no #defines or compile-time-baked uniforms, so a single
pre-baked variant covers all seven call sites. Compared to vram_read
(which I evaluated as the first target earlier in this arc):
RESOLUTION_SCALE bakes in compile-time on non-batch shaders via
WriteCommonFunctions, so vram_read would need either one variant
per scale value or a refactor of the runtime to bind the batch
cbuffer to non-batch shaders. That's a real refactor, not a
validation patch. The screen-quad VS sidesteps it entirely.

Files in this patch:

* data/shaders/d3d12/fullscreen_quad.vs.hlsl - standalone HLSL
  equivalent to what ShaderGen::GenerateScreenQuadVertexShader()
  produces in D3D12 mode after preprocessor expansion. Stripped
  the shadergen prelude (#define HLSL 1, #define vec2 float2,
  the SAMPLE_TEXTURE / LOAD_TEXTURE / FOR_UNROLL macros, the API_*
  defines) because the shader uses none of them - native HLSL
  is what fxc wants. Also dropped the dead
  #if API_OPENGL || API_OPENGL_ES || API_VULKAN branch since
  API_OPENGL=0 / API_OPENGL_ES=0 / API_VULKAN=0 for D3D12.

* src/common/d3d12/embedded_shaders.h - replaces the placeholder
  comment block from ca8c9b0 with the first concrete extern
  declaration:

    extern const uint8_t k_fullscreen_quad_vs[];
    extern const size_t k_fullscreen_quad_vs_size_bytes;

  Pattern matches the regen_d3d12_dxbc.py emission convention
  documented in ca8c9b0's commit message.

* src/common/d3d12/embedded_shaders.cpp - replaces its placeholder
  with the first #include of a generated .inc. The .inc itself
  (src/common/d3d12/embedded_dxbc/fullscreen_quad_vs.inc) is
  generated by tools/regen_d3d12_dxbc.py from the .hlsl source
  above. **The .inc is NOT included in this patch** because the
  submission environment doesn't have fxc.exe available. See the
  applying instructions at the bottom of this commit message.

* src/core/gpu_hw_d3d12.h:
  - GetFullscreenQuadVertexShader() return type changed from
    ComPtr<ID3DBlob> to D3D12_SHADER_BYTECODE. The function is no
    longer a lazy-fault helper - the embedded blob is statically
    linked, always available, no allocation. Function comment
    refreshed accordingly.
  - m_fullscreen_quad_vertex_shader member dropped. It was the
    cache slot for the lazy-faulted blob; with pre-bake there's
    no fault-in, no caching state, no mutex.

* src/core/gpu_hw_d3d12.cpp:
  - #include "common/d3d12/embedded_shaders.h" added next to the
    other common/d3d12/ includes.
  - GetFullscreenQuadVertexShader body rewritten to return a
    D3D12_SHADER_BYTECODE aggregate over the embedded blob. No
    mutex, no shader_cache.GetVertexShader, no D3DCompile.
  - Two precompile_sync if-checks removed. The block at line ~956
    used to call GetFullscreenQuadVertexShader() and increment
    progress; the block at line ~1023 used to fault it in for
    Lazy mode. Both meaningless now - the blob is statically
    linked, there is no fault to drive. Left explanatory comments
    at both sites so the absence is documented.
  - Progress unit count updated 18 -> 17. The fullscreen-quad
    VS was one of the 18 non-batch compilation units the
    progress bar ticked through; with pre-bake it has no compile
    step to tick. Inline comment refreshed at both the count
    declaration site (line ~825) and the "1 + 4 + 2 + 2 + 1 + 1
    + 6 + 1 = 18" comment that explained the breakdown.
  - Seven call sites in the GetXxxPipeline helpers converted
    from:
        ComPtr<ID3DBlob> vs = GetFullscreenQuadVertexShader();
        if (!vs)
          return {};
        ...
        gpbuilder.SetVertexShader(vs.Get());
    to:
        const D3D12_SHADER_BYTECODE vs = GetFullscreenQuadVertexShader();
        ...
        gpbuilder.SetVertexShader(vs.pShaderBytecode,
                                  static_cast<uint32_t>(vs.BytecodeLength));
    The null check is dropped because the embedded blob is never
    null. The cast to uint32_t matches the existing
    SetVertexShader(const void*, uint32_t) overload signature in
    src/common/d3d12/util.h. (A future cleanup could add a
    SetVertexShader(const D3D12_SHADER_BYTECODE&) overload to
    elide the verbose unpacking at call sites; left for the next
    patch in the arc where we'll have several more embedded
    blobs and the savings justify the overload.)
  - m_fullscreen_quad_vertex_shader.Reset() in DestroyPipelines
    dropped. Comment block trimmed accordingly.
  - Stale comment block above GetFullscreenQuadVertexShader
    refreshed to describe pre-bake semantics instead of the
    fault-in pattern that no longer applies.

Applying instructions (the .inc file isn't in this patch, so
build will fail until it lands):

  $ git am 0001-core-d3d12-pre-bake-the-fullscreen-quad-vertex-shader.patch
  $ python3 tools/regen_d3d12_dxbc.py
    # produces src/common/d3d12/embedded_dxbc/fullscreen_quad_vs.inc
  $ git add src/common/d3d12/embedded_dxbc/fullscreen_quad_vs.inc
  $ git commit --amend --no-edit
  $ git push

The amend folds the generated .inc into this commit so upstream
sees a single self-contained patch. (Alternative: commit the .inc
as a separate "regenerate fullscreen_quad_vs.inc" follow-up;
either works, but amending keeps the history one-commit-per-
migration which matches the Vulkan-side convention.)

Cost / behaviour:
  - Cold boot, shader_precompile_mode = Enabled: one fewer
    D3DCompile call, one fewer ID3DBlob allocation. Microseconds
    saved per boot, not user-visible at this scale.
  - Lazy mode pre-fill: same delta.
  - Disabled mode first FillVRAM / etc.: same delta.
  - Runtime: no behaviour change. PSOs that bind the embedded
    blob produce byte-identical bytecode to what D3DCompile would
    have produced from GenerateScreenQuadVertexShader() (modulo
    fxc version compiler-output differences, which the runtime
    cache normalises against anyway).
  - Failure mode: if fxc produces a different shader (e.g. a
    fxc version drift bug), every non-batch pipeline using the
    embedded VS would render incorrectly - blank framebuffer,
    wrong UVs, etc. The visual regression is immediate on first
    frame. Easy to spot.

Test:
  - Cold boot under shader_precompile_mode = Enabled. Progress
    bar reaches 100% (now sized to 17 non-batch units). FillVRAM
    / display / readback / etc. all render correctly.
  - Cold boot under Lazy. Pre-fill happens in the foreground
    before runloop, no nullptr at draw time on the first frame.
  - Cold boot under Disabled. First FillVRAM lazy-faults the
    fill pipeline; the embedded VS is bound, render is correct.
  - Toggle a non_dim setting (multisamples) to force full-flush
    of pipelines. CompilePipelines walks the matrix again,
    rebinds the embedded VS on every non-batch PSO. No leak,
    no use-after-free.
  - Toggle chroma_smoothing to fire the partial-flush branch
    (display pipelines only). Embedded VS is bound on the new
    display PSOs. Display still renders.
  - DestroyPipelines on shutdown / UpdateSettings: no
    m_fullscreen_quad_vertex_shader to Reset; nothing to leak.

Next patch in the arc: extend to non-batch pixel shaders that
don't bake state. vram_copy_ps and vram_update_depth_ps are
the next candidates - both are single-variant and have no
RESOLUTION_SCALE dependency (they sample VRAM coordinates
directly, no box-filter loop). After those, vram_fill_ps (two
variants: wrapped/unwrapped, interlaced/not - 4 total - so
TEMPLATE_VARIANTS gets its first non-empty entry). vram_read
and the batch matrix come later, after we have a cbuffer-
routing migration that lets RESOLUTION_SCALE be runtime-set
in non-batch shaders too.
2026-05-18 19:40:13 +02:00
LibretroAdmin
ca8c9b05e8 core/d3d12: scaffolding for pre-baked DXBC blobs
First step of the D3D12 pre-baked DXBC arc that was originally
flagged in 7b575a3's commit message as the natural follow-up to
the cbuffer / dim cache / chroma-split / non-batch-skip
optimisation series. Sets up the directory layout, regen tool,
and namespace scaffolding that subsequent patches will populate
with individual shader migrations.

Mirror of the Vulkan-side infrastructure that lives at
data/shaders/vulkan/ + src/common/vulkan/embedded_shaders.{h,cpp}
+ tools/regen_vulkan_spirv.py + src/common/vulkan/embedded_spirv/
(181 .inc files). The Vulkan side replaces glslang -> SPIR-V at
runtime with pre-compiled SPIR-V blobs; the D3D12 side will
replace D3DCompile -> DXBC at runtime with pre-compiled DXBC
blobs from fxc.exe.

Motivation: after the dim cache (10c53b8) and the chroma-split
(57ac62e), the D3D12 backend's UpdateSettings cost matrix has
one remaining 'still pays the full rebuild cost' class of
toggles - multisamples / per_sample_shading / uv_limits /
pgxp_depth / colour perspective - that genuinely invalidate
every HLSL variant in the 1164-cell batch pipeline matrix. On
a cold shader cache, walking that matrix synchronously costs on
the order of one minute under shader_precompile_mode = Enabled,
because every cell pays a fresh D3DCompile. Pre-baking the DXBC
eliminates the D3DCompile pass on those cells, dropping the
cold-flip cost to whatever the PSO-creation pass alone takes
(ID3D12Device::CreateGraphicsPipelineState, much faster than
D3DCompile + CreateGraphicsPipelineState).

The pre-bake also forecloses a class of 'd3dcompiler_47.dll
version drift invalidates the cached DXBC' failures the
runtime shader cache sometimes hits on driver updates.

Files in this scaffold patch:

* tools/regen_d3d12_dxbc.py - mirror of regen_vulkan_spirv.py
  for the fxc.exe / DXBC path. Walks data/shaders/d3d12/*.hlsl,
  determines stage from filename suffix (.vs.hlsl / .ps.hlsl /
  .cs.hlsl / .gs.hlsl), compiles each via fxc /O3 /T <stage>_5_0
  /E main, validates the output DXBC magic, and emits a .inc
  with const uint8_t array + size_t size_bytes. Honours a
  TEMPLATE_VARIANTS dict (initially empty) for shaders that need
  multiple pre-baked variants via /D defines. Auto-detects
  fxc.exe in the Windows 10 SDK install path; supports Wine on
  Linux via --wine and explicit --fxc PATH.

  In its empty-input case (the state immediately after this
  patch lands) the script exits zero with a 'nothing to do'
  message - no fxc lookup needed when there are no shaders to
  compile, so the script is runnable on systems without the
  Windows SDK / Wine until the first shader source actually
  shows up under data/shaders/d3d12/.

* data/shaders/d3d12/README.md - workflow documentation mirror
  of data/shaders/vulkan/README.md. Documents the
  edit-.hlsl -> rerun-script -> commit-both convention, the
  filename suffix -> shader stage mapping, the
  TEMPLATE_VARIANTS partition for multi-variant blobs, and the
  build-time constraint that the core build must never invoke
  fxc.exe.

* src/common/d3d12/embedded_shaders.h - namespace
  D3D12::EmbeddedShaders header. No extern declarations yet -
  this patch lays down the namespace scaffold. Subsequent
  patches add pairs of:

    extern const uint8_t k_<stem>_<stage>[];
    extern const size_t k_<stem>_<stage>_size_bytes;

  per migrated shader. Comment block documents the (data, size)
  -> D3D12_SHADER_BYTECODE aggregate-initialiser convention -
  no wrapper helper needed (unlike Vulkan's CreateShaderModule
  helper, because D3D12_SHADER_BYTECODE is a plain struct, not
  an API call).

* src/common/d3d12/embedded_shaders.cpp - storage TU. Currently
  empty inside the namespace block. As .inc files get added
  under src/common/d3d12/embedded_dxbc/, each is #included
  here from inside the namespace block so the arrays resolve
  against the header's extern declarations.

* Makefile.libretro and src/common/CMakeLists.txt - register
  embedded_shaders.cpp as a TU under the existing USE_D3D12
  gate. Compiles as part of the libretro build whenever D3D12
  support is enabled.

Subsequent patches in this arc will each:

  1. Add data/shaders/d3d12/<name>.<stage>.hlsl from the runtime
     ShaderGen output (cleaned up - no preprocessor noise that
     fxc handles at compile time anyway).
  2. Run tools/regen_d3d12_dxbc.py to produce the .inc(s).
  3. Add the matching extern declarations to embedded_shaders.h
     and the #include line to embedded_shaders.cpp.
  4. Switch the D3D12 backend call site (typically in
     gpu_hw_d3d12.cpp's GetXxxPipeline or CompilePipelines) to
     bind the embedded blob via D3D12_SHADER_BYTECODE instead
     of calling D3DCompile through the shared D3D11::ShaderCompiler
     path.

Ordering preference: start with non-batch, single-variant
shaders (vram_read / vram_write / vram_update_depth /
vram_copy / vram_fill / display) to validate the pipeline
end-to-end with minimal blast radius. Then the multi-variant
display / chroma family. Then the batch matrix - which is the
bulk of the work and where the cold-flip cost actually lives.

Note: the .inc files don't exist yet because fxc.exe isn't
runnable in this submission environment (Linux without Wine /
Windows SDK). The script is functional and will produce
.inc files as soon as it gets run on a host with fxc.exe.
This patch is intentionally a foundation: build succeeds with
no behaviour change, runtime is untouched, and the next patch
in the arc adds the first shader source + its .inc + the
matching call-site flip.

Test:
  - python3 tools/regen_d3d12_dxbc.py with no shader sources
    exits 0 with 'nothing to do' message. No fxc.exe required.
  - Build under USE_D3D12=1: embedded_shaders.cpp compiles
    cleanly as an empty namespace TU. No new symbols emitted.
  - Build under USE_D3D12=0: embedded_shaders.cpp is excluded
    from the build per the existing if(USE_D3D12) gate in
    src/common/CMakeLists.txt and the ifeq guard in
    Makefile.libretro.
  - Runtime: no behavior change. D3D12 backend continues to
    compile every shader through the existing D3DCompile path.
2026-05-18 09:14:52 +02:00