Commit graph

172 commits

Author SHA1 Message Date
LibretroAdmin
7b575a3f87 core, common: route resolution_scale, true_color, scaled_dithering through batch cbuffer
Three per-session settings used to be baked into the HLSL / GLSL
source string at shadergen time:

  - RESOLUTION_SCALE: emitted as 'CONSTANT uint RESOLUTION_SCALE =
    N u;' at the top of every batch shader. VRAM_SIZE / RCP_VRAM_SIZE
    derived from it inline. Every distinct resolution scale produced
    a distinct source string -> distinct DXBC / GLSL blob.
  - TRUE_COLOR: DefineMacro'd as a #define, guarded around #if /
    #if ! / #else / #endif blocks in ApplyDithering, the textured
    colour-truncation path, the untextured non-DITHERING fallback,
    and the final colour premultiply. Two distinct source strings
    per shader cell (true_color on / off).
  - DITHERING_SCALED: DefineMacro'd as a #define around the dither
    fragment-coordinate selector in ApplyDithering. Two distinct
    source strings (scaled_dithering on / off).

Net result: each batch fragment shader cell could produce up to
~5 (typical resolution scales) x 2 x 2 = 20 distinct DXBC blobs
across a session's settings space, every one of them requiring a
fresh D3DCompile invocation on first encounter. On D3D12 with
shader precompilation Enabled and a cold disk cache, the
combinatorial explosion is exactly the 'roughly one minute initial
startup' pain.

This patch moves the three settings out of the source string and
into the per-batch uniform buffer. The HLSL / GLSL produced by
GenerateBatchFragmentShader / GenerateBatchVertexShader becomes
INVARIANT under those three settings - a session-state toggle is
a single 4-byte cbuffer write picked up on the next FlushRender,
with no shader recompile, no PSO rebuild, no batch matrix flush.

Mechanically:

  - BatchUBOData (gpu_hw.h) grows by 16 bytes:
      uint32_t u_resolution_scale;
      uint32_t u_true_color;       // bool packed as uint32_t
      uint32_t u_scaled_dithering; // same
      uint32_t u_pad0;             // pad to 16-byte cbuffer row
    The new fields are written from m_resolution_scale /
    m_true_color / m_scaled_dithering in two places: GPU_HW::
    Initialize after the member values are set, and
    GPU_HW::UpdateHWSettings right after the same members are
    updated. Both sites set m_batch_ubo_dirty = true so the next
    FlushRender uploads.

  - WriteCommonFunctions (gpu_hw_shadergen.cpp) gains a
    'batch_uniform_buffer' parameter (default false). When true it
    skips the file-scope 'CONSTANT uint RESOLUTION_SCALE = ...',
    'CONSTANT uint2 VRAM_SIZE = ...', and 'CONSTANT float2
    RCP_VRAM_SIZE = ...' emissions; the cbuffer + macro alias path
    supplies them instead. Non-batch shaders (VRAM fill / copy /
    write / read / update-depth, display, downsample) continue
    using the file-scope CONSTANT path - they're a handful of
    shaders with a much smaller combinatorial space and don't
    benefit from the cbuffer indirection.

  - WriteBatchUniformBuffer adds the three new cbuffer fields and
    a u_pad0 entry, then emits three preprocessor aliases:
      #define RESOLUTION_SCALE u_resolution_scale
      #define VRAM_SIZE (uint2(VRAM_WIDTH u, VRAM_HEIGHT u) *
                         u_resolution_scale)
      #define RCP_VRAM_SIZE (float2(1.0, 1.0) / float2(VRAM_SIZE))
    Every existing reference in the shader body keeps working as-is
    via macro substitution. VRAM_WIDTH / VRAM_HEIGHT stay
    compile-time literals - they are fixed PSX geometry (1024 x
    512), not session state.

  - GenerateBatchVertexShader / GenerateBatchFragmentShader call
    WriteBatchUniformBuffer BEFORE WriteCommonFunctions. The
    ordering matters: fixYCoord (defined inside
    WriteCommonFunctions) references RCP_VRAM_SIZE and VRAM_SIZE,
    which after the cbuffer-aware refactor are macros expanding to
    expressions involving u_resolution_scale. u_resolution_scale
    must be declared (cbuffer emitted) before the macros are
    expanded in fixYCoord's body, otherwise the HLSL / GLSL
    single-pass parser sees an undeclared identifier.

  - GenerateBatchFragmentShader drops the DefineMacro calls for
    TRUE_COLOR and DITHERING_SCALED, and the four #if (!)TRUE_COLOR
    / #if DITHERING_SCALED preprocessor blocks become runtime
    'if (u_true_color != 0u)' / 'if (u_scaled_dithering != 0u)'
    branches. These are uniform-control-flow branches on
    cbuffer-uniform values - free on every modern GPU. The inner
    RAW_TEXTURE / DITHERING / etc. #ifs remain compile-time
    because those dimensions are still structural in the batch
    matrix.

  - Shader cache file format versions bumped on D3D11 (2 -> 3),
    D3D12 (1 -> 2), and OpenGL (3 -> 4). Existing on-disk caches
    were keyed by HLSL / GLSL source hashes that included the
    inlined RESOLUTION_SCALE / TRUE_COLOR / DITHERING_SCALED
    literals; after this patch the source no longer contains those
    literals, so the hashes change. Bumping the file version
    forces a clean rebuild of the cache file on first launch
    rather than leaving stale entries to grow the file
    indefinitely.

Vulkan is unaffected at runtime. The Vulkan backend uses the
pre-baked SPIR-V templates under data/shaders/vulkan/*.glsl,
which handle RESOLUTION_SCALE / TRUE_COLOR / DITHERING_SCALED via
VkSpecializationInfo spec constants (IDs 0, 106, 105). Those
templates are independent of GPU_HW_ShaderGen; the runtime path
patches the spec consts at vkCreateGraphicsPipelines time and the
result is the same architectural shape this patch gives D3D11 /
D3D12 / OpenGL via the cbuffer.

Smoke checks:
  - Tree-wide grep confirms no DefineMacro for TRUE_COLOR or
    DITHERING_SCALED survives in gpu_hw_shadergen.cpp; only one
    explanatory comment references them by name.
  - u_resolution_scale / u_true_color / u_scaled_dithering are
    referenced in gpu_hw_shadergen.cpp (the cbuffer declaration
    plus the runtime branch sites), gpu_hw.cpp (the two write
    paths in Initialize and UpdateHWSettings), and gpu_hw.h
    (the BatchUBOData struct definition).

Test priority:
  - D3D12, shader cache nuked. Boot a game at default settings
    (resolution scale 4x, true_color off, scaled_dithering on,
    no MSAA, Nearest). Initial precompile_sync runs - it still
    has to compile ~120 fragment shader sources once, but they
    are now invariant under the three migrated settings.
    Subsequent toggles of true_color or scaled_dithering should
    no longer trigger any D3DCompile.
  - Toggle resolution scale (1x -> 4x -> 2x -> ...). The HLSL
    source is identical across all scale values; the cache
    should hit every time after the first compile pass. The
    framebuffer is still rebuilt (textures resize), and PSOs are
    still rebuilt (driver bytecode-to-ISA pass), but no fresh
    D3DCompile invocations.
  - Toggle true_color on and off mid-session. Visually identical
    behaviour to before this patch (24-bit vs 16-bit framebuffer
    look). No precompile pause.
  - Toggle scaled_dithering on and off mid-session. Visually
    identical dithering pattern behaviour. No precompile pause.
  - Same battery on D3D11 and OpenGL backends.
  - Vulkan: no behavioural change expected (still uses pre-baked
    SPIR-V via spec consts). Confirm filter / true_color /
    scaled_dithering toggles continue to be instant on revisit
    via the dim cache from earlier work.

This is patch 1 of the D3D12 startup work. Patch 2 will add the
pre-baked DXBC infrastructure (regen_d3d12_dxbc.py-style offline
tool plus .inc tables) that pre-baked SPIR-V did for Vulkan in
the glslang elimination series. With the source invariance from
this patch, the pre-bake size is bounded to the structural
matrix (~120 blobs for the default-user MSAA=1 / no-per_sample /
no-color-perspective case) rather than the full per-session
explosion.
2026-05-18 05:24:27 +02:00
LibretroAdmin
c369aa5d8c core, common/vulkan: surgical downsample mode handling - no VRAM round-trip on Disabled <-> Box
Toggling the 'downsampling' core option from None to Box (or back)
previously triggered the same full UpdateSettings reset path that a
resolution-scale change does: a ReadVRAM -> DestroyFramebuffer ->
CreateFramebuffer -> UpdateVRAM round-trip combined with
DestroyPipelines + CompilePipelines. On a Vulkan backend with the
new dimensioned batch cache this is even more painful than it used
to be, because the full pipeline rebuild also discards every filter
/ true_color / scaled_dithering sub-cube the worker has been
populating and forces the warm-up to start over.

Downsample mode actually affects very little of the backend state:
the batch matrix never references it (no spec const, no structural
SPIR-V choice), and the only framebuffer dimensions that depend on
it are the display texture width and the existence of the optional
downsample weight texture - and even those only differ when Adaptive
is involved on one side of the transition. Disabled <-> Box keeps
the display texture at GPU_MAX_DISPLAY_WIDTH * res_scale and just
needs the downsample_texture / render pass / framebuffer / first-
pass PSO swapped in.

Three changes that work together:

1. UpdateHWSettings:
   - *framebuffer_changed no longer trips on every downsample diff.
     Now only when Adaptive is involved on at least one end of the
     transition (Disabled <-> Adaptive, Box <-> Adaptive).
     Disabled <-> Box leaves the flag false because the main
     framebuffer dimensions are unchanged.
   - Downsample mode dropped from non_dim_diff: it has never
     affected the batch matrix, and surfacing it through
     *shaders_changed forced every backend into DestroyPipelines +
     CompilePipelines when the only thing that needed to change was
     a handful of downsample resources.
   - New optional out-parameter *downsample_changed - simple
     boolean diff between cached m_downsample_mode and the new
     value. Default nullptr so the D3D11 / D3D12 callers compile
     unchanged (they will get the same targeted treatment in a
     follow-up patch once their downsample resource lifecycle is
     factored the same way; for now they continue to do the full
     reset on a downsample toggle, matching the pre-patch
     behaviour).

2. New Vulkan helpers extracted from Create/DestroyFramebuffer and
   DestroyPipelines:
   - CreateDownsampleResources(texture_width, texture_height,
                               texture_format) -> bool
     Builds the downsample textures, render pass(es), framebuffers,
     image views, and descriptor sets for the current
     m_downsample_mode. Called from the end of CreateFramebuffer
     for the full-rebuild path and directly from UpdateSettings for
     the Disabled <-> Box path.
   - DestroyDownsampleResources()
     Drops everything CreateDownsampleResources owns - textures,
     framebuffers, image views, descriptor sets. Called from
     DestroyFramebuffer and from the downsample-only path. Does
     NOT touch pipelines (those have a separate lifecycle gated on
     the render pass).
   - DestroyDownsamplePipelines()
     Drops the 4 downsample VkPipeline handles. Called from
     DestroyPipelines (existing behaviour) and from the downsample-
     only path in UpdateSettings (new behaviour - the PSOs
     reference the OLD render pass and would otherwise leak a
     stale handle).

3. GPU_HW_Vulkan::UpdateSettings:
   - Receives downsample_changed alongside the existing flags.
   - downsample_changed && !framebuffer_changed (the Disabled <->
     Box case): DestroyDownsamplePipelines +
     DestroyDownsampleResources + CreateDownsampleResources. ~1-2
     ms of work plus 1 PSO compile. No VRAM round-trip, no batch
     matrix touch.
   - downsample_changed && framebuffer_changed (Disabled <->
     Adaptive / Box <-> Adaptive): CreateFramebuffer already
     rebuilt the downsample resources via its end-of-function
     CreateDownsampleResources call. We just need to drop the
     stale PSOs.
   - downsample_changed && !shaders_changed: pre-build the new
     downsample PSOs via the existing GetDownsampleXxxPipeline
     helpers in Enabled / Lazy modes (so the next display call
     doesn't lazy-fault); Disabled stays truly lazy by contract.
   - Adaptive's full lifecycle (the side of the transition that
     does need the framebuffer round-trip) is unchanged - the
     display texture width and weight texture creation still
     require it.

Smoke tests:
  - Tree-wide grep confirms every CreateDownsampleResources /
    DestroyDownsampleResources / DestroyDownsamplePipelines call
    site is intentional, and no leftover inline copy of the
    Adaptive / Box construction blocks survives outside the helper.
  - The two GetBatchPipeline helper paths and the precompile worker
    do not touch any downsample state, so this patch is orthogonal
    to the dim-cache work from the preceding commits.

Test priority:
  - In Vulkan, with shader cache nuked, in Enabled mode: toggle
    'Downsampling' from None to 'Box - downsample 3D / smooth all'.
    Expected: no progress-bar pause, the new Box-mode output
    appears within ~one frame. Toggle back to None: same instant
    behaviour. Cycle several times. Previously each toggle paid
    5-10 seconds of pipeline rebuild plus VRAM round-trip.
  - None <-> Adaptive and Box <-> Adaptive: framebuffer rebuild is
    still required (display texture width changes), but the pause
    should now be limited to the framebuffer work (~tens of ms);
    the batch matrix is preserved across the toggle.
  - Adaptive output should still look correct after each toggle
    (the helper extraction preserves the original code byte-for-
    byte, just moved into CreateDownsampleResources).
  - With downsample at Box, toggle resolution scale or MSAA -
    these trigger the full framebuffer + shaders rebuild as
    before (downsample mode unchanged, downsample_changed=false),
    no behavioural change.
  - With downsample at Adaptive, toggle texture filter -
    only_dim_changed=true path runs, batch matrix sub-cube
    preserves other filter values, downsample resources
    untouched. Cycle back to original filter is instant.

The same factoring will be done for D3D12 and D3D11 in follow-up
patches; their downsample resource lifecycle is structurally
identical, just with ID3D12PipelineState / ID3D11PixelShader
instead of VkPipeline. For now those backends ignore the new
downsample_changed flag (default nullptr) and continue with the
full DestroyPipelines + CompilePipelines reset on a downsample
toggle - same as before this patch.
2026-05-18 04:07:34 +02:00
LibretroAdmin
dbdd273622 core, common/vulkan: add true_color and scaled_dithering as batch pipeline cache dimensions
Option B added texture filter as the outermost dimension of
m_batch_pipelines, making filter swaps instant on revisit. The same
problem still bit the user on toggling 'scaled dithering' and 'true
colour' in the core options menu: both are pure per-session spec
constants (DITHERING_SCALED = id 105, TRUE_COLOR = id 106) applied
at vkCreateGraphicsPipelines time, so the driver bakes them into
each cached PSO. With no cache dimension over them, the existing
non_filter_diff comparison in UpdateHWSettings would set
*only_filter_changed = false on a toggle, routing UpdateSettings
into the full DestroyPipelines + CompilePipelines path - the same
5-10 second pause Option B got rid of for filter.

Extend the same trick to both:

  m_batch_pipelines: 7D -> 9D
    was [filter][depth_test][render_mode][texture_mode]
        [transparency_mode][dithering][interlacing]
    now [filter][true_color][scaled_dithering][depth_test]
        [render_mode][texture_mode][transparency_mode]
        [dithering][interlacing]

m_batch_fragment_shaders stays 5D - true_color and scaled_dithering
do NOT affect SPIR-V blob choice, only the spec const value at PSO
bake time, so the same VkShaderModule backs both values. The PSO
cache doubles for each new dimension (atomic slots only - driver-
side memory grows only when a slot is populated).

API changes:

  - GPU_HW::UpdateHWSettings out-parameter renamed
    only_filter_changed -> only_dim_changed, with the semantics
    broadened: the flag is true iff the only shader-affecting
    changes are in dimensioned settings (filter, true_color,
    scaled_dithering). Default-nullptr param so the D3D11 / D3D12
    callers stay untouched - they continue doing a full destroy +
    recompile on any shaders_changed event because their batch
    caches are not yet dimensioned over anything.

  - GetBatchPipeline gains two leading parameters:
        GetBatchPipeline(filter, true_color, scaled_dithering, ...)
    The internal m_true_color / m_scaled_dithering reads (slot
    indexing context and the AddBool(105/106, ...) lines in the
    spec const setup) are replaced with the passed parameters.
    The same param-snapshot pattern Option C introduced for
    filter now covers all three dimensioned settings, so the
    helper has no implicit dependency on class-member state for
    any of its cache axes.

Call site updates:

  - DrawBatchVertices: passes (m_texture_filtering, m_true_color,
    m_scaled_dithering).
  - precompile_sync PSO loop in CompilePipelines: same.
  - ShaderCompileThreadEntryPoint: snapshots m_true_color and
    m_scaled_dithering at worker entry alongside the existing
    filter loop. The worker is responsible only for the CURRENT
    (true_color, scaled_dithering) combo's seven filter sub-
    cubes - walking all 7 x 2 x 2 = 28 sub-cubes in the
    background would balloon cold-cache warm-up to several
    minutes, well past 'useful' into 'annoying'.

Behaviour after this patch:

  - Cycling back to a previously-visited (filter, true_color,
    scaled_dithering) tuple: instant. The slot is already filled,
    GetBatchPipeline returns it from a single atomic load.
  - First time toggling true_color or scaled_dithering in a
    session: 5-10s sync compile in Enabled mode for the current
    filter's sub-cube under the new value, then the worker warms
    the other six filter sub-cubes in the background. Lazy mode
    fault-ins on first draws as before.
  - Toggling filter under the new (true_color, scaled_dithering):
    same as Option C - instant on revisit, sync compile + back-
    ground warm-up on first visit.

After enough cycling through the three settings (typically a few
back-and-forth toggles of each), all reachable combinations end up
cached and every toggle becomes instant for the rest of the
session.

Memory cost during warm-up:
  - PSO cache atomic-slot count grows by 4x relative to pre-B,
    7x already happened in Option B for filter, this patch makes
    it 14x (true_color) and 28x (scaled_dithering). Slot array
    size: ~480 KiB total. Driver-side PSO storage only grows when
    slots are populated; a typical session touches maybe 10-20%
    of one (filter, true_color, scaled_dithering) combo's
    reachable cells.
  - On hardware lacking dual-source blend the *BinAlpha and other
    non-Nearest filters are clamped to Nearest by UpdateHWSettings
    and the worker skips them via TextureFilterRequiresDualSource-
    Blend, so the actual populated count is lower.

Smoke tests:
  - Tree-wide grep for m_true_color / m_scaled_dithering /
    only_filter_changed inside the helpers and their callers:
    every remaining hit is either a comment, a callsite that
    correctly snapshots the class member to pass downward, or
    elsewhere in the file outside the batch pipeline path
    (m_true_color / m_scaled_dithering still drive other Vulkan
    structural choices like resolution scale).
  - The two GetBatchPipeline helper signatures match in header
    and impl; no stale 7D declaration of m_batch_pipelines
    survives in the header.

Test priority:
  - With shader cache nuked, in Enabled mode, toggle the
    'scaled dithering' core option on then off then on. First
    toggle pays the usual 5-10s pause for the current filter
    sub-cube under the new dithering value. Second toggle back
    to the original should be INSTANT - the slot is already
    filled.
  - Same test with 'true colour'. Same behaviour expected.
  - Toggle both: scaled dithering off, true colour off, then
    scaled dithering on, true colour off, ... cycle through all
    four (true_color, scaled_dithering) combos. After one cycle,
    every transition is instant for the rest of the session.
  - Confirm non-dimensioned changes (resolution scale, MSAA,
    PGXP depth, etc.) still trigger the full
    DestroyPipelines + CompilePipelines pause - that path is
    unchanged and required for those settings to be applied
    correctly.
  - On hardware without dual-source blend: confirm the worker
    still walks only Nearest's sub-cube across the current
    (true_color, scaled_dithering) snapshot.
  - Long session (10+ minutes) of toggling the three dimensioned
    settings: no driver-side OOM. Watch GPU memory in nvidia-smi
    or Task Manager.

The set of dimensioned settings could be extended further to
pgxp_depth_buffer or other 2-value spec consts, but those toggle
much less frequently in practice and would only add another 2x
slot cost each. Defer until requested.

After this lands the Vulkan filter / dithering / true-colour
trio is functionally complete: every common user-toggled batch
shader setting is dimensioned, with current-combo background
warm-up keeping cold-cache cost bounded.
2026-05-18 03:41:44 +02:00
LibretroAdmin
32704a9b78 core, common/vulkan: add filter dim to batch pipeline cache (Option B)
Filter swap in the core options menu used to take 5-10 seconds on a
cold pipeline cache and 1-2 seconds even on a warm one, because every
filter change blew away the entire batch pipeline cache and rebuilt
it from scratch for the new filter. The cache (m_batch_pipelines,
m_batch_fragment_shaders) had no filter dimension - the active filter
just selected which pre-baked SPIR-V blob backed every PSO in the
single shared cache, so any change to it invalidated everything.

Add filter as the outermost dimension of both cache arrays:

  m_batch_pipelines : 6D -> 7D
    was [depth_test][render_mode][texture_mode][transparency_mode]
        [dithering][interlacing]
    now [filter][depth_test][render_mode][texture_mode]
        [transparency_mode][dithering][interlacing]

  m_batch_fragment_shaders : 4D -> 5D
    was [render_mode][texture_mode][dithering][interlacing]
    now [filter][render_mode][texture_mode][dithering][interlacing]

GetBatchPipeline / GetBatchFragmentShader prepend the current
m_texture_filtering as the first index. Each filter now has its own
sub-cube of slots; populating one does not touch any other. Filter
swap behaviour:

  - First visit to a filter            : same slow PSO compile as
                                         before (cold pipeline cache),
                                         or a couple of seconds with
                                         the driver cache warm.
  - Cycling back to a previous filter  : instant. The slot is already
                                         filled, GetBatchPipeline
                                         returns it from a single
                                         atomic load, no
                                         vkCreateGraphicsPipelines /
                                         vkCreateShaderModule call.

The skip-destroy decision is made by UpdateHWSettings, which now
emits an additional out-parameter only_filter_changed. The signature
keeps backwards compat for the D3D11 / D3D12 backends - the
parameter defaults to nullptr and they continue passing only the
existing two flags (their batch caches are not filter-dimensioned
yet, so a full DestroyPipelines + CompilePipelines is still
required there). Splitting the comparison:

  filter_diff      = (m_texture_filtering != g_settings.gpu_texture_filter)
  non_filter_diff  = any other shader-affecting setting changed
                     (resolution scale, MSAA, true colour, per-sample
                      shading, scaled dithering, UV limits, chroma
                      smoothing, downsample mode, PGXP depth, color
                      perspective, precompile mode)
  *shaders_changed         = filter_diff || non_filter_diff
  *only_filter_changed     = filter_diff && !non_filter_diff

GPU_HW_Vulkan::UpdateSettings routes accordingly:

  shaders_changed && !only_filter_changed
    -> DestroyPipelines + CompilePipelines (current full-flush
       behaviour, every sub-cube invalidated because per-session
       spec consts / structural SPIR-V choice apply to all of them)
  shaders_changed && only_filter_changed
    -> CompilePipelines only. The previous filter's sub-cube remains
       populated; the new filter's sub-cube is lazy-populated by the
       precompile_sync loop (Enabled mode), filled in by the
       background worker (Lazy), or left empty for draw-time fault-
       in (Disabled).

To make this safe under Lazy mode, CompilePipelines must tolerate
being called on a partially-populated cache. Two changes:

  - The batch VS bake loop at the top of CompilePipelines was
    unconditional create + store; it now load-checks each slot first
    and skips if populated, so re-entry on a filter-only change does
    not leak the existing module. The non-batch GetXxxPipeline
    helpers were already idempotent (each guards on slot !=
    VK_NULL_HANDLE at entry) and need no change.

  - Stop the background compile worker as the very first action in
    GPU_HW_Vulkan::UpdateSettings, BEFORE UpdateHWSettings writes
    m_texture_filtering. Without this, the worker could split its
    two reads of m_texture_filtering (one inside GetBatchPipeline
    for the slot index, one inside GetBatchFragmentShader for both
    the slot index AND the SPIR-V blob selection) across the
    write, installing a FS module compiled for one filter into a
    PSO slot indexed by another. Pre-B this race was benign
    because DestroyPipelines reliably swept up after the worker;
    with B the filter-only path skips DestroyPipelines, so a stale
    cross-wired slot would persist indefinitely.
    StopShaderCompileThread is idempotent so the existing call at
    the top of CompilePipelines is unchanged.

Smoke tests:
  - g++ -fsyntax-only across the touched TUs (clean).
  - Tree-wide grep on m_batch_pipelines / m_batch_fragment_shaders:
    only Vulkan-side hits change shape; D3D12 has its own
    same-named member at a different scope (gpu_hw_d3d12.h) which
    is unrelated and unaffected.

Memory impact:
  - m_batch_pipelines: 3*4*9*5*2*2 = 2160 slots -> 7x = 15120 slots
    (std::atomic<VkPipeline> = 8 bytes typical -> ~120 KiB total)
  - m_batch_fragment_shaders: 4*9*2*2 = 144 slots -> 7x = 1008 slots
    (std::atomic<VkShaderModule> = 8 bytes typical -> ~8 KiB total)
  - VkPipeline / VkShaderModule driver-side memory only grows when
    slots are populated. A typical session visits maybe 10-20% of
    one filter's reachable cells; visiting all 7 filters would
    grow driver-side pipeline storage by ~7x of that fraction. On
    a desktop GPU this is well under 100 MiB worst case.

Test priority:
  - With the shader cache nuked: boot a game in each precompile mode
    (Enabled / Lazy / Disabled). Verify nothing regressed.
  - In Enabled: change filter (xBR -> Nearest -> Bilinear -> xBR).
    First visit to each new filter should be the usual 5-10s
    progress-bar pause on a cold pipeline cache. Cycling back to
    xBR after visiting Nearest and Bilinear should now be INSTANT -
    no progress bar, no perceptible pause, no
    vkCreateGraphicsPipelines calls (the slots are already
    populated). On a warm pipeline cache (second run) the first
    visit drops to ~1-2s, the revisit stays instant.
  - In Lazy: same cycle. First visit pauses briefly for non-batch
    pre-fill then resumes gameplay with background fill in
    progress. Revisits are instant; background fill of the new
    filter's sub-cube continues to populate even while the user
    plays.
  - In Disabled: same cycle. First visit has the usual lazy fault-
    in stutters per (render_mode, texture_mode, ...) combo as the
    game touches new ones. Revisits are instant.
  - Confirm non-filter shader-affecting changes still trigger a
    full flush: change resolution scale, MSAA, true-colour toggle,
    PGXP depth toggle, etc. Should see the full
    DestroyPipelines + CompilePipelines pause regardless of mode.
  - Confirm settings-only changes (audio volume, save state slot,
    etc.) do not flush the cache. (UpdateSettings is gated on
    GPU-relevant settings in host_interface.cpp:285-298, so this
    should be safe by construction.)

Option C (background-precompile the OTHER filter sub-cubes after
Enabled's primary work finishes, so first-visit-to-new-filter is
ALSO instant) is the natural follow-up and now trivially builds on
this patch's filter-dimensioned cache. Will come as a separate
patch after B is validated.
2026-05-18 03:00:42 +02:00
LibretroAdmin
f44c4bafc8 core, common: dead-code sweep, round 13 (five-angle audit)
A combined audit across five different abstractions, applying the
methodology toolkit accumulated over previous rounds:

  (a) empty-stub-asymmetry hunt across the controller and DMA
      dispatch tables
  (b) gpu_hw.h - the HW renderer common protocol
  (c) common/vulkan/ headers - the Vulkan helper library
  (d) cpu_code_cache.h and the recompiler's block compilation path
  (e) settings.h - the Settings struct

== (a) Empty-stub asymmetry ==

No new finds. The remaining empty '{}' impls in controller.cpp
(Reset, ResetTransferState, SetAxisState, SetButtonState,
LoadSettings) are legitimate base-class default no-ops for
controllers that don't have axes or buttons (e.g. DigitalController
has no axes). The DMA channel switch asymmetry (CDROM/PIO with no
body in DMAWrite, lines 472-476 of dma.cpp) is hardware-spec - those
channels truly don't transfer that direction.

== (b) gpu_hw.h ==

Dropped GPU_HW::EnsureVertexBufferSpace(uint32_t).

Declared in gpu_hw.h:217, impl at gpu_hw.cpp:969 (13 lines). Zero
callers. The replacement specialized form
EnsureVertexBufferSpaceForCurrentCommand (alive, 5 call sites)
switches on the current GPU command's primitive type to compute
required_vertices, then does the same flush-or-map sequence as the
old EnsureVertexBufferSpace. The simpler form was orphaned when
the specialized one was introduced.

== (c) common/vulkan/ ==

Three drops:

  Vulkan::Util::BufferMemoryBarrier - util.h:40, util.cpp:187.
  Generic vkCmdPipelineBarrier wrapper for VkBufferMemoryBarrier.
  Zero callers anywhere in the tree. The Vulkan renderer uses
  vkCmdPipelineBarrier directly with image barriers, and never
  needs the buffer-barrier variant. 19 lines.

  Vulkan::StagingBuffer::GetSize - staging_buffer.h:32. Inline
  accessor returning m_size. Zero callers.

  Vulkan::StagingBuffer::Read / ::Write - staging_buffer.h:49-50,
  staging_buffer.cpp:96-109. Memory-mapped buffer read/write
  helpers. Zero callers - the StagingBuffer is always accessed via
  GetMapPointer() returning the raw char* and the caller does the
  memcpy directly. The Read/Write methods would have made sense for
  a layer-of-abstraction approach that nobody adopted. 15 lines.

Kept (false starts re-verified):
  Vulkan::Texture::IsValid - looked dead because no external callers
  use m_texture.IsValid(). But the .cpp uses unqualified 'IsValid()'
  inside member functions at three sites. Round 6's lesson about
  within-class unqualified calls applies. Restored after build
  failure.

  Vulkan::StagingTexture::IsValid - same pattern. Four internal
  unqualified call sites in staging_texture.cpp.

== (d) cpu_code_cache ==

Six drops:

  CodeBlockKey::operator==, operator!=, operator<

  Three operator overloads on the CodeBlockKey union. The
  BlockMap is std::unordered_map<uint32_t, CodeBlock*> keyed on
  the raw bits, NOT on CodeBlockKey, so the operators are never
  invoked through stdlib container machinery. They're also never
  invoked via infix syntax (no 'key1 == key2' or 'key1 < key2'
  anywhere). Pure dead.

  CodeBlockInstruction::is_load_delay_slot
  CodeBlockInstruction::is_last_instruction
  CodeBlockInstruction::can_trap

  Three write-only bitfields. Each is set in
  cpu_code_cache.cpp::CompileBlock and never read anywhere. The
  recompiler and interpreter use the live flags
  (is_branch_instruction, is_direct_branch_instruction,
  is_unconditional_branch_instruction, is_branch_delay_slot,
  is_load_instruction, is_store_instruction, has_load_delay) but
  not these three.

  The CompileBlock function had three dead writes (lines 602, 609,
  666 before this commit) and a dead tracking local 'bool
  is_load_delay_slot' that fed cbi.is_load_delay_slot. All four
  dead writes plus the comment '// same for load delay' removed.

  Sized as bitfields, each field saved approximately 1 bit in
  CodeBlockInstruction storage - but since the struct holds 10
  bitfields with 6 other flags, the actual struct alignment didn't
  change. The 360-byte .so reduction comes from the eliminated
  setters in CompileBlock and the dropped CodeBlockKey operator
  function bodies (3 inline ALWAYS_INLINE methods with bodies but
  no inlining target callers).

== (e) settings.h ==

Two drops:

  bool bios_patch_tty_enable

  Declared in settings.h:99, default 'false'. Read at one site
  (system.cpp:689) inside an if-block that gates a call to
  BIOS::PatchBIOSEnableTTY. NEVER written anywhere - no Load()
  entry in settings.cpp, no game-settings override in
  libretro_game_settings.cpp, no external setter. The default 'false'
  means the if-branch is always false, so BIOS::PatchBIOSEnableTTY
  is also dead - dropped its decl (bios.h) and impl (bios.cpp).

  The setting was likely added for a debug feature (PS1 BIOS has a
  TTY debug output path that's normally disabled; patching the BIOS
  enables logging through it) but no UI or game-settings entry was
  ever wired up to set it true.

  DEFAULT_DMA_MAX_SLICE_TICKS
  DEFAULT_DMA_HALT_TICKS
  DEFAULT_GPU_FIFO_SIZE
  DEFAULT_GPU_MAX_RUN_AHEAD
  DEFAULT_VRAM_WRITE_DUMP_WIDTH_THRESHOLD
  DEFAULT_VRAM_WRITE_DUMP_HEIGHT_THRESHOLD

  Six static constexpr defaults declared as a compact constant
  block in settings.h:147-149. Zero callers - the actual defaults
  are written inline at the member-init point (e.g.
  'TickCount dma_max_slice_ticks = 1000') and in the GetIntValue
  fallback values inside Load(). The DEFAULT_* constants are a
  separate, redundant copy of those values that nobody consults.

== Methodology refinements ==

Two new entries for the running list:

  Within-class unqualified calls hide from member-access grep.
  When auditing a class method's call sites with
  '\.IsValid(' / '->IsValid(', the matches will miss calls of the
  form 'if (IsValid())' inside the class's own .cpp - because no
  qualifier appears. Always re-grep '\bMethod\b' in the defining
  .cpp before deciding it's dead. This was already in the list
  from round 6 but I had to re-learn it this round when both
  Texture::IsValid and StagingTexture::IsValid had to be restored
  after the build failed.

  Settings fields that are read but never written are dead.
  A Settings struct field has three logical slots: default value,
  setter (Load entry / game settings override), and reader. If the
  setter slot is empty, the field is permanently at its default and
  the reader is dead too - and so is whatever the reader gates.
  bios_patch_tty_enable was an instance of this: dead setter ->
  always-false condition -> dead BIOS::PatchBIOSEnableTTY callee.

== Build verification ==

Build clean on Makefile.libretro platform=unix at the final state.
swanstation_libretro.so size: 7,910,600 -> 7,910,240 bytes (-360).
25 retro_* exports preserved.

The 360-byte .so reduction is real codegen reduction - 64 from the
EnsureVertexBufferSpace impl, 96 from BufferMemoryBarrier impl, 11
from PatchBIOSEnableTTY impl, plus smaller savings from the
CodeBlockKey operator function bodies, the StagingBuffer Read/Write
impls, and eliminated dead-write codegen in CompileBlock.

== Audited and kept ==

(a) Controllers and DMA dispatch: no new finds.
(b) GPU_HW constants (VRAM_UPDATE_TEXTURE_BUFFER_SIZE,
    VERTEX_BUFFER_SIZE, UNIFORM_BUFFER_SIZE,
    MAX_BATCH_VERTEX_COUNTER_IDS, MAX_VERTICES_FOR_RECTANGLE),
    Transparency*/Interlaced* enums, all 19 methods other than
    EnsureVertexBufferSpace.
(c) Vulkan::Util namespace: IsDepthFormat, GetTexelSize,
    GetBlockSize, SafeDestroy* family, SetViewport, SetScissor,
    SetViewportAndScissor, LogVulkanResult (kept alive by
    LOG_VULKAN_ERROR macro with 45 expansions).
    Vulkan::Texture: all methods (IsValid restored as above).
    Vulkan::StagingTexture: all methods (IsValid restored).
    Vulkan::StreamBuffer: all methods - heavily used.
    Vulkan::ShaderCache: GetShaderSPV and GetShaderModule are
    used only internally as building blocks for GetVertexShader
    / GetFragmentShader. Could be made private in a future
    refactor, but visibility-tightening is out of scope for a
    deletion sweep.
    Vulkan::ShaderCompiler::Type::Geometry and ::Compute - reached
    by switch cases in CompileShader; kept as part of the
    type's complete enumeration even though no current caller
    passes those values.
(d) CodeBlockInstruction live flags (is_branch_instruction et al.);
    CodeBlock::GetPC and IsInRAM; FAST_MAP_TABLE_* constants;
    Dispatcher/SingleBlockDispatcher function types.
(e) gpu_pgxp_preserve_proj_fp (game-settings overridden, runtime
    read); display_force_4_3_for_24bit (same pattern);
    gpu_pgxp_tolerance (game-settings overridden, runtime read);
    cdrom_mute_cd_audio (runtime read); controller_enable_rumble
    (read in libretro_host_interface); memory_card_use_playlist_title
    (compared in host_interface for setting-change detection);
    cdrom_load_image_to_ram (referenced from system.cpp);
    log_level (Log::SetFilterLevel target); controller_show_crosshair
    (read in all three HW renderers); enable_8mb_ram (game-settings
    overridden, runtime read in bus.cpp).

12 files changed, 1 insertion(+), 92 deletions(-).
2026-05-15 00:01:04 +02:00
LibretroAdmin
7537ee7a27 common/types: use stdint typedefs everywhere instead of custom u32/s32 aliases
The codebase carried custom aliases in src/common/types.h:

  using s8  = int8_t;
  using u8  = uint8_t;
  using s16 = int16_t;
  using u16 = uint16_t;
  using s32 = int32_t;
  using u32 = uint32_t;
  using s64 = int64_t;
  using u64 = uint64_t;

These are pure aliases - they alias the C99/C++11 fixed-width
exact types from <cstdint> verbatim - and the short form was
used throughout in ~8,400 places. The short form is a
convention common in emulator/game code, but it conflicts with
the convention used by every other piece of code anyone on this
project ever touches (kernel, libretro frontends and other
cores, stdlib code, etc.), and the savings are five characters
per use.

Mechanical rename across src/:

  s8 -> int8_t
  u8 -> uint8_t
  s16 -> int16_t
  u16 -> uint16_t
  s32 -> int32_t
  u32 -> uint32_t
  s64 -> int64_t
  u64 -> uint64_t

Word-boundary substitution via \b{name}\b. Verified no false
positives:
  - No string literal contains "u32" etc. (single-line scan
    of every .cpp/.h/.inl in src/).
  - No identifier contains the alias as a substring; \b prevents
    matching inside foo_u32 / u32_bar style names but a separate
    check confirmed there are no such identifiers in src/
    anyway.

The dep/ directory is left untouched - some third-party code
there (zstd, dr_libs, libchdr) has its own unrelated "u32"
struct fields and types that are local to those compilation units.

Aliases removed from src/common/types.h. The header keeps
<cstdint> (the BCD helpers there still use uint8_t) and stays
the same shape it was post-types-cleanup.

Build: Makefile.libretro platform=unix - clean.
Codegen identical: the produced swanstation_libretro.so is
byte-for-byte the same as the pre-rename build, MD5
453480b212f78f0e0cf56fc893972b24 in both cases. This is
expected: u32 and uint32_t are the same type to the compiler;
the rename is purely lexical.

retro_* exports: 25 (unchanged).

210 files changed, +7926 -7935 (the -9 net delta is the eight
'using' lines removed from types.h plus blank-line cleanup
around them).
2026-05-14 15:13:16 +02:00
LibretroAdmin
778cb660d0 common/types: drop <cstring>, add explicit includes at the 41 callers
types.h carried <cstring> for transitive purposes only - the header
itself never references std::memcpy / std::memset / std::strlen
etc. 41 TUs across the tree used those C-string functions while
relying on types.h to supply the declaration.

Add an explicit '#include <cstring>' to each of those files and
drop it from types.h. The headers that also use cstring functions
(error.h, jit_code_buffer.h are not in the list because they
already include <cstring> directly, or use the C-namespace
<string.h> already in scope) are unaffected.

Files getting an explicit <cstring>:

  src/common:  cd_image.cpp, cd_image_ecm.cpp, cd_image_mds.cpp,
               cd_image_memory.cpp, cd_image_pbp.cpp,
               cd_image_ppf.cpp, cd_subchannel_replacement.cpp,
               cue_parser.cpp, d3d12/shader_cache.cpp,
               d3d12/staging_texture.cpp, d3d12/texture.cpp,
               d3d12/util.cpp, iso_reader.cpp, jit_code_buffer.cpp,
               md5_digest.cpp, vulkan/shader_cache.cpp,
               vulkan/staging_texture.cpp
  src/core:    bios.cpp, bios.h, bus.cpp, cdrom.cpp, cheats.cpp,
               cpu_code_cache.cpp, cpu_recompiler_code_generator.cpp,
               cpu_recompiler_register_cache.cpp, dma.cpp, gpu.cpp,
               gpu_hw.cpp, gpu_hw.h, gpu_hw_d3d11.cpp,
               gpu_hw_d3d12.cpp, gpu_hw_opengl.cpp,
               gpu_hw_vulkan.cpp, gpu_sw.cpp, gte.cpp, mdec.cpp,
               memory_card_image.cpp, pgxp.cpp, spu.cpp, system.cpp
  src/libretro: libretro_host_display.cpp

Most files get one '#include <cstring>' added into the existing
system-include block, sorted alphabetically. A handful of files
(system.cpp, memory_card_image.cpp, d3d12/shader_cache.cpp)
had pre-existing blank-line separations between the stdlib
include block and libretro third-party headers (<compat/strl.h>,
<file/file_path.h>); those separations are preserved.

Build: Makefile.libretro platform=unix - clean, no warnings.
swanstation_libretro.so size unchanged (8026128 bytes).
retro_* exports: 25 (unchanged).

types.h now only includes <cstddef>, <cstdint>, and <type_traits>
- the three headers it actually needs for its own contents.
2026-05-14 14:20:36 +02:00
LibretroAdmin
67051a0828 common: remove BoolToUInt8/16/32/64 helpers in favour of explicit casts
The BoolToUInt8/16/32/64 helpers in common/types.h are one-line
wrappers around `static_cast<uN>(bool)`. C++ already guarantees
that converting a bool to an unsigned integer yields exactly 0
(for false) or 1 (for true), so the helpers add nothing beyond a
shorter name - and a less obvious one, since 'BoolToUInt32(x)'
doesn't immediately read as 'cast to u32' the way the static_cast
spelling does.

Mechanical fold across 16 files:

  BoolToUInt8(x)   -> static_cast<u8>(x)
  BoolToUInt32(x)  -> static_cast<u32>(x)

(BoolToUInt16 and BoolToUInt64 had no callers in the tree.)

103 callsites rewritten: 82 BoolToUInt8 and 21 BoolToUInt32, spread
across gpu_commands.cpp, pgxp.cpp, gpu.cpp, gpu_hw_d3d11/d3d12/
vulkan/opengl.cpp, gpu_sw.cpp, gpu_hw.cpp, gpu.h, shadergen.cpp,
spu.cpp, analog_controller.cpp, negcon_rumble.cpp,
cpu_recompiler_code_generator.cpp, cpu_core.cpp. Most are array
indices (s_setup_time[BoolToUInt8(...)][...]), bit-packing in
shader-cache lookups, and arithmetic with vertex-count offsets
(words_per_vertex + BoolToUInt32(rc.texture_enable)).

After the rewrite, the four helper definitions are removed from
common/types.h.

Build verification:
  Makefile.libretro platform=unix - clean syntax-check on every
  touched .cpp that compiles on Linux. d3d11/d3d12 sites are all
  simple BoolToUInt8(v) -> static_cast<u8>(v) substitutions on
  bitfield values and verified by code review only.

No behaviour change. Codegen is identical at -O2 - both forms
compile to the same setcc/movzx sequence on x86-64.

Same shape of cleanup as the recently-landed SignExtend/Truncate
and ConvertToBoolUnchecked removals: kill a thin readability
wrapper, use the explicit static_cast spelling everywhere.
common/types.h shrinks by another 16 lines.
2026-05-14 06:08:13 +02:00
LibretroAdmin
e4b17615a9 common: remove SignExtend / ZeroExtend / Truncate helpers in favour of explicit casts
The src/common/types.h helpers SignExtend16/32/64, ZeroExtend16/32/64,
Truncate8/16/32, the generic SignExtend<TR,TV> and ZeroExtend<TR,TV>
templates, and SignExtendN<N,T> were thin wrappers around explicit
static_cast chains. They served a documentation role ("this cast is
intentional, not a typo") in places where the underlying intent was
"narrow this value" or "sign-extend this value", but in practice
they obscured rather than clarified - particularly when several
nested together (SignExtend32(Truncate8(x)) is just (u32)(s8)x).

Tree-wide fold:

  Truncate8(x)              -> static_cast<u8>(x)
  Truncate16(x)             -> static_cast<u16>(x)
  Truncate32(x)             -> static_cast<u32>(x)
  ZeroExtendN(u_x)          -> static_cast<uN>(u_x)
  SignExtendN(u_x)          -> static_cast<uN>(static_cast<sM>(u_x))   (M = source width)
  SignExtendN(s_x)          -> static_cast<uN>(s_x)                   (relies on int promotion)
  SignExtendN<BITS,T>(x)    -> static_cast<sN>(static_cast<uN>(x) << S) >> S   (S = N*8 - BITS)
  SignExtendK(TruncateM(x)) -> static_cast<uK>(static_cast<sM>(x))
  ZeroExtendK(TruncateM(x)) -> static_cast<uK>(static_cast<uM>(x))

Mask cleanup applied where the mask matched the truncation width:

  Truncate8(x & 0xFFu)            -> static_cast<u8>(x)
  Truncate8((x & 0xFF00u) >> 8)   -> static_cast<u8>(x >> 8)
  Truncate16(x & 0xFFFFu)         -> static_cast<u16>(x)
  Truncate16((x & 0xFFFF0000u) >> 16) -> static_cast<u16>(x >> 16)

The masks were dead-code: a static_cast to uN already keeps exactly
the low N bits.

UB fixes incidental to the fold (visible once the helpers were
unwrapped):

  - SignExtendN<NBITS,T> internally did (static_cast<signed_T>(v) << S) >> S.
    Signed left shift of a negative value is UB pre-C++20. After the
    fold the shift is done in the unsigned domain first:
      static_cast<sN>(static_cast<uN>(v) << S) >> S
    All five SignExtendN callsite expansions (gpu_commands.cpp x2,
    gpu_types.h, gte SignExtendMACResult, mdec.cpp x12) now do the
    left shift on uN. Defined behaviour on every C++ standard from
    C++98 onward. Right shift of a signed negative value remains
    implementation-defined pre-C++20; this is the same as the
    original helper and unchanged.

  - mdec.cpp:650's SignExtendN<9,s32> took an s64 expression and
    forced an implicit s64->int narrowing inside the template, which
    -Wconversion flagged. The explicit static_cast<u32>(...) now
    makes the narrow visible and the warning goes away. Bit-identical
    result.

Sites deliberately not collapsed further, with reasons:

  - spu.cpp:1347 (ADPCM pitch modulation): SignExtend32(step) where
    step is u16 deliberately produces a u32 with the s16 sign bit
    replicated, then multiplies by a u32 factor. Folding it as
    static_cast<u32>(static_cast<s16>(step)) preserves the semantics
    exactly. The naive 'static_cast<s32>(step) * factor' would not -
    it'd evaluate s32 * s32 which is signed and may overflow as UB.

  - gte.cpp:297-299 (IRGB conversion): Sign-extension here is observably
    equivalent to zero-extension because (value & 0x1F) * 0x80 is
    always <= 0xF80, bit 15 always clear. Folded as the literal
    static_cast<u32>(static_cast<s16>(static_cast<u16>(...))) rather
    than dropping the sign-extend step entirely - that would be a
    semantic claim about hardware behaviour beyond the scope of a
    helper-removal change.

  - GTE TruncateRGB, TruncateAndSetMAC, TruncateAndSetIR,
    TruncateAndSetMACAndIR (gte.cpp) and TruncateVertexPosition,
    TruncateGPUVertexPosition (pgxp.cpp, gpu_types.h): these are
    different functions, not the removed helpers. Left untouched.

bitutils.h's CountLeadingZeros / CountTrailingZeros are template
functions over T. The helper-removal leaves them inline-folding via
std::make_unsigned<T>::type, which is what ZeroExtend was doing
under the hood:

  ZeroExtend64(value) ->
  static_cast<u64>(static_cast<typename std::make_unsigned<T>::type>(value))

The remaining mechanical changes in cpu_recompiler_register_cache.h's
GetS32ConstantValue / GetS64ConstantValue and in pgxp.cpp's CPU_MULT
fold dropped redundant intermediate u-of-s-of-x casts that became
visible after the SignExtend64 expansion. Same codegen; cleaner.

Files touched: 43.
Helper definitions removed: 13 functions (~60 lines of types.h).

Build verification:
  - Makefile.libretro platform=unix: clean build, zero warnings,
    .so size 8031016 bytes (unchanged from HEAD).
  - 25 retro_* exports unchanged.
  - -Wall -Wextra on touched files: same warnings as HEAD (zero
    new warnings from the fold, all pre-existing -Wunused-parameter).
  - -Wconversion on touched files: one pre-existing warning
    eliminated (mdec.cpp:650 SignExtendN<9,s32>(s64_expr) narrowing
    is now an explicit static_cast<u32>); zero new warnings.

Codegen equivalence verified by inspection at every transformation
site:

  Truncate8(x)        = static_cast<u8>(x)   ; both emit a movzx/byte-load
  Truncate16(x)       = static_cast<u16>(x)  ; both emit a movzx/halfword-load
  ZeroExtend32(u8)    = static_cast<u32>(u8) ; both emit a movzx eax,al
  ZeroExtend64(u32)   = static_cast<u64>(u32); both emit a mov eax,reg (implicit zero-extend on x86-64)
  SignExtend32(u8)    = static_cast<u32>(static_cast<s8>(x))  ; both emit movsx eax,byte
  SignExtend32(u16)   = static_cast<u32>(static_cast<s16>(x)) ; both emit movsx eax,word
  SignExtend64(u32)   = static_cast<u64>(static_cast<s32>(x)) ; both emit movsxd rax,dword
  SignExtendN<11,s32> = static_cast<s32>(static_cast<u32>(x) << 21) >> 21
                        both emit shl ; sar, identical 2-instruction sequence
2026-05-14 05:41:46 +02:00
LibretroAdmin
5d73da3896 gpu_hw: trigger shader recompile on runtime swanstation_GPU_ShaderPrecompile change
Reported bug: flipping the swanstation_GPU_ShaderPrecompile core
option between Lazy / Enabled / Disabled at runtime had no
immediate effect. The new mode wouldn't take effect until the
user changed some OTHER shader-affecting setting (texture filter,
resolution scale, multisampling, etc.) that triggered the existing
destroy/recompile path.

Root cause: GPU_HW::UpdateHWSettings's shaders_changed predicate
checked 11 fields (resolution_scale, multisamples, true_color,
per_sample_shading, scaled_dithering, texture_filter, uv_limits,
chroma_smoothing, downsample_mode, pgxp_depth_buffer,
disable_color_perspective) but NOT g_settings.gpu_shader_precompile_mode.
So a pure precompile-mode flip computed shaders_changed = false,
the per-backend UpdateSettings skipped the DestroyPipelines /
CompilePipelines round-trip, and:

  - Lazy -> Disabled: the background worker that was already
    spawned just kept running until it naturally finished filling
    the matrix (~30 seconds on heavy filters). The user-visible
    'Disabled' semantics didn't apply until then.

  - Disabled -> Lazy: no worker spawn happened. Each draw kept
    paying first-use compile cost on the runloop. The user got
    Disabled behaviour while the setting said Lazy.

  - {Lazy, Disabled} -> Enabled: no synchronous full precompile
    happened. The user expected 'block until done' and got
    whatever state the matrix was in.

  - Enabled -> {Lazy, Disabled}: the matrix was already fully
    populated from the Enabled-mode sync pass, so this only had
    bearing on FUTURE recompile cycles. Still wrong but the
    least-visible case.

Fix: add m_shader_precompile_mode as the cached previous value
(seeded in GPU_HW::Initialize from g_settings.gpu_shader_precompile_mode,
re-stored every UpdateHWSettings call alongside the other field
copies). Include it in the shaders_changed predicate.

After this patch a runtime flip triggers shaders_changed = true,
which calls into the per-backend UpdateSettings's normal
destroy/recompile path:

  - Lazy -> Disabled: DestroyPipelines calls StopShaderCompileThread
    which joins the worker; CompilePipelines runs in Disabled
    mode (skips the precompile matrix, doesn't spawn a worker).
    The worker is gone within at most one in-flight cell's
    compile worth of latency.

  - Disabled -> Lazy: DestroyPipelines is a no-op for the worker
    (none running); CompilePipelines runs in Lazy mode (skips
    the precompile matrix, spawns a worker that fills the matrix
    asynchronously).

  - Disabled -> Enabled: full sync precompile on the calling
    thread - the documented Enabled-mode behaviour. The frontend
    blocks for tens of seconds on cold disk cache; cached, it's
    a few seconds.

  - Enabled -> Lazy / Disabled: matrix destroyed, recompiled
    according to the new mode. Symmetric with the other cases.

  - Lazy -> Enabled or vice versa with an in-flight worker:
    DestroyPipelines joins the in-flight worker first, then
    CompilePipelines starts fresh in the new mode.

Cost is one full destroy/recompile cycle on each precompile-mode
flip - same cost path the existing 11 settings already pay. For
Lazy and Disabled this is roughly 100-300 ms of teardown plus
non-batch shader rebuild. For Enabled it's that plus the actual
sync precompile of the batch matrix, dominated by driver compile
time (10-40s cold, sub-second from disk cache). The cell-fill
work hits the disk shader cache so it's only expensive on the
first time any given (filter, scale, ...) tuple is seen.

We could have written more precise handling - 'on Lazy ->
Disabled just stop the worker, keep the populated matrix' - but
that's a more complex patch and the simple destroy/recompile path
is well-trodden, well-tested, and the user already pays this cost
for any other shader-affecting setting change. Symmetry trumps
the small redundant work in the Lazy <-> Disabled case.

Files touched:
  - src/core/gpu_hw.h: m_shader_precompile_mode member added.
  - src/core/gpu_hw.cpp: Initialize seeds it from g_settings;
    UpdateHWSettings includes it in shaders_changed predicate
    and writes the latest value back.

Build verification: linux platform=unix clean, zero warnings,
zero errors. .so size 8040152 unchanged (one u8-sized field and
one extra comparison, well within an existing structure-padding
slot). 25 retro_* exports unchanged.
2026-05-11 20:37:35 +02:00
libretroadmin
521a3cb9b4 Get rid of more std::arrays 2024-04-17 12:39:47 +02:00
DarthMew
0175913d3e Reduce the amount of OSD messages 2023-03-21 17:56:39 +01:00
libretroadmin
c48ce29c50 Remove some unused functions 2023-03-09 18:32:46 +01:00
DarthMew
e6c53a15cd Revert 27c76b0a48 and fix underlying issue 2023-02-09 14:04:28 +01:00
DarthMew
27c76b0a48 Revert 28d4d33b2c 3bfe5959da 0d47de2dd7 & 826d58355c 2023-02-09 01:51:40 +01:00
DarthMew
3bfe5959da Don't allow disabling PGXP color perspective when using OpenGLES 2023-02-01 00:26:33 +01:00
DarthMew
826d58355c Backport PGXP perspective-correct color interpolation toggle & cleanup libretro_game_settings 2023-01-31 01:52:51 +01:00
LibretroAdmin
7ffe05afb4 Get rid of some align/log.h include 2022-09-12 01:13:23 +02:00
LibretroAdmin
d6c66e0d82 Remove common/assert.h 2022-09-11 10:12:54 +02:00
LibretroAdmin
048ac38a1b Remove DebugAssert 2022-09-08 07:58:20 +02:00
libretroadmin
3e5b4abaa1 Move some of the align pow2 functions that are only used for one file to
their respective proper locations
2022-07-22 21:20:00 +02:00
libretroadmin
a806334dba Remove UnreachableCode 2022-06-27 20:42:28 +02:00
libretroadmin
8af94fb6f7 - Simplify CalculateResolutionScale
- Turn IsPow2 into a macro
- JIT code buffer - Get rid of some of the logs
2022-06-26 03:03:37 +02:00
libretroadmin
3873ee74d7 - Get rid of unused GetEffectiveDisplayResolution/GetFullDisplayResolution
- Get rid of RendererStats
2022-06-24 20:06:14 +02:00
libretroadmin
f4b55de2a8 Reduce more reliance on file_system.h/FileSystem and remove
more logs
2022-06-24 08:23:21 +02:00
libretroadmin
3c0b044d91 Remove cpu_disasm.cpp/.h 2022-06-24 07:54:25 +02:00
libretroadmin
a644b95125 Remove WITH_IMGUI 2022-06-24 01:30:27 +02:00
DarthMew
b4c3d31f28 Revert https://github.com/libretro/swanstation/pull/43, fixes 'Use Software Renderer For Readbacks' 2022-01-21 21:14:41 +01:00
DarthMew
be4783514a reapply swanstation commits to latest upstream 2021-10-14 23:30:13 +02:00
Connor McLaughlin
628dc36e77 GPU: Add GPU::GetFullDisplayResolution() 2021-08-24 11:57:09 +10:00
Jake Stine
6566e665df 1X and 4X Software Up-Rendering Feature Added (#43)
* 2X and 4X Software Up-Rendering Feature Added

What this change includes:
 - 2X software uprender
 - 4X software uprender (mostly untested, but yolo)
 - significant perf improvements to all SW rendering, including native res
 - config setting '[GPU].SoftwareUprender'

What this change is missing:
 - UI integration. It can only be enabled from the settings.ini file at the moment
 - Testing. I only checked four games so far

* SW Uprender 2x Fixed.

Mainly two typos, one in SetPixel, and one in a template parameter, caused the problems.
I did a bunch of var renaming and cleanup along the way.

* Add preliminary support for on-the-fly resolution change, rename and refactor some vars

* SW uprender: simplified so HW/SW share same setting.

* Fixed crash caused by bad malloc from on-the-fly res change refactor

* Fixed another crash. Bad math typo.

* Fix mode bad math in ReadVRAM

* Fix 4x rendering (mostly) - gradients are off, but could be SW integer precision issue.

hooks up proper software display buffer texture allocation.

* Fix FMVs rendering on host 16bpp display buffers

This bug varies by user's PC hardware and OS. Hard to verify and reproduce. >_<

* Fix hardcoded upscale factor

* Reduce diff size a bit

Co-authored-by: Jean-André Santoni <jean.andre.santoni@gmail.com>
2021-07-29 17:22:51 +07:00
Connor McLaughlin
70209db402 GPU/HW: Implement oversized VRAM fills in hardware
Fixes downscaling in Bugs and Taz PAL.
2021-07-21 19:24:10 +10:00
Connor McLaughlin
096a92ba84 GPU/HW: Simplify shader compile progress updates 2021-07-11 13:21:41 +10:00
Connor McLaughlin
defce709da GPU/HW: Don't allow adaptive downsampling at non-pow2 scales 2021-06-25 00:19:14 +10:00
Connor McLaughlin
815146e7d8 GPU/HW: Fix incorrect blend factor
Regression from 75e6c175de
2021-06-17 20:04:05 +10:00
Connor McLaughlin
75e6c175de GPU/HW: Elide redundant UBO updates on draw mode change 2021-06-15 23:10:49 +10:00
Connor McLaughlin
179a7aea89 GPU/HW: Assume 240/288p for auto scale on start with all borders 2021-05-31 03:48:38 +10:00
Connor McLaughlin
245dd5b27a GPU/HW: Fix crash with oversized writes and sw readback 2021-05-20 14:14:26 +10:00
Connor McLaughlin
5d877250e9 GPU/HW: Add an option to use software renderer for readbacks 2021-05-20 13:28:36 +10:00
Connor McLaughlin
df5de7730c GPU/HW: Disable depth buffering on transparent polygons
These are the most likely to be coplanar and cause issues.
2021-03-30 01:40:05 +10:00
Connor McLaughlin
ddea2818d9 Qt: Add renderer/resolution to status bar 2021-03-28 13:47:53 +10:00
Connor McLaughlin
b13c51a2e2 GPU/SW: Use new 5-to-8 converters for RGBA8 display 2021-03-18 13:00:58 +10:00
Connor McLaughlin
c043643c4d GPU/HW: Fix typo in –IncludeVRAMDirtyRectangle() name 2021-02-07 20:00:16 +10:00
Connor McLaughlin
837fb6128b GPU/HW: Fix mask bit when rendering with transparency and no DSB
Fixes some sprites in Bloody Roar on Mali GPUs.
2021-02-06 20:14:28 +10:00
Connor McLaughlin
516d685dd0 System: Add memory-only save states and rewind 2021-01-25 01:15:45 +10:00
Connor McLaughlin
a927bfbe50 GPU/HW: Flush after each primitive for B-F transparency
Slow, but necessary for some games such as Suikoden II, where it draws
multiple polygons to the same area on screen with different transparency
modes.
2021-01-20 01:08:36 +10:00
Connor McLaughlin
40257e5b20 GPU/HW: Don't set m_pgxp_depth_buffer when PGXP is disabled
Fixes text corruption in Castlevania when PGXP is disabled and depth
buffer is enabled.
2021-01-01 17:49:20 +10:00
Connor McLaughlin
3cb2cd8235 GPU: Add adaptive and box downsampling modes 2020-12-30 17:41:39 +10:00
Connor McLaughlin
d187c8b08d GPU/HW: Fix a potential case where depth isn't cleared on viewport change 2020-12-26 00:47:03 +10:00
Connor McLaughlin
aa1543271e GPU: Support emulating a depth buffer from PGXP depth values 2020-12-23 01:39:49 +10:00