Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions dm/games/settings.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@ DM_PSO_PREBUILD toggle - 1 gfxapi:nvn Performance Pipeline prebuild The first st
DM_NVN_ENC_THREAD toggle - 1|DM_GAME_ENC_THREAD gfxapi:nvn Performance Encode thread
DM_FPS_HOLD toggle on/off DM_GAME_FPS_HOLD DM_GAME_FPS_TARGET!=0 Performance Hold frames when late
DM_METAL_HUD toggle - 0 always Performance Performance HUD
DM_BC6H_RGB9E5 toggle - 0 gfxapi:nvn Performance Sighly lower texture quality to save RAM Try this if game starts crashing in heavy scenes
124 changes: 96 additions & 28 deletions dm/gfx/nvn/nvn_mtl.m

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion dm/gfx/tests/t_geometry_hazards.m
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ static void empty_stream_contract(void) {
state_reset();
}
enum { DEP_STORAGE, DEP_UNIFORM, RUN_EMPTY_STREAM, NORUN_UNALIGNED_STREAM };
// NOLINTBEGIN(clang-analyzer-osx.cocoa.RetainCount): serial_put retains pr in g_by_serial through hm_put_id's CFBridgingRetain
static void dependency(int mode) {
int uniform=mode==DEP_UNIFORM,independent=mode>=RUN_EMPTY_STREAM; // independent: the two draws touch different memory
id<MTLLibrary> l=library(@"#include <metal_stdlib>\nusing namespace metal;\n"
Expand All @@ -130,6 +131,7 @@ static void dependency(int mode) {
"kernel void geometry(constant G&g[[buffer(0)]],uint3 t[[thread_position_in_grid]]){if(t.x||t.y||t.z)return;float x=g.in[0]*.8-.8;g.p[0]=uint(g.in[0])+1;g.out[0]=float4(x,-.5,0,1);g.out[1]=float4(x+.6,-.5,0,1);g.out[2]=float4(x,.5,0,1);g.ix[0]=0;g.ix[1]=1;g.ix[2]=2;g.ix[3]=0xffffffffu;}\n"
"struct V{device float4*p[[id(0)]];};vertex float4 reader(uint v[[vertex_id]],constant V&a[[buffer(0)]]){return a.p[v];}\nfragment float4 red(){return float4(1,0,0,1);}\n");
int helpers[]={0,1,2,3,4},rh[]={1};NvProg *pr=[NvProg new];

pr->sh[0]=shader(l,@"unused",0,NULL,0);NvShader *vs=pr->sh[0];vs->geo_fn=[l newFunctionWithName:@"capture"];
vs->rf.nb=1;vs->rf.b[0]=(nvn_rbind){.kind=uniform?NVN_RB_CBUF:NVN_RB_SBUFP,.reg=0,.aid=0};
vs->ae=[vs->geo_fn newArgumentEncoderWithBufferIndex:0];vs->arg_len=vs->ae.encodedLength;
Expand All @@ -150,7 +152,7 @@ static void dependency(int mode) {
EMIT(OP_DRAW,d);op_hdr end={OP_END,8};memcpy(cmd+used,&end,8);
#undef EMIT
state_reset();memset(&R,0,sizeof R);mtl_set_frame(100+mode);mtl_sub_begin();uint64_t cuts=g_cuts,h=(uint64_t)cmd;mtl_sub_index(&h,1);mtl_exec(cmd);
id<MTLBuffer> rb=[g_dev newBufferWithLength:4096 options:MTLResourceStorageModeShared];[blit() copyFromTexture:tex_mtl(&target) sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0,0,0) sourceSize:MTLSizeMake(32,32,1) toBuffer:rb destinationOffset:0 destinationBytesPerRow:128 destinationBytesPerImage:4096];finish();
id<MTLBuffer> rb=[g_dev newBufferWithLength:4096 options:MTLResourceStorageModeShared];if(!rb)abort();[blit() copyFromTexture:tex_mtl(&target) sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0,0,0) sourceSize:MTLSizeMake(32,32,1) toBuffer:rb destinationOffset:0 destinationBytesPerRow:128 destinationBytesPerImage:4096];finish();
uint8_t *px=rb.contents;
if(independent) {
EXPECT("first draw wrote its own storage",1,*(uint32_t*)(cmd+32768));EXPECT("second draw wrote its own storage",1,*(uint32_t*)(cmd+32768+16));
Expand All @@ -164,6 +166,7 @@ static void dependency(int mode) {
}
mtl_tex_release(&target);mtl_pool_del(cmd);mtl_drain();free(cmd);
}
// NOLINTEND(clang-analyzer-osx.cocoa.RetainCount)
int main(int argc,char **argv){@autoreleasepool{
if(argc>1&&!strcmp(argv[1],"--access-bench"))return access_benchmark();
access_contract();drain_contract();mtl_init();empty_stream_contract();dependency(DEP_STORAGE);dependency(DEP_UNIFORM);dependency(RUN_EMPTY_STREAM);dependency(NORUN_UNALIGNED_STREAM);
Expand Down
27 changes: 27 additions & 0 deletions dm/gfx/tests/t_view_swizzle.m
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,33 @@ int main(void) { @autoreleasepool {
init_fill_case(416 + i, packed[i], NVN_MEMORY_POOL_FLAGS_CPU_UNCACHED);
init_fill_case(420 + i, packed[i], NVN_MEMORY_POOL_FLAGS_CPU_NO_ACCESS);
}
{ // When g_bc_cpu is active (pre-A17 Pro GPUs with tex_bc_cpu): non-sparse BC1 upload decodes on the CPU, BC sRGB view unpacks to RGBA8Unorm_sRGB, and BC4 render-target attach is skipped
int tid = 424, saved_bc_cpu = g_bc_cpu; g_bc_cpu = 1; mtl_set_bc_path(BC_PATH_CPU_STANDARD);
tex_t t = {.magic=MAGIC('T','E','X',0), .serial=98000+(unsigned)tid, .has_layout=1};
pool_t pool = {.magic=MAGIC('P','O','O','L'), .flags=NVN_MEMORY_POOL_FLAGS_CPU_UNCACHED | NVN_MEMORY_POOL_FLAGS_GPU_CACHED};
t.d = (nvn_texdesc){.target=NVN_TEXTURE_TARGET_2D, .format=0x41, .width=4, .height=4, .depth=1, .levels=1, .samples=1};
nvn_tex_layout(&t.d, &t.L); t.mem = calloc(1, t.L.size); t.pool = &pool; pool.mem = t.mem; pool.size = t.L.size;
uint8_t blk[8] = {0x00, 0xf8, 0x1f, 0x00, 0x04, 0x00, 0x00, 0x00}; // c0 = red (0xf800), c1 = blue (0x001f); texel (0,0) = red, texel (1,0) = blue
CHECK(nvn_swizzle(&t.d, 0, 0, blk, 8, t.mem) == 0, "BC1 block swizzled into guest storage");
g_sub_thread = pthread_self(); atomic_store(&g_sub_thread_set, 1);
id<MTLTexture> base = tex_mtl(&t);
up_flush(); mtl_finish_gpu();
CHECK(base != nil && base.pixelFormat == MTLPixelFormatRGBA8Unorm, "CPU-decoded BC1 texture uploaded as RGBA8Unorm");
view_t v = {.set_format=1, .format=0x45}; // RGB_sRGB_DXT1 view on an RGB_DXT1 base texture
mtl_reg_tex(tid, &t, &v);
os_unfair_lock_lock(&g_rmu); id<MTLTexture> view = tex_by_id(tid); os_unfair_lock_unlock(&g_rmu);
CHECK(view != nil && view.pixelFormat == MTLPixelFormatRGBA8Unorm_sRGB, "BC sRGB view unpacked to RGBA8Unorm_sRGB under g_bc_cpu");
read_check(tid, view, (const float[8]){1,0,0,1, 0,0,1,1}, 0.01f);
tex_t bc4 = {.magic=MAGIC('T','E','X',0), .serial=98001+(unsigned)tid, .pool=&pool};
bc4.d = (nvn_texdesc){.target=NVN_TEXTURE_TARGET_2D, .format=0x49, .width=4, .height=4, .depth=1, .levels=1, .samples=1};
id<MTLTexture> bc4_base = tex_mtl(&bc4);
CHECK(bc4_base != nil && bc4_base.pixelFormat == MTLPixelFormatR8Unorm, "CPU-decoded BC4 texture created as R8Unorm");
MTLRenderPassColorAttachmentDescriptor *att = [MTLRenderPassColorAttachmentDescriptor new];
view_t rtv = {.set_format=1, .format=0x2c};
attach(att, &bc4, &rtv, 1);
CHECK(att.texture == nil && !(bc4_base.usage & MTLTextureUsageRenderTarget), "CPU-decoded BC4 texture is not upgraded or attached as a render target");
free(t.mem); g_bc_cpu = saved_bc_cpu; mtl_set_bc_path(saved_bc_cpu ? BC_PATH_CPU_STANDARD : BC_PATH_GPU);
}
printf("texture view swizzle: %d checks, %d failed\n", checks, fails);
return fails != 0;
} }
3 changes: 2 additions & 1 deletion dm/gfx/tex/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@ Block linear is how the Tegra X1 GPU stores textures: the data is not one row af
| `nvn_fmt_mtl.h`, `nvn_fmt_mtl.c` | `nvn_fmt_to_mtl()`: NVN format (0x01–0x9C) → Metal pixel format + component remapping. Returns 1 for an exact match, 2 for a substitute (precision, bit order or interpretation differs and a conversion is needed), 0 when Metal has no corresponding format. How each format is handled is written in the comments inside the table. Pure C, no dependency on Metal headers |
| `nvn_deswizzle.h`, `nvn_deswizzle.c` | `nvn_deswizzle()`: deswizzles one level and one layer from block linear to linear; `nvn_swizzle()`: the reverse, used for round trips in unit tests; `nvn_bl_offset()`: the block-linear address of a single point. Pure C |
| `nvn_deswizzle_gpu.h`, `nvn_deswizzle_gpu.m` | A Metal compute shader version of the same deswizzling algorithm, used by the replay layer when uploading packaged textures; when initialization fails or an unsupported format is encountered, the replay layer falls back to the CPU version |
| `nvn_bcdec.h`, `nvn_bcdec.c` | `nvn_bc_decode()`: decodes BC1–5, BC6H and BC7 texture blocks into uncompressed Metal pixel formats via bcdec.h |
| `tests/` | Unit tests |

The offsets of each level and layer within the storage, and the block height and block depth actually used by each level, are all taken from `../nvn/nvn_tex.c` (`nvn_tex_layout`, `nvn_tex_level_offset`, `nvn_tex_level_tiles`); this directory only does addressing and moving within a level. Packaged parameters override the automatic block dimensions: [Packaged texture block dimensions and linear storage rows](../../../docs/reference/nvn-objects.md#packaged-texture-block-dimensions-and-linear-storage-rows).

## BC textures

Only GPUs with BC compressed textures are supported (`supportsBCTextureCompression` of `MTLDevice`: Apple silicon Macs and the latest iPhones), so BC textures are created and uploaded as BC; there is no decompression path. A device without them is refused at start ([GPUs without BC textures](../../../docs/reference/rendering.md#gpus-without-bc-textures-are-refused-at-start)). A BC texture is never a render target and its raw blocks are not sampled through an uncompressed view (Metal has no such views; Breath of the Wild encodes one 32×32 BC4 texture on the GPU, GitHub issue #4).
On GPUs with hardware BC compressed textures (`supportsBCTextureCompression` of `MTLDevice`: Apple Silicon Macs and A17 Pro+ iPhones), BC textures are created and uploaded directly as BC. On GPUs without native BC compression (A16 and older iPhones), BC textures are decompressed on the CPU into standard Metal formats (or RGB9E5 for BC6H to save RAM) via launch-time function dispatch ([GPUs without BC textures](../../../docs/reference/rendering.md#gpus-without-bc-textures-are-refused-at-start)). A BC texture is never a render target and its raw blocks are not sampled through an uncompressed view (Metal has no such views; Breath of the Wild encodes one 32×32 BC4 texture on the GPU, GitHub issue #4).

## Tests

Expand Down
172 changes: 172 additions & 0 deletions dm/gfx/tex/nvn_bcdec.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
// 见 nvn_bcdec.h。解码用 bcdec(dm/third_party/bcdec,单头文件,MIT / 公有领域)。
// See nvn_bcdec.h. Decoding uses bcdec (dm/third_party/bcdec, single header, MIT / public domain).
#include "nvn_bcdec.h"
#include <stdlib.h>
#include <string.h>

enum { R8Unorm = 10, R8Snorm = 12, RG8Unorm = 30, RG8Snorm = 32, RGBA8Unorm = 70, RGBA8Unorm_sRGB = 71, RGB9E5Float = 93, RGBA16Float = 115 };

// Path 1 (GPU Direct BC): No CPU unpacking or decoding
int nvn_bc_unpacked_gpu(uint32_t f, uint32_t *pf, int *bpp) {
(void)f; (void)pf; (void)bpp;
return 0;
}

int nvn_bc_decode_gpu(uint32_t f, const uint8_t *src, size_t pitch, uint32_t w, uint32_t h, uint8_t *dst, size_t dpitch) {
(void)f; (void)src; (void)pitch; (void)w; (void)h; (void)dst; (void)dpitch;
return -1;
}

#define BCDEC_IMPLEMENTATION
#define BCDEC_BC4BC5_PRECISE // BC4 / BC5 带有符号版本的接口 | interface with signed variants of BC4 / BC5
#include "../../third_party/bcdec/bcdec.h"
#include <math.h>

#define RGB9E5_MANTISSA_BITS 9
#define RGB9E5_EXP_BIAS 15
#define RGB9E5_MAX_VALID_BIASED_EXP 31
#define MAX_RGB9E5_EXP (RGB9E5_MAX_VALID_BIASED_EXP - RGB9E5_EXP_BIAS)
#define RGB9E5_MANTISSA_VALUES (1 << RGB9E5_MANTISSA_BITS)
#define MAX_RGB9E5_MANTISSA (RGB9E5_MANTISSA_VALUES - 1)
#define MAX_RGB9E5 (((float)(MAX_RGB9E5_MANTISSA)) / RGB9E5_MANTISSA_VALUES * (1 << MAX_RGB9E5_EXP))

static inline uint32_t float3_to_rgb9e5(float r, float g, float b) {
float rc = fminf(fmaxf(r, 0.0f), MAX_RGB9E5);
float gc = fminf(fmaxf(g, 0.0f), MAX_RGB9E5);
float bc = fminf(fmaxf(b, 0.0f), MAX_RGB9E5);
float maxrgb = fmaxf(rc, fmaxf(gc, bc));
int exp_shared;
if (maxrgb < 1.0f / (1 << (RGB9E5_EXP_BIAS - 1))) {
exp_shared = 0;
} else {
int exp;
frexpf(maxrgb, &exp);
exp_shared = exp + RGB9E5_EXP_BIAS;
if (exp_shared > RGB9E5_MAX_VALID_BIASED_EXP) exp_shared = RGB9E5_MAX_VALID_BIASED_EXP;
}
float scale = ldexpf(1.0f, RGB9E5_EXP_BIAS + RGB9E5_MANTISSA_BITS - exp_shared);
int maxm = (int)floorf(maxrgb * scale + 0.5f);
if (maxm == RGB9E5_MANTISSA_VALUES) {
scale *= 0.5f;
exp_shared++;
if (exp_shared > RGB9E5_MAX_VALID_BIASED_EXP) exp_shared = RGB9E5_MAX_VALID_BIASED_EXP;
}
int rm = (int)floorf(rc * scale + 0.5f);
int gm = (int)floorf(gc * scale + 0.5f);
int bm = (int)floorf(bc * scale + 0.5f);
if (rm > MAX_RGB9E5_MANTISSA) rm = MAX_RGB9E5_MANTISSA;
if (gm > MAX_RGB9E5_MANTISSA) gm = MAX_RGB9E5_MANTISSA;
if (bm > MAX_RGB9E5_MANTISSA) bm = MAX_RGB9E5_MANTISSA;
return (uint32_t)rm | ((uint32_t)gm << 9) | ((uint32_t)bm << 18) | ((uint32_t)exp_shared << 27);
}

// Path 2 (Standard CPU decode): BC1-7 standard, BC6H -> RGBA16Float (8 bpp)
int nvn_bc_unpacked_standard(uint32_t f, uint32_t *pf, int *bpp) {
uint32_t dummy_pf; int dummy_bpp;
if (!pf) pf = &dummy_pf;
if (!bpp) bpp = &dummy_bpp;
switch (f) {
case 0x41: case 0x42: case 0x43: case 0x44: case 0x4d: *pf = RGBA8Unorm; *bpp = 4; return 1;
case 0x45: case 0x46: case 0x47: case 0x48: case 0x4e: *pf = RGBA8Unorm_sRGB; *bpp = 4; return 1;
case 0x49: *pf = R8Unorm; *bpp = 1; return 1;
case 0x4a: *pf = R8Snorm; *bpp = 1; return 1;
case 0x4b: *pf = RG8Unorm; *bpp = 2; return 1;
case 0x4c: *pf = RG8Snorm; *bpp = 2; return 1;
case 0x4f: case 0x50: *pf = RGBA16Float; *bpp = 8; return 1;
default: return 0;
}
}

static void block_standard(uint32_t f, const uint8_t *b, uint8_t *o, int op) {
switch (f) {
case 0x41: case 0x42: case 0x45: case 0x46: bcdec_bc1(b, o, op); break;
case 0x43: case 0x47: bcdec_bc2(b, o, op); break;
case 0x44: case 0x48: bcdec_bc3(b, o, op); break;
case 0x49: bcdec_bc4(b, o, op, 0); break;
case 0x4a: bcdec_bc4(b, o, op, 1); break;
case 0x4b: bcdec_bc5(b, o, op, 0); break;
case 0x4c: bcdec_bc5(b, o, op, 1); break;
case 0x4d: case 0x4e: bcdec_bc7(b, o, op); break;
case 0x4f: case 0x50: {
uint16_t rgb[16 * 3]; bcdec_bc6h_half(b, rgb, 4 * 3, f == 0x4f);
for (int y = 0; y < 4; y++) for (int x = 0; x < 4; x++) {
uint16_t *d = (uint16_t *)(o + y * op) + x * 4; const uint16_t *s = rgb + (y * 4 + x) * 3;
d[0] = s[0]; d[1] = s[1]; d[2] = s[2]; d[3] = 0x3c00;
}
break; }
}
}

int nvn_bc_decode_standard(uint32_t f, const uint8_t *src, size_t pitch, uint32_t w, uint32_t h, uint8_t *dst, size_t dpitch) {
uint32_t pf; int bpp; if (!nvn_bc_unpacked_standard(f, &pf, &bpp)) return -1;
int bb = (f == 0x41 || f == 0x42 || f == 0x45 || f == 0x46 || f == 0x49 || f == 0x4a) ? 8 : 16;
uint8_t tmp[4 * 4 * 8];
for (uint32_t by = 0; by * 4 < h; by++) for (uint32_t bx = 0; bx * 4 < w; bx++) {
const uint8_t *b = src + by * pitch + bx * bb;
uint32_t cw = w - bx * 4 < 4 ? w - bx * 4 : 4, ch = h - by * 4 < 4 ? h - by * 4 : 4;
uint8_t *o = dst + (size_t)by * 4 * dpitch + (size_t)bx * 4 * bpp;
if (cw == 4 && ch == 4) { block_standard(f, b, o, (int)dpitch); continue; }
block_standard(f, b, tmp, 4 * bpp);
for (uint32_t y = 0; y < ch; y++) memcpy(o + y * dpitch, tmp + y * 4 * bpp, cw * bpp);
}
return 0;
}

// Path 3 (Reduced RAM CPU decode): BC1-7 standard, BC6H -> RGB9E5Float (4 bpp)
int nvn_bc_unpacked_rgb9e5(uint32_t f, uint32_t *pf, int *bpp) {
uint32_t dummy_pf; int dummy_bpp;
if (!pf) pf = &dummy_pf;
if (!bpp) bpp = &dummy_bpp;
switch (f) {
case 0x41: case 0x42: case 0x43: case 0x44: case 0x4d: *pf = RGBA8Unorm; *bpp = 4; return 1;
case 0x45: case 0x46: case 0x47: case 0x48: case 0x4e: *pf = RGBA8Unorm_sRGB; *bpp = 4; return 1;
case 0x49: *pf = R8Unorm; *bpp = 1; return 1;
case 0x4a: *pf = R8Snorm; *bpp = 1; return 1;
case 0x4b: *pf = RG8Unorm; *bpp = 2; return 1;
case 0x4c: *pf = RG8Snorm; *bpp = 2; return 1;
case 0x4f: case 0x50: *pf = RGB9E5Float; *bpp = 4; return 1;
default: return 0;
}
}

static void block_rgb9e5(uint32_t f, const uint8_t *b, uint8_t *o, int op) {
switch (f) {
case 0x41: case 0x42: case 0x45: case 0x46: bcdec_bc1(b, o, op); break;
case 0x43: case 0x47: bcdec_bc2(b, o, op); break;
case 0x44: case 0x48: bcdec_bc3(b, o, op); break;
case 0x49: bcdec_bc4(b, o, op, 0); break;
case 0x4a: bcdec_bc4(b, o, op, 1); break;
case 0x4b: bcdec_bc5(b, o, op, 0); break;
case 0x4c: bcdec_bc5(b, o, op, 1); break;
case 0x4d: case 0x4e: bcdec_bc7(b, o, op); break;
case 0x4f: case 0x50: {
float rgb[16 * 3]; bcdec_bc6h_float(b, rgb, 4 * 3, f == 0x4f);
for (int y = 0; y < 4; y++) {
uint32_t *d = (uint32_t *)(o + y * op);
for (int x = 0; x < 4; x++) {
const float *s = rgb + (y * 4 + x) * 3;
d[x] = float3_to_rgb9e5(s[0], s[1], s[2]);
}
}
break; }
}
}

int nvn_bc_decode_rgb9e5(uint32_t f, const uint8_t *src, size_t pitch, uint32_t w, uint32_t h, uint8_t *dst, size_t dpitch) {
uint32_t pf; int bpp; if (!nvn_bc_unpacked_rgb9e5(f, &pf, &bpp)) return -1;
int bb = (f == 0x41 || f == 0x42 || f == 0x45 || f == 0x46 || f == 0x49 || f == 0x4a) ? 8 : 16;
uint8_t tmp[4 * 4 * 8];
for (uint32_t by = 0; by * 4 < h; by++) for (uint32_t bx = 0; bx * 4 < w; bx++) {
const uint8_t *b = src + by * pitch + bx * bb;
uint32_t cw = w - bx * 4 < 4 ? w - bx * 4 : 4, ch = h - by * 4 < 4 ? h - by * 4 : 4;
uint8_t *o = dst + (size_t)by * 4 * dpitch + (size_t)bx * 4 * bpp;
if (cw == 4 && ch == 4) { block_rgb9e5(f, b, o, (int)dpitch); continue; }
block_rgb9e5(f, b, tmp, 4 * bpp);
for (uint32_t y = 0; y < ch; y++) memcpy(o + y * dpitch, tmp + y * 4 * bpp, cw * bpp);
}
return 0;
}

// Initialized to standard CPU decode by default
nvn_bc_unpacked_fn g_nvn_bc_unpacked = nvn_bc_unpacked_standard;
nvn_bc_decode_fn g_nvn_bc_decode = nvn_bc_decode_standard;
Loading