Repository navigation
Conversation
|
Device testing found a real bug, now fixed in
The cause is that the original patch raised every sampler, including comparison samplers. A comparison sampler is a shadow map lookup. Anisotropy changes which depth texels each comparison averages, so either side of a shadow cascade boundary resolves slightly differently and the join stops being invisible. Two more sampler kinds should never have been raised either:
So the rule is now what it should have been from the start: raise only samplers that read a mipmapped colour texture. if (!p.cmp_mode && !p.reduction && d.mipFilter != MTLSamplerMipFilterNotMipmapped && dm_aniso() > a) a = dm_aniso();A rebuild with the fix is going to the device now and I will confirm the line is gone. Worth noting for anyone reviewing: this class of bug only shows up on hardware in a game with cascaded shadows, so the "it is only sampling, it cannot change anything" reasoning in the original commit message was wrong. |
Game carries six unrelated rows: how fast the game runs, how large it renders, which console mode it reports, how the finished frame is scaled, which language it speaks, and a frame-rate read-out. The only thing they have in common is that none of them belonged in Controls or Performance. Picture takes the two rows that are about the finished frame rather than about the game: Render scale and Upscaling. Game keeps Frame rate, Console mode and Game language. The frame-rate counter moves to Performance next to the Performance HUD, since both are read-outs rather than settings. The split matters more as the section grows. With the anisotropic and trilinear filtering of seedds#335 and the upscaling detail and sharpening of seedds#345, Game would hold ten rows, six of which are about how the picture looks. The heading order on screen is the order of SECTIONS, and rows keep their table order inside a section, so settings.tsv still decides the layout on its own.
|
Thanks for this. I've been trying anisotropic filtering on Breath of the Wild 1.9.0 on the Mac (M5 Max), along the same lines, and ran into a second failure besides the shadow cascade line you found. I think the current rule ( Every edge turned jagged when the raised sampler read a one-level texture. My first version raised every trilinear sampler, whatever texture it was bound with. Every silhouette in the picture then turned jagged, distant mountain ridges included. One of the anti-aliasing pass's samplers is trilinear but reads a one-level texture. Anisotropy spreads extra samples along the pixel's footprint, and with no smaller level to fall back to they all land on level 0 wherever the shader's coordinates jump within a pixel quad. The anti-aliasing pass then finds its edges in the wrong places. Binding the raised state only with textures that have more than one level made the edges smooth again. The rule here looks at the sampler alone ( A sampler with mips whose LOD range clamps it to level 0 (max LOD below 1) also reads only one level, just as a one-level texture does. yuzu gates its anisotropy on that range ("video_core: Apply AF only to samplers with normal LOD range"). What I ended up with:
On BotW (M5 Max, 1520x855, by the Temple of Time), the cost was nothing measurable. I alternated the raised and the game's states within one run, 12 phases each: GPU p50 was 6.60 ms with the game's states and 6.59 ms raised, and frame time stayed at 16.7 ms. I haven't tested on an iPhone or iPad. I also wrote the same for the Vulkan layer (combined image samplers) and for GL (per-texture sampler state), and a unit test for the rule and the texture gate (47 checks). I'm happy to share the patch here or send it as a follow-up on top of yours, whichever you prefer. |
|
Rebased onto main (2e6edda) as one commit, retitled to the Checked on this commit (M4 Max): host build, |
Game carries eleven unrelated rows: how fast the game runs, how large it renders, which console mode it reports, how the finished frame is scaled, fitted and shaped, which language it speaks, how the Mac window opens, and a frame-rate read-out. The only thing they have in common is that none of them belonged in Controls or Performance. Picture takes the rows that are about the finished frame rather than about the game: Render scale, Upscaling, Game's upscaler, Picture and Picture shape. Game keeps Frame rate, Dynamic resolution, Console mode, Game language and the Mac's Display mode. The frame-rate counter moves to Performance next to the Performance HUD, since both are read-outs rather than settings. The iOS in-game menu follows the sections, so the counter comes after the controls there. The split matters more as the section grows. With the anisotropic and trilinear filtering of seedds#335 and the upscaling detail and sharpening of seedds#345, Game would hold fifteen rows, nine of which are about how the picture looks. The heading order on screen is the order of SECTIONS, and rows keep their table order inside a section, so settings.tsv still decides the layout on its own. In docs/settings.md the Picture section takes the anchor #picture, and the Picture setting inside it becomes #picture-1. The thermal cap (seedds#220) holds the frame step at 30 fps while iOS reports a serious or critical thermal state, and DM_THERMAL_CAP=0 turned it off only from an env file. It is a trade a player should be able to make: with a phone cooler, or for a player who would rather have an uneven 45 to 55 than an even 30, it costs more than it saves. "Halve when hot" in Performance, on by default, so nothing changes for anyone who does not touch it. Shown only for a game with a frame step, as Hold frames when late is. The note says what the thermal state does not catch. On an iPhone 17 Pro Max, Breath of the Wild 1.9.0 dropped a third of its frames for ten minutes with the state reading nominal throughout, and one scene's GPU time went from 8.40 ms to 21.83 ms while it still read nominal: iOS lowers the clock well before it calls the device hot. The same phone, charged over USB while large apps were installed onto it, started a game already at serious and was held at 30 from the first frame, which is the case the setting is for. The tests follow: Render scale is a basic row under Picture, and in the Mac window's list for Breath of the Wild every Game row is basic, so its Advanced settings start at Picture.
|
@CatPawPrint thanks, and sorry for the slow reply. You're right about the rule here: it looks at the sampler alone, so a trilinear sampler bound with a one-level texture is raised too. My device runs looked for the shadow line and the cost; I didn't check the anti-aliasing pass's edges, so I can't say it doesn't happen here. Choosing per binding, by the view's level count and the sampler's LOD range, is the better rule. Please send your patch, either on top of this branch or as your own PR that replaces this one, whichever is easier for you. If it replaces it I'll close this in its favour, and I can test yours on an iPad Pro M4 and an iPhone 17 Pro Max. |
|
Thanks, happy to. I'll send it as a patch on top of |
|
Now that this Mac has the chain lock's compiler (Xcode 27.2), regress.py check (full): REGRESSIONBaseline
BOTW
|
|
Here is the patch, as two commits on top of What it does:
Checked on a Mac (M5 Max): the host builds with the same warnings as this branch; host and gfx tests pass (only 0001-nvn-sampler-anisotropy-raised-per-binding-also-in-Vulkan-and-GL.patchFrom c5da67ef5b189b0e9c2dc30b5d82f4c6b61cc535 Mon Sep 17 00:00:00 2001
From: CatPawPrint <[email protected]>
Date: Sat, 14 Nov 2026 03:57:56 +0800
Subject: [PATCH 1/2] nvn/sampler: anisotropy raised per binding, also in
Vulkan and GL
DM_ANISO raised every mipmapped sampler that is not a comparison or
reduction sampler, in samp_by_id, and with it every texture bound
through that sampler. Bound with a texture that is read at one level,
a raised state spreads its extra samples across that level wherever a
shader's coordinates jump within a pixel quad. Breath of the Wild's
anti-aliasing pass reads a one-level texture through a trilinear
sampler, and with every trilinear sampler raised, every silhouette in
the picture turned jagged.
The rule is now pure functions in sampler_aniso.h. A sampler is raised
when it filters linearly in both directions, has a mip filter and the
regular LOD range (minimum 0, maximum at least 1), or when the game
already gave it anisotropy; a sampler with a depth comparison, a min /
max reduction or unnormalized coordinates keeps the game's value, as
before for the first two. samp_by_id keeps the game's state and makes
the raised one beside it, and encode_args_ binds it only for a combined
handle (SAMPT, SAMPU) whose texture view is 2D or a 2D array with more
than one level (samp_aniso). Vulkan does the same for combined image
samplers (vkCreateSampler, bind_res), and GL puts the raised value in
its per-texture sampler cache key (tex_sampler). Separate samplers,
sampler pools and arrays keep the game's value, so a game that binds
its samplers apart from its textures gets no change, where the
sampler-only rule raised them.
DM_ANISO takes 0 or 1 (off) or 2 to 16; anything else is a red line
and off. Every value the launcher row offers behaves as before, and
the row now shows for Vulkan and GL games too. DM_TRILINEAR, its row
and its code are unchanged: a sampler it makes trilinear is judged,
and raised, with its new mip filter. DM_NVN_ANISO=0 binds no raised
state, and ab with DM_AB alternates them by phase, to compare cost and
picture in one run.
t_aniso checks the rule for each kind of sampler and LOD range, the
clamp, a view's levels, the texture gate and the switch's values (47
checks); no test reaches the call sites (samp_aniso, bind_res,
tex_sampler). The host builds with the same warnings as before.
On a Mac (M5 Max), Ocarina of Time (NVN) from a save in Link's house:
with DM_ANISO unset the picture and the kinds of red lines are those of
PR #335's head; DM_ANISO=16 logs the setting once, adds no red line and
the edges stay smooth; DM_NVN_ANISO=ab with DM_AB=60 measured GPU p50
13.67 ms with the game's states and 13.77 ms with the raised ones
(about 50 phases each), frame time 16.66 ms in both. A temporary
counter (not kept) showed the texture gate at work there: of 10.5
million combined-handle binds of a sampler with a raised state, 4.8
million took it and 5.7 million kept the game's. Balatro (OpenGL)
with DM_ANISO=16 reaches the rule (it logs the setting), with no red
line and the same picture.
Not run: a Vulkan game (none here), Breath of the Wild on this tree
(its measurements in the docs are from an earlier version of the same
rule), the iPhone and the iPad.
---
dm/games/settings.tsv | 2 +-
dm/gfx/gl/hle_gl.m | 10 ++++-
dm/gfx/nvn/nvn_mtl.m | 49 +++++++++++++++--------
dm/gfx/nvn/sampler_aniso.h | 46 +++++++++++++++++++++
dm/gfx/tests/Makefile | 2 +
dm/gfx/tests/t_aniso.c | 82 ++++++++++++++++++++++++++++++++++++++
dm/gfx/vk/hle_vk.m | 24 +++++++----
docs/env_switches.tsv | 3 +-
8 files changed, 189 insertions(+), 29 deletions(-)
create mode 100644 dm/gfx/nvn/sampler_aniso.h
create mode 100644 dm/gfx/tests/t_aniso.c
diff --git a/dm/games/settings.tsv b/dm/games/settings.tsv
index d3521d35..ac1d8352 100644
--- a/dm/games/settings.tsv
+++ b/dm/games/settings.tsv
@@ -20,7 +20,7 @@ DM_RENDER_SCALE range 0.5:1.0:0.05 1.0 fixups:RENDER_SCALE Game Render scale le
DM_OPMODE choice 1=Docked,0=Handheld DM_GAME_OPMODE always Game Console mode level=basic
DM_PRESENT_UPSCALE choice off=Standard,metalfx=MetalFX off always Game Upscaling Uses more GPU time and can increase heat.
DM_UPSCALER choice game=Game's own,metalfx=MetalFX game DM_GAME_UPSCALER_N!=0 Game Game's upscaler
-DM_ANISO choice 0=Off,2=2x,4=4x,8=8x,16=16x 0 gfxapi:nvn Game Anisotropic filtering Uses a little more GPU time.
+DM_ANISO choice 0=Off,2=2x,4=4x,8=8x,16=16x 0 always Game Anisotropic filtering Uses a little more GPU time.
DM_TRILINEAR toggle - 0 gfxapi:nvn Game Trilinear filtering
DM_LANG choice languages build:DM_LANG languages>1 Game Game language level=basic
DM_FULLSCREEN choice 0=Window,1=Fullscreen 0 platform:mac Game Display mode level=basic
diff --git a/dm/gfx/gl/hle_gl.m b/dm/gfx/gl/hle_gl.m
index 029e0382..28cf25da 100644
--- a/dm/gfx/gl/hle_gl.m
+++ b/dm/gfx/gl/hle_gl.m
@@ -19,6 +19,7 @@
// Environment: DM_GL_LOG=1 logs object creation and the deletion of shaders and programs; DM_GL_CAPTURE=<dir> writes every shader source the game compiles (<key>.vert / <key>.frag, read by gl_shaders.py).
#include "../../host/hle.h"
#include "../nvn/nvn_mtl.h"
+#include "../nvn/sampler_aniso.h"
#include "../nvn/host_msl.h"
#import <Metal/Metal.h>
#include <CommonCrypto/CommonDigest.h>
@@ -563,11 +564,16 @@ static MTLTextureSwizzleChannels tex_swz(const tex_t *t) {
static id<MTLSamplerState> tex_sampler(tex_t *t) {
if (!t->smp_dirty && t->smp) return t->smp;
// sampler states are shared: one per distinct parameter set
- typedef struct { GLint minf, magf, ws, wt, wr, lv, cmp; float aniso, b; } skey;
+ typedef struct { GLint minf, magf, ws, wt, wr, lv, cmp; float aniso, b; unsigned af; } skey; // af: the anisotropy given to Metal (DM_ANISO, below)
static struct { skey k; __strong id<MTLSamplerState> s; } cache[256]; static int n;
int mips = t->levels > 1;
skey k = {t->minf, t->magf, t->ws, t->wt, t->target == GL_TEXTURE_CUBE_MAP ? GL_CLAMP_TO_EDGE : t->wr, mips ? (GLint)umin((uint32_t)t->maxlv, (uint32_t)t->levels - 1) : 0, t->cmp, t->aniso,
t->border[3] > 0.5f ? (t->border[0] > 0.5f ? 2.f : 1.f) : 0.f};
+ // DM_ANISO (sampler_aniso.h): raised only for a 2D or 2D-array texture sampled at more than one level (its levels and GL_TEXTURE_MAX_LEVEL), as in the NVN and Vulkan
+ // layers; otherwise the game's value. One state per texture's parameters: the raised value is in the cache key
+ int mip = !mips || k.minf == GL_NEAREST || k.minf == GL_LINEAR ? ANISO_MIP_NONE : k.minf == GL_NEAREST_MIPMAP_NEAREST || k.minf == GL_LINEAR_MIPMAP_NEAREST ? ANISO_MIP_NEAREST : ANISO_MIP_LINEAR;
+ int min_linear = !(k.minf == GL_NEAREST || k.minf == GL_NEAREST_MIPMAP_NEAREST || k.minf == GL_NEAREST_MIPMAP_LINEAR);
+ k.af = aniso_tex_ok(t->target == GL_TEXTURE_2D || t->target == GL_TEXTURE_2D_ARRAY, mips ? (unsigned)k.lv + 1 : 1) ? aniso_for(k.aniso, min_linear, k.magf != GL_NEAREST, mip, 0, (float)k.lv, k.cmp) : aniso_clamp(k.aniso);
for (int i = 0; i < n; i++) if (!memcmp(&cache[i].k, &k, sizeof k)) { t->smp = cache[i].s; t->smp_dirty = 0; return t->smp; }
MTLSamplerDescriptor *d = [MTLSamplerDescriptor new];
d.magFilter = k.magf == GL_NEAREST ? MTLSamplerMinMagFilterNearest : MTLSamplerMinMagFilterLinear;
@@ -578,7 +584,7 @@ static MTLTextureSwizzleChannels tex_swz(const tex_t *t) {
d.lodMaxClamp = mips ? k.lv : 0;
d.sAddressMode = wrap_of(k.ws); d.tAddressMode = wrap_of(k.wt); d.rAddressMode = wrap_of(k.wr);
d.borderColor = k.b == 2.f ? MTLSamplerBorderColorOpaqueWhite : k.b == 1.f ? MTLSamplerBorderColorOpaqueBlack : MTLSamplerBorderColorTransparentBlack;
- d.maxAnisotropy = (NSUInteger)fmaxf(1, fminf(16, k.aniso));
+ d.maxAnisotropy = k.af;
if (k.cmp) d.compareFunction = (MTLCompareFunction)(k.cmp - GL_NEVER);
id<MTLSamplerState> s = [g_dev newSamplerStateWithDescriptor:d];
if (n < 256) { cache[n].k = k; cache[n].s = s; n++; } else RED1("more than 256 distinct sampler parameter sets");
diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m
index 790875c1..bb120a68 100644
--- a/dm/gfx/nvn/nvn_mtl.m
+++ b/dm/gfx/nvn/nvn_mtl.m
@@ -32,6 +32,7 @@
#include "nvn_refl.h"
#include "nvn_cover.h"
#include "nvn_border.h"
+#include "sampler_aniso.h"
#include "nvn_primitive.h"
#include "nvn_timestamp.h"
#include "msl_image.h"
@@ -6469,6 +6470,7 @@ static void treg_sparse_notes(void) {
static void **g_sview_w; static uint64_t *g_srid_w; static float (*g_sbk)[4]; // a sampler's twin for a border colour Metal lacks (retained, NULL = none) and the shader's factors k (see nvn_border.h)
static _Atomic int g_border_any; // a sampler needing corrections has been registered (sticky). Set before its lazy Metal creation, so its very first draw keeps the corrections
static int border_need(NvShader *sh, int nvn_stage);
+static void **g_sview_a; static uint64_t *g_srid_a; // a sampler's variant with the anisotropy DM_ANISO raises it to (retained, NULL = none: off, or the rule keeps the game's; sampler_aniso.h, samp_aniso)
// Memory pool Finalize: for texture IDs whose registered texture lives on this pool, drop the cached MTLTexture (view or base texture). The cache used to be released only when the ID was registered again,
// so a linear texture built directly on a pool kept the whole pool buffer alive (6 to 17 finalized 16 MB pool buffers stayed alive in Engage's title demo). If the ID is still used, the next lookup rebuilds it on the slow path
static void treg_drop_im(treg_t *r) { if (r->im) { defer_obj_unref((__bridge id)r->im); CFRelease(r->im); r->im = r->im_of = NULL; r->im_rid = 0; } } // the image class view (img_fit)
@@ -6766,10 +6768,13 @@ void mtl_reg_samp(int sid, const samp_par *sp) {
os_unfair_lock_lock(&g_rmu);
if (id_ >= g_nsreg) { int n = id_ + 256; g_sreg = realloc_or_die(g_sreg, n * sizeof *g_sreg, "the sampler registrations"); g_sreg_ok = realloc_or_die(g_sreg_ok, n, "the sampler registrations"); g_sview = realloc_or_die(g_sview, n * sizeof *g_sview, "the sampler registrations"); g_srid = realloc_or_die(g_srid, n * sizeof *g_srid, "the sampler registrations");
g_sview_w = realloc_or_die(g_sview_w, n * sizeof *g_sview_w, "the sampler registrations"); g_srid_w = realloc_or_die(g_srid_w, n * sizeof *g_srid_w, "the sampler registrations"); g_sbk = realloc_or_die(g_sbk, n * sizeof *g_sbk, "the sampler registrations");
+ g_sview_a = realloc_or_die(g_sview_a, n * sizeof *g_sview_a, "the sampler registrations"); g_srid_a = realloc_or_die(g_srid_a, n * sizeof *g_srid_a, "the sampler registrations");
+ memset(g_sview_a + g_nsreg, 0, (n - g_nsreg) * sizeof *g_sview_a); memset(g_srid_a + g_nsreg, 0, (n - g_nsreg) * sizeof *g_srid_a);
memset(g_sreg_ok + g_nsreg, 0, n - g_nsreg); memset(g_sview + g_nsreg, 0, (n - g_nsreg) * sizeof *g_sview); memset(g_srid + g_nsreg, 0, (n - g_nsreg) * sizeof *g_srid);
memset(g_sview_w + g_nsreg, 0, (n - g_nsreg) * sizeof *g_sview_w); memset(g_srid_w + g_nsreg, 0, (n - g_nsreg) * sizeof *g_srid_w); g_nsreg = n; }
if (g_sview[id_]) { CFRelease(g_sview[id_]); g_sview[id_] = NULL; g_srid[id_] = 0; }
if (g_sview_w[id_]) { CFRelease(g_sview_w[id_]); g_sview_w[id_] = NULL; g_srid_w[id_] = 0; }
+ if (g_sview_a[id_]) { CFRelease(g_sview_a[id_]); g_sview_a[id_] = NULL; g_srid_a[id_] = 0; }
g_sreg[id_] = *sp; g_sreg_ok[id_] = 1;
int bn, bw; float k[4]; const uint8_t wrap[3] = {sp->ws, sp->wt, sp->wr};
if (nvn_border(sp->border, wrap, sp->reduction, &bn, &bw, k)) atomic_store(&g_border_any, 1);
@@ -7135,12 +7140,6 @@ static MTLSamplerAddressMode wrapm(int w) {
}
// Filtering the host can raise for any game, because it builds every sampler the game uses: the setting
// is a floor, never a ceiling, so a game that asks for more keeps what it asked for.
-static float dm_aniso(void) {
- static float v = -1;
- if (v < 0) { const char *e = getenv("DM_ANISO"); v = e ? strtof(e, NULL) : 0; if (v < 1) v = 0; if (v > 16) v = 16;
- if (v) MLOG("DM_ANISO=%g: every sampler filters at least this anisotropy", v); }
- return v;
-}
static int dm_trilinear(void) {
static int v = -1;
if (v < 0) { const char *e = getenv("DM_TRILINEAR"); v = e && atoi(e) ? 1 : 0;
@@ -7165,16 +7164,12 @@ static int dm_trilinear(void) {
d.sAddressMode = wrapm(p.ws); d.tAddressMode = wrapm(p.wt); d.rAddressMode = wrapm(p.wr);
d.lodMinClamp = p.lod_min < 0 ? 0 : p.lod_min; d.lodMaxClamp = p.lod_max;
d.lodBias = p.lod_bias < -16 ? -16 : p.lod_bias > 15.99f ? 15.99f : p.lod_bias; // SetLodBias: Maxwell's sampler bias, Metal 26's range [-16, 15.99]
- // DM_ANISO=2..16 raises the game's own anisotropy to at least that, for every sampler. The games were
- // built for a handheld and mostly ask for 1, so ground and wall textures blur at a glancing angle.
- // Sampling only: no render target, no allocation, and a sampler that asks for more keeps what it asked for.
- // Only a sampler that reads a mipmapped colour texture is raised. A comparison sampler is a shadow map: anisotropy
- // changes which depth texels the comparison averages, and across a cascade boundary the two sides then disagree,
- // which draws a line along the join on open ground (seen in Breath of the Wild's fields). A reduction sampler is a
- // min or max pyramid, whose value has to stay the extreme of the footprint. Without mipmaps there is no second level.
- { float a = p.aniso;
- if (!p.cmp_mode && !p.reduction && d.mipFilter != MTLSamplerMipFilterNotMipmapped && dm_aniso() > a) a = dm_aniso();
- d.maxAnisotropy = a < 1 ? 1 : a > 16 ? 16 : (NSUInteger)a; }
+ // DM_ANISO (sampler_aniso.h) is made below as a variant. A comparison sampler is a shadow map and a reduction sampler a min or max
+ // pyramid, so both keep the game's value (raised, the two sides of a shadow cascade boundary stop agreeing: a line along the join on
+ // open ground, found on Breath of the Wild's fields in PR #335).
+ d.maxAnisotropy = aniso_clamp(p.aniso);
+ unsigned af = aniso_for(p.aniso, d.minFilter == MTLSamplerMinMagFilterLinear, d.magFilter == MTLSamplerMinMagFilterLinear,
+ d.mipFilter == MTLSamplerMipFilterLinear ? ANISO_MIP_LINEAR : d.mipFilter == MTLSamplerMipFilterNearest ? ANISO_MIP_NEAREST : ANISO_MIP_NONE, p.lod_min, p.lod_max, p.cmp_mode || p.reduction);
if (p.cmp_mode) d.compareFunction = (MTLCompareFunction)(p.cmp_func - 1);
// Reduction (NVN 1 min / 2 max): the minimum or maximum of the texels a filtered sample covers, per channel (Metal 26). Pokémon Legends: Z-A builds its depth pyramid with a min sampler
// (151607c7a92386cc reads the level above at an explicit LOD) and tests occlusion boxes against it; averaged, the pyramid is nearer than the scene at depth edges. Metal ignores the reduction
@@ -7195,8 +7190,25 @@ static int dm_trilinear(void) {
if (t) { g_sview_w[sid] = (void *)CFBridgingRetain(t); g_srid_w[sid] = t.gpuResourceID._impl; memcpy(g_sbk[sid], k, sizeof k); }
static int nlog; if (nlog++ < 16) MLOG("sampler ID %d: border colour %g,%g,%g,%g, which Metal lacks: Metal colour %d, corrected in the shaders through a twin of colour %d", sid, p.border[0], p.border[1], p.border[2], p.border[3], bn, bw);
}
+ if (s && af > d.maxAnisotropy) { // the raised variant, which samp_aniso hands out per binding (the twin keeps the game's value)
+ d.borderColor = (MTLSamplerBorderColor)bn; d.maxAnisotropy = af; id<MTLSamplerState> a = [g_dev newSamplerStateWithDescriptor:d];
+ if (a) { g_sview_a[sid] = (void *)CFBridgingRetain(a); g_srid_a[sid] = a.gpuResourceID._impl; }
+ }
return s;
}
+// DM_ANISO: whether sampler sid, sampled together with texture tid (one combined handle), takes its raised variant: only where the texture's view is 2D or a 2D array with
+// more than one level (aniso_tex_ok, sampler_aniso.h; the levels as tex_by_id counts them, at most those a texture of its size has). A texture of one level sampled through a raised
+// state spreads its extra samples across level 0 wherever a shader's coordinates jump within a pixel quad: Breath of the Wild's anti-aliasing pass found its edges wrong and the
+// picture turned jagged. DM_NVN_ANISO=0 binds no raised state, =ab with DM_AB alternates them by phase (cost and picture in one run). Caller holds g_rmu, after samp_fast(sid)
+static inline int samp_aniso(int sid, int tid) {
+ if (sid <= 0 || sid >= g_nsreg || !g_srid_a[sid] || tid <= 0 || tid >= g_ntreg || !g_treg[tid].ok) return 0;
+ static int mode = -1; if (mode < 0) mode = sw_mode("DM_NVN_ANISO", 1); // g_rmu serializes the first call
+ if (!sw_on(mode)) return 0;
+ const treg_t *r = &g_treg[tid]; int target = r->has_v && r->v.set_target ? r->v.target : r->t.d.target;
+ unsigned tl = r->t.d.levels, cap = aniso_level_cap(r->t.d.width, r->t.d.height); if (tl > cap) tl = cap;
+ unsigned levels = aniso_view_levels(tl, r->has_v && r->v.set_levels, r->has_v ? r->v.base_level : 0, r->has_v ? r->v.nlevels : 0);
+ return aniso_tex_ok(target == NVN_TEXTURE_TARGET_2D || target == NVN_TEXTURE_TARGET_2D_ARRAY, levels);
+}
static inline __attribute__((always_inline)) void *samp_fast(int sid) {
if (sid > 0 && sid < g_nsreg && g_sreg_ok[sid] && g_sview[sid]) return g_sview[sid];
return (__bridge void *)samp_by_id(sid);
@@ -11566,10 +11578,13 @@ static int encode_args_(id<MTLCommandEncoder> en, NvShader *sh, int nvn_stage, i
} else if (b->kind == NVN_RB_SAMP || b->kind == NVN_RB_SAMPT || b->kind == NVN_RB_SAMPU || b->kind == NVN_RB_SAMPI) { // SAMPT: the sampler part of a combined handle (texture ID | sampler ID << 20); SAMPU: the same, with the handle in a uniform buffer
int sid = bind_sid(nvn_stage, b);
__unsafe_unretained id<MTLSamplerState> ss = sid ? (__bridge id<MTLSamplerState>)samp_fast(sid) : nil;
+ // the texture of the same handle (SAMPT, SAMPU): DM_ANISO's variant where it has mips; a separate or constant sampler (SAMP, SAMPI) has no texture of its own and keeps the game's value
+ int htid = !(ss && sid < g_nsreg && g_srid_a[sid]) ? 0 : b->kind == NVN_RB_SAMPU ? ubo_tex_id(ubo_bind_handle(nvn_stage, b)) : b->kind == NVN_RB_SAMPT && reg < NTEX ? (int)(S.tex[nvn_stage][reg] & 0xfffff) : 0;
if (b->bw && ss && g_sview_w[sid]) { // a twin (dmsh_rewrite.py border_emu) of a sampler whose border colour Metal lacks: the shader corrects its samples
ss = (__bridge id<MTLSamplerState>)g_sview_w[sid]; slots[aid] = g_srid_w[sid];
bmask |= 1u << (b->bw - 1); memcpy(bk[b->bw - 1], g_sbk[sid], sizeof bk[0]);
- } else slots[aid] = sid && sid < g_nsreg && g_srid[sid] ? g_srid[sid] : dummy_samp_rid(); // a twin of any other sampler is never sampled
+ } else if (ss && samp_aniso(sid, htid)) { ss = (__bridge id<MTLSamplerState>)g_sview_a[sid]; slots[aid] = g_srid_a[sid]; }
+ else slots[aid] = sid && sid < g_nsreg && g_srid[sid] ? g_srid[sid] : dummy_samp_rid(); // a twin of any other sampler is never sampled
USE(ss ? ss : dummy_samp(), MTLResourceUsageRead);
if (bl && sid > 0) { int ok = sid < g_nsreg && g_sreg_ok[sid]; samp_par sp = ok ? g_sreg[sid] : (samp_par){0}; // g_rmu is already held in this section
if (ok) PD("B %llu st%d samp reg%d sid=%d mag=%d min=%d (0 nearest / 1 linear; 2–5 with mips) wrap=%d,%d,%d border=%g,%g,%g,%g lod=%g..%g bias=%g aniso=%g cmp=%d/%d %s", g_stat_pass, nvn_stage, reg, sid, (int)sp.magf, (int)sp.minf,
diff --git a/dm/gfx/nvn/sampler_aniso.h b/dm/gfx/nvn/sampler_aniso.h
new file mode 100644
index 00000000..ce6da7c2
--- /dev/null
+++ b/dm/gfx/nvn/sampler_aniso.h
@@ -0,0 +1,46 @@
+// Anisotropic filtering raised for the game's textures (DM_ANISO, a launcher setting; pure functions, unit test tests/t_aniso.c). Off, the default, every sampler state
+// takes the game's own anisotropy (clamped to Metal's 1 to 16). With DM_ANISO=<2..16> each graphics layer (NVN samp_by_id, Vulkan vkCreateSampler, GL tex_sampler) also gets a
+// raised state, by aniso_for, for a sampler that filters linearly in both directions, has a mip filter and the regular LOD range (minimum 0, maximum at least 1), or one the game
+// already gave anisotropy, and binds it only with a 2D or 2D-array texture whose view has more than one level (aniso_tex_ok; NVN samp_aniso, Vulkan's combined image samplers,
+// GL's per-texture state). A texture read at one level, through a one-level texture or a sampler clamped to level 0, spreads the extra samples across that level wherever a
+// shader's coordinates jump within a pixel quad: Breath of the Wild's anti-aliasing pass then found its edges wrong and the picture turned jagged (yuzu gates its anisotropy on the
+// same LOD range). Samplers with a depth comparison, a min / max reduction or unnormalized coordinates, and samplers bound apart from their texture (NVN separate samplers, pools
+// and arrays; Vulkan separate samplers), keep the game's value; samples at an explicit level (textureLod, compute shaders) are never anisotropic
+#pragma once
+#include <stdio.h>
+#include <stdlib.h>
+
+enum { ANISO_MIP_NONE, ANISO_MIP_NEAREST, ANISO_MIP_LINEAR };
+static inline unsigned aniso_clamp(float v) { return !(v >= 1) ? 1 : v > 16 ? 16 : (unsigned)v; } // NaN and values below 1 give 1
+// setting: DM_ANISO (0 off, else 2 to 16); game: the anisotropy the game set; mip: ANISO_MIP_*; lod_min, lod_max: the sampler's LOD clamp; excluded: non-zero for a depth
+// comparison, a min / max reduction or unnormalized coordinates
+static inline unsigned aniso_rule(unsigned setting, float game, int min_linear, int mag_linear, int mip, float lod_min, float lod_max, int excluded) {
+ unsigned g = aniso_clamp(game);
+ if (setting < 2 || excluded) return g;
+ int mips = mip != ANISO_MIP_NONE && lod_min <= 0 && lod_max >= 1; // a sampler clamped to level 0 reads one level, as a one-level texture does
+ return (min_linear && mag_linear && mips) || g > 1 ? (g > setting ? g : setting) : g;
+}
+// The levels a texture view exposes (NVN tex_by_id's rule): from its base level to the end of the texture when it sets no count or 0, cut to the levels the texture has
+static inline unsigned aniso_view_levels(unsigned tex_levels, int set_levels, unsigned base, unsigned n) {
+ if (!set_levels) return tex_levels;
+ if (base >= tex_levels) return 0;
+ unsigned left = tex_levels - base; return n && n < left ? n : left;
+}
+// The levels a w x h texture can have (Metal makes no more): 1 + floor(log2(max(w, h)))
+static inline unsigned aniso_level_cap(unsigned w, unsigned h) { unsigned m = w > h ? w : h, n = 1; while (m > 1) { m >>= 1; n++; } return n; }
+// Whether a raised state may be bound with a texture: a 2D or 2D-array view with more than one level
+static inline int aniso_tex_ok(int is_2d, unsigned levels) { return is_2d && levels > 1; }
+// DM_ANISO, read once: 0 when unset, 0 or 1 (off); 2 to 16 samples; anything else is red and off
+static inline unsigned aniso_setting(void) {
+ static int v = -1;
+ if (v < 0) {
+ const char *e = getenv("DM_ANISO"); char *end = NULL; long n = e && *e ? strtol(e, &end, 10) : 0; int s = 0;
+ if (e && *e && (*end || n < 0 || n > 16)) fprintf(stderr, "[dm] [RED] DM_ANISO=%s: 0 (off) or 2 to 16; off\n", e);
+ else if (n >= 2) { s = (int)n; fprintf(stderr, "[dm] anisotropic filtering (DM_ANISO): %dx for linear samplers of textures with mips (once for each graphics layer)\n", s); }
+ v = s; // a race of two first readers stores the same value; each translation unit that includes this header has its own copy, so a layer logs it once
+ }
+ return (unsigned)v;
+}
+static inline unsigned aniso_for(float game, int min_linear, int mag_linear, int mip, float lod_min, float lod_max, int excluded) {
+ return aniso_rule(aniso_setting(), game, min_linear, mag_linear, mip, lod_min, lod_max, excluded);
+}
diff --git a/dm/gfx/tests/Makefile b/dm/gfx/tests/Makefile
index 6b54fa20..f9f12431 100644
--- a/dm/gfx/tests/Makefile
+++ b/dm/gfx/tests/Makefile
@@ -80,6 +80,8 @@ t_hmap: t_hmap.c ../nvn/nvn_hmap.h
clang -O1 -Wall -o $@ t_hmap.c
t_cover: t_cover.c ../nvn/nvn_cover.h
clang -O1 -Wall -o $@ t_cover.c
+t_aniso: t_aniso.c ../nvn/sampler_aniso.h
+ clang -O1 -Wall -Werror -o $@ t_aniso.c
t_pace: t_pace.c ../nvn/nvn_pace.h
clang -O1 -Wall -o $@ t_pace.c
t_timestamp: t_timestamp.c ../nvn/nvn_timestamp.h
diff --git a/dm/gfx/tests/t_aniso.c b/dm/gfx/tests/t_aniso.c
new file mode 100644
index 00000000..733ef790
--- /dev/null
+++ b/dm/gfx/tests/t_aniso.c
@@ -0,0 +1,82 @@
+// Unit tests for the anisotropy of the game's sampler states (sampler_aniso.h, DM_ANISO): which samplers the setting raises, which keep the game's value, the LOD range,
+// the clamp to Metal's 1 to 16, the texture gate (a view's levels as tex_by_id counts them, the levels a texture's size allows, 2D only), and the switch's parsing (each case in a
+// child process, since the setting is read once)
+#include "../nvn/sampler_aniso.h"
+#include <stdio.h>
+#include <string.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+static int fail, total;
+static void t(const char *name, unsigned want, unsigned got) {
+ total++; fail += want != got;
+ printf("%-72s expected %2u, got %2u %s\n", name, want, got, want == got ? "✓" : "✗");
+}
+static unsigned setting_of(const char *v) { // aniso_setting() in a child with DM_ANISO=v (NULL: unset)
+ int fd[2]; if (pipe(fd)) return 99;
+ pid_t pid = fork();
+ if (pid == 0) {
+ if (v) setenv("DM_ANISO", v, 1); else unsetenv("DM_ANISO");
+ unsigned s = aniso_setting(); if (write(fd[1], &s, sizeof s) != sizeof s) _exit(1); _exit(0);
+ }
+ unsigned s = 99; close(fd[1]); if (read(fd[0], &s, sizeof s) != sizeof s) s = 99; close(fd[0]); waitpid(pid, NULL, 0);
+ return s;
+}
+int main(void) {
+ enum { N = ANISO_MIP_NONE, MN = ANISO_MIP_NEAREST, ML = ANISO_MIP_LINEAR };
+ const float L0 = 0, L1 = 1000; // the default LOD range (NVN -1000..1000 starts at or below 0)
+ volatile float nan = 0.f; nan = nan / nan; // a NaN the compiler cannot fold
+ // Off: the game's value, clamped
+ t("off: trilinear 1x keeps 1x", 1, aniso_rule(0, 1, 1, 1, ML, L0, L1, 0));
+ t("off: game 4x keeps 4x", 4, aniso_rule(0, 4, 1, 1, ML, L0, L1, 0));
+ t("off: game 0 (never set) is 1x", 1, aniso_rule(0, 0, 1, 1, ML, L0, L1, 0));
+ t("off: game 32x is clamped to 16x", 16, aniso_rule(0, 32, 1, 1, ML, L0, L1, 0));
+ t("off: game NaN is 1x", 1, aniso_rule(0, nan, 1, 1, ML, L0, L1, 0));
+ t("setting 1 is off", 1, aniso_rule(1, 1, 1, 1, ML, L0, L1, 0));
+ // On: linear samplers with mips and the regular LOD range, and samplers the game gave anisotropy
+ t("16x: trilinear 1x is raised", 16, aniso_rule(16, 1, 1, 1, ML, L0, L1, 0));
+ t("16x: trilinear 1x with NVN's default LOD range (-1000..1000) is raised", 16, aniso_rule(16, 1, 1, 1, ML, -1000, 1000, 0));
+ t("8x: trilinear 1x is raised to 8x", 8, aniso_rule(8, 1, 1, 1, ML, L0, L1, 0));
+ t("8x: the game's 16x is kept (never lowered)", 16, aniso_rule(8, 16, 1, 1, ML, L0, L1, 0));
+ t("16x: linear sampler with a nearest mip filter is raised", 16, aniso_rule(16, 1, 1, 1, MN, L0, L1, 0));
+ t("16x: nearest minification with a nearest mip filter keeps 1x", 1, aniso_rule(16, 1, 0, 1, MN, L0, L1, 0));
+ t("16x: linear sampler without mips keeps 1x", 1, aniso_rule(16, 1, 1, 1, N, L0, L1, 0));
+ t("16x: nearest minification keeps 1x", 1, aniso_rule(16, 1, 0, 1, ML, L0, L1, 0));
+ t("16x: nearest magnification keeps 1x", 1, aniso_rule(16, 1, 1, 0, ML, L0, L1, 0));
+ t("16x: trilinear clamped to level 0 (max LOD 0) keeps 1x", 1, aniso_rule(16, 1, 1, 1, ML, 0, 0, 0));
+ t("16x: trilinear with max LOD 0.25 (Vulkan's GL-style no mips) keeps 1x", 1, aniso_rule(16, 1, 1, 1, ML, 0, 0.25f, 0));
+ t("16x: trilinear with min LOD 2 keeps 1x", 1, aniso_rule(16, 1, 1, 1, ML, 2, 1000, 0));
+ t("16x: trilinear with max LOD exactly 1 is raised", 16, aniso_rule(16, 1, 1, 1, ML, 0, 1, 0));
+ t("16x: game 4x, nearest filters, no mips: raised (the game asked for it)", 16, aniso_rule(16, 4, 0, 0, N, L0, L1, 0));
+ t("16x: game 2x, linear without mips: raised (the game asked for it)", 16, aniso_rule(16, 2, 1, 1, N, L0, L1, 0));
+ t("16x: game 2x clamped to level 0: raised (the game asked for it)", 16, aniso_rule(16, 2, 1, 1, ML, 0, 0, 0));
+ t("16x: excluded (comparison, reduction or unnormalized) keeps the game's 1x", 1, aniso_rule(16, 1, 1, 1, ML, L0, L1, 1));
+ t("16x: excluded keeps the game's 4x", 4, aniso_rule(16, 4, 1, 1, ML, L0, L1, 1));
+ // The texture gate: a view's levels (tex_by_id's rule), the size's cap, 2D only
+ t("view: no level range set: all 8 levels", 8, aniso_view_levels(8, 0, 3, 1));
+ t("view: levels 2 + 3 of 8", 3, aniso_view_levels(8, 1, 2, 3));
+ t("view: levels 0 + 0 of 8 (0 = to the end)", 8, aniso_view_levels(8, 1, 0, 0));
+ t("view: levels 5 + 0 of 8 (0 = to the end)", 3, aniso_view_levels(8, 1, 5, 0));
+ t("view: levels 7 + 2 of 8 are cut to 1", 1, aniso_view_levels(8, 1, 7, 2));
+ t("view: base level at the texture's level count: 0", 0, aniso_view_levels(8, 1, 8, 1));
+ t("view: base level past the texture's levels: 0", 0, aniso_view_levels(8, 1, 9, 1));
+ t("level cap: 1600x900 has 11 levels", 11, aniso_level_cap(1600, 900));
+ t("level cap: 1x1 has 1 level", 1, aniso_level_cap(1, 1));
+ t("level cap: 256x2 has 9 levels", 9, aniso_level_cap(256, 2));
+ t("texture gate: 2D with 8 levels", 1, aniso_tex_ok(1, 8));
+ t("texture gate: 2D with 1 level", 0, aniso_tex_ok(1, 1));
+ t("texture gate: 2D view of 0 levels", 0, aniso_tex_ok(1, 0));
+ t("texture gate: not 2D (cube, 3D) with 8 levels", 0, aniso_tex_ok(0, 8));
+ // The switch
+ t("DM_ANISO unset is off", 0, setting_of(NULL));
+ t("DM_ANISO= (empty) is off", 0, setting_of(""));
+ t("DM_ANISO=0 is off", 0, setting_of("0"));
+ t("DM_ANISO=1 is off", 0, setting_of("1"));
+ t("DM_ANISO=4", 4, setting_of("4"));
+ t("DM_ANISO=16", 16, setting_of("16"));
+ t("DM_ANISO=17 is red and off", 0, setting_of("17"));
+ t("DM_ANISO=-2 is red and off", 0, setting_of("-2"));
+ t("DM_ANISO=16x is red and off", 0, setting_of("16x"));
+ printf("anisotropy: %d checks, %d failed\n", total, fail);
+ return fail != 0;
+}
diff --git a/dm/gfx/vk/hle_vk.m b/dm/gfx/vk/hle_vk.m
index f29743af..f871ad9d 100644
--- a/dm/gfx/vk/hle_vk.m
+++ b/dm/gfx/vk/hle_vk.m
@@ -16,6 +16,7 @@
#define VK_NO_PROTOTYPES
#include "../../host/hle.h"
#include "../nvn/nvn_mtl.h"
+#include "../nvn/sampler_aniso.h"
#include <vulkan/vulkan_core.h>
#include <vulkan/vulkan_vi.h>
#import <Metal/Metal.h>
@@ -196,7 +197,7 @@ static void dev_init_once(void) {
VkDeviceMemory cmem; VkDeviceSize coff; uint8_t *shadow; // a linear image of a converted format (fmt_t.conv): its memory, and the texels last unpacked
int swap; }; // one of a swap chain's images: the swap chain owns it
struct VkImageView_T { __strong id<MTLTexture> tex; VkImage img; };
-struct VkSampler_T { __strong id<MTLSamplerState> s; };
+struct VkSampler_T { __strong id<MTLSamplerState> s, a; }; // a: the variant with the anisotropy DM_ANISO raises it to (nil: none; sampler_aniso.h), for combined image samplers whose image has mips
struct VkShaderModule_T { const shinfo *si; __strong id<MTLFunction> fn, fn_d; char key[17]; int tried_d; }; // fn_d: the dual-source variant vk_<key>_d, looked up on first use
struct VkPipelineCache_T { int unused; };
// Query pool: a result is valid once the submit that wrote it has completed (g_done >= ticket). Timestamps are the completion time of their submit (in ns,
@@ -214,7 +215,7 @@ static void dev_init_once(void) {
// used to point at this layer's view / sampler / buffer structs, and Super Mario Galaxy 2 crashed reading a freed view's texture from element 1 of its 8-texture array
// when the ship took off after its first galaxy (GitHub issue 68). buf / off: the buffer's memory and its offset there plus the descriptor's; tex: an image view's
// texture or a texel buffer's
-typedef struct { __strong id<MTLBuffer> buf; VkDeviceSize off; __strong id<MTLTexture> tex; __strong id<MTLSamplerState> smp; } desc_t;
+typedef struct { __strong id<MTLBuffer> buf; VkDeviceSize off; __strong id<MTLTexture> tex; __strong id<MTLSamplerState> smp, smp_a; } desc_t; // smp_a: the sampler's raised variant (VkSampler_T a)
struct VkDescriptorPool_T { struct VkDescriptorSet_T *sets; };
struct VkDescriptorSet_T { VkDescriptorSetLayout L; VkDescriptorPool pool; struct VkDescriptorSet_T *prev, *next; desc_t *d; }; // d: L->total descriptors (ARC objects: no flexible array)
struct VkDescriptorUpdateTemplate_T { uint32_t n; VkDescriptorUpdateTemplateEntry e[]; };
@@ -698,7 +699,10 @@ static MTLSamplerAddressMode addr_mode(VkSamplerAddressMode m) {
sd.magFilter = ci->magFilter == VK_FILTER_LINEAR ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest;
sd.mipFilter = ci->mipmapMode == VK_SAMPLER_MIPMAP_MODE_LINEAR ? MTLSamplerMipFilterLinear : MTLSamplerMipFilterNearest;
sd.sAddressMode = addr_mode(ci->addressModeU); sd.tAddressMode = addr_mode(ci->addressModeV); sd.rAddressMode = addr_mode(ci->addressModeW);
- sd.maxAnisotropy = ci->anisotropyEnable ? (NSUInteger)fminf(fmaxf(ci->maxAnisotropy, 1), 16) : 1;
+ sd.maxAnisotropy = aniso_clamp(ci->anisotropyEnable ? ci->maxAnisotropy : 1);
+ unsigned af = aniso_for(ci->anisotropyEnable ? ci->maxAnisotropy : 1, ci->minFilter == VK_FILTER_LINEAR, ci->magFilter == VK_FILTER_LINEAR, // DM_ANISO (sampler_aniso.h)
+ ci->mipmapMode == VK_SAMPLER_MIPMAP_MODE_LINEAR ? ANISO_MIP_LINEAR : ANISO_MIP_NEAREST, ci->minLod, ci->maxLod, // maxLod 0 or 0.25: GL's "no mips" (excluded)
+ ci->compareEnable || ci->unnormalizedCoordinates); // Vulkan forbids anisotropy with unnormalized coordinates
if (ci->compareEnable) sd.compareFunction = (MTLCompareFunction)ci->compareOp; // VkCompareOp and MTLCompareFunction share their values
sd.borderColor = ci->borderColor >= VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE ? MTLSamplerBorderColorOpaqueWhite :
ci->borderColor >= VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK ? MTLSamplerBorderColorOpaqueBlack : MTLSamplerBorderColorTransparentBlack;
@@ -706,12 +710,13 @@ static MTLSamplerAddressMode addr_mode(VkSamplerAddressMode m) {
sd.normalizedCoordinates = !ci->unnormalizedCoordinates;
sd.lodBias = fminf(fmaxf(ci->mipLodBias, -15), 15); // Metal 26's sampler bias; the device reports maxSamplerLodBias 15
VkSampler s = zalloc(sizeof *s); s->s = [g_dev newSamplerStateWithDescriptor:sd];
+ if (af > sd.maxAnisotropy) { sd.maxAnisotropy = af; s->a = [g_dev newSamplerStateWithDescriptor:sd]; }
if (!s->s) LOG("[vk] [RED] cannot create the sampler");
*out = s;
}
return VK_SUCCESS;
}
-VKB(vkDestroySampler, void, VkDevice d, VkSampler s, const VkAllocationCallbacks *a) { (void)d; (void)a; if (s) { s->s = nil; free(s); } }
+VKB(vkDestroySampler, void, VkDevice d, VkSampler s, const VkAllocationCallbacks *a) { (void)d; (void)a; if (s) { s->s = nil; s->a = nil; free(s); } }
// ---------- Descriptor sets ----------
static int is_dyn(VkDescriptorType t) { return t == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC || t == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC; }
@@ -774,7 +779,7 @@ static void set_free(VkDescriptorSet s) {
VkDescriptorSetLayout L = ai->pSetLayouts[i];
VkDescriptorSet s = zalloc(sizeof *s); s->d = zalloc(umax(1, L->total) * sizeof(desc_t));
s->L = L; s->pool = ai->descriptorPool; s->next = s->pool->sets; if (s->next) s->next->prev = s; s->pool->sets = s; set_live(s, 1);
- if (L->imm) for (uint32_t k = 0; k < L->total; k++) s->d[k].smp = L->imm[k] ? L->imm[k]->s : nil;
+ if (L->imm) for (uint32_t k = 0; k < L->total; k++) { s->d[k].smp = L->imm[k] ? L->imm[k]->s : nil; s->d[k].smp_a = L->imm[k] ? L->imm[k]->a : nil; }
out[i] = s;
}
return VK_SUCCESS;
@@ -792,8 +797,8 @@ static void set_free(VkDescriptorSet s) {
}
static void desc_write(desc_t *e, const lbind *lb, VkDescriptorType t, const VkDescriptorImageInfo *ii, const VkDescriptorBufferInfo *bi, const VkBufferView *bv) {
switch (t) {
- case VK_DESCRIPTOR_TYPE_SAMPLER: if (!lb->imm) e->smp = ii->sampler ? ii->sampler->s : nil; break;
- case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: e->tex = ii->imageView ? ii->imageView->tex : nil; if (!lb->imm) e->smp = ii->sampler ? ii->sampler->s : nil; break;
+ case VK_DESCRIPTOR_TYPE_SAMPLER: if (!lb->imm) { e->smp = ii->sampler ? ii->sampler->s : nil; e->smp_a = ii->sampler ? ii->sampler->a : nil; } break;
+ case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: e->tex = ii->imageView ? ii->imageView->tex : nil; if (!lb->imm) { e->smp = ii->sampler ? ii->sampler->s : nil; e->smp_a = ii->sampler ? ii->sampler->a : nil; } break;
case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: e->tex = ii->imageView ? ii->imageView->tex : nil; break;
case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: e->tex = *bv ? bview_tex(*bv) : nil; break;
case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: {
@@ -1333,7 +1338,10 @@ static void bind_res(rs_t *s, const shinfo *si, int frag) {
case 't': case 'c': {
if (!e->tex) { RED1("shader %s: texture %u.%u[%u] is empty", si->key, r->set, r->binding, k); break; }
if (frag) [re setFragmentTexture:e->tex atIndex:slot]; else [re setVertexTexture:e->tex atIndex:slot];
- if (r->kind == 'c' && e->smp) { if (frag) [re setFragmentSamplerState:e->smp atIndex:slot]; else [re setVertexSamplerState:e->smp atIndex:slot]; }
+ // DM_ANISO's variant only where the image has mips and is 2D or a 2D array: a one-level image sampled through it spreads its extra samples across
+ // level 0 wherever coordinates jump within a pixel quad (sampler_aniso.h); a separate sampler ('s') has no image of its own and keeps the game's value
+ id<MTLSamplerState> smp = e->smp_a && aniso_tex_ok(e->tex.textureType == MTLTextureType2D || e->tex.textureType == MTLTextureType2DArray, (unsigned)e->tex.mipmapLevelCount) ? e->smp_a : e->smp;
+ if (r->kind == 'c' && smp) { if (frag) [re setFragmentSamplerState:smp atIndex:slot]; else [re setVertexSamplerState:smp atIndex:slot]; }
break;
}
case 's':
diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv
index b8932008..36803ad3 100644
--- a/docs/env_switches.tsv
+++ b/docs/env_switches.tsv
@@ -3,7 +3,7 @@ DM_AB diagnostic `=<frames>` splits the run into phases of that many frames and
DM_ALIAS_SIZE diagnostic `=<bytes>` gives the guest an alias region of that size instead of the platform's, which is at least the Switch's 64 GB on the Mac and the profile's `mem_alias` on an iPhone (at least 256 MB, whole host pages; the heap and stacks stay as they are): the profile's value reproduces an iPhone's address space on the Mac, as the NSP script's heap check does; its address region check sets 64 GB (Mac only: an iPhone has no room)
DM_ALIAS_WINDOWS diagnostic `=<MB>` logs every 30 s how much of each window of that size in the alias region is mapped (windows aligned to their size in absolute addresses)
DM_ALLOW_OTHER_METAL switch `1` lets `own_compilers.py` build the shader libraries with a Metal compiler other than the one in `dmsh_chain.lock` (it stops otherwise, GitHub issue #242); the NSP script sets it for `--allow-other-metal`
-DM_ANISO player `=2`..`16` raises every sampler the game creates to at least that anisotropy; `0` (the default) keeps what the game asked for
+DM_ANISO player `=<2..16>` raises the anisotropic filtering of the game's linear samplers with mips and the regular LOD range, and of those it gave anisotropy, to at least that many samples where they read a 2D texture with mip levels (NVN, Vulkan and GL; `sampler_aniso.h`); `0`, the default, keeps the game's own ([reference](reference/rendering.md#anisotropic-filtering-raised-for-the-games-samplers))
DM_AOC_DIR path Folder of add-on content: one numbered subfolder per DLC index holding that DLC's RomFS, reported by `aoc` and mounted read-only; the app, the Mac launcher and the NSP script set it when the build has DLC
DM_AOC_OWNED switch `0` reports no add-on content even when `DM_AOC_DIR` has some, for runs without the DLC
DM_APP_DM path Set by the iOS app of a game of several programs: the running program's `dm/p<N>` folder, where the settings screen finds its `launcher.json`
@@ -124,6 +124,7 @@ DM_NRO switch `0` turns off loading of the NRO modules the game's NRR files regi
DM_NRO_CAPTURE diagnostic folder: a `nn::ro::LoadModule` with no rewritten copy writes the image to `<folder>/<SHA-256>.nro` and ends the run (the NSP script's capture of an NRO the game decodes at run time)
DM_NRO_DIR path folder of NROs the shader split reads like `main`, and in which it finds a CRA archive's file table (the NSP script sets it for a captured NRO)
DM_NVN_ALLOCPROF diagnostic `=1` charges Metal allocation growth to each replayed op type and function, and logs command allocator sizes and each new texture (serial, size, format, storage); `=2` also gives each main submission a fresh command allocator and reports command memory by operation, by encoder, by submission size and the indirect-count multi-draws encoded
+DM_NVN_ANISO diagnostic With `DM_ANISO` set: `0` binds none of the raised sampler states in the NVN layer, `ab` (with `DM_AB=<frames>`) alternates them by phase, to compare cost and picture in one run ([reference](reference/rendering.md#anisotropic-filtering-raised-for-the-games-samplers))
DM_NVN_API switch `=<major>.<minor>` overrides the NVN API version `nvnDeviceGetInteger` reports (by default decided by the SDK version or the profile's `device_api`: 55.15 for SDK 11 and later, 53.313 before)
DM_NVN_BARRIER switch How draw passes are ordered: `full` (default) waits for all earlier GPU work, `game` only for the previous pass's fragment stage unless the game set a barrier, `ab` alternates with the `DM_AB` phases
DM_NVN_BC_ALIAS diagnostic Set 0 to send copies to an uncompressed alias instead of its block-compressed storage, for an A/B check; default 1 |
|
The second commit, the docs: 0002-docs-anisotropic-filtering-per-binding-measured-in-Breath-of-the-Wild.patchFrom 4300af16b8e22b35919526cda92d86142aa208f6 Mon Sep 17 00:00:00 2001
From: CatPawPrint <[email protected]>
Date: Sat, 14 Nov 2026 03:58:05 +0800
Subject: [PATCH 2/2] docs: anisotropic filtering per binding, measured in
Breath of the Wild
The settings page's Anisotropic filtering section now says which
textures the setting reaches: a 2D texture or 2D array with more than
one mip level, read through a linear sampler with mips and the regular
level range, or one the game already gave anisotropy, in all three
graphics layers. It says why one-level textures and samplers clamped
to the first level keep the game's value (Breath of the Wild's
silhouettes turned jagged), why shadow maps and depth pyramids do (the
shadow cascade line reported in PR #335), that a game binding its
textures apart from their samplers sees no change, the cost measured
on a Mac, and where the setting is on the Mac. Trilinear filtering is
unchanged.
The rendering reference gets an entry (Symptom, Cause, Fix, Not
covered, Measuring, Found on, Check) for the rule, Breath of the Wild's
note a section with its samplers, the binds, the cost (GPU p50 6.60 ms
off, 6.59 ms on, M5 Max, one run with DM_NVN_ANISO=ab), the picture,
the shadow cascade line and what is open, and dm/gfx/README.md a line
for DM_ANISO. The symptom index is regenerated.
---
dm/games/01007EF00011E000/README.md | 12 ++++++++++++
dm/gfx/README.md | 1 +
docs/agents/symptoms.md | 1 +
docs/reference/rendering.md | 10 ++++++++++
docs/settings.md | 8 +++++---
5 files changed, 29 insertions(+), 3 deletions(-)
diff --git a/dm/games/01007EF00011E000/README.md b/dm/games/01007EF00011E000/README.md
index 81333214..13d9588d 100644
--- a/dm/games/01007EF00011E000/README.md
+++ b/dm/games/01007EF00011E000/README.md
@@ -107,6 +107,17 @@ A screen taller than 16:9 (the iPhone Duo's, about 1.43:1) gets a picture of its
Checked on a Mac (M-series, macOS 27, headless with a Master Mode save) against the same routes at 16:9: the map and footprint mode at four zoom levels (every region of the trail at 0 offset), the inventory, system and options pages, the album and compendium, the weapon wheels, the scope (zoomed), the camera rune with its shutter and save prompt, a memory cutscene with subtitles, the Adventure Log, the map's sensor settings, fast travel, loading screens and a shrine. A photo taken at 1.43 now matches the 16:9 photo at scale 1.0 (it needed a 1.24 stretch). An NPC's dialog box (Kakariko Village, a save of an iPhone Duo player standing by an NPC) was checked on the Mac at 1.43 after the dark band at its bottom was reported from the phone: the box is now as dark below the 720 space's edge as above it, and the blurred scene in it lines up with the scene around it. Earlier builds of this ran on an iPhone Duo (iOS 27.1). Not seen in game: shops (their layouts were checked against the rules only) and a compendium registration photo. The taller picture renders about a quarter more pixels.
+### Anisotropic filtering
+
+The game asks for almost no anisotropic filtering. Of the first 50 samplers it makes, entering the Great Plateau, 11 are trilinear (10 at 1x, one at 2x), 22 bilinear with a nearest mip filter, 6 linear without mips, 10 nearest and one a depth comparison, all at 1x. It binds every texture through combined handles (`NVN_RB_SAMPT`), so the host knows the texture each sampler reads. [`DM_ANISO=16`](../../../docs/reference/rendering.md#anisotropic-filtering-raised-for-the-games-samplers) is checked on the Mac (M5 Max, render scale 0.95 to hold the resolution, by the Temple of Time, 2026-11-03):
+
+- **The anti-aliasing pass needs the mip gate.** Raised for every trilinear sampler regardless of texture, the picture turned jagged everywhere, distant mountain silhouettes included: a sampler of the anti-aliasing pass reads a one-level texture. With the raised state bound only to textures with mips, the edges are smooth again.
+- **Binds:** in about 75 s of play, 17.6 million combined-handle sampler binds took the raised state, 15.2 million kept the game's because their texture has one level or is not 2D, and 5.2 million were outside the rule (nearest, no mips, comparison). Counted with a temporary counter, not kept, before the LOD range and the view-level rule were added to the gate.
+- **Cost:** none measurable. With the raised states alternating in one run (`DM_ANISO=16 DM_NVN_ANISO=ab DM_AB=60`), 12 phases each: GPU p50 6.60 ms off, 6.59 ms on; mean 8.45 and 8.47 ms. Frame time stayed at 16.7 ms.
+- **Picture:** a small change at 1520x855. Grass covers most of the ground there, and the rock faces in view are seen nearly head-on. The dirt patches at mid distance show slightly more detail. Separate runs cannot be compared pixel by pixel (clouds, wind and the time of day differ between runs), so the A/B frames came from one run.
+- **Comparison samplers keep the game's value.** Raised, they drew a line along a shadow cascade join on open ground (the fields; iPad Pro 13" M4, PR #335), so a depth-comparison sampler is never raised.
+- **Open:** the iPhone (cost and picture), and a view along a bare path or a cliff top, where anisotropic filtering matters most.
+
## Memory
- **Resolved: the world-load crash (about 1 run in 3 on the Mac) came from the host's command record sizes.** About 3 s after Start, a task worker's `operator new` (`main+0x155a79c`) got null and the game wrote through it (`main+0x155a7a4`). Each model file gets a heap of its resource size table entry + 0x1008; the file goes in 4 KB aligned, and the model's setup (`main+0x155a2ac`) takes the rest as a frame heap (vtable `main+0x1d4f950`, head +0xe0, tail +0xe8). Part of the setup is GPU memory for the model's prerecorded commands, sized by recording each mesh's draw and each shape's state for each pass into a scratch command buffer and summing `nvnCommandBufferGetCommandMemoryUsed` (`main+0xf9aeb4`, `main+0xf9bb54`), so the host's record sizes count against the table. Draw records had grown to carry the indirect and multi-draw fields (0x38 → 0x50 per recorded draw on 2026-10-18 and 10-20), and every recording began with an 8-byte BEGIN record. `Obj_TreeConiferous`, `Obj_TreeBroadleaf_B` and `FldObj_HyliaBridge_A-02` then needed one 4 KB page more than their entries allow, which fit only when the file's alignment pad (0 to 0xff8) was small (about 15% of loads each failed; most models have about 0xd00 to spare). Plain draws now leave those fields out and recordings have no BEGIN (0x30 per recorded draw, `nvn_obj.h` `draw_rec`): all 510 models of the world load fit whatever the pad. To check a whole scene, probe where the setup heap is cut (`main+0x155a520` with `!x21`) and the end of the setup (`main+0x155a5f4` with `!x2`) with `DM_PROBE_HEAP=28,38,40,e0,f8 DM_PROBE_HEAPFRAME=1d4f950 DM_PROBE_HEAPWORDS=1`. A model fits any placement when entry + 0x1008 covers the resource heap's header and object (0x310), the file, the frame heap's block header and its peak use, plus 0xff8 of pad.
@@ -234,6 +245,7 @@ General host changes first needed here; each applies to every game:
- **No sound on an iPhone set to silent** (`front_ios_audio_session`): [The ring / silent switch muted the game on iOS](../../../docs/reference/audio.md#the-ring--silent-switch-muted-the-game-on-ios); the device check is open.
- **Resolved: the Mac settings window stayed on screen after Play** (`dm/mac/Launcher.swift`): [The Mac settings window stays on screen after Play](../../../docs/reference/packing.md#the-mac-settings-window-stays-on-screen-after-play).
- **Upscaling in the present** (`fx_encode`, `DM_PRESENT_UPSCALE`): [The present upscales through MetalFX](../../../docs/reference/rendering.md#the-present-upscales-through-metalfx).
+- **Anisotropic filtering on request** (`samp_aniso`, `DM_ANISO`): [Anisotropic filtering raised for the game's samplers](../../../docs/reference/rendering.md#anisotropic-filtering-raised-for-the-games-samplers).
- **Thermal cap; resolved movie recovery and acquire/present races** (`thermal_capped`, `DM_THERMAL_CAP`): [A thermally serious iPhone holds 30 fps](../../../docs/reference/frame-rate.md#a-thermally-serious-iphone-holds-30-fps).
- **Resolved in the host: frame-step recovery after a 30 fps cap**: [The frame step after a 30 fps cap ends](../../../docs/reference/frame-rate.md#the-frame-step-after-a-30-fps-cap-ends). Modelled with the measured iPhone GPU times; recovery on the device has not been observed here.
- **Pipeline keys omit disabled blend factors** (`pso_key_norm`): [Pipeline keys omit unused colour state](../../../docs/reference/shaders.md#pipeline-keys-omit-unused-colour-state).
diff --git a/dm/gfx/README.md b/dm/gfx/README.md
index a1c3db4c..8d72b55b 100644
--- a/dm/gfx/README.md
+++ b/dm/gfx/README.md
@@ -207,6 +207,7 @@ Comparison and testing:
| `DM_NVN_BARRIER=game`, `DM_NVN_CUT` | Pass ordering and segment commits: see [docs/agents/04-graphics.md](../../docs/agents/04-graphics.md) section 7 |
| `DM_PRESENT_HZ=N` | The frequency of presentation pacing (default 60); 0 means no frame limit and is for performance profiling only |
| `DM_PRESENT_UPSCALE=metalfx` or `off` | How the present scales a picture smaller than its rectangle on the screen: `metalfx` through MetalFX's spatial scaler, `off` (the default) bilinearly. An option on both platforms (the iOS launcher's Upscaling; `env.txt` on the Mac); rendering at the screen's resolution stays the reference for sharpness ([reference](../../docs/reference/rendering.md#the-present-upscales-through-metalfx)) |
+| `DM_ANISO=<2..16>` | Raises the anisotropic filtering of the game's linear samplers with mips and the regular LOD range, and of those it gave anisotropy, to at least that many samples where they read a 2D texture with mip levels, in the NVN, Vulkan and GL layers (`sampler_aniso.h`); `0`, the default, keeps the game's own. The launcher's Anisotropic filtering ([reference](../../docs/reference/rendering.md#anisotropic-filtering-raised-for-the-games-samplers)) |
## Known limitations
diff --git a/docs/agents/symptoms.md b/docs/agents/symptoms.md
index ba3e1559..5d0cfa12 100644
--- a/docs/agents/symptoms.md
+++ b/docs/agents/symptoms.md
@@ -757,6 +757,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- a small CPU-filled sparse texture shows part of its image beside fragments, cut off at the bottom (Yoshi's Crafted World's loading icon: the left half of a chalk drawing and two stray strokes). → [Sparse textures smaller than a tile keep the automatic block height](../reference/rendering.md#sparse-textures-smaller-than-a-tile-keep-the-automatic-block-height)
- streamed textures read 0 (magenta on Monster Hunter Rise's title screen's clothes). → [Sparse textures bound from their first mapped level](../reference/rendering.md#sparse-textures-bound-from-their-first-mapped-level)
- textures a mip level sharper or blurrier than on the Switch where the game biases its sampler; in the Vulkan layer, a red line `sampler LOD bias … not implemented`. → [Sampler LOD bias](../reference/rendering.md#sampler-lod-bias)
+- ground and walls seen at a slant blur a few metres from the camera, as on the Switch: the game asks for little or no anisotropic filtering, and the host gave Metal the game's value. → [Anisotropic filtering raised for the game's samplers](../reference/rendering.md#anisotropic-filtering-raised-for-the-games-samplers)
- whatever a game keeps in a texture that it samples past its edge with clamp-to-border reads the wrong value there: grass flattened along Link's path in Tears of the Kingdom, its bend map filled with "bent" wherever the window scrolled. → [Border colours Metal has no sampler state for](../reference/rendering.md#border-colours-metal-has-no-sampler-state-for)
- material pipelines spill registers even when every sampler uses a native Metal border colour. → [Unused border corrections retain sample registers](../reference/rendering.md#unused-border-corrections-retain-sample-registers)
- the process ends at once (the window vanishes), with `-[MTLTextureDescriptorInternal validateWithDevice:]` failing an assertion such as `requests 9 mipmap levels, but the dimensions (1, 1, 1) can only support 1`, or `sampleCount must be > 1 for multisample textures`. → [Texture fields Metal refuses](../reference/rendering.md#texture-fields-metal-refuses)
diff --git a/docs/reference/rendering.md b/docs/reference/rendering.md
index 1489762e..fb1e010e 100644
--- a/docs/reference/rendering.md
+++ b/docs/reference/rendering.md
@@ -300,6 +300,16 @@ The replay on Metal (`dm/gfx/nvn/nvn_mtl.m`) and the Vulkan and OpenGL layers. E
- **Fix:** `samp_by_id` (NVN) and `vkCreateSampler` set it, clamped to that range (Vulkan to the ±15 the device reports as `maxSamplerLodBias`).
- **Found on:** [Super Mario Galaxy](../../dm/games/010099C022B96000/README.md) (the Vulkan red line). MacNativeGames uses the property for its own MetalFX bias, which pointed to it.
+### Anisotropic filtering raised for the game's samplers
+
+- **Symptom:** ground and walls seen at a slant blur a few metres from the camera, as on the Switch: the game asks for little or no anisotropic filtering, and the host gave Metal the game's value.
+- **Cause:** a choice of the game's, made for the Switch's GPU budget, not a host error. The first 50 samplers Breath of the Wild makes ask for 1x but one (2x).
+- **Fix:** `DM_ANISO=<2..16>` (the launcher's **Anisotropic filtering**; off by default on every platform, no profile key; `sampler_aniso.h`). A sampler is raised to at least that value when it filters linearly in both directions, has a mip filter and the regular LOD range (minimum 0, maximum at least 1), or when the game already asked for more than 1x; the raised state is bound only with a 2D or 2D-array texture whose view has more than one level. NVN (`samp_by_id`, `samp_aniso`) and Vulkan (`vkCreateSampler`) keep the game's state and make the raised one beside it, choosing per binding: NVN for combined handles (the texture of the same handle, its view's levels counted as `tex_by_id` counts them), Vulkan for combined image samplers. GL makes one state per texture's parameters with the raised value in its cache key (`tex_sampler`). Bound with a texture read at one level, the raised state broke Breath of the Wild's anti-aliasing: every silhouette turned jagged, because a shader whose coordinates jump within a pixel quad gets its extra samples spread across that level. yuzu gates its anisotropy on the same LOD range ("video_core: Apply AF only to samplers with normal LOD range").
+- **Not covered:** samplers bound apart from their texture (NVN separate samplers, sampler pools and arrays; Vulkan separate samplers) keep the game's value, as do samplers with a depth comparison (raised, a comparison sampler changes which depth texels each comparison averages, and the two sides of a shadow cascade boundary stop agreeing: a line along the join on open ground in Breath of the Wild, reported in PR #335 from an iPad Pro 13" M4), a min / max reduction (its value must stay the extreme of its footprint) or unnormalized coordinates, a sampler whose border-colour twin the shader samples, and a same-pass feedback snapshot that replaces the bound texture (`fb_prepare`). Samples at an explicit level (`textureLod`, compute shaders) are never anisotropic. Each raised sampler is one more argument-buffer sampler state, of which Metal allows a limited number (`maxArgumentBufferSamplerCount`); a game near that limit could then fail to make its own later ones (not seen).
+- **Measuring:** `DM_NVN_ANISO=ab` with `DM_AB=<frames>` alternates the raised states by phase in one run (NVN), so cost and picture are compared in the same scene; `DM_NVN_ANISO=0` binds none.
+- **Found on:** [The Legend of Zelda: Breath of the Wild](../../dm/games/01007EF00011E000/README.md#anisotropic-filtering): its samplers, the anti-aliasing failure and the cost.
+- **Check:** `t_aniso` (the rule for each kind of sampler and LOD range, the clamp, a view's levels and the texture gate, the switch's values).
+
### Border colours Metal has no sampler state for
- **Symptom:** whatever a game keeps in a texture that it samples past its edge with clamp-to-border reads the wrong value there: grass flattened along Link's path in Tears of the Kingdom, its bend map filled with "bent" wherever the window scrolled.
diff --git a/docs/settings.md b/docs/settings.md
index b271e722..a6832a52 100644
--- a/docs/settings.md
+++ b/docs/settings.md
@@ -81,11 +81,13 @@ flowchart LR
How sharp a texture stays when you look along it rather than at it: the ground ahead of you, a wall seen edge on, a road running to the horizon. The games were built for a handheld and nearly all ask for none, so those surfaces blur a short way from the camera.
-**Off**, the default, keeps what the game asked for. **2x** to **16x** raise every texture to at least that, leaving a game that already asks for more alone.
+**Off**, the default, keeps what the game asked for. **2x** to **16x** raise a texture to at least that, leaving a game that already asks for more alone. It works in all three graphics layers (NVN, Vulkan and OpenGL).
- **When to change it:** any game with ground or walls stretching away from the camera. It works in games that have no render scale.
-- **Cost:** a little more GPU time where it applies. Nothing is allocated and no render target changes, so memory is unaffected.
-- **Note:** only mipmapped colour textures are affected. Shadow maps and the depth pyramids a game uses to decide what is visible keep what the game asked for, because filtering those along an angle changes what they mean rather than how they look. **Trilinear filtering** below turns mip blending on for a texture whose mips the game picked nearest.
+- **Which textures:** a 2D texture, or a 2D array, with more than one mip level, read through a linear sampler with mips and the regular level range, or one the game already gave anisotropy. A one-level texture, or a sampler clamped to the first level, keeps the game's value: raised, a one-level texture turned every silhouette in Breath of the Wild jagged, because its anti-aliasing pass reads one that way. Shadow maps and the depth pyramids a game uses to decide what is visible keep what the game asked for too, because filtering those along an angle changes what they mean rather than how they look (a raised shadow sampler drew a line along a shadow cascade join on open ground, reported in PR #335). **Trilinear filtering** below turns mip blending on for a texture whose mips the game picked nearest.
+- **Note:** the choice is made for each texture bound with its sampler. A game that binds its textures apart from their samplers sees no change from this setting.
+- **Cost:** little on a Mac (M5 Max, GPU p50 off → on: Breath of the Wild 6.60 → 6.59 ms, Ocarina of Time 13.67 → 13.77 ms); an iPhone is not measured. Nothing is allocated and no render target changes, so memory is unaffected.
+- **On the Mac:** choose it under **Anisotropic filtering** in the [settings window](#the-mac-settings-window)'s Advanced settings, or set `DM_ANISO=16` in its `env.txt` (off by default).
### Trilinear filtering
|
DM_ANISO raised every mipmapped sampler that is not a comparison or reduction sampler, in samp_by_id, and with it every texture bound through that sampler. Bound with a texture that is read at one level, a raised state spreads its extra samples across that level wherever a shader's coordinates jump within a pixel quad. Breath of the Wild's anti-aliasing pass reads a one-level texture through a trilinear sampler, and with every trilinear sampler raised, every silhouette in the picture turned jagged. The rule is now pure functions in sampler_aniso.h. A sampler is raised when it filters linearly in both directions, has a mip filter and the regular LOD range (minimum 0, maximum at least 1), or when the game already gave it anisotropy; a sampler with a depth comparison, a min / max reduction or unnormalized coordinates keeps the game's value, as before for the first two. samp_by_id keeps the game's state and makes the raised one beside it, and encode_args_ binds it only for a combined handle (SAMPT, SAMPU) whose texture view is 2D or a 2D array with more than one level (samp_aniso). Vulkan does the same for combined image samplers (vkCreateSampler, bind_res), and GL puts the raised value in its per-texture sampler cache key (tex_sampler). Separate samplers, sampler pools and arrays keep the game's value, so a game that binds its samplers apart from its textures gets no change, where the sampler-only rule raised them. DM_ANISO takes 0 or 1 (off) or 2 to 16; anything else is a red line and off. Every value the launcher row offers behaves as before, and the row now shows for Vulkan and GL games too. DM_TRILINEAR, its row and its code are unchanged: a sampler it makes trilinear is judged, and raised, with its new mip filter. DM_NVN_ANISO=0 binds no raised state, and ab with DM_AB alternates them by phase, to compare cost and picture in one run. t_aniso checks the rule for each kind of sampler and LOD range, the clamp, a view's levels, the texture gate and the switch's values (47 checks); no test reaches the call sites (samp_aniso, bind_res, tex_sampler). The host builds with the same warnings as before. On a Mac (M5 Max), Ocarina of Time (NVN) from a save in Link's house: with DM_ANISO unset the picture and the kinds of red lines are those of PR seedds#335's head; DM_ANISO=16 logs the setting once, adds no red line and the edges stay smooth; DM_NVN_ANISO=ab with DM_AB=60 measured GPU p50 13.67 ms with the game's states and 13.77 ms with the raised ones (about 50 phases each), frame time 16.66 ms in both. A temporary counter (not kept) showed the texture gate at work there: of 10.5 million combined-handle binds of a sampler with a raised state, 4.8 million took it and 5.7 million kept the game's. Balatro (OpenGL) with DM_ANISO=16 reaches the rule (it logs the setting), with no red line and the same picture. Not run: a Vulkan game (none here), Breath of the Wild on this tree (its measurements in the docs are from an earlier version of the same rule), the iPhone and the iPad.
The settings page's Anisotropic filtering section now says which textures the setting reaches: a 2D texture or 2D array with more than one mip level, read through a linear sampler with mips and the regular level range, or one the game already gave anisotropy, in all three graphics layers. It says why one-level textures and samplers clamped to the first level keep the game's value (Breath of the Wild's silhouettes turned jagged), why shadow maps and depth pyramids do (the shadow cascade line reported in PR seedds#335), that a game binding its textures apart from their samplers sees no change, the cost measured on a Mac, and where the setting is on the Mac. Trilinear filtering is unchanged. The rendering reference gets an entry (Symptom, Cause, Fix, Not covered, Measuring, Found on, Check) for the rule, Breath of the Wild's note a section with its samplers, the binds, the cost (GPU p50 6.60 ms off, 6.59 ms on, M5 Max, one run with DM_NVN_ANISO=ab), the picture, the shadow cascade line and what is open, and dm/gfx/README.md a line for DM_ANISO. The symptom index is regenerated.
|
@CatPawPrint thank you. Both commits are on the branch as you wrote them, with your authorship (c67c9fe, 2fe70e4); Checked here on that head (M4 Max): the host builds with the same warnings as before, Device runs are mine to do: Breath of the Wild on an iPad Pro M4 and an iPhone 17 Pro Max with |
DM_ANISO raised every mipmapped sampler that is not a comparison or reduction sampler, in samp_by_id, and with it every texture bound through that sampler. Bound with a texture that is read at one level, a raised state spreads its extra samples across that level wherever a shader's coordinates jump within a pixel quad. Breath of the Wild's anti-aliasing pass reads a one-level texture through a trilinear sampler, and with every trilinear sampler raised, every silhouette in the picture turned jagged. The rule is now pure functions in sampler_aniso.h. A sampler is raised when it filters linearly in both directions, has a mip filter and the regular LOD range (minimum 0, maximum at least 1), or when the game already gave it anisotropy; a sampler with a depth comparison, a min / max reduction or unnormalized coordinates keeps the game's value, as before for the first two. samp_by_id keeps the game's state and makes the raised one beside it, and encode_args_ binds it only for a combined handle (SAMPT, SAMPU) whose texture view is 2D or a 2D array with more than one level (samp_aniso). Vulkan does the same for combined image samplers (vkCreateSampler, bind_res), and GL puts the raised value in its per-texture sampler cache key (tex_sampler). Separate samplers, sampler pools and arrays keep the game's value, so a game that binds its samplers apart from its textures gets no change, where the sampler-only rule raised them. DM_ANISO takes 0 or 1 (off) or 2 to 16; anything else is a red line and off. Every value the launcher row offers behaves as before, and the row now shows for Vulkan and GL games too. DM_TRILINEAR, its row and its code are unchanged: a sampler it makes trilinear is judged, and raised, with its new mip filter. DM_NVN_ANISO=0 binds no raised state, and ab with DM_AB alternates them by phase, to compare cost and picture in one run. t_aniso checks the rule for each kind of sampler and LOD range, the clamp, a view's levels, the texture gate and the switch's values (47 checks); no test reaches the call sites (samp_aniso, bind_res, tex_sampler). The host builds with the same warnings as before. On a Mac (M5 Max), Ocarina of Time (NVN) from a save in Link's house: with DM_ANISO unset the picture and the kinds of red lines are those of PR seedds#335's head; DM_ANISO=16 logs the setting once, adds no red line and the edges stay smooth; DM_NVN_ANISO=ab with DM_AB=60 measured GPU p50 13.67 ms with the game's states and 13.77 ms with the raised ones (about 50 phases each), frame time 16.66 ms in both. A temporary counter (not kept) showed the texture gate at work there: of 10.5 million combined-handle binds of a sampler with a raised state, 4.8 million took it and 5.7 million kept the game's. Balatro (OpenGL) with DM_ANISO=16 reaches the rule (it logs the setting), with no red line and the same picture. Not run: a Vulkan game (none here), Breath of the Wild on this tree (its measurements in the docs are from an earlier version of the same rule), the iPhone and the iPad. Hand merge (hle_vk.m): main has since counted a set layout's references (L->refs) and copies descriptors through desc_copy, which keeps the destination's immutable sampler; it keeps that sampler's raised variant (smp_a) with it. (cherry picked from commit c67c9fe)
The settings page's Anisotropic filtering section now says which textures the setting reaches: a 2D texture or 2D array with more than one mip level, read through a linear sampler with mips and the regular level range, or one the game already gave anisotropy, in all three graphics layers. It says why one-level textures and samplers clamped to the first level keep the game's value (Breath of the Wild's silhouettes turned jagged), why shadow maps and depth pyramids do (the shadow cascade line reported in PR seedds#335), that a game binding its textures apart from their samplers sees no change, the cost measured on a Mac, and where the setting is on the Mac. Trilinear filtering is unchanged. The rendering reference gets an entry (Symptom, Cause, Fix, Not covered, Measuring, Found on, Check) for the rule, Breath of the Wild's note a section with its samplers, the binds, the cost (GPU p50 6.60 ms off, 6.59 ms on, M5 Max, one run with DM_NVN_ANISO=ab), the picture, the shadow cascade line and what is open, and dm/gfx/README.md a line for DM_ANISO. The symptom index is regenerated. (cherry picked from commit 2fe70e4)
The host builds every sampler the game uses in samp_by_id, and NVN's own anisotropy already arrives there from nvnSamplerBuilderSetMaxAnisotropy. The games were built for a handheld and nearly all ask for 1, so ground and wall textures blur a short way from the camera at a glancing angle. DM_ANISO=2..16 raises a sampler that reads a mipmapped colour texture to at least that. It is a floor, never a ceiling: a sampler that asks for more keeps what it asked for. Sampling only, so nothing is allocated and no render target changes. Comparison and reduction samplers and samplers without mipmaps are not raised. DM_ANISO=16 on every sampler drew a line across open ground in Breath of the Wild, along the join between two shadow cascades. A comparison sampler is a shadow map: raising its anisotropy changes which depth texels each comparison averages, so the two sides of a cascade boundary stop agreeing and the seam becomes visible. A reduction sampler is a min or max pyramid, usually an occlusion test, whose value has to stay the extreme of its footprint rather than an average of it. A sampler with no mipmaps has no second level to filter between. Reported from an iPad Pro 13" M4. DM_TRILINEAR=1 blends mip levels where the game picked the nearer one, which removes the seam that runs across the floor at the distance a mip changes. Only a sampler that already filters the texture linearly is raised, so menus, fonts and lookup tables keep the sharp mip steps they were drawn with. A mip filter is also what makes anisotropy do anything, so the two go together on such a sampler. Both are off by default and need no game knowledge, so they reach games that have no render scale stub. Run so far on Breath of the Wild 1.9.0 on an iPad Pro 13" M4 and an iPhone 17 Pro Max, built against an older main. Picture quality at DM_ANISO=16 and the frame time at both settings are still being measured; numbers will follow in a comment.
DM_ANISO raised every mipmapped sampler that is not a comparison or reduction sampler, in samp_by_id, and with it every texture bound through that sampler. Bound with a texture that is read at one level, a raised state spreads its extra samples across that level wherever a shader's coordinates jump within a pixel quad. Breath of the Wild's anti-aliasing pass reads a one-level texture through a trilinear sampler, and with every trilinear sampler raised, every silhouette in the picture turned jagged. The rule is now pure functions in sampler_aniso.h. A sampler is raised when it filters linearly in both directions, has a mip filter and the regular LOD range (minimum 0, maximum at least 1), or when the game already gave it anisotropy; a sampler with a depth comparison, a min / max reduction or unnormalized coordinates keeps the game's value, as before for the first two. samp_by_id keeps the game's state and makes the raised one beside it, and encode_args_ binds it only for a combined handle (SAMPT, SAMPU) whose texture view is 2D or a 2D array with more than one level (samp_aniso). Vulkan does the same for combined image samplers (vkCreateSampler, bind_res), and GL puts the raised value in its sampler cache key, made per texture (samp_state), whether the texture's own parameters or a bound sampler object's apply. Separate samplers, sampler pools and arrays keep the game's value, so a game that binds its samplers apart from its textures gets no change, where the sampler-only rule raised them. DM_ANISO takes 0 or 1 (off) or 2 to 16; anything else is a red line and off. Every value the launcher row offers behaves as before, and the row now shows for Vulkan and GL games too. DM_TRILINEAR, its row and its code are unchanged: a sampler it makes trilinear is judged, and raised, with its new mip filter. DM_NVN_ANISO=0 binds no raised state, and ab with DM_AB alternates them by phase, to compare cost and picture in one run. t_aniso checks the rule for each kind of sampler and LOD range, the clamp, a view's levels, the texture gate and the switch's values (47 checks); no test reaches the call sites (samp_aniso, bind_res, samp_state). The host builds with the same warnings as before. On a Mac (M5 Max), Ocarina of Time (NVN) from a save in Link's house: with DM_ANISO unset the picture and the kinds of red lines are those of PR seedds#335's head; DM_ANISO=16 logs the setting once, adds no red line and the edges stay smooth; DM_NVN_ANISO=ab with DM_AB=60 measured GPU p50 13.67 ms with the game's states and 13.77 ms with the raised ones (about 50 phases each), frame time 16.66 ms in both. A temporary counter (not kept) showed the texture gate at work there: of 10.5 million combined-handle binds of a sampler with a raised state, 4.8 million took it and 5.7 million kept the game's. Balatro (OpenGL) with DM_ANISO=16 reaches the rule (it logs the setting), with no red line and the same picture. Not run: a Vulkan game (none here), Breath of the Wild on this tree (its measurements in the docs are from an earlier version of the same rule), the iPhone and the iPad.
The settings page's Anisotropic filtering section now says which textures the setting reaches: a 2D texture or 2D array with more than one mip level, read through a linear sampler with mips and the regular level range, or one the game already gave anisotropy, in all three graphics layers. It says why one-level textures and samplers clamped to the first level keep the game's value (Breath of the Wild's silhouettes turned jagged), why shadow maps and depth pyramids do (the shadow cascade line reported in PR seedds#335), that a game binding its textures apart from their samplers sees no change, the cost measured on a Mac, and where the setting is on the Mac. Trilinear filtering is unchanged. The rendering reference gets an entry (Symptom, Cause, Fix, Not covered, Measuring, Found on, Check) for the rule, Breath of the Wild's note a section with its samplers, the binds, the cost (GPU p50 6.60 ms off, 6.59 ms on, M5 Max, one run with DM_NVN_ANISO=ab), the picture, the shadow cascade line and what is open, and dm/gfx/README.md a line for DM_ANISO. The symptom index is regenerated.
|
Rebased onto current main (48f6bd3), with CatPawPrint's two commits kept as theirs. Main moved GL sampler creation into |
Game carries eleven unrelated rows: how fast the game runs, how large it renders, which console mode it reports, how the finished frame is scaled, fitted and shaped, which language it speaks, how the Mac window opens, and a frame-rate read-out. The only thing they have in common is that none of them belonged in Controls or Performance. Picture takes the rows that are about the finished frame rather than about the game: Render scale, Upscaling, Game's upscaler, Picture and Picture shape. Game keeps Frame rate, Dynamic resolution, Console mode, Game language and the Mac's Display mode. The frame-rate counter moves to Performance next to the Performance HUD, since both are read-outs rather than settings. The iOS in-game menu follows the sections, so the counter comes after the controls there. The split matters more as the section grows. With the anisotropic and trilinear filtering of seedds#335 and the upscaling detail and sharpening of seedds#345, Game would hold fifteen rows, nine of which are about how the picture looks. The heading order on screen is the order of SECTIONS, and rows keep their table order inside a section, so settings.tsv still decides the layout on its own. In docs/settings.md the Picture section takes the anchor #picture, and the Picture setting inside it becomes #picture-1. The thermal cap (seedds#220) holds the frame step at 30 fps while iOS reports a serious or critical thermal state, and DM_THERMAL_CAP=0 turned it off only from an env file. It is a trade a player should be able to make: with a phone cooler, or for a player who would rather have an uneven 45 to 55 than an even 30, it costs more than it saves. "Halve when hot" in Performance, on by default, so nothing changes for anyone who does not touch it. Shown only for a game with a frame step, as Hold frames when late is. The note says what the thermal state does not catch. On an iPhone 17 Pro Max, Breath of the Wild 1.9.0 dropped a third of its frames for ten minutes with the state reading nominal throughout, and one scene's GPU time went from 8.40 ms to 21.83 ms while it still read nominal: iOS lowers the clock well before it calls the device hot. The same phone, charged over USB while large apps were installed onto it, started a game already at serious and was held at 30 from the first frame, which is the case the setting is for. The tests follow: Render scale is a basic row under Picture, and in the Mac window's list for Breath of the Wild every Game row is basic, so its Advanced settings start at Picture.
|
Main has moved again, and #335 (cd3f5d5) no longer merges with it. The only conflict is in A resolution that keeps main's structures: the raised state becomes one more property of
|
Two filtering settings the host can raise for any game, because it builds every sampler the game uses in
samp_by_id. Neither needs game knowledge, so they also reach the games that have no render scale stub.DM_ANISO
NVN's own anisotropy already arrives in
samp_by_idfromnvnSamplerBuilderSetMaxAnisotropy. The games were built for a handheld and nearly all ask for 1, so ground and wall textures blur a short way from the camera at a glancing angle.DM_ANISO=2..16raises every sampler to at least that. It is a floor, never a ceiling: a sampler that asks for more keeps what it asked for. Sampling only, so nothing is allocated and no render target changes.DM_TRILINEAR
DM_TRILINEAR=1blends mip levels where the game picked the nearer one, which removes the seam that runs across the floor at the distance a mip changes.Only a sampler that already filters the texture linearly is raised, so menus, fonts and lookup tables keep the sharp mip steps they were drawn with. A mip filter is also what makes anisotropy do anything, so the two go together on such a sampler.
Changes
dm/gfx/nvn/nvn_mtl.m:dm_aniso()anddm_trilinear(), both read once, applied insamp_by_iddm/games/settings.tsv: two rows in Game,gfxapi:nvn, both off by defaultdocs/settings.md,docs/env_switches.tsvState of testing
Running on Breath of the Wild 1.9.0 on an iPad Pro 13" M4 and an iPhone 17 Pro Max, built against an older
main. Picture comparisons and frame times are still being measured and will follow in a comment. Opening now because the change is small and off by default.test_docs,test_env_switchesandtest_launcher_settingspass.