Skip to content

nvn/vulkan: add software linear filtering fallback for formats without HW linear support - #436

Merged
mamcjr merged 1 commit into
mamcjr:mainfrom
Propinbo:fix/soft-linear-filter
Nov 17, 2026
Merged

mamcjr merged 1 commit into
mamcjr:mainfrom
Propinbo:fix/soft-linear-filter

Conversation

@Propinbo

@Propinbo Propinbo commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds a targeted shader-level software bilinear filtering fallback (soft_linear) for sampled 2D and 2D-array textures whose sampled VkFormat lacks VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT on the host Vulkan GPU, while keeping native hardware linear filtering wherever supported, keeping zero draw-path overhead on GPUs with full linear filtering, keeping the nearest-sampler fallback (vk_sampler_nearest) from #307 for non-2D/shadow/integer cases, and preserving LARECOMP_NO_FILTER_FALLBACK=1.


Root Cause

Commit from #307 (vk_sampler_nearest) fixed black grass / sample hangs on GPUs that reject linear filtering on unsupported formats, but replaced bilinear filtering with VK_FILTER_NEAREST whenever !vk_format_filters_linear(tfmt).

On Arm Immortalis-G925 (Vulkan 1.3.278), VK_FORMAT_R16G16B16A16_UNORM (NVN 0x2a, VK_FORMAT 91) lacks hardware SAMPLED_IMAGE_FILTER_LINEAR. During BOTW's cascading 64x64 water clipmap passes (which sample with wrap=1 REPEAT before GPU->CPU readback into Havok water heightfields), nearest-neighbor sampling smeared elevated river texels out across dry adjacent terrain instead of interpolating them down at the shoreline, producing a persistent phantom physical and visual water volume near Dueling Peaks Stable.


Changes (rebased onto main 26da3fa, commit a106b0c)

  • runtime/nvn/maxwell/shader.h:
    • Added soft_linear, soft_linear_mip, soft_linear_rep_u, and soft_linear_rep_v (4 x uint64_t bitmasks, sizeof(ShaderKey) == 88) plus bool sampled on ShaderTexture.
  • runtime/nvn/maxwell/translate.c:
    • Emits slinN / slinN_i / slinN_b helpers using texelFetch with 1/256 sub-texel coordinate quantization.
    • Uses per-axis REPEAT (fract(uv) and % isz) when soft_linear_rep_u / soft_linear_rep_v is set and [0, isz - 1] clamping otherwise.
    • Emits int il = 0 directly without textureQueryLevels/textureQueryLod when !(soft_linear_mip & bit); when mipmapped (min_filter > 1), clamps/rounds textureQueryLod(...).x (on raw uv) against max(textureQueryLevels(tN) - 1, 0).
  • runtime/nvn/vulkan/exec.c:
    • Added stage_fill_soft_linear() handling CLAMP/CLAMP_TO_EDGE (0, 7) and REPEAT (1) per axis (skipping MIRROR* and CLAMP_TO_BORDER) for active non-shadow, non-integer 2D / 2D-array samplers requesting linear filtering.
    • Pre-populates vkey/fkey from last_prog in draw_() before hashing so steady-state draws keep hitting last_prog, falls back to the base program if a soft_linear variant fails to compile (state == 2) in draw_() and dispatch_compute(), and hashes/matches all four masks in get_program() and compute_program().
    • Memoizes tfmt (vk_sampled_format(rt, ...) behind rt && rt->backend) inside texture_info()'s per-frame memo[1024] slot and guards copy_texture() vkCmdBlitImage linear filter flag on vk_format_filters_linear().
  • runtime/nvn/vulkan/textures.c & runtime/nvn/vulkan/vk.h:
    • Added vk_format_is_int() and race-safe atomic_fetch_or_explicit lazy init in vk_any_format_no_linear() (bit 1 = initialized, bit 2 = non-integer format lacks linear filtering; updated in vk_format_filters_linear() if any non-integer format lacks linear support; respects LARECOMP_NO_FILTER_FALLBACK), ensuring zero draw-path work or startup log noise when hardware linear filtering is available.
    • Disabled anisotropy in make_sampler() when g_force_nearest is active for vk_sampler_nearest().
  • tools/test_soft_linear.py:
    • Automated host suite covering production C helpers (wasm32), Vulkan 1.1 glslc SPIR-V compilation across CLAMP/REPEAT and mip/!mip combinations, atomic_fetch_or race safety, state == 2 / memo[ms].tfmt invariants, and numerical bilinear accuracy checks.

Testing & Device Validation

  • Automated host & build checks (a106b0c on 26da3fa):
    • python -B tools/test_soft_linear.py: 23 wasm32 C tests + 3 Vulkan 1.1 glslc SPIR-V compile checks + 203 numerical math checks PASS (rc=0).
    • test_vulkan_compat.py (16), test_vulkan_startup.py (33), ./gradlew :app:assembleDebug (JDK 17), and tools/test_android_runtime.ps1 (6/6 Bionic arm64 tests on SM-X730: test_kernel_affinity, test_bc_shadow, test_buffer_copy, test_nvn_lifetime, test_object_cache, test_benchmark_trace): PASS.
  • Great Plateau grass check (SM-X730, Mali-G925, plateau benchmark scene at 30 fps, updated a106b0c build):
    • status = "ok", 30.0 fps (1% low 29.52, gpu.p50 27.101 ms, over_50ms = 0, 0 Vulkan/shader errors); [vk] format 91 can't be filtered linearly and [vk] sampled format 91 (nvn 0x2a, 64x64) has no linear filtering here active; Great Plateau grass renders cleanly green without black or stretched blades.
  • Physical Android A/B (SM-X730, Mali-G925-Immortalis MC12, LARECOMP_NATIVE=1, Dueling Peaks Stable):
    • #461 (6f83821) alone (runA-461only.log): [vk] format 91 can't be filtered linearly fires and the translucent phantom water box remains visible in the dry stable yard (30.0 fps, 0 errors).
    • #461 + #436 (6f83821 + f92454e) (runB-461plus436.log): [vk] format 91 can't be filtered linearly still fires (93 write-backs including 8 f0x2a, fbcopy 540 (breaks 0), 30.0 fps max 35ms, 0 errors), and the dry stable yard renders cleanly with the phantom water volume eliminated.
View (Dueling Peaks Stable) Before (#461 6f83821 only) After (#461 6f83821 + #436 f92454e)
Stable yard (facing dry ground) Before: yard After: yard
Little Twin River / bank Before: river After: river

Known Limitations

  • Software bilinear filtering applies only to non-shadow, non-integer TEXTYPE_2D and TEXTYPE_2D_ARRAY sampled textures using CLAMP, CLAMP_TO_EDGE, or REPEAT wrap modes; MIRROR*, CLAMP_TO_BORDER, 1D, 3D, CUBE, shadow (compare), and integer formats continue using #307 vk_sampler_nearest when hardware linear filtering is unavailable.
  • Mip selection uses nearest integer mip (floor(clamp(lod, 0, ml) + 0.5f)) without cross-mip trilinear interpolation, and sub-texel weights are quantized to 1/256 steps.

@mamcjr

mamcjr commented Nov 16, 2026

Copy link
Copy Markdown
Owner

Thanks! Real bilinear instead of nearest where the format can't be filtered is the right fix, and the vkCmdBlitImage LINEAR check (a real VUID) and the check on the view's format are good on their own. It merges cleanly onto current main (6113c61), and onto #461 too.

A few things before merging:

  1. Cost on GPUs that filter everything (Adreno): stage_soft_linear_mask runs for every 2D slot on every draw and dispatch: handle read, pool lookups, vk_sampled_format, then a linear search in the format cache. That bypasses the per-frame texture memo. It should cost nothing there: a global "some format failed linear" flag set in vk_format_filters_linear and checked first (exec.c ~6027) would do it.
  2. Wrap modes: the soft path always clamps to the edge, so REPEAT / MIRROR give wrong edges and there's no border colour. Toroidal clipmaps often use REPEAT. Please set the bit only for clamp wrap modes (exec.c ~6040) and keep nearest otherwise, or implement the wrap.
  3. Mip selection: it ignores the sampler's minLod / maxLod / bias and the "not mipmapped" clamp (mf <= 1 in make_sampler: base level only). Using textureQueryLod(...).x instead of .y (translate.c ~2995) keeps those clamps from the bound sampler. For explicit LOD, clamp to level 0 when mf <= 1.
  4. Optional: the base program is compiled first just to get its ShaderInfo, an extra compile per variant on Mali, and two get_program calls per draw skip the last-program fast path.

On the evidence: #461 describes the same tiles (64x64 R16G16B16A16_UNORM, Little Twin River, Dueling Peaks) as a sync bug that loses the water. Could you redo the phantom-water repro on the G925 with #461 applied, to show this is a separate bug? Logs or before/after screenshots would help. On the Adreno 830 here I'll check that no [vk] format N can't be filtered linearly line appears and that render-thread time doesn't change.

@Propinbo
Propinbo force-pushed the fix/soft-linear-filter branch from ab828a1 to f92454e Compare November 17, 2026 06:06
Propinbo added a commit to Propinbo/BOTWRecompAndroid that referenced this pull request Nov 17, 2026
…30 A/B + clock check, and 11-scene audit [skip ci]
@Propinbo

Propinbo commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review. I have updated fix/soft-linear-filter onto main (6113c61 / v0.4.5-beta, commit f92454e, 6 files) to address each point:

  • Zero draw-path work / startup scan overhead when HW linear filtering is available (vk_any_format_no_linear):
    • Added a lazy _Atomic int g_any_no_linear check (vk_any_format_no_linear() in runtime/nvn/vulkan/textures.c) that queries VK_FORMAT_R16G16B16A16_UNORM on first check (respecting LARECOMP_NO_FILTER_FALLBACK), and sets g_any_no_linear = 1 in vk_format_filters_linear() if any non-integer format lacks SAMPLED_IMAGE_FILTER_LINEAR_BIT. On GPUs with full linear filtering (e.g., Adreno/Turnip), stage_fill_soft_linear() returns immediately with no extra logging or sampler loops.
  • Wrap-mode safety + per-axis REPEAT for BOTW's water clipmaps (soft_linear_rep_u, soft_linear_rep_v):
    • Device testing on SM-X730 showed that BOTW's 64x64 NVN 0x2a (format 91) water clipmaps bind samplers with wrap 1 (REPEAT), so gating soft_linear solely to clamp modes left the phantom water volume at Dueling Peaks Stable unaddressed.
    • stage_fill_soft_linear() now handles CLAMP/CLAMP_TO_EDGE (0, 7) and REPEAT (1) per axis, while skipping MIRROR* and CLAMP_TO_BORDER. In runtime/nvn/maxwell/translate.c, REPEAT axes apply fract(uv) and modulo (p0 + 1) % isz / (p0 + isz) % isz instead of clamping.
  • Mip vs non-mip specialization (soft_linear_mip) & integer/depth guards:
    • Samplers without mip filtering (min_filter <= 1) leave soft_linear_mip cleared, emit int il = 0 directly without textureQueryLevels/textureQueryLod, and compute slinN(uv, 0.0f). Samplers with min_filter > 1 pass textureQueryLod(...).x (on raw uv) into slinN and clamp/round against max(textureQueryLevels(tN) - 1, 0).
    • Added vk_format_is_int() so pure integer formats do not trigger nearest fallback or soft_linear.
  • last_prog pre-population & ShaderKey matching:
    • ShaderKey now packs all four uint64_t bitmasks (soft_linear, soft_linear_mip, soft_linear_rep_u, soft_linear_rep_v, sizeof(ShaderKey) == 88), pre-populates vkey/fkey from last_prog in draw_() before hashing so steady-state draws hit last_prog without an extra cache miss, and includes all four fields in get_program() and compute_program().
  • Verification:
    • python -B tools/test_soft_linear.py: 20 wasm32 C tests + 3 Vulkan 1.1 glslc SPIR-V compile checks (covering CLAMP/REPEAT combinations and mip/non-mip helpers) + 203 numerical math checks passed (rc=0).
    • test_vulkan_compat.py (16 checks), test_vulkan_startup.py (33 checks), ./gradlew assembleDebug, and test_kernel_affinity, test_bc_shadow, test_buffer_copy, test_object_cache on SM-X730 passed.
    • In-game A/B on SM-X730 (Mali-G925, LARECOMP_NATIVE=1, Dueling Peaks Stable):
      • #461 alone (6f83821) (runA-461only.log): [vk] format 91 can't be filtered linearly fires and the phantom translucent water box remains visible in the dry stable yard.
      • #461 + #436 (6f83821 + f92454e) (runB-461plus436.log): [vk] format 91 can't be filtered linearly still fires (93 write-backs including 8 f0x2a, fbcopy 540 (breaks 0), 30.0 fps max 35ms, 0 errors), and the dry stable yard renders cleanly with the phantom water volume eliminated.
View (Dueling Peaks Stable) Before (#461 6f83821 only) After (#461 6f83821 + #436 f92454e)
Stable yard (facing dry ground) Before: yard After: yard
Little Twin River / bank Before: river After: river

@mamcjr

mamcjr commented Nov 17, 2026

Copy link
Copy Markdown
Owner

Thanks, the REPEAT handling looks right and the redone repro on top of #461 is what I needed. Two small things before merging:

  1. If a soft-linear variant fails to compile (state 2), its draws are skipped forever (exec.c ~6859). Please fall back to the base program instead.
  2. texture_info now calls vk_sampled_format() for every texture on every draw on all GPUs (exec.c ~6236), outside the per-frame memo; for aliases that reaches vkGetPhysicalDeviceFormatProperties. Please keep it in the memo slot or behind the backend guard.

Minor: the lazy init in vk_any_format_no_linear could use atomic_fetch_or so a late store of 0 can't overwrite a 1. After that I'll check the Adreno 830 here (no non-integer "can't be filtered linearly" lines, same render-thread time) and the Plateau grass on the Mali path, since the grass vertex shader moves from the nearest twin to the soft path.

…t HW linear support

When a sampled 2D or 2D-array texture format lacks hardware
SAMPLED_IMAGE_FILTER_LINEAR support (e.g., VK_FORMAT_R16G16B16A16_UNORM /
NVN 0x2a on Mali-G925), mamcjr#307's vk_sampler_nearest fallback smears
shoreline texel heights across BOTW's cascading 64x64 water clipmap
passes before GPU->CPU readback into Havok heightfields, causing a
phantom physical and visual water volume near Dueling Peaks Stable.

Emulate 1/256-quantized bilinear filtering in translated GLSL shaders
via texelFetch (slinN / slinN_i / slinN_b) for active non-shadow,
non-integer 2D / 2D_ARRAY slots requesting linear filtering, while
preserving hardware linear filtering where supported, mamcjr#307's nearest
fallback for other cases, and LARECOMP_NO_FILTER_FALLBACK=1.

Also checks vk_sampled_format before fallback, disables anisotropy on
nearest-fallback samplers, and guards copy_texture blits on
vk_format_filters_linear.

Validated on v0.4.3-beta (5946454) using SM-X730 (Mali-G925,
Vulkan 1.3.278) and CPH2653 (Adreno 830, Vulkan 1.3.284), plus
tools/test_soft_linear.py.
@Propinbo
Propinbo force-pushed the fix/soft-linear-filter branch from f92454e to a106b0c Compare November 17, 2026 14:23
@Propinbo

Copy link
Copy Markdown
Contributor Author

Thanks for the review — I have rebased fix/soft-linear-filter onto main (26da3fa, commit a106b0c) and addressed all three points:

  1. Base-program fallback on soft_linear compile failure (state == 2, runtime/nvn/vulkan/exec.c):
    • draw_() now saves vbase/fbase before masks_done: if the masks_done pre-populated soft_linear variant reaches state == 2, it falls back to get_program(st.program, &vbase, &fbase); on the !masks_done path, if sl_state == 2, pr stays the ready base program instead of skipping draws forever (and dispatch_compute() similarly keeps the ready base CsProg if a soft_linear compute variant fails to compile). Meanwhile texture_info() still switches the sampler to vk_sampler_nearest when !vk_format_filters_linear(tfmt).
  2. Memoized tfmt in texture_info() (runtime/nvn/vulkan/exec.c):
    • Moved tfmt into memo[1024] (computed on memo miss from rt = naliases ? alias_read(e->tex) : e->tex behind rt && rt->backend), removing the separate un-memoized vk_sampled_format() call on every draw (stage_fill_soft_linear() also resolves alias_read when naliases is non-zero).
  3. atomic_fetch_or in vk_any_format_no_linear() (runtime/nvn/vulkan/textures.c):
    • Switched g_any_no_linear to bitmask flags (1 = initialized, 2 = non-integer format lacks linear support) updated via atomic_fetch_or_explicit, so a late store of 0 cannot overwrite 1.

Re-verification (a106b0c on 26da3fa):

  • python -B tools/test_soft_linear.py: 23 wasm32 C tests (including atomic_fetch_or race-safety and memo[ms].tfmt / state == 2 fallback checks) + 3 Vulkan 1.1 glslc SPIR-V checks + 203 bilinear math checks passed (rc=0).
  • test_vulkan_compat.py (16), test_vulkan_startup.py (33), ./gradlew :app:assembleDebug (JDK 17), and tools/test_android_runtime.ps1 (6/6 Bionic arm64 tests on SM-X730) passed.
  • Great Plateau grass on SM-X730 (Mali-G925-Immortalis MC12, plateau scene at 30 fps): 30.0 fps (1% low 29.52, gpu.p50 27.101 ms, over_50ms = 0, 0 Vulkan/shader errors); [vk] format 91 can't be filtered linearly and [vk] sampled format 91 (nvn 0x2a, 64x64) has no linear filtering here active, and the Great Plateau grass renders cleanly green without black or stretched blades.

Propinbo added a commit to Propinbo/BOTWRecompAndroid that referenced this pull request Nov 17, 2026
@mamcjr

mamcjr commented Nov 17, 2026

Copy link
Copy Markdown
Owner

Thanks, all three are done right: the fallback to the base program, the format in the memo, and atomic_fetch_or. I'll test it on the Adreno 830 here (no "can't be filtered linearly" line for a non-integer format, the same render-thread time) and on the Mali path (the Plateau grass), and merge if both are clean.

@mamcjr

mamcjr commented Nov 17, 2026

Copy link
Copy Markdown
Owner

Thanks! Tested on the POCO F7 Ultra (Adreno 830, Turnip) merged with #475 on current main: no "can't be filtered linearly" line, so the soft path stays off there, and the Plateau benchmark's GPU times match main's (23.0 / 22.9 ms vs 22.8 / 25.5 ms). The Mali side rests on your G925 runs. Merging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants