From 116a70eae288b671ca8fe0d3a576c154963fa55c Mon Sep 17 00:00:00 2001 From: LibretroAdmin Date: Tue, 19 May 2026 01:25:23 +0000 Subject: [PATCH] core: route PGXP_DEPTH through the batch UBO for the FS Companion to 49c0f82 (VS-side PGXP_DEPTH routing). The FS-side routing converts SV_Depth from a per-variant signature decision to an always-declared output, with a single runtime-branch write at the end of main() picking the right depth expression based on the u_pgxp_depth cbuffer scalar (added to BatchUBOData in 49c0f82 and already populated by Initialize / Reset / UpdateHWSettings). C++ shadergen path only this commit (D3D11 / D3D12 / OpenGL). Vulkan FS templates still have PGXP_DEPTH as a -D variant axis and a follow-up commit will collapse it across all five FS templates (parallel to the UV_LIMITS Nearest-FS-routing follow-up pattern). m_pgxp_depth_buffer stays in shader_source_changed for now because Vulkan still needs the rebuild to switch pre-baked SPIR-V variants and because the PSO depth comparison func (LESS_EQUAL vs GREATER_EQUAL) still depends on m_pgxp_depth_buffer at PSO build time across all backends. What changes in the shadergen: DefineMacro(ss, "PGXP_DEPTH", m_pgxp_depth); -> dropped from the FS prelude. m_pgxp_depth at shadergen ctor capture is now unused for the batch FS body / signature. (The member field stays - the VS still captures it for the body comment / documentation, the constructor still accepts it because the gpu_hw_*.cpp shadergen instantiations still pass it, and the vram_write / vram_copy / vram_fill non- batch shaders below in the same file still use PGXP_DEPTH as a -D macro on their own variant matrices.) DeclareFragmentEntryPoint(ss, ..., !m_pgxp_depth, ...) -> DeclareFragmentEntryPoint(ss, ..., true, ...) Both call sites (textured and untextured arms of the batch FS) unconditionally request SV_Depth declaration. FS body o_depth writes: four `#if !PGXP_DEPTH / o_depth = oalpha * v_pos.z / #endif` blocks inside the four transparency arms (TRANSPARENCY + TEXTURED semitransparent, TRANSPARENCY + TEXTURED opaque, TRANSPARENCY-only-untextured, non-TRANSPARENCY) collapse to a single unconditional write at the end of main(): o_depth = (u_pgxp_depth != 0u) ? v_pos.z : (oalpha * v_pos.z); All four old sites wrote the same expression with the same operand values in scope, so hoisting to a single end-of- function site is value-equivalent. The discards in the TRANSPARENCY_ONLY_OPAQUE / _TRANSPARENT arms above end the FS before the o_depth write runs, just as they did pre-routing. Why the ternary is correct: u_pgxp_depth != 0 (PGXP-depth mode): The VS computes pos_z from a_pos.w (PGXP-replayed depth) and writes it through v_pos.z. The rasterizer interpolates it. Writing v_pos.z back to o_depth is a pass-through that produces the same depth value the pre-routing PGXP-on path got from omitting SV_Depth entirely (rasterizer-interpolated depth goes straight to the depth buffer). u_pgxp_depth == 0 (legacy mask-bit mode): The VS computes pos_z from a_pos.z (mask-bit Z). oalpha is 0 or 1 in this mode (set by the C++ side based on whether the pixel should mask). oalpha * v_pos.z is either 0 (mask off) or v_pos.z (mask on) - the same encoding the pre-routing PGXP-off path wrote. Performance trade: Pre-routing, only the PGXP-on batch FS variants retained early-Z TEST. Every PGXP-off variant lost it to SV_Depth declaration, and every batch FS variant (both PGXP modes) lost early-Z WRITEBACK to the discard keyword's static presence (texture-transparent discard plus the u_interlacing discard added in eb42ffb). Post-routing, all batch FS variants lose early-Z TEST. This is the same character of trade Lib accepted for earlier cbuffer-routing commits (the discard-driven WRITEBACK loss in eb42ffb, called out in the GenerateBatchFragmentShader comment around the u_interlacing branch). The PGXP-on path was the last remaining variant with early-Z TEST; this commit takes it. For PSX content on modern GPUs: - Native framebuffer is 1024x512 = ~0.5 Mpix. At 16x resolution scale that's ~134 Mpix. Even with 5x overdraw that's ~670 Mpix of FS work, well within sub-millisecond throughput on a 5090. - PSX overdraw is low. The original hardware can't handle much, so games are designed around 1-3x typical / 5-10x in particle-heavy moments, not the 20-50x modern engines see. - PSX renders are typically painter's-algorithm sorted back-to-front (for transparency correctness). Front- to-back sort + early-Z is the configuration where early-Z TEST pays off - PSX deliberately does the opposite to be sort-correct. - The depth buffer in legacy mode is mask-bit storage, not perspective depth. Hi-Z hierarchical compression can't compress essentially-random values, so even when early-Z TEST was active, Hi-Z wasn't doing much. Net: the early-Z TEST loss is theoretical; on the target hardware it is sub-noise. Same character as the prior cbuffer-routing trades. PSO depth-comp dependency is OUTSIDE this commit: Per gpu_hw_d3d12.cpp:1317-1319, the PSO depth comparison func is set at PSO build time: depth_test ? (m_pgxp_depth_buffer ? LESS_EQUAL : GREATER_EQUAL) : ALWAYS; m_pgxp_depth_buffer flips therefore still require PSO rebuilds to swap the comparison func. The FS bytecode is now invariant across the flip (cache-served) but the PSO cache key still includes m_pgxp_depth_buffer indirectly via the depth-comp field. This commit does not unify the depth-comp func across PGXP modes - that would require either always-using one comparison func and inverting the depth values in the other mode (a meaningful algorithmic change) or making depth-comp a matrix dim (which doubles m_batch_pipelines count). Neither belongs in a routing commit. The eventual decision: most likely keep depth-comp as a PSO-state dep on m_pgxp_depth_buffer and accept that PGXP toggles re-assemble PSOs from cached FS blobs. Pre-bake variant count, cumulative arc progress: Pre-arc: 75 264 After DITHERING: 37 632 After INTERLACING: 18 816 After PGXP-VS: no change (FS pre-bake unaffected) After UV_LIMITS: 9 408 After PGXP-FS (this): 4 704 Remaining axes that would need decision before pre-bake: multisamples x 6 (kept as a variant axis) per_sample_shading x 2 (decision pending) disable_color_perspective x 2 (decision pending) If both per_sample / dcp collapse via forced-always settings: 4704 / 4 = 1176. That is the rough target the pre-bake commits will aim at. Cost matrix delta (D3D12): PGXP toggle mid-session (m_pgxp_depth_buffer flips): Pre-commit: FS bytecode varies across the flip, so shader_source_changed fires the full ~252 FS blob + ~2520 PSO rebuild. With disk shader cache populated, the FS compiles are cache hits and the cost is ~2520 PSO assembly calls. Post-commit: FS bytecode is invariant. The full rebuild path STILL fires (PSO depth-comp swap), but every FS lookup is now a byte-identical hash hit. PSO assembly is unchanged. Net: 252 fewer D3DCompile calls on a cold cache (was zero on a warm cache, so no change there). Pre-bake variant count halved. Steady-state runtime cost: + one runtime branch + one MUL in every batch FS invocation. The branch is uniform across the warp (u_pgxp_depth is a cbuffer scalar) so it costs a single divergent-free predicated select on modern hardware. Sub-microsecond at the framebuffer sizes PSX rendering produces. Cross-backend impact: D3D11 / D3D12 / OpenGL: get the routed FS bytecode starting this commit. PSO depth-comp dep on m_pgxp_depth_buffer unchanged. Vulkan: untouched - its batch FS templates live in data/shaders/vulkan/batch_*.frag.glsl and have their own PGXP_DEPTH -D variant axis. Routing those is a follow-up commit (parallel to the UV_LIMITS Nearest FS routing pattern: add u_pgxp_depth to the Vulkan FS UBO, drop the #if defined(PGXP_DEPTH) guards, regen 5 FS template variant sets). Test: - Build: D3D11 / D3D12 / OpenGL compile. Vulkan untouched. - Default render (PGXP off): u_pgxp_depth = 0, FS ternary picks oalpha * v_pos.z (mask-bit-depth-encode). PSO depth comp is GREATER_EQUAL (m_pgxp_depth_buffer is false). Output identical to pre-commit. - Toggle PGXP-depth-buffer on: m_pgxp_depth_buffer flips, shader_source_changed fires, the FS / PSO matrix rebuilds. With disk shader cache warmed, the FS blobs are cache hits (byte-identical pre vs post commit, AND pre vs post PGXP toggle); PSO assembly runs with the new LESS_EQUAL depth comp. u_pgxp_depth = 1, FS ternary picks v_pos.z (pass-through). Output identical to pre-commit PGXP-on state. - Specific titles to validate the mask-bit-depth-encode path: * Crash 1/2/3 - heavy semitransparent particle work relies on mask-bit encoding for correct depth masking. Any visual difference vs pre-commit would show up as wrong-Z particle layering. * Final Fantasy VII/VIII/IX combat backgrounds - the framebuffer-effects layer uses the mask bit for compositing. Visual sanity at 4-16x resolution scale. * Silent Hill 1 - heavy use of the mask bit for the fog plane. PGXP off baseline. - Specific titles for the PGXP-on pass-through: * Tekken 3 / Soul Blade - PGXP-on textured polygons. Any FS depth-writing error would show up as z-fighting on co-planar stage geometry. * Tomb Raider 1/2 - PGXP-corrected world geometry, polygon-level visibility. Next: - Vulkan FS PGXP_DEPTH routing across all 5 templates (parallel structure to the UV_LIMITS Nearest FS routing). - per_sample / dcp collapse decisions. - Pre-bake the resulting D3D12 FS matrix. --- src/core/gpu_hw_shadergen.cpp | 100 ++++++++++++++++++++++++---------- 1 file changed, 72 insertions(+), 28 deletions(-) diff --git a/src/core/gpu_hw_shadergen.cpp b/src/core/gpu_hw_shadergen.cpp index de4ab8f5..5078441c 100644 --- a/src/core/gpu_hw_shadergen.cpp +++ b/src/core/gpu_hw_shadergen.cpp @@ -141,15 +141,15 @@ std::string GPU_HW_ShaderGen::GenerateBatchVertexShader(bool textured) // session is a single 4-byte cbuffer write picked up on the next // FlushRender on the VS side - the VS source is now invariant // under the m_pgxp_depth member. - // The FS still captures m_pgxp_depth: it gates SV_Depth declaration - // in the FS entry-point signature (DeclareFragmentEntryPoint's - // `depth_output` parameter), which is a signature change that - // can't be cbuffer-routed without always-emitting SV_Depth and - // taking the early-Z hit unconditionally. Routing the FS side is - // a future commit pending perf measurement. Until then, PGXP - // toggle still triggers a FS / PSO matrix rebuild via the - // shader_source_changed path - it just doesn't trigger a VS - // rebuild anymore. + // The FS-side PGXP_DEPTH routing also exists now (this commit's + // sibling): the FS unconditionally declares SV_Depth and the four + // per-branch o_depth writes in the body collapse to a single + // runtime-branch ternary at the end of main(). Both VS and FS + // bytecode are invariant under m_pgxp_depth post-routing. PSO + // depth comparison func still depends on m_pgxp_depth_buffer + // (LESS_EQUAL vs GREATER_EQUAL set at PSO build), so a PGXP flip + // still triggers PSO rebuild for the depth-comp swap - but the + // FS bytecode is cache-served and the variant count is halved. // Order matters: WriteBatchUniformBuffer must emit before // WriteCommonFunctions so the #define aliases for RESOLUTION_SCALE @@ -804,7 +804,27 @@ std::string GPU_HW_ShaderGen::GenerateBatchFragmentShader(GPU_HW::BatchRenderMod // so u_uv_limits is guaranteed 1 here) and the non-filtered path // (gated by runtime branch on u_uv_limits). DefineMacro(ss, "USE_DUAL_SOURCE", use_dual_source); - DefineMacro(ss, "PGXP_DEPTH", m_pgxp_depth); + // PGXP_DEPTH used to live as a compile-time #define driving four + // `#if !PGXP_DEPTH / o_depth = oalpha * v_pos.z / #endif` writes in + // the body and the depth_output argument to + // DeclareFragmentEntryPoint (which gates SV_Depth declaration). It + // is now routed through the batch UBO (u_uv_limits's neighbour + // u_pgxp_depth, added to the cbuffer for the VS-side routing in + // 49c0f82); the FS unconditionally declares SV_Depth and writes a + // single ternary expression at the end of main() that picks + // v_pos.z when u_pgxp_depth != 0 (pass-through of the PGXP-replayed + // depth from the VS) or oalpha * v_pos.z when u_pgxp_depth == 0 + // (mask-bit encoding for the legacy non-PGXP depth-buffer use). + // m_pgxp_depth at shadergen ctor capture is now unused for the FS + // body / signature. The PSO depth comparison func still depends on + // m_pgxp_depth_buffer (LESS_EQUAL vs GREATER_EQUAL) and that + // dependency is OUTSIDE the shader source - it lives in the + // backend's SetDepthState call at PSO build time - so flipping + // PGXP still triggers a PSO rebuild for the depth-comp swap, just + // not a shader recompile (the FS bytecode is identical across + // flips post-routing). The pre-bake win is that FS bytecode loses + // PGXP_DEPTH as a variant axis - 9408 / 2 = 4704 variants for the + // eventual full bake. // Same ordering rule as in GenerateBatchVertexShader: cbuffer // declaration before helpers, so RESOLUTION_SCALE / VRAM_SIZE / @@ -921,14 +941,31 @@ float4 SampleFromVRAM(uint4 texpage, float2 coords) // to u_uv_limits=1 via ShouldUseUVLimits(), so the // FilteredSampleFromVRAM path can rely on v_uv_limits being // valid without an explicit runtime check there. + // + // depth_output is now passed unconditionally true (was: !m_pgxp_depth). + // Pre-routing, the PGXP-on path omitted SV_Depth so the rasterizer- + // interpolated v_pos.z passed through to the depth buffer + // unmodified, while the PGXP-off path declared SV_Depth and wrote + // (oalpha * v_pos.z) to encode the PSX mask bit. Post-routing, + // SV_Depth is always declared; the body picks v_pos.z or + // oalpha * v_pos.z via a single runtime ternary on u_pgxp_depth at + // the end of main(). The PGXP-on path was the only batch FS + // variant that still had early-Z TEST (every other variant lost it + // to SV_Depth already, and they all lost early-Z WRITEBACK to + // discard); this commit loses that one remaining early-Z TEST + // path. For PSX on modern GPUs the cost is sub-noise: native + // framebuffer is half a megapixel, overdraw is low (painter's- + // algorithm sorting in stock content), the FS itself is cheap, + // and the depth buffer is mask-bit storage with random values + // that Hi-Z can't compress anyway. DeclareFragmentEntryPoint(ss, 1, 1, {{"nointerpolation", "uint4 v_texpage"}, {"nointerpolation", "float4 v_uv_limits"}}, - true, use_dual_source ? 2 : 1, !m_pgxp_depth, UsingMSAA(), UsingPerSampleShading(), + true, use_dual_source ? 2 : 1, true, UsingMSAA(), UsingPerSampleShading(), false, m_disable_color_perspective); } else { - DeclareFragmentEntryPoint(ss, 1, 0, {}, true, use_dual_source ? 2 : 1, !m_pgxp_depth, UsingMSAA(), + DeclareFragmentEntryPoint(ss, 1, 0, {}, true, use_dual_source ? 2 : 1, true, UsingMSAA(), UsingPerSampleShading(), false, m_disable_color_perspective); } @@ -1090,10 +1127,6 @@ float4 SampleFromVRAM(uint4 texpage, float2 coords) o_col0 = float4(color, oalpha); #endif - #if !PGXP_DEPTH - o_depth = oalpha * v_pos.z; - #endif - #if TRANSPARENCY_ONLY_OPAQUE discard; #endif @@ -1107,10 +1140,6 @@ float4 SampleFromVRAM(uint4 texpage, float2 coords) o_col0 = float4(color, oalpha); #endif - #if !PGXP_DEPTH - o_depth = oalpha * v_pos.z; - #endif - #if TRANSPARENCY_ONLY_TRANSPARENT discard; #endif @@ -1123,10 +1152,6 @@ float4 SampleFromVRAM(uint4 texpage, float2 coords) #else o_col0 = float4(color, oalpha); #endif - - #if !PGXP_DEPTH - o_depth = oalpha * v_pos.z; - #endif #else // Non-transparency won't enable blending so we can write the mask here regardless. o_col0 = float4(color, oalpha); @@ -1134,11 +1159,30 @@ float4 SampleFromVRAM(uint4 texpage, float2 coords) #if USE_DUAL_SOURCE o_col1 = float4(0.0, 0.0, 0.0, 1.0 - ialpha); #endif - - #if !PGXP_DEPTH - o_depth = oalpha * v_pos.z; - #endif #endif + + // SV_Depth output (always declared now - was conditional on !PGXP_DEPTH + // pre-routing). The four per-branch `#if !PGXP_DEPTH / o_depth = oalpha * + // v_pos.z / #endif` writes that used to live inside each transparency + // arm above collapse to this single runtime-branch write at the end of + // main(). All four old sites wrote the same expression with the same + // operand values in scope (oalpha, v_pos.z), so hoisting is + // value-equivalent; the discards inside the transparency-only-opaque / + // transparency-only-transparent arms above end the FS before this line + // runs, just as they ended the FS before the per-branch writes ran + // pre-routing. + // + // u_pgxp_depth != 0: PGXP-perspective-correct depth mode. The + // rasterizer interpolates v_pos.z from a_pos.w (PGXP-replayed), so + // writing v_pos.z back is a pass-through that matches what the + // pre-routing PGXP-on path got from omitting SV_Depth entirely. The + // PSO depth comparison func is LESS_EQUAL in this mode (set in the + // backend at PSO build time per m_pgxp_depth_buffer). + // u_pgxp_depth == 0: legacy mask-bit depth mode. The + // (oalpha * v_pos.z) expression encodes the PSX mask bit into the + // depth buffer (oalpha is 0 or 1 in this mode, so depth is either 0 + // or v_pos.z). The PSO depth comparison func is GREATER_EQUAL. + o_depth = (u_pgxp_depth != 0u) ? v_pos.z : (oalpha * v_pos.z); } )";