Initial public release
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
t_nvn
|
||||
t_nvn.dSYM/
|
||||
t_builtin
|
||||
t_deswz_gpu
|
||||
t_deswz_gpu.dSYM/
|
||||
t_builtin.dSYM/
|
||||
t_pace
|
||||
.precommit.err
|
||||
.precommit_snap/
|
||||
t_refl
|
||||
t_refl.dSYM
|
||||
t_hmap
|
||||
t_cover
|
||||
t_fuse_check
|
||||
t_fuse_check.dSYM/
|
||||
t_present_crop
|
||||
t_present_crop.dSYM/
|
||||
t_reorder_chain
|
||||
t_reorder_chain.dSYM/
|
||||
t_mip_extent
|
||||
t_mip_extent.dSYM/
|
||||
t_rt_range_shape
|
||||
t_rt_range_shape.dSYM/
|
||||
t_rt_range_ro
|
||||
t_rt_range_ro.dSYM/
|
||||
t_rt_range
|
||||
t_rt_range.dSYM/
|
||||
t_rt_depth_ro
|
||||
t_rt_depth_ro.dSYM/
|
||||
t_pso_skey
|
||||
t_pso_skey.dSYM/
|
||||
t_dirty_slots
|
||||
t_dirty_slots.dSYM/
|
||||
t_pfv
|
||||
t_pfv.dSYM/
|
||||
t_defer_chain
|
||||
t_defer_chain.dSYM/
|
||||
t_zskip
|
||||
t_zskip.dSYM/
|
||||
t_xv
|
||||
t_xv.dSYM/
|
||||
t_ub
|
||||
t_ub.dSYM/
|
||||
@@ -0,0 +1,84 @@
|
||||
# 单测:make 编译并运行(秒级)
|
||||
# 源文件按通配纳入,口径与宿主 Makefile 的 GFX 一致(hle_nvn.c 由 t_nvn.c 直接 #include,故剔除);新增源文件无需改这里
|
||||
# Unit tests: make compiles and runs them (seconds)
|
||||
# Source files are included by wildcard, same convention as GFX in the host Makefile (hle_nvn.c is #included directly by t_nvn.c, so it is excluded); adding new source files needs no change here
|
||||
CFLAGS=-O1 -g -Wall -Wno-unused-function -I../nvn/include
|
||||
GFX=$(filter-out ../nvn/hle_nvn.c,$(sort $(wildcard ../nvn/*.c ../nvn/*.m ../nvn/*.S ../tex/*.c ../tex/*.m)))
|
||||
GFX_H=$(wildcard ../nvn/*.h ../nvn/*.inc ../nvn/include/*.h ../tex/*.h)
|
||||
FW=-framework Metal -framework Foundation -framework QuartzCore -framework ImageIO -framework CoreGraphics -framework UniformTypeIdentifiers
|
||||
# 宿主 crash.c 一并链入:写保护单测走生产同一套缺页钩子
|
||||
# Host crash.c is linked in as well: the write-protect unit tests go through the same page-fault hook as production
|
||||
t_nvn: t_nvn.c ../nvn/hle_nvn.c ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_nvn.c ../../host/crash.c $(GFX) $(FW)
|
||||
t_dirty_slots: t_dirty_slots.c ../nvn/nvn_dirty.c ../../host/crash.c ../nvn/nvn_dirty.h
|
||||
clang $(CFLAGS) -o $@ t_dirty_slots.c ../../host/crash.c ../nvn/nvn_dirty.c
|
||||
t_builtin: t_builtin.m ../nvn/nvn_builtin.h
|
||||
clang -O1 -g -Wall -fobjc-arc -o $@ t_builtin.m -framework Metal -framework Foundation
|
||||
t_deswz_gpu: t_deswz_gpu.m ../tex/nvn_deswizzle.c ../tex/nvn_deswizzle_gpu.m ../tex/nvn_deswizzle.h ../tex/nvn_deswizzle_gpu.h ../nvn/nvn_tex.c ../nvn/nvn_tex.h
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_deswz_gpu.m ../tex/nvn_deswizzle.c ../tex/nvn_deswizzle_gpu.m ../nvn/nvn_tex.c -framework Metal -framework Foundation
|
||||
t_refl: t_refl.m ../nvn/nvn_refl.m ../nvn/nvn_refl.h ../nvn/dmsh_chain.h
|
||||
clang -O1 -g -Wall -fobjc-arc -o $@ t_refl.m ../nvn/nvn_refl.m -framework Metal -framework Foundation
|
||||
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_pace: t_pace.c ../nvn/nvn_pace.h
|
||||
clang -O1 -Wall -o $@ t_pace.c
|
||||
t_fuse_check: t_fuse_check.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_fuse_check.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW)
|
||||
t_present_crop: t_present_crop.m ../nvn/hle_nvn.c ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_present_crop.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m,$(GFX)) $(FW)
|
||||
t_reorder_chain: t_reorder_chain.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_reorder_chain.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW)
|
||||
t_defer_chain: t_defer_chain.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_defer_chain.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW)
|
||||
t_zskip: t_zskip.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_zskip.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW)
|
||||
t_xv: t_xv.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_xv.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW)
|
||||
t_ub: t_ub.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_ub.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW)
|
||||
t_mip_extent: t_mip_extent.m ../nvn/hle_nvn.c ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_mip_extent.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m,$(GFX)) $(FW)
|
||||
t_rt_range_shape: t_rt_range_shape.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_rt_range_shape.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW)
|
||||
t_rt_range_ro: t_rt_range_ro.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_rt_range_ro.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW)
|
||||
t_rt_range: t_rt_range.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_rt_range.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW)
|
||||
t_rt_depth_ro: t_rt_depth_ro.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_rt_depth_ro.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW)
|
||||
t_pso_skey: t_pso_skey.m ../nvn/nvn_pso_skey.h ../nvn/nvn_obj.h
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_pso_skey.m -framework Foundation
|
||||
t_pfv: t_pfv.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_pfv.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW)
|
||||
run: t_nvn t_dirty_slots t_builtin t_deswz_gpu t_pace t_refl t_hmap t_cover t_fuse_check t_present_crop t_reorder_chain t_defer_chain t_zskip t_xv t_ub t_mip_extent t_rt_range_shape t_rt_range_ro t_rt_range t_rt_depth_ro t_pso_skey t_pfv
|
||||
./t_nvn
|
||||
./t_dirty_slots
|
||||
./t_builtin
|
||||
./t_deswz_gpu
|
||||
./t_pace
|
||||
./t_refl
|
||||
./t_hmap
|
||||
./t_cover
|
||||
./t_fuse_check
|
||||
./t_present_crop
|
||||
MTL_DEBUG_LAYER=1 ./t_reorder_chain
|
||||
MTL_DEBUG_LAYER=1 ./t_defer_chain
|
||||
./t_zskip
|
||||
./t_xv
|
||||
./t_ub
|
||||
MTL_DEBUG_LAYER=1 ./t_mip_extent
|
||||
MTL_DEBUG_LAYER=1 ./t_mip_extent --stencil-only
|
||||
./t_rt_depth_ro
|
||||
./t_rt_range_shape
|
||||
./t_rt_range_ro
|
||||
DM_NVN_UNWRITTEN_DC=0 MTL_DEBUG_LAYER=1 ./t_rt_range
|
||||
MTL_DEBUG_LAYER=1 ./t_rt_range # DontCare 缺省开:附件字节按「每通道省一次深度模板写回」闭式期望 | DontCare on by default: attachment bytes use the closed-form expectation of "one depth-stencil store saved per pass"
|
||||
DM_NVN_UNWRITTEN_DC=0 MTL_DEBUG_LAYER=1 ./t_rt_range --disabled
|
||||
DM_NVN_UNWRITTEN_DC=0 MTL_DEBUG_LAYER=1 ./t_rt_range --small-depth
|
||||
DM_NVN_UNWRITTEN_DC=0 MTL_DEBUG_LAYER=1 ./t_rt_range --sample-attachment --both-flags
|
||||
./t_pso_skey
|
||||
MTL_DEBUG_LAYER=1 ./t_pfv
|
||||
python3 test_tbdr_budget.py
|
||||
.PHONY: run
|
||||
@@ -0,0 +1,58 @@
|
||||
// main 内嵌 4 个计算核的 MSL 单测:期望值按 Maxwell 反汇编语义在 C 里直接算(nvn_builtin.h 头注释),不经被测 MSL。
|
||||
// 负对照:4×4 交叉矩阵——每个核对每个期望都跑一遍,只有对角线全等(核之间可区分、哈希→核的对应配错会被抓)。
|
||||
// MSL unit tests for the 4 compute kernels embedded in main: expected values are computed directly in C from the Maxwell disassembly semantics (header comment of nvn_builtin.h), without going through the MSL under test.
|
||||
// Negative control: 4×4 cross matrix - every kernel is run against every expectation, and only the diagonal matches exactly (kernels are distinguishable, and a wrong hash→kernel mapping would be caught).
|
||||
#import <Metal/Metal.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "../nvn/nvn_builtin.h"
|
||||
|
||||
enum { NREC = 40, N = 37, CAP = 64 }; // n = 37:跨两个线程组(32 + 5),第 37..63 个元素必须保持哨兵值 | n = 37: spans two thread groups (32 + 5); elements 37..63 must keep the sentinel value
|
||||
|
||||
static void expect(int k, const uint64_t *s, uint64_t *e) {
|
||||
for (int i = 0; i < CAP; i++) e[i] = 0xAAAAAAAAAAAAAAAAull;
|
||||
for (int i = 0; i < N; i++)
|
||||
switch (k) {
|
||||
case 0: e[i] = s[2 * i]; break; // src + (id<<4)
|
||||
case 1: e[i] = s[2 * i + 1]; break; // src + (id<<4) + 8
|
||||
case 2: e[i] = s[4 * i + 2] - s[4 * i]; break; // src + (id<<5) + 16 − src + (id<<5)
|
||||
case 3: e[i] = s[4 * i + 3] - s[4 * i + 1]; break; // src + (id<<5) + 24 − src + (id<<5) + 8
|
||||
}
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
id<MTLDevice> dev = MTLCreateSystemDefaultDevice();
|
||||
NSError *err = nil;
|
||||
id<MTLLibrary> lib = [dev newLibraryWithSource:@(k_nvn_builtin_msl) options:nil error:&err];
|
||||
if (!lib) { printf("MSL 编译失败 %s\n", err.localizedDescription.UTF8String); return 1; }
|
||||
id<MTLCommandQueue> q = [dev newCommandQueue];
|
||||
// 源数据:NREC 条 32 字节记录(= 2×NREC 条 16 字节记录),值带高位与「后小于前」的回绕情形
|
||||
// Source data: NREC 32-byte records (= 2×NREC 16-byte records), with values that have high bits set and wraparound cases where "the later is smaller than the earlier"
|
||||
uint64_t src[4 * NREC];
|
||||
for (int i = 0; i < 4 * NREC; i++) src[i] = 0x0123456789ABCDEFull * (uint64_t)(i + 1) ^ ((uint64_t)i << 40);
|
||||
src[2] = 5; src[0] = 9; // 第 0 条计数差 = 5 − 9 → 64 位回绕 | count difference of entry 0 = 5 − 9 → 64-bit wraparound
|
||||
uint32_t n = N;
|
||||
id<MTLBuffer> bn = [dev newBufferWithBytes:&n length:4 options:MTLResourceStorageModeShared];
|
||||
id<MTLBuffer> bs = [dev newBufferWithBytes:src length:sizeof src options:MTLResourceStorageModeShared];
|
||||
id<MTLBuffer> bd = [dev newBufferWithLength:CAP * 8 options:MTLResourceStorageModeShared];
|
||||
int fail = 0;
|
||||
for (int k = 0; k < 4; k++) {
|
||||
id<MTLComputePipelineState> ps = [dev newComputePipelineStateWithFunction:[lib newFunctionWithName:@(k_nvn_builtin_map[k].fn)] error:&err];
|
||||
int row[4];
|
||||
for (int j = 0; j < 4; j++) {
|
||||
memset(bd.contents, 0xAA, CAP * 8);
|
||||
id<MTLCommandBuffer> cb = [q commandBuffer]; id<MTLComputeCommandEncoder> ce = [cb computeCommandEncoder];
|
||||
[ce setComputePipelineState:ps]; [ce setBuffer:bn offset:0 atIndex:0]; [ce setBuffer:bs offset:0 atIndex:1]; [ce setBuffer:bd offset:0 atIndex:2];
|
||||
[ce dispatchThreadgroups:MTLSizeMake((N + 31) / 32, 1, 1) threadsPerThreadgroup:MTLSizeMake(32, 1, 1)];
|
||||
[ce endEncoding]; [cb commit]; [cb waitUntilCompleted];
|
||||
uint64_t e[CAP]; expect(j, src, e);
|
||||
row[j] = !memcmp(bd.contents, e, sizeof e);
|
||||
}
|
||||
int ok = row[k] && !row[(k + 1) % 4] && !row[(k + 2) % 4] && !row[(k + 3) % 4];
|
||||
printf("%s(%s):对自身期望 %s;对其余 3 个期望全等数 %d(期望 0)→ %s\n", k_nvn_builtin_map[k].fn, k_nvn_builtin_map[k].ctl,
|
||||
row[k] ? "全等(含回绕、哨兵 27 个未动)" : "不等", row[(k + 1) % 4] + row[(k + 2) % 4] + row[(k + 3) % 4], ok ? "✓" : "✗");
|
||||
fail += !ok;
|
||||
}
|
||||
printf("== 4 项,失败 %d ==\n", fail);
|
||||
return fail != 0;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// 全覆盖首绘几何证明单测(nvn_cover.h):期望值按几何手算,不跑被测实现。
|
||||
// 正例:全屏大三角形(-1,-1)(3,-1)(-1,3)、全屏四边形条带;负例:视口只占附件一部分、剪裁只占一部分、三角形缺一角、
|
||||
// 被背面剔除、z 越界、w ≠ 1、两三角形各包一半(单个三角形都包不住四角,按规则不成立——保守)。
|
||||
// Unit tests for the geometric proof of a full-coverage first draw (nvn_cover.h): expected values are hand-calculated from geometry, without running the implementation under test.
|
||||
// Positive cases: fullscreen big triangle (-1,-1)(3,-1)(-1,3), fullscreen quad strip; negative cases: viewport covers only part of the attachment, scissor covers only part, triangle missing a corner,
|
||||
// back-face culled, z out of range, w ≠ 1, two triangles each covering half (no single triangle covers all four corners, so by the rule it does not hold - conservative).
|
||||
#include "../nvn/nvn_cover.h"
|
||||
#include <stdio.h>
|
||||
|
||||
static int fail, total;
|
||||
static void t(const char *name, int want, int got) {
|
||||
total++; fail += want != got;
|
||||
printf("%-44s 期望 %s → 真结果 %s %s\n", name, want ? "成立" : "不成立", got ? "成立" : "不成立", want == got ? "✓" : "✗");
|
||||
}
|
||||
int main(void) {
|
||||
const float big[3][4] = {{-1, -1, 0, 1}, {3, -1, 0, 1}, {-1, 3, 0, 1}}; // 逆时针(NDC y 向上) | counterclockwise (NDC y up)
|
||||
const float big_cw[3][4] = {{-1, -1, 0, 1}, {-1, 3, 0, 1}, {3, -1, 0, 1}}; // 同一三角形,顺时针 | same triangle, clockwise
|
||||
const float quad[4][4] = {{-1, -1, 0.5f, 1}, {1, -1, 0.5f, 1}, {-1, 1, 0.5f, 1}, {1, 1, 0.5f, 1}}; // 条带:两三角形各半屏 | strip: two triangles each covering half the screen
|
||||
const float small[3][4] = {{-1, -1, 0, 1}, {1.9f, -1, 0, 1}, {-1, 1.9f, 0, 1}}; // 斜边 x+y=0.9 切掉 (1,1) 角 | hypotenuse x+y=0.9 cuts off the (1,1) corner
|
||||
const float zout[3][4] = {{-1, -1, 1.5f, 1}, {3, -1, 1.5f, 1}, {-1, 3, 1.5f, 1}};
|
||||
const float w2[3][4] = {{-2, -2, 0, 2}, {6, -2, 0, 2}, {-2, 6, 0, 2}};
|
||||
const float vp_full[4] = {0, 0, 1600, 900}, vp_half[4] = {0, 0, 800, 900}, vp_off[4] = {0, 450, 1600, 900};
|
||||
const int sc_full[4] = {0, 0, 1600, 900}, sc_part[4] = {0, 0, 1600, 450};
|
||||
t("全屏三角形,视口 = 整块,不剔除", 1, nvn_cover(big, 3, 4, 0, 1, 1, vp_full, 0, NULL, 1600, 900));
|
||||
t("全屏三角形,无视口设置(缺省整块)", 1, nvn_cover(big, 3, 4, 0, 1, 0, NULL, 0, NULL, 1600, 900));
|
||||
t("全屏三角形,剔背面,逆时针为正面", 1, nvn_cover(big, 3, 4, 2, 1, 1, vp_full, 1, sc_full, 1600, 900));
|
||||
t("负:同一三角形顺时针,剔背面(被剔)", 0, nvn_cover(big_cw, 3, 4, 2, 1, 1, vp_full, 0, NULL, 1600, 900));
|
||||
t("负:视口只占附件左半", 0, nvn_cover(big, 3, 4, 0, 1, 1, vp_half, 0, NULL, 1600, 900));
|
||||
t("负:视口下移(不从 0 起)", 0, nvn_cover(big, 3, 4, 0, 1, 1, vp_off, 0, NULL, 1600, 900));
|
||||
t("负:视口整块 1600x900,附件是 1920x1080", 0, nvn_cover(big, 3, 4, 0, 1, 1, vp_full, 0, NULL, 1920, 1080));
|
||||
t("负:剪裁只占上半", 0, nvn_cover(big, 3, 4, 0, 1, 1, vp_full, 1, sc_part, 1600, 900));
|
||||
t("负:三角形缺 (1,1) 角", 0, nvn_cover(small, 3, 4, 0, 1, 1, vp_full, 0, NULL, 1600, 900));
|
||||
t("负:z 超出 [0,1]", 0, nvn_cover(zout, 3, 4, 0, 1, 1, vp_full, 0, NULL, 1600, 900));
|
||||
t("负:w ≠ 1", 0, nvn_cover(w2, 3, 4, 0, 1, 1, vp_full, 0, NULL, 1600, 900));
|
||||
t("负:全屏四边形条带(单个三角形包不住,保守)", 0, nvn_cover(quad, 4, 5, 0, 1, 1, vp_full, 0, NULL, 1600, 900));
|
||||
t("负:正背面都剔", 0, nvn_cover(big, 3, 4, 3, 1, 1, vp_full, 0, NULL, 1600, 900));
|
||||
t("负:图元是线(非三角形)", 0, nvn_cover(big, 3, 1, 0, 1, 1, vp_full, 0, NULL, 1600, 900));
|
||||
printf("== %d 项,失败 %d ==\n", total, fail);
|
||||
return fail != 0;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
void *front_metal_layer(void) { return NULL; }
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
module_t g_mod[MAX_MOD]; int g_nmod;
|
||||
void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { return bp_now(); }
|
||||
static int fail, count;
|
||||
#define EXPECT(name, want, got) do { uint64_t w=(want), g=(got); count++; printf("%s 期望 %llu → 真结果 %llu %s\n", name, (unsigned long long)w, (unsigned long long)g, w==g?"✓":"✗"); fail += w != g; } while (0)
|
||||
typedef struct { uint8_t *p; size_t n; } chain;
|
||||
static chain chain_new(void) { chain c={0}; if (posix_memalign((void **)&c.p,getpagesize(),65536)) abort(); memset(c.p,0,65536); mtl_pool_add(c.p,65536); return c; }
|
||||
static void emit(chain *c, unsigned op, const void *a, size_t n) { size_t z=(8+n+7)&~7ull; op_hdr h={op,(uint32_t)z}; memcpy(c->p+c->n,&h,8); if(n) memcpy(c->p+c->n+8,a,n); c->n+=z; }
|
||||
static tex_t tex(unsigned w) { static uint64_t s=9000; tex_t t={.serial=s++}; t.d.width=t.d.height=w; t.d.depth=t.d.samples=1; t.d.levels=2; t.d.target=NVN_TEXTURE_TARGET_2D; t.d.format=NVN_FORMAT_RGBA8; return t; }
|
||||
static int view(const tex_t *t, int lv) { static int id=1200; view_t v={.set_levels=1,.base_level=lv,.nlevels=1}; mtl_reg_tex(id,t,&v); return id++; }
|
||||
static void set_rt(chain *c, const tex_t *a, const tex_t *b, int alv) { p_set_rt r={.n=b?2:1}; r.color[0]=a; r.color[1]=b; for(int i=0;i<r.n;i++){r.has_cview[i]=1;r.cview[i].set_levels=1;r.cview[i].base_level=i?0:alv;r.cview[i].nlevels=1;} emit(c,OP_SET_RT,&r,sizeof r); p_viewports v={.n=1};v.v[0][2]=v.v[0][3]=8;emit(c,OP_VIEWPORTS,&v,sizeof v);p_scissor sc={0,0,8,8};emit(c,OP_SCISSOR,&sc,sizeof sc); }
|
||||
static void clear_color(chain *c, int i, float r, float g, float b) { p_clear_color x={.index=i,.mask=15,.rgba={r,g,b,1}}; emit(c,OP_CLEAR_COLOR,&x,sizeof x); }
|
||||
static void bind_prog(chain *c, prog_t *p) { p_bind_program b={p,3}; emit(c,OP_BIND_PROGRAM,&b,sizeof b); }
|
||||
static void bind_tex(chain *c, int id) { p_bind_handles b={.stage=1,.first=0,.n=1};b.h[0]=id;emit(c,OP_BIND_TEX,&b,sizeof b); }
|
||||
static void draw_cmd(chain *c) { p_draw d={NVN_DRAW_PRIMITIVE_TRIANGLES,0,3}; emit(c,OP_DRAW,&d,sizeof d); }
|
||||
static void blend(chain *c) { color_st col={1,NVN_LOGIC_OP_COPY,NVN_ALPHA_FUNC_ALWAYS}; p_bind_state x={.kind=1};memcpy(x.bytes,&col,sizeof col);emit(c,OP_BIND_STATE,&x,sizeof x); blend_st b={0,NVN_BLEND_FUNC_SRC_ALPHA,NVN_BLEND_FUNC_ONE_MINUS_SRC_ALPHA,NVN_BLEND_FUNC_ONE,NVN_BLEND_FUNC_ZERO,NVN_BLEND_EQUATION_ADD,NVN_BLEND_EQUATION_ADD};x.kind=0;memcpy(x.bytes,&b,sizeof b);emit(c,OP_BIND_STATE,&x,sizeof x); }
|
||||
static void ds_off(chain *c) { ds_st d={0,0,NVN_DEPTH_FUNC_ALWAYS,0,NVN_STENCIL_FUNC_ALWAYS,NVN_STENCIL_FUNC_ALWAYS,NVN_STENCIL_OP_KEEP,NVN_STENCIL_OP_KEEP,NVN_STENCIL_OP_KEEP,NVN_STENCIL_OP_KEEP,NVN_STENCIL_OP_KEEP,NVN_STENCIL_OP_KEEP}; p_bind_state x={.kind=5}; memcpy(x.bytes,&d,sizeof d); emit(c,OP_BIND_STATE,&x,sizeof x); }
|
||||
static void readback(const tex_t *t, uint8_t out[256]) { id<MTLBuffer> b=[g_dev newBufferWithLength:256 options:MTLResourceStorageModeShared]; [blit() copyFromTexture:tex_mtl(t) sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0,0,0) sourceSize:MTLSizeMake(8,8,1) toBuffer:b destinationOffset:0 destinationBytesPerRow:32 destinationBytesPerImage:256]; uint64_t f=mtl_sub_commit(); EXPECT("提交完成",1,mtl_wait(f,5000000000ull)); EXPECT("提交反馈无错误",0,mtl_last_commit_error()); memcpy(out,b.contents,256); }
|
||||
static NvProg *g_tkeep[256]; static int g_tnkeep; /* 测试里的程序对象常驻:释放后新对象可能落在同一地址,管线缓存按对象地址认会取到旧管线(生产里程序对象不释放) | Program objects in the tests are permanent: after a free, a new object may land at the same address, and the pipeline cache, keyed by object address, would return the old pipeline (in production program objects are never freed) */
|
||||
static void setup_prog(prog_t *pg) { NSError *e=nil; id<MTLLibrary> l=[g_dev newLibraryWithSource:@"#include <metal_stdlib>\nusing namespace metal; vertex float4 v(uint n[[vertex_id]]){float2 p[3]={float2(-1,-1),float2(3,-1),float2(-1,3)};return float4(p[n],0,1);}\nfragment float4 red(){return float4(1,0,0,0.5);}\nstruct A{texture2d<float> t[[id(0)]];}; fragment float4 sample(constant A&a[[buffer(0)]]){return a.t.read(uint2(0));}\n" options:nil error:&e]; if(!l){fprintf(stderr,"%s\n",e.localizedDescription.UTF8String);abort();} for(int i=0;i<2;i++)pg[i].serial=8000+i; for(int i=0;i<2;i++){NvProg *p=[NvProg new];p->sh[0]=[NvShader new];p->sh[0]->fn=[l newFunctionWithName:@"v"];p->sh[1]=[NvShader new];p->sh[1]->stage=1;p->sh[1]->fn=[l newFunctionWithName:i?@"sample":@"red"];if(i){p->sh[1]->rf.nb=1;p->sh[1]->rf.b[0]=(nvn_rbind){.kind=NVN_RB_TEX,.reg=0,.dtt=2};p->sh[1]->ae=[p->sh[1]->fn newArgumentEncoderWithBufferIndex:0];}if(g_tnkeep<256)g_tkeep[g_tnkeep++]=p;serial_put(pg[i].serial,p);} }
|
||||
static uint64_t run_case(int mode, int enabled, uint8_t px[256]) { tex_t a=tex(8),b=tex(8),q2=tex(8); int aid=view(&a,0), a1=view(&a,1); chain c=chain_new(); prog_t pg[2]={0}; setup_prog(pg); set_rt(&c,&a,NULL,0);clear_color(&c,0,0,0,0);ds_off(&c);bind_prog(&c,&pg[0]);blend(&c);draw_cmd(&c);set_rt(&c,&b,NULL,0);clear_color(&c,0,0,0,0);if(mode==1){uint64_t t=NVN_COUNTER_TYPE_SAMPLES_PASSED;emit(&c,OP_RESET_COUNTER,&t,sizeof t);}if(mode==2){bind_prog(&c,&pg[1]);bind_tex(&c,aid);}ds_off(&c);draw_cmd(&c);set_rt(&c,&a,&q2,0);if(mode==3)clear_color(&c,0,0,0,0);bind_prog(&c,&pg[1]);bind_tex(&c,mode==5?aid:a1);draw_cmd(&c);emit(&c,OP_END,NULL,0);state_reset();memset(&R,0,sizeof R);vis_clear();g_vis_on=g_vis_counting=0;if(!enabled)setenv("DM_NVN_DEFER","0",1);else setenv("DM_NVN_DEFER","1",1);uint64_t start=g_stat_pass;mtl_sub_begin();uint64_t hh=(uint64_t)c.p;mtl_sub_index(&hh,1);mtl_exec(c.p);readback(&a,px);return g_stat_pass-start; }
|
||||
static uint64_t run_multi(int enabled, uint8_t px[256]) { tex_t a=tex(8),b=tex(8),mid=tex(8); chain c=chain_new(); static prog_t pg[2]; memset(pg,0,sizeof pg); /* 静态:程序缓存按 prog_t 地址认,栈上会与 run_case 的 pg 重址 | Static: the program cache is keyed by prog_t address, and on the stack it would share an address with run_case's pg */ setup_prog(pg); set_rt(&c,&a,NULL,0);clear_color(&c,0,0,0,0);ds_off(&c);bind_prog(&c,&pg[0]);blend(&c);draw_cmd(&c);set_rt(&c,&mid,NULL,0);ds_off(&c);draw_cmd(&c);set_rt(&c,&b,NULL,0);clear_color(&c,0,0,0,0);draw_cmd(&c);set_rt(&c,&a,&b,0);bind_prog(&c,&pg[0]);draw_cmd(&c);emit(&c,OP_END,NULL,0);state_reset();memset(&R,0,sizeof R);vis_clear();g_vis_on=g_vis_counting=0;setenv("DM_NVN_DEFER",enabled?"1":"0",1);uint64_t start=g_stat_pass;mtl_sub_begin();uint64_t hh=(uint64_t)c.p;mtl_sub_index(&hh,1);mtl_exec(c.p);readback(&a,px);return g_stat_pass-start; }
|
||||
static uint64_t run_chain_id(int enabled, uint8_t px[256]) { /* 链式正例:A 在三个通道里都是第 0 个附件——P1 画 A;P2 的通道 (A, D) 是 P1 的 Q,P2 画 A 并整体推迟进 Q2 (A, D) | Chained positive case: A is attachment 0 in all three passes - P1 draws A; P2's pass (A, D) is P1's Q, P2 draws A and is deferred as a whole into Q2 (A, D) */
|
||||
tex_t a=tex(8),d=tex(8),mid=tex(8); chain c=chain_new(); static prog_t pg[2]; memset(pg,0,sizeof pg); setup_prog(pg);
|
||||
set_rt(&c,&a,NULL,0);clear_color(&c,0,0,0,0);ds_off(&c);bind_prog(&c,&pg[0]);blend(&c);draw_cmd(&c);
|
||||
set_rt(&c,&mid,NULL,0);ds_off(&c);draw_cmd(&c);
|
||||
set_rt(&c,&a,&d,0);clear_color(&c,1,0,0,0);draw_cmd(&c);
|
||||
set_rt(&c,&mid,NULL,0);draw_cmd(&c);
|
||||
set_rt(&c,&a,&d,0);bind_prog(&c,&pg[0]);draw_cmd(&c);emit(&c,OP_END,NULL,0);
|
||||
state_reset();memset(&R,0,sizeof R);vis_clear();g_vis_on=g_vis_counting=0;setenv("DM_NVN_DEFER",enabled?"1":"0",1);
|
||||
uint64_t start=g_stat_pass;mtl_sub_begin();uint64_t hh=(uint64_t)c.p;mtl_sub_index(&hh,1);mtl_exec(c.p);readback(&a,px);return g_stat_pass-start; }
|
||||
static uint64_t run_chain(int enabled, uint8_t px[256]) { /* 链式:P1 画 A;P2 的通道 (D, A) 正是 P1 的 Q,P2 自己画 D 并整体推迟进 Q2 (A, D)——A 在两个通道里的下标不同(1 → 0),映射复合错了 A 就画到 D 上 | Chained: P1 draws A; P2's pass (D, A) is exactly P1's Q, P2 itself draws D and is deferred as a whole into Q2 (A, D) - A's index differs between the two passes (1 → 0), and if the mapping is composed wrongly A gets drawn onto D */
|
||||
tex_t a=tex(8),d=tex(8),mid=tex(8); chain c=chain_new(); static prog_t pg[2]; memset(pg,0,sizeof pg); setup_prog(pg);
|
||||
set_rt(&c,&a,NULL,0);clear_color(&c,0,0,0,0);ds_off(&c);bind_prog(&c,&pg[0]);blend(&c);draw_cmd(&c);
|
||||
set_rt(&c,&mid,NULL,0);ds_off(&c);draw_cmd(&c);
|
||||
set_rt(&c,&d,&a,0);clear_color(&c,0,0,0,0);draw_cmd(&c);
|
||||
set_rt(&c,&mid,NULL,0);draw_cmd(&c);
|
||||
set_rt(&c,&a,&d,0);bind_prog(&c,&pg[0]);draw_cmd(&c);emit(&c,OP_END,NULL,0);
|
||||
state_reset();memset(&R,0,sizeof R);vis_clear();g_vis_on=g_vis_counting=0;setenv("DM_NVN_DEFER",enabled?"1":"0",1);
|
||||
uint64_t start=g_stat_pass;mtl_sub_begin();uint64_t hh=(uint64_t)c.p;mtl_sub_index(&hh,1);mtl_exec(c.p);readback(&a,px);return g_stat_pass-start; }
|
||||
int main(void){@autoreleasepool{setvbuf(stdout,NULL,_IONBF,0);setenv("DM_NVN_TBDR","1",1);mtl_init();uint8_t p[256];uint8_t off[256];uint64_t n0=run_case(0,0,off);uint64_t d0=g_defer_n;uint64_t n1=run_case(0,1,p);uint64_t d1=g_defer_n;EXPECT("正例推迟计数",1,d1-d0);EXPECT("正例开通道少一",1,n0-n1);EXPECT("正例像素非黑",1,p[0]>0);EXPECT("正例开关逐字节相同",0,(uint64_t)memcmp(p,off,256));
|
||||
uint64_t m0=run_multi(0,off);uint64_t md0=g_defer_n;uint64_t m1=run_multi(1,p);EXPECT("同Q两组推迟计数(B 在 Q 里下标不同,只成立 A)",1,g_defer_n-md0);EXPECT("同Q两组开通道少一",1,m0-m1);EXPECT("同Q两组开关逐字节相同",0,(uint64_t)memcmp(p,off,256));
|
||||
uint64_t k0=run_chain(0,off);uint64_t kd0=g_defer_n;uint64_t k1=run_chain(1,p);EXPECT("链式下标不同不推迟",0,g_defer_n-kd0);EXPECT("链式下标不同开通道数不变",0,k0-k1);EXPECT("链式开关逐字节相同",0,(uint64_t)memcmp(p,off,256));
|
||||
uint64_t j0=run_chain_id(0,off);uint64_t jd0=g_defer_n;uint64_t j1=run_chain_id(1,p);EXPECT("链式恒等两组成立",2,g_defer_n-jd0);EXPECT("链式恒等开通道少二",2,j0-j1);EXPECT("链式恒等开关逐字节相同",0,(uint64_t)memcmp(p,off,256));
|
||||
for(int m=1;m<=5;m++){run_case(m,0,off);uint64_t before=g_defer_n;run_case(m,1,p);EXPECT(m==2||m==3||m==5?"反例不推迟":"另一个正例仍推迟",m==2||m==3||m==5?0:1,g_defer_n-before);EXPECT("开关逐字节相同",0,(uint64_t)memcmp(p,off,256));}printf("== %d 项,失败 %d ==\n",count,fail);return fail!=0;}}
|
||||
@@ -0,0 +1,122 @@
|
||||
#import <Metal/Metal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include "../nvn/include/nvn.h"
|
||||
#include "../nvn/nvn_tex.h"
|
||||
#include "../tex/nvn_deswizzle.h"
|
||||
#include "../tex/nvn_deswizzle_gpu.h"
|
||||
|
||||
typedef struct { const char *name; nvn_texdesc d; } test_case;
|
||||
typedef struct { size_t off, pitch, bytes; unsigned level, layer, slices, rows; } record;
|
||||
|
||||
static uint64_t now_ns(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint64_t)t.tv_sec * 1000000000ull + t.tv_nsec; }
|
||||
static void fill_bytes(unsigned char *p, size_t n, uint32_t seed) { for (size_t i = 0; i < n; i++) p[i] = (unsigned char)(seed + i * 37u + (i >> 7)); }
|
||||
|
||||
static int run_case(id<MTLDevice> dev, id<MTLCommandQueue> queue, const test_case *tc, int special) {
|
||||
nvn_texlayout layout; nvn_tex_layout(&tc->d, &layout);
|
||||
size_t source_off = special ? 4 : 0;
|
||||
unsigned levels = tc->d.levels ? tc->d.levels : 1;
|
||||
unsigned count = 0; size_t dst_size = 32;
|
||||
for (unsigned l = 0; l < levels; l++) {
|
||||
uint32_t rb, rows, slices, bpb; uint64_t base; unsigned th, td;
|
||||
if (nvn_deswizzle_geom(&tc->d, l, 0, &rb, &rows, &slices, &base, &th, &td, &bpb)) return 1;
|
||||
unsigned layers = layout.layers;
|
||||
for (unsigned layer = 0; layer < layers; layer++) {
|
||||
size_t pitch = rb + ((special && !count) ? 3 : 0);
|
||||
size_t bytes = (size_t)slices * rows * pitch;
|
||||
count++; dst_size += bytes + 7;
|
||||
}
|
||||
}
|
||||
record *records = calloc(count, sizeof(*records));
|
||||
unsigned char *expected = calloc(1, dst_size + 32), *source = calloc(1, source_off + layout.size + 32);
|
||||
if (!records || !expected || !source) return 1;
|
||||
size_t cursor = 4;
|
||||
unsigned ri = 0;
|
||||
for (unsigned l = 0; l < levels; l++) {
|
||||
uint32_t rb, rows, slices, bpb; uint64_t base; unsigned th, td;
|
||||
nvn_deswizzle_geom(&tc->d, l, 0, &rb, &rows, &slices, &base, &th, &td, &bpb);
|
||||
for (unsigned layer = 0; layer < layout.layers; layer++) {
|
||||
size_t pitch = rb + ((special && ri == 0) ? 3 : 0), bytes = (size_t)slices * rows * pitch;
|
||||
cursor = (cursor + 3) & ~3ull;
|
||||
records[ri] = (record){cursor, pitch, (size_t)slices * rows * rb, l, layer, slices, rows};
|
||||
fill_bytes(expected + cursor, bytes, 17u + ri * 29u);
|
||||
if (nvn_swizzle(&tc->d, l, layer, expected + cursor, pitch, source + source_off)) return 1;
|
||||
cursor += bytes + 7; ri++;
|
||||
}
|
||||
}
|
||||
id<MTLBuffer> src = [dev newBufferWithBytes:source length:source_off + layout.size + 32 options:MTLResourceStorageModeShared];
|
||||
id<MTLBuffer> dst = [dev newBufferWithLength:dst_size + 32 options:MTLResourceStorageModeShared];
|
||||
memset(dst.contents, 0xCD, dst.length);
|
||||
id<MTLCommandBuffer> cb = [queue commandBuffer]; id<MTLComputeCommandEncoder> enc = [cb computeCommandEncoder];
|
||||
int fail = 0;
|
||||
for (unsigned i = 0; i < count; i++)
|
||||
fail |= nvn_deswz_gpu_encode(enc, src, source_off, &tc->d, records[i].level, records[i].layer, dst, records[i].off, records[i].pitch) != 0;
|
||||
[enc endEncoding]; [cb commit]; [cb waitUntilCompleted];
|
||||
for (unsigned i = 0; i < count; i++) {
|
||||
size_t row_bytes = records[i].bytes / (records[i].slices * records[i].rows);
|
||||
int ok = 1;
|
||||
for (unsigned z = 0; z < records[i].slices; z++)
|
||||
for (unsigned y = 0; y < records[i].rows; y++)
|
||||
ok &= !memcmp((unsigned char *)dst.contents + records[i].off + ((size_t)z * records[i].rows + y) * records[i].pitch,
|
||||
expected + records[i].off + ((size_t)z * records[i].rows + y) * records[i].pitch, row_bytes);
|
||||
printf("%s L%u layer%u: %s %zu 字节\n", tc->name, records[i].level, records[i].layer, ok ? "OK" : "BAD", records[i].bytes);
|
||||
fail |= !ok;
|
||||
}
|
||||
free(records); free(expected); free(source);
|
||||
return fail;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
@autoreleasepool {
|
||||
id<MTLDevice> dev = MTLCreateSystemDefaultDevice();
|
||||
if (!dev) { printf("BAD:无 Metal 设备\n"); return 1; }
|
||||
if (nvn_deswz_gpu_init(dev)) { printf("BAD:GPU 解排布管线初始化失败\n"); return 1; }
|
||||
id<MTLCommandQueue> queue = [dev newCommandQueue];
|
||||
test_case cases[] = {
|
||||
{"RGBA8 1x1", {1, NVN_FORMAT_RGBA8, 0, 0, 1, 1, 1, 1, 0}},
|
||||
{"RGBA8 3x5", {1, NVN_FORMAT_RGBA8, 0, 0, 3, 5, 1, 1, 0}},
|
||||
{"RGBA8 64x64", {1, NVN_FORMAT_RGBA8, 0, 0, 64, 64, 1, 1, 0}},
|
||||
{"RGBA8 1000x700", {1, NVN_FORMAT_RGBA8, 0, 0, 1000, 700, 1, 1, 0}},
|
||||
{"RGBA8 2048x2048 mip", {1, NVN_FORMAT_RGBA8, 0, 0, 2048, 2048, 1, 12, 0}},
|
||||
{"R8 3", {1, NVN_FORMAT_R8, 0, 0, 3, 1, 1, 1, 0}},
|
||||
{"R8 17", {1, NVN_FORMAT_R8, 0, 0, 17, 1, 1, 1, 0}},
|
||||
{"RGBA16F", {1, NVN_FORMAT_RGBA16F, 0, 0, 17, 9, 1, 2, 0}},
|
||||
{"RGBA32F", {1, NVN_FORMAT_RGBA32F, 0, 0, 17, 9, 1, 2, 0}},
|
||||
{"BC1 30x18 mip", {1, NVN_FORMAT_RGBA_DXT1, 0, 0, 30, 18, 1, 4, 0}},
|
||||
{"BC3 30x18 mip", {1, NVN_FORMAT_RGBA_DXT3, 0, 0, 30, 18, 1, 4, 0}},
|
||||
{"BC7 30x18 mip", {1, NVN_FORMAT_BPTC_UNORM, 0, 0, 30, 18, 1, 4, 0}},
|
||||
{"2D array 5", {4, NVN_FORMAT_RGBA8, 0, 0, 17, 9, 5, 2, 0}},
|
||||
{"cube", {8, NVN_FORMAT_RGBA8, 0, 0, 17, 9, 1, 2, 0}},
|
||||
{"3D 64x64x16 mip", {2, NVN_FORMAT_RGBA8, 0, 0, 64, 64, 16, 7, 0}},
|
||||
};
|
||||
int fail = 0; unsigned n = 0;
|
||||
for (unsigned i = 0; i < sizeof(cases) / sizeof(*cases); i++) { fail |= run_case(dev, queue, &cases[i], i == 1); n++; }
|
||||
|
||||
test_case neg = {"负对照", {1, NVN_FORMAT_RGBA8, 0, 0, 64, 64, 1, 2, 0}};
|
||||
nvn_texlayout nl; nvn_tex_layout(&neg.d, &nl);
|
||||
size_t rb, expected_bytes = 64 * 64 * 4; rb = 64 * 4;
|
||||
unsigned char *lin = malloc(expected_bytes), *srcmem = calloc(1, nl.size + 32);
|
||||
fill_bytes(lin, expected_bytes, 91); nvn_swizzle(&neg.d, 0, 0, lin, rb, srcmem);
|
||||
id<MTLBuffer> sb = [dev newBufferWithBytes:srcmem length:nl.size + 32 options:MTLResourceStorageModeShared];
|
||||
id<MTLBuffer> db = [dev newBufferWithLength:expected_bytes options:MTLResourceStorageModeShared]; memset(db.contents, 0xCD, db.length);
|
||||
id<MTLCommandBuffer> ncb = [queue commandBuffer]; id<MTLComputeCommandEncoder> ne = [ncb computeCommandEncoder];
|
||||
int enc_bad = nvn_deswz_gpu_encode(ne, sb, 0, &neg.d, 1, 0, db, 0, rb); [ne endEncoding]; [ncb commit]; [ncb waitUntilCompleted];
|
||||
int mismatch = enc_bad || memcmp(db.contents, lin, expected_bytes) != 0; printf("负对照(错误 level): %s %zu 字节\n", mismatch ? "OK(判红)" : "BAD(未判红)", expected_bytes); fail |= !mismatch;
|
||||
free(lin); free(srcmem);
|
||||
|
||||
test_case perf = {"性能参考", {1, NVN_FORMAT_RGBA8, 0, 0, 2048, 2048, 1, 12, 0}};
|
||||
nvn_texlayout pl; nvn_tex_layout(&perf.d, &pl); size_t perf_size = 0;
|
||||
for (unsigned l = 0; l < perf.d.levels; l++) { uint32_t pr, py, pz, pb; uint64_t pbase; unsigned pth, ptd; nvn_deswizzle_geom(&perf.d, l, 0, &pr, &py, &pz, &pbase, &pth, &ptd, &pb); perf_size += (size_t)pr * py; }
|
||||
unsigned char *ps = calloc(1, pl.size), *pd = calloc(1, perf_size); size_t perf_cursor = 0;
|
||||
for (unsigned l = 0; l < perf.d.levels; l++) { uint32_t pr, py, pz, pb; uint64_t pbase; unsigned pth, ptd; nvn_deswizzle_geom(&perf.d, l, 0, &pr, &py, &pz, &pbase, &pth, &ptd, &pb); fill_bytes(pd + perf_cursor, (size_t)pr * py, 7 + l); nvn_swizzle(&perf.d, l, 0, pd + perf_cursor, pr, ps); perf_cursor += (size_t)pr * py; }
|
||||
uint64_t c0 = now_ns(); perf_cursor = 0; for (unsigned l = 0; l < perf.d.levels; l++) { uint32_t pr, py, pz, pb; uint64_t pbase; unsigned pth, ptd; nvn_deswizzle_geom(&perf.d, l, 0, &pr, &py, &pz, &pbase, &pth, &ptd, &pb); nvn_deswizzle(&perf.d, l, 0, ps, pd + perf_cursor, pr); perf_cursor += (size_t)pr * py; } uint64_t cpu_ns = now_ns() - c0;
|
||||
id<MTLBuffer> psrc = [dev newBufferWithBytes:ps length:pl.size options:MTLResourceStorageModeShared];
|
||||
id<MTLBuffer> pdst = [dev newBufferWithLength:perf_size options:MTLResourceStorageModeShared];
|
||||
c0 = now_ns(); id<MTLCommandBuffer> pcb = [queue commandBuffer]; id<MTLComputeCommandEncoder> pe = [pcb computeCommandEncoder]; perf_cursor = 0; for (unsigned l = 0; l < perf.d.levels; l++) { uint32_t pr, py, pz, pb; uint64_t pbase; unsigned pth, ptd; nvn_deswizzle_geom(&perf.d, l, 0, &pr, &py, &pz, &pbase, &pth, &ptd, &pb); nvn_deswz_gpu_encode(pe, psrc, 0, &perf.d, l, 0, pdst, perf_cursor, pr); perf_cursor += (size_t)pr * py; } [pe endEncoding]; uint64_t encode_ns = now_ns() - c0; [pcb commit]; [pcb waitUntilCompleted]; uint64_t gpu_ns = now_ns() - c0;
|
||||
printf("性能参考:2048x2048 RGBA8 带 mip(约 22 MB),CPU nvn_deswizzle %.3f ms;GPU 编码 %.3f ms + waitUntilCompleted 总计 %.3f ms\n", cpu_ns / 1e6, encode_ns / 1e6, gpu_ns / 1e6); free(ps); free(pd);
|
||||
printf("== %u 例全过 / 负对照判红 ==\n", n);
|
||||
return fail != 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
#include "../nvn/nvn_dirty.h"
|
||||
#include "../../host/dm.h"
|
||||
#include <sys/mman.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
module_t g_mod[MAX_MOD];
|
||||
int g_nmod;
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
void crash_install(void);
|
||||
|
||||
static int g_fail;
|
||||
#define EXPECT(name, want, got) do { \
|
||||
long long want_ = (long long)(want), got_ = (long long)(got); \
|
||||
printf("%-52s 期望 %-4lld → 真结果 %-4lld %s\n", name, want_, got_, want_ == got_ ? "✓" : "✗"); \
|
||||
if (want_ != got_) g_fail++; \
|
||||
} while (0)
|
||||
|
||||
static void *page_map(void) {
|
||||
void *p = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
|
||||
if (p == MAP_FAILED) { perror("mmap"); exit(2); }
|
||||
return p;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
crash_install();
|
||||
|
||||
for (int i = 0; i < 65; i++) {
|
||||
void *p = page_map();
|
||||
nvn_dirty_add_range(p, 4096);
|
||||
nvn_dirty_remove_range(p);
|
||||
munmap(p, 4096);
|
||||
}
|
||||
|
||||
void *reused = page_map();
|
||||
nvn_dirty_add_range(reused, 4096);
|
||||
nvn_dirty_protect(reused, 4096);
|
||||
uint64_t stamp = nvn_dirty_now();
|
||||
((volatile uint8_t *)reused)[0] = 1;
|
||||
EXPECT("累计 65 次销池后新池写入被判脏", 1, nvn_dirty_since(reused, 4096, stamp));
|
||||
nvn_dirty_remove_range(reused);
|
||||
munmap(reused, 4096);
|
||||
|
||||
void *live[300];
|
||||
for (int i = 0; i < 300; i++) {
|
||||
live[i] = page_map();
|
||||
nvn_dirty_add_range(live[i], 4096);
|
||||
}
|
||||
void *overflow = live[299];
|
||||
nvn_dirty_protect(overflow, 4096);
|
||||
stamp = nvn_dirty_now();
|
||||
((volatile uint8_t *)overflow)[0] = 2;
|
||||
EXPECT("同时存活超过上限的池保守判脏", 1, nvn_dirty_since(overflow, 4096, stamp));
|
||||
for (int i = 0; i < 300; i++) {
|
||||
nvn_dirty_remove_range(live[i]);
|
||||
munmap(live[i], 4096);
|
||||
}
|
||||
return g_fail != 0;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// 局内双渲染回归:直接走生产 fz_end / fz_check_run,用 16×16 真 Metal 附件。
|
||||
// 后通道逻辑 c0 位于并集物理 c3;红色与蓝色的期望值由常量定义,不借被测实现算。
|
||||
// In-run double-render regression: goes directly through production fz_end / fz_check_run, with real 16×16 Metal attachments.
|
||||
// The later pass's logical c0 is at physical c3 of the union; the expected red and blue values are defined by constants, not computed via the implementation under test.
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
void *front_metal_layer(void) { return NULL; }
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
module_t g_mod[MAX_MOD]; int g_nmod;
|
||||
void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { return bp_now(); }
|
||||
|
||||
static int fail, count;
|
||||
#define EXPECT(name, want, got) do { uint64_t w = (want), v = (got); count++; \
|
||||
printf("%s 期望 %llu → 真结果 %llu %s\n", name, (unsigned long long)w, \
|
||||
(unsigned long long)v, w == v ? "✓" : "✗"); fail += w != v; } while (0)
|
||||
|
||||
static void check_color(int blue, const prog_t *pg, tex_t t[4]) {
|
||||
uint64_t same = g_fzc_same, diff = g_fzc_diff;
|
||||
state_reset(); S.prog = pg;
|
||||
memset(&R, 0, sizeof R); R.has_rt = 1; R.rt.n = 4;
|
||||
for (int i = 0; i < 4; i++) R.rt.color[i] = &t[i];
|
||||
R.clear_c[3] = 1; R.cc[3] = MTLClearColorMake(!blue, 0, blue, 1);
|
||||
memset(&g_fz, 0, sizeof g_fz);
|
||||
g_fz.active = 1; g_fz.phase = 2; g_fz.n1 = 3;
|
||||
g_fz.rt2.n = 1; g_fz.rt2.color[0] = &t[3];
|
||||
memset(g_fz.p2map, -1, sizeof g_fz.p2map); g_fz.p2map[0] = 3;
|
||||
g_fz.wrote[3] = 1;
|
||||
p_draw dw = {NVN_DRAW_PRIMITIVE_TRIANGLES, 0, 3};
|
||||
fz_snap_take(&dw, NULL);
|
||||
mtl_sub_begin(); rp_begin_ex(1); rp_end();
|
||||
uint64_t f = mtl_sub_commit();
|
||||
EXPECT("GPU 完成", 1, mtl_wait(f, 5000000000ull));
|
||||
EXPECT(blue ? "负对照:蓝色合并结果 vs 红色普通结果,确实比到不同附件" : "物理 c3 → 逻辑 c0,确实比到同一红色附件",
|
||||
1, blue ? g_fzc_diff - diff : g_fzc_same - same);
|
||||
EXPECT("本例恰好登记一个比对,不漏报也不重复", 1, g_fzc_same - same + g_fzc_diff - diff);
|
||||
EXPECT("结束后保持后通道逻辑目标", 1, R.rt.n == 1 && R.rt.color[0] == &t[3]);
|
||||
EXPECT("快照释放", 0, g_nfzs);
|
||||
}
|
||||
|
||||
int main(void) { @autoreleasepool {
|
||||
setenv("DM_NVN_FUSE_CHECK", "1", 1); mtl_init();
|
||||
NSError *error = nil;
|
||||
id<MTLLibrary> lib = [g_dev newLibraryWithSource:@"#include <metal_stdlib>\nusing namespace metal;\n"
|
||||
"vertex float4 v(uint n [[vertex_id]]) { float2 p[3] = {float2(-1,-1),float2(3,-1),float2(-1,3)}; return float4(p[n],0,1); }\n"
|
||||
"fragment float4 f() { return float4(1,0,0,1); }\n" options:nil error:&error];
|
||||
if (!lib) { fprintf(stderr, "%s\n", error.localizedDescription.UTF8String); return 2; }
|
||||
NvProg *pr = [NvProg new];
|
||||
pr->sh[0] = [NvShader new]; pr->sh[0]->fn = [lib newFunctionWithName:@"v"];
|
||||
pr->sh[1] = [NvShader new]; pr->sh[1]->fn = [lib newFunctionWithName:@"f"]; pr->sh[1]->stage = 1;
|
||||
prog_t pg = {.serial = 100}; serial_put(pg.serial, pr);
|
||||
tex_t t[4] = {0};
|
||||
for (int i = 0; i < 4; i++) { t[i].serial = 101 + i; t[i].d.width = t[i].d.height = 16;
|
||||
t[i].d.depth = t[i].d.levels = t[i].d.samples = 1; t[i].d.target = NVN_TEXTURE_TARGET_2D; t[i].d.format = NVN_FORMAT_RGBA8; }
|
||||
check_color(0, &pg, t); check_color(1, &pg, t);
|
||||
printf("== %d 项,失败 %d ==\n", count, fail); return fail != 0;
|
||||
} }
|
||||
@@ -0,0 +1,31 @@
|
||||
// 哈希表单测:随机插入 / 覆盖 / 删除 / 清空对照朴素数组模型;键空间小、键长取 8 与 20(含非 8 倍数尾巴),逼出长探测链与回移删除。
|
||||
// Hash table unit tests: random insert / overwrite / delete / clear checked against a naive array model; small key space, key lengths 8 and 20 (including a tail that is not a multiple of 8), to force long probe chains and backward-shift deletion.
|
||||
#include "../nvn/nvn_hmap.h"
|
||||
#include <stdio.h>
|
||||
|
||||
#define KS 3000
|
||||
static uint64_t rng = 88172645463325252ull;
|
||||
static uint64_t rnd(void) { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return rng; }
|
||||
static int run(uint32_t klen, int ops) {
|
||||
static void *ref[KS]; memset(ref, 0, sizeof ref);
|
||||
nvn_hmap m; nvn_hm_init(&m, klen);
|
||||
uint8_t k[32]; int bad = 0, live = 0;
|
||||
for (int t = 0; t < ops && !bad; t++) {
|
||||
uint32_t x = (uint32_t)(rnd() % KS); memset(k, 0xab, sizeof k); memcpy(k, &x, 4);
|
||||
int op = (int)(rnd() % 10);
|
||||
if (op < 5) { void *v = (void *)(uintptr_t)(t + 1), *old = nvn_hm_put(&m, k, v); bad |= old != ref[x]; live += !ref[x]; ref[x] = v; }
|
||||
else if (op < 8) { void *old = nvn_hm_del(&m, k); bad |= old != ref[x]; live -= !!ref[x]; ref[x] = NULL; }
|
||||
else bad |= nvn_hm_get(&m, k) != ref[x];
|
||||
if (t % 50000 == 49999) { nvn_hm_clear(&m, NULL); memset(ref, 0, sizeof ref); live = 0; }
|
||||
bad |= (int)m.n != live;
|
||||
}
|
||||
for (uint32_t x = 0; x < KS && !bad; x++) { memset(k, 0xab, sizeof k); memcpy(k, &x, 4); bad |= nvn_hm_get(&m, k) != ref[x]; } // 终态全量对照 | full comparison of the final state
|
||||
printf("键长 %2u:%d 次随机操作 + 终态 %d 键全量对照 期望全等 → 真结果 %s(终态 %u 项、容量 %u)\n", klen, ops, KS, bad ? "不等 ✗" : "全等 ✓", m.n, m.cap);
|
||||
free(m.keys); free(m.vals);
|
||||
return bad;
|
||||
}
|
||||
int main(void) {
|
||||
int fail = run(8, 190000) + run(20, 190000);
|
||||
printf("== 2 项,失败 %d ==\n", fail);
|
||||
return fail != 0;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// 真实NVN录制入口→生产Metal回放;8x6各mip独立手算,未设置viewport不借显式viewport规避。
|
||||
// Real NVN recording entry → production Metal replay; each mip of 8x6 is hand-calculated independently; with no viewport set, an explicit viewport is not used to dodge it.
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
#include "../nvn/hle_nvn.c"
|
||||
uint64_t g_t0_ns; // 宿主 main.c 的进程起点(hle_nvn 逐帧 @t_s 用),单测替身 | process start time from host main.c (used by hle_nvn's per-frame @t_s); unit test stub
|
||||
void *front_metal_layer(void) { return NULL; }
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
module_t g_mod[MAX_MOD]; int g_nmod;
|
||||
void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { return bp_now(); }
|
||||
static int cases,failed; static prog_t colour_pg,depth_pg;
|
||||
#define EXPECT(n,w,v) do { uint64_t a=(w),b=(v);cases++;printf("%s 期望 %llu → 真结果 %llu %s\n",n,(unsigned long long)a,(unsigned long long)b,a==b?"✓":"✗");failed+=a!=b;}while(0)
|
||||
static tex_t make_tex(int w,int h,int levels,int format) {
|
||||
static uint64_t ser=90000; tex_t t={.serial=ser++};t.d.width=w;t.d.height=h;
|
||||
t.d.depth=t.d.samples=1;t.d.levels=levels;t.d.target=NVN_TEXTURE_TARGET_2D;t.d.format=format;return t;
|
||||
}
|
||||
typedef struct { NVNcommandBuffer cb; pool_t pool; void *mem; } recording;
|
||||
static recording begin(void) {
|
||||
recording r={0};if(posix_memalign(&r.mem,getpagesize(),65536))abort();memset(r.mem,0,65536);
|
||||
r.pool.mem=r.mem;r.pool.size=65536;mtl_pool_add(r.mem,65536);
|
||||
EXPECT("NVN command初始化",1,h_nvnCommandBufferInitialize(&r.cb,NULL));
|
||||
h_nvnCommandBufferAddCommandMemory(&r.cb,(const NVNmemoryPool *)&r.pool,0,65536);h_nvnCommandBufferBeginRecording(&r.cb);return r;
|
||||
}
|
||||
static void target(recording *r,const tex_t *t,int lv,int slot,const tex_t *other,int other_lv,int depth) {
|
||||
NVNtextureView view,ov;h_nvnTextureViewSetDefaults(&view);h_nvnTextureViewSetLevels(&view,lv,1);
|
||||
h_nvnTextureViewSetDefaults(&ov);h_nvnTextureViewSetLevels(&ov,other_lv,1);
|
||||
const NVNtexture *ct[2]={NULL,NULL};const NVNtextureView *cv[2]={NULL,NULL};
|
||||
if(!depth){ct[slot]=(const NVNtexture *)t;cv[slot]=&view;if(other){ct[1]=(const NVNtexture *)other;cv[1]=&ov;}}
|
||||
h_nvnCommandBufferSetRenderTargets(&r->cb,depth?0:other?2:slot+1,ct,cv,depth?(const NVNtexture *)t:NULL,depth?&view:NULL);
|
||||
// 录制后改view不应改变已录level;源码保留原参数快照。
|
||||
// Changing the view after recording must not change the recorded level; the source keeps a snapshot of the original parameters.
|
||||
h_nvnTextureViewSetLevels(&view,0,1);
|
||||
}
|
||||
static void finish(recording *r) {
|
||||
NVNcommandHandle h=h_nvnCommandBufferEndRecording(&r->cb);state_reset();memset(&R,0,sizeof R);
|
||||
mtl_sub_begin();mtl_exec((const uint8_t *)h);
|
||||
int done=mtl_wait(mtl_sub_commit(),5000000000ull);EXPECT("生产GPU完成",1,done);if(!done)abort();EXPECT("提交反馈无错误",0,mtl_last_commit_error());
|
||||
mtl_pool_del(r->mem);free(r->mem);
|
||||
}
|
||||
static void seed(const tex_t *t) {
|
||||
id<MTLTexture> m=tex_mtl(t);id<MTLCommandBuffer> cb=[g_q commandBuffer];
|
||||
for(int l=0;l<t->d.levels;l++){MTLRenderPassDescriptor *p=[MTLRenderPassDescriptor renderPassDescriptor];
|
||||
if(t->d.format==NVN_FORMAT_RGBA8){p.colorAttachments[0].texture=m;p.colorAttachments[0].level=l;
|
||||
p.colorAttachments[0].loadAction=MTLLoadActionClear;p.colorAttachments[0].storeAction=MTLStoreActionStore;p.colorAttachments[0].clearColor=MTLClearColorMake(0,0,1,1);}
|
||||
else if(t->d.format==NVN_FORMAT_STENCIL8){p.stencilAttachment.texture=m;p.stencilAttachment.level=l;p.stencilAttachment.loadAction=MTLLoadActionClear;p.stencilAttachment.storeAction=MTLStoreActionStore;p.stencilAttachment.clearStencil=0;}
|
||||
else {p.depthAttachment.texture=m;p.depthAttachment.level=l;p.depthAttachment.loadAction=MTLLoadActionClear;p.depthAttachment.storeAction=MTLStoreActionStore;p.depthAttachment.clearDepth=.75;}
|
||||
if(t->d.format==NVN_FORMAT_DEPTH32F_STENCIL8){p.stencilAttachment.texture=m;p.stencilAttachment.level=l;p.stencilAttachment.loadAction=MTLLoadActionClear;p.stencilAttachment.storeAction=MTLStoreActionStore;p.stencilAttachment.clearStencil=0;}
|
||||
[[cb renderCommandEncoderWithDescriptor:p] endEncoding];}
|
||||
[cb commit];[cb waitUntilCompleted];EXPECT("独立Metal种子完成",4,cb.status);
|
||||
}
|
||||
static uint8_t *read_mip(const tex_t *t,int lv,int w,int h,int bpp) {
|
||||
NSUInteger row=(w*bpp+15)&~15u;id<MTLBuffer> buf=[g_dev newBufferWithLength:row*h options:MTLResourceStorageModeShared];
|
||||
id<MTLCommandBuffer> cb=[g_q commandBuffer];id<MTLBlitCommandEncoder> b=[cb blitCommandEncoder];
|
||||
id<MTLTexture> src=tex_mtl(t);MTLBlitOption opt=t->d.format==NVN_FORMAT_DEPTH32F_STENCIL8?(bpp==1?MTLBlitOptionStencilFromDepthStencil:MTLBlitOptionDepthFromDepthStencil):MTLBlitOptionNone;
|
||||
[b copyFromTexture:src sourceSlice:0 sourceLevel:lv sourceOrigin:MTLOriginMake(0,0,0) sourceSize:MTLSizeMake(w,h,1)
|
||||
toBuffer:buf destinationOffset:0 destinationBytesPerRow:row destinationBytesPerImage:row*h options:opt];[b endEncoding];[cb commit];[cb waitUntilCompleted];EXPECT("逐纹素读回完成",4,cb.status);
|
||||
uint8_t *out=malloc(w*h*bpp);for(int y=0;y<h;y++)memcpy(out+y*w*bpp,(uint8_t *)buf.contents+y*row,w*bpp);return out;
|
||||
}
|
||||
static void save(const char *name,int lv,const uint8_t *out,int n) {
|
||||
const char *dir=getenv("DM_GFX_FIXTURE_OUT");if(!dir)return;char path[1024];snprintf(path,sizeof path,"%s/%s_lv%d.raw",dir,name,lv);
|
||||
FILE *f=fopen(path,"wb");if(!f||fwrite(out,1,n,f)!=n)abort();fclose(f);
|
||||
}
|
||||
static void colour_check(const char *name,const tex_t *t,int lv,int kind,int draw_w,int draw_h,int partial) {
|
||||
// 四级尺寸是题面常数表,不调被测mip helper。
|
||||
// The four level sizes are a constant table given by the problem statement; the mip helper under test is not called.
|
||||
static const int W[]={8,4,2,1},H[]={6,3,1,1};
|
||||
for(int l=0;l<4;l++){int w=W[l],h=H[l],bad=0;uint8_t *out=read_mip(t,l,w,h,4);
|
||||
for(int y=0;y<h;y++)for(int x=0;x<w;x++){uint8_t want[4]={0,0,255,255};
|
||||
int in=l==lv&&x<draw_w&&y<draw_h&&(!partial||(x>=1&&x<3&&y==1));
|
||||
if(in&&kind==1){want[0]=255;want[2]=0;} // 合法NVN full clear红 | valid NVN full clear: red
|
||||
if(in&&kind==2){int rx=5*(2*x+1)>=4*draw_w,by=5*(2*y+1)>=4*draw_h;
|
||||
want[0]=rx?0:255;want[1]=rx?255:0;want[2]=by?255:0;}
|
||||
bad+=memcmp(out+4*(y*w+x),want,4)!=0;}
|
||||
char label[128];snprintf(label,sizeof label,"%s lv%d %d纹素",name,l,w*h);EXPECT(label,0,bad);save(name,l,out,w*h*4);free(out);}
|
||||
}
|
||||
static void colour_case(const char *name,int lv,int sc,int clear_only,int slot,int mrt) {
|
||||
static const int W[]={8,4,2,1},H[]={6,3,1,1};int w=W[lv],h=H[lv];tex_t t=make_tex(8,6,4,NVN_FORMAT_RGBA8),other=make_tex(8,6,4,NVN_FORMAT_RGBA8);
|
||||
seed(&t);if(mrt)seed(&other);recording r=begin();target(&r,&t,lv,slot,mrt?&other:NULL,1,0);
|
||||
if(mrt){w=4;h=3;}
|
||||
if(sc==1)h_nvnCommandBufferSetScissor(&r.cb,0,0,w,h);
|
||||
if(sc==2)h_nvnCommandBufferSetScissor(&r.cb,-2,-3,30,40);
|
||||
if(sc==3)h_nvnCommandBufferSetScissor(&r.cb,1,1,2,1);
|
||||
if(clear_only){float red[4]={1,0,0,1};h_nvnCommandBufferClearColor(&r.cb,slot,red,15);}
|
||||
else {h_nvnCommandBufferBindProgram(&r.cb,(const NVNprogram *)&colour_pg,3);h_nvnCommandBufferDrawArrays(&r.cb,NVN_DRAW_PRIMITIVE_TRIANGLES,0,3);}
|
||||
finish(&r);NSUInteger pre_w,pre_h;rt_dims(&pre_w,&pre_h);EXPECT("预检查首目标selected宽上界",W[lv],pre_w);EXPECT("预检查首目标selected高上界",H[lv],pre_h);
|
||||
if(sc!=3||!clear_only){EXPECT("实际pass有效宽",w,g_pass.tw);EXPECT("实际pass有效高",h,g_pass.th);}
|
||||
colour_check(name,&t,lv,clear_only?(sc==3?0:1):2,w,h,sc==3);
|
||||
if(mrt)colour_check("MRT未写附件",&other,-1,0,0,0,0);
|
||||
}
|
||||
static void plane_case(const char *name,int stencil,int clear_only) {
|
||||
tex_t t=make_tex(8,6,4,stencil?NVN_FORMAT_DEPTH32F_STENCIL8:NVN_FORMAT_DEPTH32F);seed(&t);recording r=begin();target(&r,&t,1,0,NULL,0,1);
|
||||
if(clear_only){h_nvnCommandBufferSetScissor(&r.cb,0,0,4,3);h_nvnCommandBufferClearDepthStencil(&r.cb,.25,!stencil,0x5a,stencil?255:0);}
|
||||
else {ds_st ds={.dt=!stencil,.dw=!stencil,.df=NVN_DEPTH_FUNC_ALWAYS,.st=stencil,.sf_f=8,.sf_b=8,.fail_f=1,.zfail_f=1,.zpass_f=3,.fail_b=1,.zfail_b=1,.zpass_b=3};
|
||||
p_bind_state st={.kind=5};memcpy(st.bytes,&ds,sizeof ds);*REC(&r.cb,OP_BIND_STATE,p_bind_state)=st;
|
||||
if(stencil)for(int k=0;k<3;k++)*REC(&r.cb,OP_STENCIL,p_stencil)=(p_stencil){.face=3,.which=k,.value_mask=255,.mask=255,.ref=0x5a};
|
||||
h_nvnCommandBufferBindProgram(&r.cb,(const NVNprogram *)&depth_pg,1);h_nvnCommandBufferDrawArrays(&r.cb,NVN_DRAW_PRIMITIVE_TRIANGLES,0,3);}
|
||||
finish(&r);EXPECT("depth/stencil有效宽",4,g_pass.tw);EXPECT("depth/stencil有效高",3,g_pass.th);
|
||||
static const int W[]={8,4,2,1},H[]={6,3,1,1};for(int l=0;l<4;l++){int n=W[l]*H[l],bad=0;uint8_t *b=read_mip(&t,l,W[l],H[l],stencil?1:4);
|
||||
for(int i=0;i<n;i++)if(stencil)bad+=b[i]!=(l==1?0x5a:0);else bad+=((float *)b)[i]!=(l==1?.25f:.75f);
|
||||
EXPECT("选中plane逐纹素/未选级不变",0,bad);save(name,l,b,n*(stencil?1:4));free(b);}
|
||||
if(stencil)for(int l=0;l<4;l++){int n=W[l]*H[l],bad=0;uint8_t *b=read_mip(&t,l,W[l],H[l],4);
|
||||
for(int i=0;i<n;i++)bad+=((float *)b)[i]!=.75f;EXPECT("模板操作不改深度plane",0,bad);
|
||||
char label[96];snprintf(label,sizeof label,"%s_preserved_depth",name);save(label,l,b,n*4);free(b);}
|
||||
}
|
||||
int main(int argc,char **argv){@autoreleasepool{
|
||||
setvbuf(stdout,NULL,_IONBF,0);int stencil_only=argc>1&&!strcmp(argv[1],"--stencil-only");setenv("DM_NVN_TBDR",stencil_only?"1":"0",1);mtl_init();NSError *e=nil;
|
||||
id<MTLLibrary> lib=[g_dev newLibraryWithSource:@"#include <metal_stdlib>\nusing namespace metal;struct O{float4 p[[position]];float2 uv[[user(locn0)]];};\n"
|
||||
"vertex O v(uint n[[vertex_id]]){float2 p[3]={float2(-1,-1),float2(3,-1),float2(-1,3)};return {float4(p[n],.25,1),float2((p[n].x+1)/2,(1-p[n].y)/2)};}\n"
|
||||
"fragment float4 f(O o[[stage_in]]){return float4(o.uv.x<.4?1:0,o.uv.x<.4?0:1,o.uv.y<.4?0:1,1);}\n" options:nil error:&e];if(!lib){fprintf(stderr,"%s\n",e.localizedDescription.UTF8String);return 2;}
|
||||
for(int i=0;i<2;i++){NvProg *p=[NvProg new];p->sh[0]=[NvShader new];p->sh[0]->fn=[lib newFunctionWithName:@"v"];
|
||||
if(!i){p->sh[1]=[NvShader new];p->sh[1]->fn=[lib newFunctionWithName:@"f"];p->sh[1]->stage=1;}
|
||||
(i?&depth_pg:&colour_pg)->serial=80000+i;serial_put(80000+i,p);}
|
||||
if(stencil_only){plane_case("stencil_only",1,0);EXPECT("现有only-stencil模式",3,g_enc_mode);EXPECT("仅模板不挂深度",1,g_pass.hs&&!g_pass.hd);}
|
||||
else if(argc>1&&!strcmp(argv[1],"--default"))colour_case("default",1,0,0,0,0);
|
||||
else if(argc>1&&!strcmp(argv[1],"--oversized"))colour_case("oversized",1,2,0,0,0);
|
||||
else {for(int lv=0;lv<4;lv++){char name[64];snprintf(name,sizeof name,"bounded_L%d",lv);colour_case(name,lv,1,0,0,0);
|
||||
snprintf(name,sizeof name,"clear_L%d",lv);colour_case(name,lv,1,1,0,0);}
|
||||
colour_case("partial_draw",1,3,0,0,0);colour_case("partial_clear_reject",1,3,1,0,0);colour_case("slot1_clear",1,1,1,1,0);
|
||||
if(argc==1){colour_case("default",1,0,0,0,0);colour_case("oversized",1,2,0,0,0);colour_case("MRT_min",0,0,0,0,1);plane_case("depth",0,0);plane_case("stencil",1,0);plane_case("depth_clear",0,1);plane_case("stencil_clear",1,1);}}
|
||||
printf("== %d 项,失败 %d ==\n",cases,failed);return failed!=0;
|
||||
}}
|
||||
@@ -0,0 +1,371 @@
|
||||
// NVN 空设备单测:照游戏的用法从 nvnBootstrapLoader 取址,一路走到出图;期望值全部手算,不调被测实现。
|
||||
// 编译运行见 dm/gfx/tests/Makefile(make -C dm/gfx/tests)。
|
||||
// NVN null device unit tests: look up addresses from nvnBootstrapLoader the way the game does and go all the way to present; all expected values are hand-calculated, without calling the implementation under test.
|
||||
// For build and run see dm/gfx/tests/Makefile (make -C dm/gfx/tests).
|
||||
#include "../nvn/hle_nvn.c"
|
||||
uint64_t g_t0_ns; // 宿主 main.c 的进程起点(hle_nvn 逐帧 @t_s 用),单测替身 | process start time from host main.c (used by hle_nvn's per-frame @t_s); unit test stub
|
||||
#include "../tex/nvn_deswizzle.h"
|
||||
#include <time.h>
|
||||
void *front_metal_layer(void) { return NULL; } // 单测无窗口:出图只计数 | no window in unit tests: present only counts
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; } // 单测无客体模块 | no guest modules in unit tests
|
||||
module_t g_mod[MAX_MOD]; int g_nmod; // crash.c 依赖的宿主符号 | host symbols that crash.c depends on
|
||||
void svc_thread_dump(void) {}
|
||||
void crash_install(void);
|
||||
void nvn_present_config(int hz, int display_mode);
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
#include <unistd.h>
|
||||
uint64_t now_ns(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint64_t)t.tv_sec * 1000000000ull + t.tv_nsec; }
|
||||
|
||||
static int g_fail, g_n;
|
||||
#define EXPECT(name, want, got) do { long long w_ = (long long)(want), g_ = (long long)(got); g_n++; \
|
||||
printf("%-44s 期望 %-12lld → 真结果 %-12lld %s\n", name, w_, g_, w_ == g_ ? "✓" : "✗"); if (w_ != g_) g_fail++; } while (0)
|
||||
|
||||
#define P(name) ((NVNT_##name)proc(#name))
|
||||
static PFNNVNDEVICEGETPROCADDRESSPROC gpa; static NVNdevice dev;
|
||||
static void *proc(const char *n) { void *p = (void *)gpa(&dev, n); if (!p) { printf("取址失败 %s\n", n); exit(1); } return p; }
|
||||
|
||||
// 命令内存回调:每次给一段 256 字节的新内存(强制多段 JUMP 链)
|
||||
// Command memory callback: hands out a new 256-byte memory segment each time (forces a multi-segment JUMP chain)
|
||||
static uint8_t g_cmdmem[64 * 1024]; static size_t g_cmdoff; static int g_cb_calls; static NVNmemoryPool g_cmdpool;
|
||||
static void mem_cb(NVNcommandBuffer *c, NVNcommandBufferMemoryEvent ev, size_t minsz, void *data) {
|
||||
(void)data; g_cb_calls++;
|
||||
if (ev != NVN_COMMAND_BUFFER_MEMORY_EVENT_OUT_OF_COMMAND_MEMORY) return;
|
||||
size_t n = minsz > 256 ? minsz : 256;
|
||||
P(nvnCommandBufferAddCommandMemory)(c, &g_cmdpool, (ptrdiff_t)g_cmdoff, n); g_cmdoff += n;
|
||||
}
|
||||
|
||||
// 挂起单测:另一线程里做提交
|
||||
// Suspend unit test: do the submit on another thread
|
||||
static _Atomic int g_sstarted, g_sdone; static pthread_mutex_t g_smu = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t g_scv = PTHREAD_COND_INITIALIZER;
|
||||
static NVNqueue *g_sq; static NVNcommandHandle g_sh; static NVNT_nvnQueueSubmitCommands g_sub;
|
||||
static void *susp_thr(void *a) { (void)a; pthread_mutex_lock(&g_smu); atomic_store(&g_sstarted, 1); pthread_cond_broadcast(&g_scv); pthread_mutex_unlock(&g_smu); g_sub(g_sq, 1, &g_sh); atomic_store(&g_sdone, 1); return NULL; }
|
||||
static int wait_started(void) { struct timespec dl; clock_gettime(CLOCK_REALTIME, &dl); dl.tv_sec += 10; pthread_mutex_lock(&g_smu); while (!atomic_load(&g_sstarted) && pthread_cond_timedwait(&g_scv, &g_smu, &dl) == 0) {} int ok = atomic_load(&g_sstarted); pthread_mutex_unlock(&g_smu); return ok; }
|
||||
|
||||
static size_t tex_size(int fmt, int w, int h, int flags, size_t *align) {
|
||||
NVNtextureBuilder tb;
|
||||
P(nvnTextureBuilderSetDevice)(&tb, &dev); P(nvnTextureBuilderSetDefaults)(&tb);
|
||||
P(nvnTextureBuilderSetFlags)(&tb, flags); P(nvnTextureBuilderSetTarget)(&tb, NVN_TEXTURE_TARGET_2D);
|
||||
P(nvnTextureBuilderSetWidth)(&tb, w); P(nvnTextureBuilderSetHeight)(&tb, h); P(nvnTextureBuilderSetFormat)(&tb, fmt);
|
||||
if (align) *align = P(nvnTextureBuilderGetStorageAlignment)(&tb);
|
||||
return P(nvnTextureBuilderGetStorageSize)(&tb);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
crash_install(); // 生产同一套 SIGSEGV / SIGBUS 处理(缺页钩子在其中分发) | the same SIGSEGV / SIGBUS handling as production (the page-fault hook is dispatched from within it)
|
||||
// 1. 引导取址:bootstrap 取 GetProcAddress,再用它取全部名字
|
||||
// 1. Bootstrap address lookup: bootstrap gets GetProcAddress, then uses it to get all the names
|
||||
PFNNVNBOOTSTRAPLOADERPROC boot = (PFNNVNBOOTSTRAPLOADERPROC)h_nvnBootstrapLoader;
|
||||
gpa = (PFNNVNDEVICEGETPROCADDRESSPROC)boot("nvnDeviceGetProcAddress");
|
||||
EXPECT("bootstrap 取 GetProcAddress 非空", 1, gpa != NULL);
|
||||
int nonnull = 0; for (unsigned i = 0; i < NVN_NFUNC; i++) nonnull += gpa(NULL, nvn_names[i]) != NULL;
|
||||
EXPECT("523 个名字全部取到地址", 523, nonnull);
|
||||
EXPECT("未知名字取址返回空", 0, gpa(NULL, "nvnNoSuchFunction") != NULL);
|
||||
|
||||
// 2. 设备
|
||||
// 2. Device
|
||||
NVNdeviceBuilder db; P(nvnDeviceBuilderSetDefaults)(&db); P(nvnDeviceBuilderSetFlags)(&db, 0);
|
||||
EXPECT("DeviceInitialize 成功", 1, P(nvnDeviceInitialize)(&dev, &db));
|
||||
int v; P(nvnDeviceGetInteger)(&dev, NVN_DEVICE_INFO_UNIFORM_BUFFER_ALIGNMENT, &v);
|
||||
EXPECT("uniform 缓冲对齐(X1 实测 256)", 256, v);
|
||||
P(nvnDeviceGetInteger)(&dev, NVN_DEVICE_INFO_TEXTURE_DESCRIPTOR_SIZE, &v); EXPECT("贴图描述符大小(32)", 32, v);
|
||||
P(nvnDeviceGetInteger)(&dev, NVN_DEVICE_INFO_QUEUE_COMMAND_MEMORY_MIN_SIZE, &v); EXPECT("队列命令内存下限(65536)", 65536, v);
|
||||
|
||||
// 3. 内存池:GPU 地址 = 游戏给的存储地址
|
||||
// 3. Memory pool: GPU address = the storage address given by the game
|
||||
static uint8_t poolmem[1 << 20] __attribute__((aligned(4096)));
|
||||
NVNmemoryPoolBuilder pb; NVNmemoryPool pool;
|
||||
P(nvnMemoryPoolBuilderSetDevice)(&pb, &dev); P(nvnMemoryPoolBuilderSetDefaults)(&pb);
|
||||
P(nvnMemoryPoolBuilderSetStorage)(&pb, poolmem, sizeof poolmem); P(nvnMemoryPoolBuilderSetFlags)(&pb, 0x24);
|
||||
EXPECT("MemoryPoolInitialize 成功", 1, P(nvnMemoryPoolInitialize)(&pool, &pb));
|
||||
EXPECT("池 GPU 地址 = 存储地址", (long long)(uintptr_t)poolmem, P(nvnMemoryPoolGetBufferAddress)(&pool));
|
||||
|
||||
// 4. 贴图存储尺寸(块线性:GOB = 64 B × 8 行;块高按「高×1.5」取 GOB 数 ≥16→16、≥8→8 …)
|
||||
// 256×256 RGBA8:每行 1024 B = 16 GOB;高 256 行 = 32 GOB 行,块高 16 GOB → 2 块;16×2×(512×16) = 262144
|
||||
// 4. Texture storage size (block-linear: GOB = 64 B × 8 rows; block height from the GOB count of "height × 1.5": ≥16→16, ≥8→8 ...)
|
||||
// 256×256 RGBA8: 1024 B per row = 16 GOBs; height 256 rows = 32 GOB rows, block height 16 GOBs → 2 blocks; 16×2×(512×16) = 262144
|
||||
size_t al; EXPECT("256x256 RGBA8 尺寸", 262144, tex_size(NVN_FORMAT_RGBA8, 256, 256, 0, &al));
|
||||
EXPECT("块线性对齐", 512, al);
|
||||
// 100×100 RGBA8:400 B → 7 GOB 宽;高 100 → 13 GOB 行,1.5 倍 = 150 行 = 19 GOB → 块高 16 → 1 块;7×1×8192 = 57344
|
||||
// 100×100 RGBA8: 400 B → 7 GOBs wide; height 100 → 13 GOB rows, ×1.5 = 150 rows = 19 GOBs → block height 16 → 1 block; 7×1×8192 = 57344
|
||||
EXPECT("100x100 RGBA8 尺寸", 57344, tex_size(NVN_FORMAT_RGBA8, 100, 100, 0, NULL));
|
||||
// 128×128 DXT1:32×32 块、8 B/块 → 256 B = 4 GOB 宽;32 行 → 1.5 倍 48 行 = 6 GOB → 块高 4 → 4 GOB 行 = 1 块;4×1×2048 = 8192
|
||||
// 128×128 DXT1: 32×32 blocks, 8 B/block → 256 B = 4 GOBs wide; 32 rows → ×1.5 = 48 rows = 6 GOBs → block height 4 → 4 GOB rows = 1 block; 4×1×2048 = 8192
|
||||
EXPECT("128x128 DXT1 尺寸", 8192, tex_size(NVN_FORMAT_RGBA_DXT1, 128, 128, 0, NULL));
|
||||
// LINEAR 100×100 RGBA8:行距 400 按 32 对齐 = 416;416×100 = 41600,对齐 32
|
||||
// LINEAR 100×100 RGBA8: row pitch 400 aligned to 32 = 416; 416×100 = 41600, aligned to 32
|
||||
EXPECT("线性 100x100 RGBA8 尺寸", 41600, tex_size(NVN_FORMAT_RGBA8, 100, 100, NVN_TEXTURE_FLAGS_LINEAR, &al));
|
||||
EXPECT("线性对齐", 32, al);
|
||||
|
||||
// 5. 命令缓冲:录 uniform 更新 / 事件 / 计数器 / 缓冲拷贝 / 嵌套调用,内存 256 B 一段逼出多段链接
|
||||
// 5. Command buffer: record uniform updates / events / counters / buffer copies / nested calls, with memory in 256 B segments to force multi-segment linking
|
||||
NVNcommandBuffer cb; P(nvnCommandBufferInitialize)(&cb, &dev);
|
||||
NVNmemoryPoolBuilder cpb; P(nvnMemoryPoolBuilderSetDefaults)(&cpb); P(nvnMemoryPoolBuilderSetStorage)(&cpb, g_cmdmem, sizeof g_cmdmem);
|
||||
P(nvnMemoryPoolInitialize)(&g_cmdpool, &cpb);
|
||||
P(nvnCommandBufferSetMemoryCallback)(&cb, mem_cb); P(nvnCommandBufferSetMemoryCallbackData)(&cb, NULL);
|
||||
NVNeventBuilder eb; NVNevent ev; P(nvnEventBuilderSetDefaults)(&eb); P(nvnEventBuilderSetStorage)(&eb, &pool, 0x1000);
|
||||
P(nvnEventInitialize)(&ev, &eb);
|
||||
uint8_t *ub = poolmem + 0x2000, *cnt = poolmem + 0x3000, *src = poolmem + 0x4000, *dst = poolmem + 0x5000;
|
||||
for (int i = 0; i < 64; i++) src[i] = (uint8_t)(i * 3 + 1);
|
||||
uint32_t data[16];
|
||||
|
||||
P(nvnCommandBufferBeginRecording)(&cb);
|
||||
EXPECT("录制中", 1, P(nvnCommandBufferIsRecording)(&cb));
|
||||
for (int k = 0; k < 20; k++) { // 20 次更新同一缓冲不同偏移,每次 64 B 数据 | 20 updates to different offsets of the same buffer, 64 B of data each
|
||||
for (int i = 0; i < 16; i++) data[i] = k * 100 + i;
|
||||
P(nvnCommandBufferUpdateUniformBuffer)(&cb, (NVNbufferAddress)ub, 4096, k * 64, 64, data);
|
||||
memset(data, 0xEE, sizeof data); // 录完改原数据:提交时必须用录制时拷进去的值 | modify the original data after recording: the submit must use the values copied in at record time
|
||||
}
|
||||
P(nvnCommandBufferSignalEvent)(&cb, &ev, NVN_EVENT_SIGNAL_MODE_WRITE, NVN_EVENT_SIGNAL_LOCATION_BOTTOM, 0, 7);
|
||||
P(nvnCommandBufferSignalEvent)(&cb, &ev, NVN_EVENT_SIGNAL_MODE_ADD, NVN_EVENT_SIGNAL_LOCATION_BOTTOM, 0, 5);
|
||||
P(nvnCommandBufferReportCounter)(&cb, NVN_COUNTER_TYPE_TIMESTAMP, (NVNbufferAddress)cnt);
|
||||
NVNcommandHandle h1 = P(nvnCommandBufferEndRecording)(&cb);
|
||||
EXPECT("录完不在录制", 0, P(nvnCommandBufferIsRecording)(&cb));
|
||||
P(nvnCommandBufferBeginRecording)(&cb);
|
||||
P(nvnCommandBufferCopyBufferToBuffer)(&cb, (NVNbufferAddress)src, (NVNbufferAddress)dst, 64, 0);
|
||||
P(nvnCommandBufferCopyCommands)(&cb, 1, &h1); // 嵌套:再执行一遍 h1(事件 7 → +5 → 再写 7 → +5) | nested: execute h1 once more (event 7 → +5 → write 7 again → +5)
|
||||
NVNcommandHandle h2 = P(nvnCommandBufferEndRecording)(&cb);
|
||||
printf("(命令内存回调 %d 次,用掉 %zu B)\n", g_cb_calls, g_cmdoff);
|
||||
EXPECT("命令内存回调至少 2 次(多段)", 1, g_cb_calls >= 2);
|
||||
EXPECT("提交前事件值仍为 0", 0, P(nvnEventGetValue)(&ev));
|
||||
|
||||
NVNqueueBuilder qb; NVNqueue q; static uint8_t qmem[1 << 19];
|
||||
P(nvnQueueBuilderSetDevice)(&qb, &dev); P(nvnQueueBuilderSetDefaults)(&qb);
|
||||
size_t qsz = P(nvnQueueBuilderGetQueueMemorySize)(&qb);
|
||||
EXPECT("队列内存 = 64K+256K+16K 取整 4K", 65536 + 262144 + 16384, qsz);
|
||||
P(nvnQueueBuilderSetQueueMemory)(&qb, qmem, qsz);
|
||||
EXPECT("QueueInitialize 成功", 1, P(nvnQueueInitialize)(&q, &qb));
|
||||
NVNcommandHandle hs[2] = {h1, h2};
|
||||
P(nvnQueueSubmitCommands)(&q, 2, hs);
|
||||
NVNsync sf; P(nvnSyncInitialize)(&sf, &dev); P(nvnQueueFenceSync)(&q, &sf, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0);
|
||||
int wr = P(nvnSyncWait)(&sf, 5000000000ull);
|
||||
EXPECT("提交后围栏等待成功(0 或 1)", 1, wr == 0 || wr == 1);
|
||||
int ub_ok = 1;
|
||||
for (int k = 0; k < 20; k++) for (int i = 0; i < 16; i++) { uint32_t w; memcpy(&w, ub + k * 64 + i * 4, 4); ub_ok &= w == (uint32_t)(k * 100 + i); }
|
||||
EXPECT("uniform 缓冲 20×16 个字全等录制值", 1, ub_ok);
|
||||
EXPECT("事件值:h1(7,+5) h2 拷贝后再跑 h1(7,+5) = 12", 12, P(nvnEventGetValue)(&ev));
|
||||
EXPECT("缓冲拷贝 64 B 全等", 0, memcmp(src, dst, 64));
|
||||
uint64_t ts[2]; memcpy(ts, cnt, 16);
|
||||
EXPECT("计数器时间戳已写(非 0)", 1, ts[0] != 0 && ts[0] == ts[1]);
|
||||
|
||||
// 5b. 同步必须挡住 CPU:先排 24 次 64 MiB 拷贝把 GPU 占住,最后一条把 src 拷到 dst;
|
||||
// 等围栏返回后 CPU 才改写 src。若等待提前放行,最后那条拷贝会读到改写后的 src。
|
||||
// 5b. Sync must hold the CPU back: first queue 24 copies of 64 MiB to keep the GPU busy, with the last one copying src to dst;
|
||||
// the CPU rewrites src only after the fence wait returns. If the wait is released early, that last copy reads the rewritten src.
|
||||
{
|
||||
size_t big = 64u << 20, pgsz = 16384;
|
||||
uint8_t *heap; posix_memalign((void **)&heap, pgsz, 4 * big);
|
||||
uint8_t *busy_a = heap, *busy_b = heap + big, *bsrc = heap + 2 * big, *bdst = heap + 3 * big;
|
||||
memset(heap, 0, 4 * big); memset(bsrc, 0x5A, big);
|
||||
NVNmemoryPoolBuilder hb; NVNmemoryPool hp; P(nvnMemoryPoolBuilderSetDefaults)(&hb); P(nvnMemoryPoolBuilderSetStorage)(&hb, heap, 4 * big);
|
||||
P(nvnMemoryPoolInitialize)(&hp, &hb);
|
||||
P(nvnCommandBufferBeginRecording)(&cb);
|
||||
for (int i = 0; i < 24; i++) P(nvnCommandBufferCopyBufferToBuffer)(&cb, (NVNbufferAddress)busy_a, (NVNbufferAddress)busy_b, big, 0);
|
||||
P(nvnCommandBufferCopyBufferToBuffer)(&cb, (NVNbufferAddress)bsrc, (NVNbufferAddress)bdst, big, 0);
|
||||
NVNcommandHandle hb2 = P(nvnCommandBufferEndRecording)(&cb);
|
||||
NVNsync sb; P(nvnSyncInitialize)(&sb, &dev);
|
||||
uint64_t t0 = now_ns();
|
||||
P(nvnQueueSubmitCommands)(&q, 1, &hb2); P(nvnQueueFenceSync)(&q, &sb, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0);
|
||||
int w0 = P(nvnSyncWait)(&sb, 0);
|
||||
int w1 = P(nvnSyncWait)(&sb, 10000000000ull);
|
||||
double ms = (now_ns() - t0) / 1e6;
|
||||
memset(bsrc, 0xC3, big); // 等待放行后才改写 | rewrite only after the wait is released
|
||||
size_t bad = 0; for (size_t i = 0; i < big; i += 4096) bad += bdst[i] != 0x5A;
|
||||
printf("(GPU 占用约 %.1f ms)\n", ms);
|
||||
EXPECT("刚提交时零超时等待 = 超时(2)", 2, w0);
|
||||
EXPECT("长等待 = 满足(1)", 1, w1);
|
||||
EXPECT("dst 全为改写前的值(抽 16384 处)", 0, bad);
|
||||
P(nvnMemoryPoolFinalize)(&hp); free(heap);
|
||||
}
|
||||
|
||||
// 6. 同步 / 窗口 / 出图
|
||||
// 6. Sync / window / present
|
||||
NVNsync s1, s2; P(nvnSyncInitialize)(&s1, &dev); P(nvnSyncInitialize)(&s2, &dev);
|
||||
EXPECT("未围栏的同步等待 = 超时(2)", 2, P(nvnSyncWait)(&s1, 0));
|
||||
P(nvnQueueFenceSync)(&q, &s1, NVN_SYNC_CONDITION_ALL_GPU_COMMANDS_COMPLETE, 0);
|
||||
EXPECT("围栏后等待 = 已就绪(0)", 0, P(nvnSyncWait)(&s1, 0));
|
||||
NVNtexture sc[2]; NVNtextureBuilder tb; P(nvnTextureBuilderSetDevice)(&tb, &dev); P(nvnTextureBuilderSetDefaults)(&tb);
|
||||
P(nvnTextureBuilderSetWidth)(&tb, 1280); P(nvnTextureBuilderSetHeight)(&tb, 720); P(nvnTextureBuilderSetFormat)(&tb, NVN_FORMAT_RGBA8);
|
||||
P(nvnTextureBuilderSetStorage)(&tb, &pool, 0); P(nvnTextureInitialize)(&sc[0], &tb); P(nvnTextureInitialize)(&sc[1], &tb);
|
||||
EXPECT("贴图宽", 1280, P(nvnTextureGetWidth)(&sc[0]));
|
||||
NVNtexture *scp[2] = {&sc[0], &sc[1]};
|
||||
NVNwindowBuilder wb; NVNwindow win; P(nvnWindowBuilderSetDevice)(&wb, &dev); P(nvnWindowBuilderSetDefaults)(&wb);
|
||||
P(nvnWindowBuilderSetTextures)(&wb, 2, scp); EXPECT("WindowInitialize 成功", 1, P(nvnWindowInitialize)(&win, &wb));
|
||||
int idx[4];
|
||||
for (int f = 0; f < 4; f++) {
|
||||
P(nvnWindowAcquireTexture)(&win, &s2, &idx[f]);
|
||||
for (int b = 0; b < 5; b++) P(nvnCommandBufferBarrier)(&cb, 0);
|
||||
P(nvnQueuePresentTexture)(&q, &win, idx[f]);
|
||||
}
|
||||
EXPECT("交换链轮转 0,1,0,1", 0x0101, idx[0] << 12 | idx[1] << 8 | idx[2] << 4 | idx[3]);
|
||||
EXPECT("取图后同步已就绪(0)", 0, P(nvnSyncWait)(&s2, 0));
|
||||
unsigned bi = 0; while (strcmp(nvn_names[bi], "nvnCommandBufferBarrier")) bi++;
|
||||
EXPECT("Barrier 计数 = 4 帧 × 5", 20, nvn_slot[bi].cnt);
|
||||
|
||||
// 6b. 读回:像素 (x,y) = {x*16+y, y*16+x, 0x55, 0xAA}(期望按公式直接算)
|
||||
// 6b. Readback: pixel (x,y) = {x*16+y, y*16+x, 0x55, 0xAA} (expected values computed directly from the formula)
|
||||
{
|
||||
#define PX(x, y, c) ((uint8_t)((c) == 0 ? (x) * 16 + (y) : (c) == 1 ? (y) * 16 + (x) : (c) == 2 ? 0x55 : 0xAA))
|
||||
static uint8_t rb[256 << 10] __attribute__((aligned(16384)));
|
||||
NVNmemoryPoolBuilder rpb; NVNmemoryPool rp; P(nvnMemoryPoolBuilderSetDefaults)(&rpb); P(nvnMemoryPoolBuilderSetStorage)(&rpb, rb, sizeof rb);
|
||||
P(nvnMemoryPoolInitialize)(&rp, &rpb);
|
||||
uint8_t *stage = rb + 0x8000, *outb = rb + 0xC000;
|
||||
for (int y = 0; y < 4; y++) for (int x = 0; x < 8; x++) for (int c = 0; c < 4; c++) stage[(y * 8 + x) * 4 + c] = PX(x, y, c);
|
||||
NVNtextureBuilder b; NVNtexture ta; P(nvnTextureBuilderSetDevice)(&b, &dev); P(nvnTextureBuilderSetDefaults)(&b);
|
||||
P(nvnTextureBuilderSetWidth)(&b, 8); P(nvnTextureBuilderSetHeight)(&b, 4); P(nvnTextureBuilderSetFormat)(&b, NVN_FORMAT_RGBA8);
|
||||
P(nvnTextureBuilderSetStorage)(&b, &rp, 0); P(nvnTextureInitialize)(&ta, &b);
|
||||
NVNcopyRegion all = {0, 0, 0, 8, 4, 1}, sub = {2, 1, 0, 5, 3, 1}, cp = {1, 0, 0, 4, 2, 1};
|
||||
P(nvnCommandBufferBeginRecording)(&cb);
|
||||
P(nvnCommandBufferSetCopyRowStride)(&cb, 0);
|
||||
P(nvnCommandBufferCopyBufferToTexture)(&cb, (NVNbufferAddress)stage, &ta, NULL, &all, 0);
|
||||
P(nvnCommandBufferSetCopyRowStride)(&cb, 64);
|
||||
P(nvnCommandBufferCopyTextureToBuffer)(&cb, &ta, NULL, &cp, (NVNbufferAddress)outb, 0);
|
||||
NVNcommandHandle hr = P(nvnCommandBufferEndRecording)(&cb);
|
||||
memset(outb, 0xEE, 256);
|
||||
P(nvnQueueSubmitCommands)(&q, 1, &hr); P(nvnQueueFinish)(&q);
|
||||
uint8_t got[5 * 3 * 4]; P(nvnTextureReadTexels)(&ta, NULL, &sub, got);
|
||||
int bad = 0; for (int y = 0; y < 3; y++) for (int x = 0; x < 5; x++) for (int c = 0; c < 4; c++) bad += got[(y * 5 + x) * 4 + c] != PX(x + 2, y + 1, c);
|
||||
EXPECT("ReadTexels 子区域 5x3 逐字节(GPU 写入的贴图)", 0, bad);
|
||||
uint8_t gs[4 * 40]; memset(gs, 0xEE, sizeof gs); P(nvnTextureReadTexelsStrided)(&ta, NULL, &all, gs, 40, 0);
|
||||
bad = 0; for (int y = 0; y < 4; y++) { for (int x = 0; x < 8; x++) for (int c = 0; c < 4; c++) bad += gs[y * 40 + x * 4 + c] != PX(x, y, c); for (int k = 32; k < 40; k++) bad += gs[y * 40 + k] != 0xEE; }
|
||||
EXPECT("ReadTexelsStrided 行距 40(行尾填充不动)", 0, bad);
|
||||
bad = 0; for (int y = 0; y < 2; y++) { for (int x = 0; x < 4; x++) for (int c = 0; c < 4; c++) bad += outb[y * 64 + x * 4 + c] != PX(x + 1, y, c); for (int k = 16; k < 64; k++) bad += outb[y * 64 + k] != 0xEE; }
|
||||
EXPECT("CopyTextureToBuffer 行距 64(GPU 拷回)", 0, bad);
|
||||
// 预排布贴图:池内存就是真值(块线性),ReadTexels 解排布直读
|
||||
// Packaged texture: the pool memory is the ground truth (block-linear); ReadTexels deswizzles and reads it directly
|
||||
uint8_t lin[16 * 8 * 4]; for (int y = 0; y < 8; y++) for (int x = 0; x < 16; x++) for (int c = 0; c < 4; c++) lin[(y * 16 + x) * 4 + c] = PX(x, y, c);
|
||||
NVNtexture tb; NVNpackagedTextureLayout lay = {{1, 0, 0, 0, 7, 0, 1, 0}};
|
||||
P(nvnTextureBuilderSetDefaults)(&b); P(nvnTextureBuilderSetWidth)(&b, 16); P(nvnTextureBuilderSetHeight)(&b, 8); P(nvnTextureBuilderSetFormat)(&b, NVN_FORMAT_RGBA8);
|
||||
P(nvnTextureBuilderSetPackagedTextureLayout)(&b, &lay); P(nvnTextureBuilderSetStorage)(&b, &rp, 0x10000); P(nvnTextureInitialize)(&tb, &b);
|
||||
nvn_texdesc dd = ((tex_t *)&tb)->d;
|
||||
if (nvn_swizzle(&dd, 0, 0, lin, 64, rb + 0x10000)) { printf("nvn_swizzle 失败\n"); g_fail++; }
|
||||
NVNcopyRegion s2 = {3, 2, 0, 9, 5, 1}; uint8_t g2[9 * 5 * 4];
|
||||
P(nvnTextureReadTexels)(&tb, NULL, &s2, g2);
|
||||
bad = 0; for (int y = 0; y < 5; y++) for (int x = 0; x < 9; x++) for (int c = 0; c < 4; c++) bad += g2[(y * 9 + x) * 4 + c] != PX(x + 3, y + 2, c);
|
||||
EXPECT("ReadTexels 预排布贴图 9x5(池内存块线性直读)", 0, bad);
|
||||
P(nvnMemoryPoolFinalize)(&rp);
|
||||
}
|
||||
|
||||
// 6c. 写保护脏页:预排布贴图上传后池页只读;游戏写 → 缺页 → 标脏 → 下次使用重传;宿主 read() 直写需先 prepare
|
||||
// 6c. Write-protected dirty pages: after a packaged texture is uploaded its pool pages are read-only; game write → page fault → mark dirty → re-upload on next use; a direct host read() write needs prepare first
|
||||
{
|
||||
static uint8_t wb_[256 << 10] __attribute__((aligned(16384)));
|
||||
NVNmemoryPoolBuilder wpb; NVNmemoryPool wp; P(nvnMemoryPoolBuilderSetDefaults)(&wpb); P(nvnMemoryPoolBuilderSetStorage)(&wpb, wb_, sizeof wb_);
|
||||
P(nvnMemoryPoolInitialize)(&wp, &wpb);
|
||||
NVNtextureBuilder b; NVNtexture tw; NVNpackagedTextureLayout lay = {{1, 0, 0, 0, 7, 0, 1, 0}};
|
||||
P(nvnTextureBuilderSetDevice)(&b, &dev); P(nvnTextureBuilderSetDefaults)(&b); P(nvnTextureBuilderSetWidth)(&b, 16); P(nvnTextureBuilderSetHeight)(&b, 8);
|
||||
P(nvnTextureBuilderSetFormat)(&b, NVN_FORMAT_RGBA8); P(nvnTextureBuilderSetPackagedTextureLayout)(&b, &lay);
|
||||
P(nvnTextureBuilderSetStorage)(&b, &wp, 0x10000); P(nvnTextureInitialize)(&tw, &b);
|
||||
nvn_texdesc dd = ((tex_t *)&tw)->d;
|
||||
uint8_t lin[16 * 8 * 4], *store = wb_ + 0x10000, *outb = wb_ + 0x20000;
|
||||
#define FILLPAT(k) for (int y = 0; y < 8; y++) for (int x = 0; x < 16; x++) for (int c = 0; c < 4; c++) lin[(y * 16 + x) * 4 + c] = (uint8_t)(x * 16 + y + (k) * 3 + c * 41)
|
||||
FILLPAT(0); nvn_swizzle(&dd, 0, 0, lin, 64, store);
|
||||
NVNcopyRegion all = {0, 0, 0, 16, 8, 1};
|
||||
// 用 GPU 拷回(CopyTextureToBuffer 读 MTLTexture)检验 GPU 侧实际内容:期望 = 第 k 版图案
|
||||
// Check the actual GPU-side contents with a GPU copy-back (CopyTextureToBuffer reading the MTLTexture): expected = pattern version k
|
||||
#define GPU_READ_EQ(k, name) do { P(nvnCommandBufferBeginRecording)(&cb); P(nvnCommandBufferSetCopyRowStride)(&cb, 0); \
|
||||
P(nvnCommandBufferCopyTextureToBuffer)(&cb, &tw, NULL, &all, (NVNbufferAddress)outb, 0); NVNcommandHandle hh = P(nvnCommandBufferEndRecording)(&cb); \
|
||||
P(nvnQueueSubmitCommands)(&q, 1, &hh); P(nvnQueueFinish)(&q); FILLPAT(k); EXPECT(name, 0, memcmp(outb, lin, sizeof lin)); } while (0)
|
||||
uint64_t up0, re0, fa0, pr0, up, re, fa, pr; mtl_pkg_stats(&up0, &re0); nvn_dirty_stats(&fa0, &pr0);
|
||||
GPU_READ_EQ(0, "首传:GPU 侧内容 = 第 0 版");
|
||||
mtl_pkg_stats(&up, &re); EXPECT("首传次数 +1", 1, up - up0);
|
||||
FILLPAT(1); nvn_swizzle(&dd, 0, 0, lin, 64, store); // 游戏式 CPU 写:受保护页 → 缺页 → 钩子标脏 | game-style CPU write: protected page → page fault → hook marks it dirty
|
||||
nvn_dirty_stats(&fa, &pr); EXPECT("游戏写触发缺页 ≥ 1 次(已被钩子接住、未崩)", 1, fa - fa0 >= 1);
|
||||
GPU_READ_EQ(1, "重传后 GPU 侧内容 = 第 1 版");
|
||||
mtl_pkg_stats(&up, &re); EXPECT("池内容变化重传 +1", 1, re - re0);
|
||||
uint64_t fa1 = fa; GPU_READ_EQ(1, "内容不变再用:仍为第 1 版");
|
||||
nvn_dirty_stats(&fa, &pr); mtl_pkg_stats(&up, &re); EXPECT("内容不变:缺页 +0", 0, fa - fa1); EXPECT("内容不变:重传仍为 1", 1, re - re0);
|
||||
// 坑一:宿主 read() 直写受保护页。不 prepare 时内核返回 EFAULT(不缺页);prepare 后读成功、标脏、下次重传
|
||||
// Pitfall 1: host read() writing directly into protected pages. Without prepare the kernel returns EFAULT (no page fault); after prepare the read succeeds, the pages are marked dirty and re-uploaded next time
|
||||
char path[1024]; snprintf(path, sizeof path, "%s/t_nvn_rd_XXXXXX", getenv("TMPDIR") ? getenv("TMPDIR") : "."); int fd = mkstemp(path); // 每用户临时目录,不写 /tmp | per-user temp directory, do not write to /tmp
|
||||
FILLPAT(2); uint8_t tmpst[sizeof lin * 4]; memset(tmpst, 0, sizeof tmpst);
|
||||
static uint8_t full[0x10000]; memcpy(full, store, sizeof full); // 现有存储内容(块线性),把第 2 版写进副本再存文件 | existing storage contents (block-linear); write version 2 into a copy and then save it to a file
|
||||
nvn_swizzle(&dd, 0, 0, lin, 64, full); if (write(fd, full, ((tex_t *)&tw)->L.size) < 0) g_fail++;
|
||||
ssize_t r0 = pread(fd, store, ((tex_t *)&tw)->L.size, 0); int e0 = errno;
|
||||
EXPECT("不 prepare:read() 进受保护页返回 -1 且 EFAULT", 1, r0 == -1 && e0 == EFAULT);
|
||||
dm_guest_write_prepare(store, ((tex_t *)&tw)->L.size);
|
||||
ssize_t r1 = pread(fd, store, ((tex_t *)&tw)->L.size, 0);
|
||||
EXPECT("prepare 后 read() 成功", (long long)((tex_t *)&tw)->L.size, r1);
|
||||
close(fd); unlink(path);
|
||||
GPU_READ_EQ(2, "宿主写后重传:GPU 侧内容 = 第 2 版");
|
||||
mtl_pkg_stats(&up, &re); EXPECT("宿主写触发重传,累计 2", 2, re - re0);
|
||||
P(nvnMemoryPoolFinalize)(&wp);
|
||||
}
|
||||
|
||||
// 6d. 生命周期:挂起返回时在途 GPU 工作为 0;挂起期间提交被挡住,恢复后放行
|
||||
// 6d. Lifecycle: in-flight GPU work is 0 when suspend returns; submits are blocked during suspend and let through after resume
|
||||
{
|
||||
size_t big = 64u << 20; uint8_t *heap; posix_memalign((void **)&heap, 16384, 2 * big); memset(heap, 0, 2 * big);
|
||||
NVNmemoryPoolBuilder hb; NVNmemoryPool hp; P(nvnMemoryPoolBuilderSetDefaults)(&hb); P(nvnMemoryPoolBuilderSetStorage)(&hb, heap, 2 * big);
|
||||
P(nvnMemoryPoolInitialize)(&hp, &hb);
|
||||
P(nvnCommandBufferBeginRecording)(&cb);
|
||||
for (int i = 0; i < 24; i++) P(nvnCommandBufferCopyBufferToBuffer)(&cb, (NVNbufferAddress)heap, (NVNbufferAddress)(heap + big), big, 0);
|
||||
NVNcommandHandle hbusy = P(nvnCommandBufferEndRecording)(&cb);
|
||||
P(nvnQueueSubmitCommands)(&q, 1, &hbusy);
|
||||
uint64_t f = mtl_last_fence();
|
||||
int busy_before = !mtl_wait(f, 0);
|
||||
dm_gfx_suspend(1);
|
||||
EXPECT("挂起前 GPU 确实在忙(零超时等待未完成)", 1, busy_before);
|
||||
EXPECT("挂起返回时在途工作已完成", 1, mtl_wait(f, 0));
|
||||
P(nvnCommandBufferBeginRecording)(&cb); P(nvnCommandBufferBarrier)(&cb, 0); NVNcommandHandle hsmall = P(nvnCommandBufferEndRecording)(&cb);
|
||||
g_sq = &q; g_sh = hsmall; g_sub = P(nvnQueueSubmitCommands); atomic_store(&g_sstarted, 0); atomic_store(&g_sdone, 0);
|
||||
pthread_t th; pthread_create(&th, NULL, susp_thr, NULL);
|
||||
int started = wait_started();
|
||||
EXPECT("挂起期间另一线程已进入提交且尚未返回", 1, started && !atomic_load(&g_sdone));
|
||||
dm_gfx_suspend(0);
|
||||
pthread_join(th, NULL);
|
||||
EXPECT("恢复后该提交放行返回", 1, atomic_load(&g_sdone));
|
||||
P(nvnQueueFinish)(&q); P(nvnMemoryPoolFinalize)(&hp); free(heap);
|
||||
}
|
||||
|
||||
// 6e. 出图节拍(真机语义):出图立即返回;阻塞在取图——交换链 3 张、间隔 1、60 Hz,第 4 次取图等到第 0 张显示满一周期
|
||||
// 6e. Present pacing (real-device semantics): present returns immediately; blocking happens at acquire - swapchain of 3, interval 1, 60 Hz, the 4th acquire waits until texture 0 has been displayed for a full period
|
||||
{
|
||||
nvn_present_config(60, 0);
|
||||
NVNwindowBuilder wb2; NVNwindow w2; P(nvnWindowBuilderSetDevice)(&wb2, &dev); P(nvnWindowBuilderSetDefaults)(&wb2);
|
||||
NVNtexture *sc3[3] = {&sc[0], &sc[1], &sc[0]};
|
||||
P(nvnWindowBuilderSetTextures)(&wb2, 3, sc3); P(nvnWindowInitialize)(&w2, &wb2); P(nvnWindowSetPresentInterval)(&w2, 1);
|
||||
int ix;
|
||||
for (int k = 0; k < 3; k++) {
|
||||
P(nvnWindowAcquireTexture)(&w2, NULL, &ix);
|
||||
P(nvnQueuePresentTexture)(&q, &w2, ix);
|
||||
}
|
||||
P(nvnWindowAcquireTexture)(&w2, NULL, &ix);
|
||||
EXPECT("第 4 次取到的是第 0 张", 0, ix);
|
||||
P(nvnQueuePresentTexture)(&q, &w2, ix);
|
||||
P(nvnWindowAcquireTexture)(&w2, NULL, &ix);
|
||||
EXPECT("第 5 次取到的是第 1 张", 1, ix);
|
||||
nvn_present_config(0, 0);
|
||||
}
|
||||
|
||||
// 6f. 出图线程:drawable 迟迟不可用(出图线程每次停 200 ms)时,出图调用仍立即返回;
|
||||
// 交换链转满一圈后,取回第 0 张要等它那次出图被处理完(第一次入队 + 200 ms)
|
||||
// 6f. Present thread: when the drawable stays unavailable for a long time (the present thread stalls 200 ms each time), the present call still returns immediately;
|
||||
// after the swapchain has gone a full round, re-acquiring texture 0 has to wait until its present has been processed (first enqueue + 200 ms)
|
||||
{
|
||||
nvn_present_config(0, 0); // 不按节拍等,只看出图线程归还 | do not wait on the display link; only check that the present thread hands it back
|
||||
const double S = 200;
|
||||
mtl_present_test_stall((uint64_t)(S * 1e6));
|
||||
NVNwindowBuilder wb3; NVNwindow w3; P(nvnWindowBuilderSetDevice)(&wb3, &dev); P(nvnWindowBuilderSetDefaults)(&wb3);
|
||||
NVNtexture *sc3[3] = {&sc[0], &sc[1], &sc[0]};
|
||||
P(nvnWindowBuilderSetTextures)(&wb3, 3, sc3); P(nvnWindowInitialize)(&w3, &wb3);
|
||||
int ix;
|
||||
for (int k = 0; k < 3; k++) {
|
||||
P(nvnWindowAcquireTexture)(&w3, NULL, &ix);
|
||||
P(nvnQueuePresentTexture)(&q, &w3, ix);
|
||||
}
|
||||
P(nvnWindowAcquireTexture)(&w3, NULL, &ix);
|
||||
EXPECT("取到的是第 0 张", 0, ix);
|
||||
mtl_present_test_stall(0); mtl_present_flush();
|
||||
}
|
||||
|
||||
// 7. 未实现函数:返回 0、报红、只报一次
|
||||
// 7. Unimplemented functions: return 0, report a failure, report only once
|
||||
unsigned ui = 0; while (strcmp(nvn_names[ui], "nvnBufferBuilderSetDefaults")) ui++;
|
||||
((void (*)(void *))proc("nvnBufferBuilderSetDefaults"))(NULL); ((void (*)(void *))proc("nvnBufferBuilderSetDefaults"))(NULL);
|
||||
EXPECT("未实现函数被调用后记为已报红", 1, g_unimpl_seen[ui] > 0);
|
||||
EXPECT("未实现函数计数 2", 2, nvn_slot[ui].cnt);
|
||||
|
||||
printf("== %d 项,失败 %d ==\n", g_n, g_fail);
|
||||
return g_fail != 0;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// 节拍器单测:给定时钟序列,期望等待时长手算。周期 16.666 ms 记为 P = 16666667 ns。
|
||||
// Pacer unit tests: given a clock sequence, the expected wait durations are hand-calculated. The period 16.666 ms is written as P = 16666667 ns.
|
||||
#include "../nvn/nvn_pace.h"
|
||||
#include <stdio.h>
|
||||
|
||||
int main(void) {
|
||||
const uint64_t P = 16666667, MS = 1000000;
|
||||
struct { uint64_t now, period, want; const char *why; } c[] = {
|
||||
{1000 * MS, P, 0, "首帧:起拍,不等"},
|
||||
{1005 * MS, P, 1000 * MS + P - 1005 * MS, "早到 5 ms:等到 1000+P"},
|
||||
{1000 * MS + 2 * P - 2 * MS, P, 2 * MS, "第三帧早 2 ms:等 2 ms"},
|
||||
{1000 * MS + 3 * P + 3 * MS, P, 0, "迟到 3 ms(不足一周期):立即出图,节拍点仍为 1000+3P"},
|
||||
{1000 * MS + 4 * P - 1 * MS, P, 1 * MS, "下一帧早 1 ms:按原相位等到 1000+4P"},
|
||||
{1000 * MS + 7 * P, P, 0, "落后两个周期(卡顿):重新起拍于当时,不连发追帧"},
|
||||
{1000 * MS + 7 * P + 4 * MS, P, P - 4 * MS, "重新起拍后的下一帧:等到新目标"},
|
||||
{1000 * MS + 9 * P, 0, 0, "周期 0(DM_PRESENT_HZ=0):不等"},
|
||||
{1000 * MS + 9 * P + 1 * MS, 2 * P, 2 * P - 1 * MS, "切回间隔 2:节拍点 = 上帧时刻 9P + 2P"},
|
||||
{1000 * MS + 11 * P + 3 * MS, 2 * P, 2 * P - 3 * MS, "间隔 2 下一帧:节拍点 13P"},
|
||||
};
|
||||
nvn_pacer p = {0}; int fail = 0, n = sizeof c / sizeof *c;
|
||||
for (int i = 0; i < n; i++) {
|
||||
uint64_t got = nvn_pace(&p, c[i].now, c[i].period);
|
||||
int ok = got == c[i].want;
|
||||
printf("%-52s 期望等 %8.3f ms → 真结果 %8.3f ms %s\n", c[i].why, c[i].want / 1e6, got / 1e6, ok ? "✓" : "✗");
|
||||
fail += !ok;
|
||||
}
|
||||
printf("== %d 项,失败 %d ==\n", n, fail);
|
||||
return fail != 0;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
|
||||
void *front_metal_layer(void) { return NULL; }
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
module_t g_mod[MAX_MOD]; int g_nmod;
|
||||
void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { return bp_now(); }
|
||||
|
||||
int main(void) {
|
||||
int failed = 0;
|
||||
failed += tex_need_pfv(MTLPixelFormatRGBA8Unorm, MTLPixelFormatRGBA8Unorm) != 0;
|
||||
failed += tex_need_pfv(MTLPixelFormatRGBA8Unorm, MTLPixelFormatRGBA8Unorm_sRGB) != 0;
|
||||
failed += tex_need_pfv(MTLPixelFormatBGRA8Unorm, MTLPixelFormatBGRA8Unorm_sRGB) != 0;
|
||||
failed += tex_need_pfv(MTLPixelFormatBC7_RGBAUnorm, MTLPixelFormatBC7_RGBAUnorm_sRGB) != 0;
|
||||
failed += tex_need_pfv(MTLPixelFormatRGBA8Unorm, MTLPixelFormatR32Uint) != 1;
|
||||
tex_t t = {.serial = 70001};
|
||||
t.d.width = 4; t.d.height = 1; t.d.depth = 1; t.d.levels = 1; t.d.target = NVN_TEXTURE_TARGET_2D; t.d.format = NVN_FORMAT_RGBA8;
|
||||
mtl_init();
|
||||
MTLTextureDescriptor *d = tex_desc(&t, 0);
|
||||
failed += (d.usage & MTLTextureUsagePixelFormatView) != 0;
|
||||
id<MTLTexture> base = [g_dev newTextureWithDescriptor:d];
|
||||
uint8_t bytes[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
|
||||
id<MTLBuffer> src = [g_dev newBufferWithBytes:bytes length:sizeof bytes options:MTLResourceStorageModeShared];
|
||||
mtl_sub_begin();
|
||||
res_add(src); res_add(base); // Metal 4:拷贝两端都要在驻留集里 | Metal 4: both ends of a copy must be in the residency set
|
||||
id fill = blit(); // 主命令缓冲上的拷贝走宿主封装(自带屏障) | copies on the main command buffer go through the host wrapper (which carries its own barrier)
|
||||
[fill copyFromBuffer:src sourceOffset:0 sourceBytesPerRow:16 sourceBytesPerImage:16 sourceSize:MTLSizeMake(4, 1, 1)
|
||||
toTexture:base destinationSlice:0 destinationLevel:0 destinationOrigin:MTLOriginMake(0, 0, 0)];
|
||||
enc_b_end(g_blit); g_blit = nil;
|
||||
serial_put(t.serial, base);
|
||||
id<MTLTexture> upgraded = tex_upgrade_pfv(&t, base, MTLPixelFormatR32Uint);
|
||||
failed += upgraded.pixelFormat != MTLPixelFormatRGBA8Unorm; // 升级保留原格式 | the upgrade keeps the original format
|
||||
failed += !(upgraded.usage & MTLTextureUsagePixelFormatView);
|
||||
failed += serial_get(t.serial) != upgraded; // 登记已替换 | the registration has been replaced
|
||||
if (g_blit) { enc_b_end(g_blit); g_blit = nil; }
|
||||
id<MTLTexture> view = [upgraded newTextureViewWithPixelFormat:MTLPixelFormatR32Uint];
|
||||
id<MTLBuffer> dst = [g_dev newBufferWithLength:sizeof bytes options:MTLResourceStorageModeShared];
|
||||
res_add(dst);
|
||||
id read = blit();
|
||||
[read copyFromTexture:view sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0, 0, 0) sourceSize:MTLSizeMake(4, 1, 1)
|
||||
toBuffer:dst destinationOffset:0 destinationBytesPerRow:16 destinationBytesPerImage:16];
|
||||
enc_b_end(g_blit); g_blit = nil;
|
||||
mtl_sub_commit(); mtl_drain();
|
||||
failed += memcmp(dst.contents, bytes, sizeof bytes) != 0;
|
||||
printf("pfv predicate failed=%d\n", failed);
|
||||
return failed != 0;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// 出图裁切回归:彩色8×8纹理,闭式RGBA期望;真实Metal渲染,不依赖游戏或跨局确定性。
|
||||
// Present crop regression: colored 8×8 texture, closed-form RGBA expectations; real Metal rendering, no dependence on the game or on cross-run determinism.
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
#include "../nvn/hle_nvn.c"
|
||||
uint64_t g_t0_ns; // 宿主 main.c 的进程起点(hle_nvn 逐帧 @t_s 用),单测替身 | process start time from host main.c (used by hle_nvn's per-frame @t_s); unit test stub
|
||||
void *front_metal_layer(void) { return NULL; }
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
module_t g_mod[MAX_MOD]; int g_nmod;
|
||||
void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { return bp_now(); }
|
||||
#ifdef CROP_LEGACY_HEADER
|
||||
#include CROP_LEGACY_HEADER
|
||||
#define ENCODE legacy_present_encode
|
||||
#else
|
||||
#define ENCODE present_encode
|
||||
#endif
|
||||
static int failed, cases;
|
||||
#define EXPECT(n, w, v) do { int a=(w),b=(v); cases++; printf("%s 期望 %d → 真结果 %d %s\n",n,a,b,a==b?"✓":"✗");failed+=a!=b; } while(0)
|
||||
static const uint8_t colors[4][4]={{255,0,0,255},{0,255,0,255},{0,0,255,255},{255,255,0,255}};
|
||||
|
||||
static void check(id<MTLTexture> src, const char *name, const int crop[4], int w, int h, int color) {
|
||||
MTLTextureDescriptor *d=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:w height:h mipmapped:NO];
|
||||
d.storageMode=MTLStorageModeShared;d.usage=MTLTextureUsageRenderTarget;
|
||||
id<MTLTexture> dst=[g_dev newTextureWithDescriptor:d];id<MTLCommandBuffer> cb=[g_q commandBuffer];
|
||||
EXPECT("编码成功",1,ENCODE(cb,src,dst,crop));[cb commit];[cb waitUntilCompleted];
|
||||
EXPECT("GPU完成",MTLCommandBufferStatusCompleted,cb.status);
|
||||
uint8_t *out=malloc(w*h*4);[dst getBytes:out bytesPerRow:w*4 fromRegion:MTLRegionMake2D(0,0,w,h) mipmapLevel:0];
|
||||
int bad=0;
|
||||
for(int y=0;y<h;y++)for(int x=0;x<w;x++) {
|
||||
int q=color;
|
||||
if(q==4) { // 正方形有效区对2:1目标:两侧各4列黑,中间8列全红。 | square valid area onto a 2:1 target: 4 black columns on each side, the middle 8 columns all red.
|
||||
static const uint8_t black[4]={0,0,0,255};
|
||||
const uint8_t *want=x<4||x>=12?black:colors[0];bad+=memcmp(out+4*(y*w+x),want,4)!=0;continue;
|
||||
}
|
||||
if(q==-2) { // crop=(1,1,4,4):3×3红、末列绿、末行蓝、右下1格黄。 | crop=(1,1,4,4): 3×3 red, last column green, last row blue, bottom-right 1 cell yellow.
|
||||
q=(x+1>=4)+2*(y+1>=4);
|
||||
} else if(q<0) { // 同尺寸默认整帧:分界在正中。 | same-size default whole frame: the boundary is dead center.
|
||||
q=(x>=w/2)+2*(y>=h/2);
|
||||
}
|
||||
bad+=memcmp(out+4*(y*w+x),colors[q],4)!=0;
|
||||
}
|
||||
EXPECT(name,0,bad);free(out);
|
||||
}
|
||||
|
||||
int main(void) { @autoreleasepool {
|
||||
mtl_init();
|
||||
MTLTextureDescriptor *d=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:8 height:8 mipmapped:NO];d.storageMode=MTLStorageModeShared;d.usage=MTLTextureUsageShaderRead;
|
||||
id<MTLTexture> src=[g_dev newTextureWithDescriptor:d];uint8_t px[8*8*4];
|
||||
for(int y=0;y<8;y++)for(int x=0;x<8;x++)memcpy(px+4*(y*8+x),colors[(x>=4)+2*(y>=4)],4);
|
||||
[src replaceRegion:MTLRegionMake2D(0,0,8,8) mipmapLevel:0 withBytes:px bytesPerRow:32];
|
||||
int zero[4]={0},tl[4]={0,0,4,4},tr[4]={4,0,4,4},bl[4]={0,4,4,4},br[4]={4,4,4,4},one[4]={3,3,1,1},inset[4]={1,1,4,4};
|
||||
check(src,"默认整帧64像素",zero,8,8,-1);
|
||||
check(src,"NULL默认整帧64像素",NULL,8,8,-1);
|
||||
check(src,"左上裁切放大256像素全红",tl,16,16,0);
|
||||
check(src,"非零x裁切放大256像素全绿",tr,16,16,1);
|
||||
check(src,"非零y裁切放大256像素全蓝",bl,16,16,2);
|
||||
check(src,"右下裁切贴边256像素全黄",br,16,16,3);
|
||||
check(src,"单纹素放大不跨边界256像素全红",one,16,16,0);
|
||||
check(src,"非零双偏移16像素逐字节等手写子矩形",inset,4,4,-2);
|
||||
check(src,"有效区比例保留,128像素中间红/两侧黑",tl,16,8,4);
|
||||
int invalid[4][4]={{-1,0,4,4},{0,-1,4,4},{0,0,0,4},{7,0,4,4}};
|
||||
for(int i=0;i<4;i++) {
|
||||
MTLTextureDescriptor *dd=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:8 height:8 mipmapped:NO];dd.usage=MTLTextureUsageRenderTarget;dd.storageMode=MTLStorageModeShared;
|
||||
id<MTLTexture> dst=[g_dev newTextureWithDescriptor:dd];
|
||||
EXPECT("无效crop不编码、不把整张拉伸冒充成功",0,ENCODE([g_q commandBuffer],src,dst,invalid[i]));
|
||||
}
|
||||
// 真实QueuePresent入口:先设crop入队,再立即改window,出图票号必须保留当帧副本。
|
||||
// Real QueuePresent entry: set crop and enqueue first, then immediately change the window; the present ticket must keep that frame's copy.
|
||||
PFNNVNDEVICEGETPROCADDRESSPROC get=(PFNNVNDEVICEGETPROCADDRESSPROC)h_nvnBootstrapLoader("nvnDeviceGetProcAddress");
|
||||
NVNT_nvnWindowSetCrop set=(NVNT_nvnWindowSetCrop)get(NULL,"nvnWindowSetCrop");
|
||||
NVNT_nvnQueuePresentTexture present=(NVNT_nvnQueuePresentTexture)get(NULL,"nvnQueuePresentTexture");
|
||||
tex_t tex={.serial=10001};tex.d.width=tex.d.height=8;tex.d.depth=tex.d.levels=1;tex.d.format=NVN_FORMAT_RGBA8;tex.d.target=NVN_TEXTURE_TARGET_2D;serial_put(tex.serial,src);
|
||||
win_t win={.ntex=1};win.tex[0]=(NVNtexture *)&tex;set((NVNwindow *)&win,4,4,4,4);
|
||||
mtl_present_test_stall(100000000);present(NULL,(NVNwindow *)&win,0);uint64_t tk=win.ticket[0];set((NVNwindow *)&win,0,0,8,8);
|
||||
#ifdef CROP_LEGACY_HEADER
|
||||
EXPECT("旧队列结构没有四参数副本空间(结构检查)",1,sizeof(pq_item)>=sizeof(tex_t)+sizeof(double)+sizeof(uint64_t)+sizeof br);
|
||||
#else
|
||||
pthread_mutex_lock(&g_pq_mu);int saved=memcmp(g_pq[(tk-1)%PQ].crop,br,sizeof br)==0;pthread_mutex_unlock(&g_pq_mu);
|
||||
EXPECT("真实QueuePresent当帧crop副本不随window变化",1,saved);
|
||||
#endif
|
||||
mtl_present_wait(tk);mtl_present_test_stall(0);
|
||||
printf("== %d 项,失败 %d ==\n",cases,failed);return failed!=0;
|
||||
} }
|
||||
@@ -0,0 +1,33 @@
|
||||
// 可序列化管线键单测:pso_skey 十六进制往返逐字节一致,篡改 / 长度错 / 非法字符被识别(期望由构造直接给出)。
|
||||
// Serializable pipeline key unit tests: the pso_skey hex round trip is byte-identical; tampering / wrong length / illegal characters are detected (expectations given directly by construction).
|
||||
#import <Foundation/Foundation.h>
|
||||
#include <assert.h>
|
||||
#include <stdlib.h>
|
||||
#include "../nvn/nvn_obj.h"
|
||||
@interface NvShader : NSObject { @public int stage; char key[24]; } @end
|
||||
@implementation NvShader @end
|
||||
#include "../nvn/nvn_pso_skey.h"
|
||||
|
||||
static void fill(pso_key *k, unsigned seed) {
|
||||
memset(k, 0, sizeof *k);
|
||||
for (size_t i = 0; i < sizeof *k; i++) ((unsigned char *)k)[i] = (unsigned char)(seed + i * 13);
|
||||
k->vs = (void *)1; k->fs = (void *)2; k->fsfn = (void *)3;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
for (unsigned seed = 1; seed <= 3; seed++) {
|
||||
pso_key k; fill(&k, seed);
|
||||
NvShader *vs = [NvShader new], *fs = [NvShader new];
|
||||
vs->stage = (int)seed; fs->stage = (int)(seed + 1);
|
||||
snprintf(vs->key, sizeof vs->key, "vs-%u", seed); snprintf(fs->key, sizeof fs->key, "fs-%u", seed);
|
||||
pso_fz_desc fz = {.kind = 1, .fbmask = 0xa5};
|
||||
for (int i = 0; i < 32; i++) fz.fx[i] = (int8_t)(i - 7);
|
||||
pso_skey a, b; char hex[sizeof a * 2 + 1];
|
||||
pso_skey_from(&k, vs, fs, seed & 1, &fz, &a); pso_skey_hex(&a, hex);
|
||||
assert(pso_skey_parse(hex, &b) == 0); assert(memcmp(&a, &b, sizeof a) == 0);
|
||||
hex[0] = hex[0] == '0' ? '1' : '0'; assert(pso_skey_parse(hex, &b) == 0); assert(memcmp(&a, &b, sizeof a) != 0);
|
||||
assert(pso_skey_parse(hex + 1, &b) == -1); hex[0] = 'g'; assert(pso_skey_parse(hex, &b) == -1);
|
||||
}
|
||||
puts("PSO_SKEY OK 3 例往返一致;篡改一字符不等、缺位 / 非法字符拒收");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// 反射转换单测:真实 B 反射 json(Switch 原版翻译,build/cache/metal_shader_cache/<键>_b.json)→ C 数组,期望按 json 原文手抄。
|
||||
// 哑贴图类型 MTLTextureType:1D=0 1DArray=1 2D=2 2DArray=3 Cube=5 CubeArray=6 3D=7
|
||||
// Reflection conversion unit tests: real B reflection json (translation of the original Switch shaders, build/cache/metal_shader_cache/<key>_b.json) → C arrays, expectations hand-copied from the json text.
|
||||
// Dummy texture type MTLTextureType: 1D=0 1DArray=1 2D=2 2DArray=3 Cube=5 CubeArray=6 3D=7
|
||||
#import "../nvn/nvn_refl.h"
|
||||
#import <Foundation/Foundation.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "../nvn/dmsh_chain.h"
|
||||
|
||||
enum { C = NVN_RB_CBUF, S = NVN_RB_SAMP, T = NVN_RB_TEX, I = NVN_RB_IMG, TB = NVN_RB_TBUF };
|
||||
enum { F = NVN_DPF_FLOAT, U = NVN_DPF_UINT, D = NVN_DPF_DEPTH };
|
||||
static int fail, n;
|
||||
static void check(const char *what, long want, long got) {
|
||||
n++; int ok = want == got; fail += !ok;
|
||||
if (!ok) printf(" %-40s 期望 %ld → 真结果 %ld ✗\n", what, want, got);
|
||||
}
|
||||
static NSDictionary *load(const char *key) {
|
||||
NSString *p = [NSString stringWithFormat:@"%s%s/build/cache/metal_shader_cache/b-%s/%s.json", getenv("DM_ROOT") ?: getenv("HOME"), getenv("DM_ROOT") ? "" : "/dm-work", DMSH_CHAIN, key]; // 现行翻译链版本的那一份库 | the library of the current translation chain version
|
||||
NSData *d = [NSData dataWithContentsOfFile:p];
|
||||
if (!d) { printf("【红】缺反射样本 %s\n", p.UTF8String); fail++; return nil; }
|
||||
return [NSJSONSerialization JSONObjectWithData:d options:0 error:nil];
|
||||
}
|
||||
|
||||
int main(void) { @autoreleasepool {
|
||||
nvn_refl r; char err[160] = "";
|
||||
{ int f0 = fail; // A 路线已退役:PC 链反射(无 route = B)必须被拒 | Route A is retired: PC-chain reflection (no route = B) must be rejected
|
||||
NSDictionary *pc = @{@"arg_buffer_index": @0, @"bindings": @[@{@"type": @"cbuffer", @"reg": @10, @"arg_id": @0, @"access": @"constant", @"msl_type": @"constant cb1_struct*"}], @"vertex_inputs": @[]};
|
||||
check("PC 链反射(无 route = B)报失败", 1, nvn_refl_from_json(pc, &r, err, sizeof err) != 0);
|
||||
printf("%-60s %s\n", "负对照:PC 链反射被拒(A 路线已退役)", fail == f0 ? "✓" : "✗");
|
||||
}
|
||||
|
||||
// B 路线(Switch 原版翻译,tools/dmsh_build.py 出):真实反射 ps_models_p#0 / vs_models_v#0,期望按 json 原文手抄
|
||||
// Route B (translation of the original Switch shaders, produced by tools/dmsh_build.py): real reflection ps_models_p#0 / vs_models_v#0, expectations hand-copied from the json text
|
||||
{ NSDictionary *j = load("5c1ca4e7c3e4657c_b");
|
||||
if (j) { int f1 = fail;
|
||||
check("B 片元:转换成功", 0, nvn_refl_from_json(j, &r, err, sizeof err));
|
||||
check("B 片元:B 标记", 1, r.route_b); check("B 片元:参数缓冲槽", 0, r.abi); check("B 片元:绑定数", 44, r.nb); check("B 片元:顶点输入数", 0, r.nv);
|
||||
check("B 片元:有 c1", 1, r.has_c1); check("B 片元:c1 长 256(控制段字段)", 256, r.c1_len);
|
||||
uint32_t c1w; memcpy(&c1w, r.c1, 4); check("B 片元:c1 首字 = −√1.5(0xbf9cc471)", 0xbf9cc471u, c1w);
|
||||
struct { int i, kind, reg, aid, rw, dtt, dpf; } w[] = {
|
||||
{0, NVN_RB_SUPPORT, 0, 0, 0, -1, -1}, {1, C, 10, 1, 0, -1, -1}, {4, NVN_RB_C1, 0, 4, 0, -1, -1}, {7, NVN_RB_DRV0, 0, 7, 0, -1, -1},
|
||||
{8, NVN_RB_DRV2, 0, 8, 0, -1, -1}, {11, NVN_RB_SBUFP, 4, 11, 0, -1, -1}, {13, TB, 8, 13, 0, -1, -1}, {14, T, 41, 14, 0, 2, F},
|
||||
{15, S, 3, 15, 0, -1, -1}, {28, T, 39, 28, 0, 3, D}, {34, T, 33, 34, 0, 5, D}, {36, T, 46, 36, 0, 7, F}};
|
||||
for (unsigned k = 0; k < sizeof w / sizeof *w; k++) {
|
||||
const nvn_rbind *g = &r.b[w[k].i]; char m[64];
|
||||
snprintf(m, sizeof m, "B 绑定[%d] 种类", w[k].i); check(m, w[k].kind, g->kind);
|
||||
snprintf(m, sizeof m, "B 绑定[%d] 槽号", w[k].i); check(m, w[k].reg, g->reg);
|
||||
snprintf(m, sizeof m, "B 绑定[%d] 参数序号", w[k].i); check(m, w[k].aid, g->aid);
|
||||
snprintf(m, sizeof m, "B 绑定[%d] 读写", w[k].i); check(m, w[k].rw, g->rw);
|
||||
if (w[k].dtt >= 0) { snprintf(m, sizeof m, "B 绑定[%d] 哑贴图类型", w[k].i); check(m, w[k].dtt, g->dtt);
|
||||
snprintf(m, sizeof m, "B 绑定[%d] 哑贴图像素类", w[k].i); check(m, w[k].dpf, g->dpf); }
|
||||
}
|
||||
printf("%-60s %s\n", "B 片元 ps_models_p#0:44 个绑定(含 support / c1 / 驱动段 / 存储缓冲指针)", fail == f1 ? "✓" : "✗");
|
||||
} }
|
||||
{ NSDictionary *j = load("54f730a6c0efc118_b");
|
||||
if (j) { int f1 = fail;
|
||||
check("B 顶点:转换成功", 0, nvn_refl_from_json(j, &r, err, sizeof err));
|
||||
check("B 顶点:绑定数", 2, r.nb); check("B 顶点:输入数", 4, r.nv); check("B 顶点:c1 长 0(控制段 +0x704 − +0x700)→ 无 c1", 0, r.has_c1);
|
||||
for (int i = 0; i < 4 && i < r.nv; i++) { char m[48]; snprintf(m, sizeof m, "B 顶点输入[%d] 属性号 = 位置", i); check(m, i, r.v[i].nvn); check(m, i, r.v[i].loc); check("B 顶点分量 float", NVN_CT_FLOAT, r.v[i].ct); }
|
||||
check("B 顶点:绑定[0] uniform 槽 0", 0, r.b[0].reg); check("B 顶点:绑定[1] uniform 槽 3", 3, r.b[1].reg);
|
||||
printf("%-60s %s\n", "B 顶点 vs_models_v#0:4 个属性(属性号 = MSL attribute)", fail == f1 ? "✓" : "✗");
|
||||
} }
|
||||
{ int f1 = fail;
|
||||
NSDictionary *b1 = @{@"route": @"B", @"bindings": @[@{@"kind": @"foo", @"arg_id": @0, @"msl_name": @"x", @"msl_type": @"constant _16*"}]};
|
||||
NSDictionary *b2 = @{@"route": @"B", @"bindings": @[@{@"kind": @"tex", @"reg": [NSNull null], @"arg_id": @0, @"msl_name": @"fp_t_x", @"msl_type": @"texture2d<float>"}]};
|
||||
check("B 未知种类报失败", 1, nvn_refl_from_json(b1, &r, err, sizeof err) != 0);
|
||||
check("B 贴图没解出槽号报失败", 1, nvn_refl_from_json(b2, &r, err, sizeof err) != 0);
|
||||
printf("%-60s %s\n", "B 负对照:未知种类 / 槽号缺失", fail == f1 ? "✓" : "✗");
|
||||
}
|
||||
printf("== %d 项,失败 %d ==\n", n, fail);
|
||||
return fail != 0;
|
||||
} }
|
||||
@@ -0,0 +1,283 @@
|
||||
// 固定命令链实验:生产 mtl_exec,手写常量着色器和闭式期望;不含生产重排器。
|
||||
// G 完整模板块、M 小视图+复制、U 混合、R 模板 resolve;只交换 G/M。
|
||||
// Fixed command chain experiment: production mtl_exec, hand-written constant shaders and closed-form expectations; does not include the production reorderer.
|
||||
// G full stencil block, M small view + copy, U blend, R stencil resolve; only G/M are swapped.
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
void *front_metal_layer(void) { return NULL; }
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
module_t g_mod[MAX_MOD]; int g_nmod;
|
||||
void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { return bp_now(); }
|
||||
static int fail, count, all_independent;
|
||||
#define EXPECT(n,w,v) do { uint64_t a=(w), b=(v); count++; \
|
||||
printf("%s 期望 %llu → 真结果 %llu %s\n",n,(unsigned long long)a,(unsigned long long)b,a==b?"✓":"✗"); fail+=a!=b; } while(0)
|
||||
typedef struct { uint8_t *p; size_t n; int width; } chain;
|
||||
static chain make_chain(void) {
|
||||
chain c={0}; if(posix_memalign((void **)&c.p,getpagesize(),65536)) abort();
|
||||
memset(c.p,0,65536); mtl_pool_add(c.p,65536); return c;
|
||||
}
|
||||
static void emit(chain *c, unsigned op, const void *a, size_t n) {
|
||||
size_t sz=(8+n+7)&~7ull; if(c->n+sz>65536) abort();
|
||||
op_hdr h={op,(uint32_t)sz}; memcpy(c->p+c->n,&h,8);
|
||||
if(n) memcpy(c->p+c->n+8,a,n); c->n+=sz;
|
||||
}
|
||||
static void state(chain *c, int kind, const void *s, size_t n) {
|
||||
p_bind_state b={.kind=kind}; if(n>sizeof b.bytes) abort(); memcpy(b.bytes,s,n); emit(c,OP_BIND_STATE,&b,sizeof b);
|
||||
}
|
||||
static tex_t texture(unsigned w, unsigned levels, int depth) {
|
||||
static uint64_t ser=5000; tex_t t={.serial=ser++}; t.d.width=t.d.height=w;
|
||||
t.d.depth=t.d.samples=1; t.d.levels=levels; t.d.target=NVN_TEXTURE_TARGET_2D;
|
||||
t.d.format=depth?NVN_FORMAT_DEPTH32F_STENCIL8:NVN_FORMAT_RGBA8; return t;
|
||||
}
|
||||
static void rt(chain *c, const tex_t *t, unsigned lv, const tex_t *ds) {
|
||||
p_set_rt r={.n=1,.depth=ds}; r.color[0]=t;
|
||||
r.has_cview[0]=1; r.cview[0].set_levels=1; r.cview[0].base_level=lv; r.cview[0].nlevels=1;
|
||||
emit(c,OP_SET_RT,&r,sizeof r);
|
||||
p_viewports v={.n=1}; v.v[0][2]=v.v[0][3]=MAX(t->d.width>>lv,1u); emit(c,OP_VIEWPORTS,&v,sizeof v);
|
||||
c->width=(int)v.v[0][2];
|
||||
// clear的剪裁覆盖基尺寸,兼容现有scissor_full;每次draw再显式取实际mip尺寸。
|
||||
// The clear's scissor covers the base size, compatible with the existing scissor_full; each draw then explicitly takes the actual mip size.
|
||||
p_scissor sc={0,0,(int)t->d.width,(int)t->d.height}; emit(c,OP_SCISSOR,&sc,sizeof sc);
|
||||
}
|
||||
static void clear(chain *c, const tex_t *t, unsigned lv, const tex_t *ds, int red, int green, int blue) {
|
||||
rt(c,t,lv,ds); p_clear_color b={.index=0,.mask=15,.rgba={red,green,blue,1}}; emit(c,OP_CLEAR_COLOR,&b,sizeof b);
|
||||
if(ds) { p_clear_ds d={.depth=1,.depth_mask=1,.stencil=2,.stencil_mask=255}; emit(c,OP_CLEAR_DS,&d,sizeof d); }
|
||||
}
|
||||
static ds_st ds_state(int stencil, int func, int op) {
|
||||
return (ds_st){0,0,NVN_DEPTH_FUNC_ALWAYS,stencil,func,func,1,1,op,1,1,op};
|
||||
}
|
||||
static void stencil(chain *c, int enabled, int func, int op, unsigned read, unsigned write, unsigned ref) {
|
||||
ds_st d=ds_state(enabled,func,op); state(c,5,&d,sizeof d);
|
||||
for(int k=0;k<3;k++) { p_stencil s={.face=3,.which=k,.value_mask=read,.mask=write,.ref=ref}; emit(c,OP_STENCIL,&s,sizeof s); }
|
||||
}
|
||||
static void blending(chain *c, int enabled) {
|
||||
color_st col={enabled,NVN_LOGIC_OP_COPY,NVN_ALPHA_FUNC_ALWAYS}; state(c,1,&col,sizeof col);
|
||||
blend_st b={0,NVN_BLEND_FUNC_SRC_ALPHA,NVN_BLEND_FUNC_ONE_MINUS_SRC_ALPHA,NVN_BLEND_FUNC_ONE,NVN_BLEND_FUNC_ZERO,NVN_BLEND_EQUATION_ADD,NVN_BLEND_EQUATION_ADD};
|
||||
state(c,0,&b,sizeof b);
|
||||
}
|
||||
static prog_t pg[8];
|
||||
static void draw_prog(chain *c, int p, int tid) {
|
||||
p_bind_program b={&pg[p],3}; emit(c,OP_BIND_PROGRAM,&b,sizeof b);
|
||||
if(tid) { p_bind_handles h={.stage=1,.first=0,.n=1}; h.h[0]=tid; emit(c,OP_BIND_TEX,&h,sizeof h); }
|
||||
p_scissor sc={0,0,c->width,c->width}; emit(c,OP_SCISSOR,&sc,sizeof sc);
|
||||
p_draw d={NVN_DRAW_PRIMITIVE_TRIANGLES,0,3}; emit(c,OP_DRAW,&d,sizeof d);
|
||||
}
|
||||
static int bind_view_range(const tex_t *t, int lv, int levels, int sl, int slices) {
|
||||
static int tid=1000; view_t v={.set_levels=1,.base_level=lv,.nlevels=levels,
|
||||
.set_layers=slices>0,.min_layer=sl,.nlayers=slices};
|
||||
mtl_reg_tex(tid,t,&v); return tid++;
|
||||
}
|
||||
static int bind_view(const tex_t *t, int lv) { return bind_view_range(t,lv,1,0,0); }
|
||||
typedef struct { uint8_t a[256],b[256],c[256],e[256]; uint64_t query; } result;
|
||||
static result execute(chain *c, const tex_t *a, const tex_t *b, const tex_t *out, const tex_t *e, uint64_t *q) {
|
||||
emit(c,OP_END,NULL,0); state_reset(); memset(&R,0,sizeof R); vis_clear(); g_vis_on=g_vis_counting=0;
|
||||
mtl_sub_begin(); mtl_exec(c->p);
|
||||
const tex_t *t[4]={a,b,out,e}; id<MTLBuffer> buf[4];
|
||||
for(int k=0;k<4;k++) { buf[k]=[g_dev newBufferWithLength:256 options:MTLResourceStorageModeShared];
|
||||
[blit() copyFromTexture:tex_mtl(t[k]) sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0,0,0) sourceSize:MTLSizeMake(8,8,1)
|
||||
toBuffer:buf[k] destinationOffset:0 destinationBytesPerRow:32 destinationBytesPerImage:256]; }
|
||||
uint64_t f=mtl_sub_commit(); EXPECT("生产提交完成",1,mtl_wait(f,5000000000ull)); EXPECT("提交反馈无错误",0,mtl_last_commit_error());
|
||||
result r={0}; uint8_t *dst[4]={r.a,r.b,r.c,r.e}; for(int k=0;k<4;k++) memcpy(dst[k],buf[k].contents,256);
|
||||
if(q) r.query=*q; mtl_pool_del(c->p); free(c->p); return r;
|
||||
}
|
||||
static void uniform_pixels(const char *name, const uint8_t *b, uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) {
|
||||
uint8_t want[4]={red,green,blue,alpha}; unsigned bad=0;
|
||||
for(int k=0;k<64;k++) bad+=memcmp(b+4*k,want,4)!=0; EXPECT(name,0,bad);
|
||||
}
|
||||
static void save_raw(const char *name, int reordered, const void *r, size_t n) {
|
||||
const char *dir=getenv("DM_GFX_FIXTURE_OUT"); if(!dir) return;
|
||||
char path[1024]; snprintf(path,sizeof path,"%s/%s_%s.raw",dir,name,reordered?"reordered":"original");
|
||||
FILE *f=fopen(path,"wb"); if(!f || fwrite(r,1,n,f)!=n) abort(); fclose(f);
|
||||
}
|
||||
static void save_result(const char *name, int reordered, const result *r) { save_raw(name,reordered,r,sizeof *r); }
|
||||
enum { INDEPENDENT, SAME_MIP, STENCIL_INDEPENDENT, STENCIL_DEPENDENT, COPY_DEPENDENT, INTERNAL_ORDER };
|
||||
static void full_block(chain *c,const tex_t *a,const tex_t *ds,int reverse) {
|
||||
rt(c,a,0,ds); blending(c,0);
|
||||
for(int i=0;i<2;i++) { int reader=reverse?i==0:i==1;
|
||||
stencil(c,1,reader?NVN_STENCIL_FUNC_NOTEQUAL:NVN_STENCIL_FUNC_ALWAYS,reader?NVN_STENCIL_OP_KEEP:NVN_STENCIL_OP_REPLACE,
|
||||
reader?0x34:0,reader?0:0x10,reader?0:0x30); draw_prog(c,reader?1:0,0); }
|
||||
}
|
||||
static void middle_block(chain *c,const tex_t *a,const tex_t *b,const tex_t *ds,const tex_t *d,const tex_t *e,int tid,int mode) {
|
||||
rt(c,b,0,mode==STENCIL_INDEPENDENT||mode==STENCIL_DEPENDENT?ds:NULL); blending(c,0);
|
||||
unsigned mask=mode==STENCIL_DEPENDENT?0x10:0x2;
|
||||
stencil(c,mode==STENCIL_INDEPENDENT||mode==STENCIL_DEPENDENT,NVN_STENCIL_FUNC_EQUAL,NVN_STENCIL_OP_KEEP,mask,0,mask); draw_prog(c,2,tid);
|
||||
p_copy_t2t cp={.src=mode==COPY_DEPENDENT?a:d,.dst=e,.sr={0,0,0,8,8,1},.dr={0,0,0,8,8,1}};
|
||||
emit(c,OP_COPY_T2T,&cp,sizeof cp);
|
||||
}
|
||||
static result render_case(int mode,int reordered) {
|
||||
tex_t a=texture(8,2,0), b=texture(8,1,0), out=texture(8,1,0), ds=texture(8,1,1), d=texture(8,1,0), e=texture(8,1,0);
|
||||
int at=bind_view(&a,mode==SAME_MIP?0:1),bt=bind_view(&b,0),af=bind_view(&a,0); chain c=make_chain();
|
||||
clear(&c,&a,0,&ds,0,0,0); clear(&c,&a,1,NULL,0,1,0); clear(&c,&b,0,NULL,0,0,0);
|
||||
clear(&c,&d,0,NULL,0,0,1); clear(&c,&e,0,NULL,0,0,0); clear(&c,&out,0,NULL,0,0,0);
|
||||
if(reordered) middle_block(&c,&a,&b,&ds,&d,&e,at,mode);
|
||||
full_block(&c,&a,&ds,reordered&&mode==INTERNAL_ORDER);
|
||||
if(!reordered) middle_block(&c,&a,&b,&ds,&d,&e,at,mode);
|
||||
rt(&c,&a,0,NULL); stencil(&c,0,8,1,255,255,0); blending(&c,1); draw_prog(&c,3,bt);
|
||||
rt(&c,&out,0,&ds); stencil(&c,1,NVN_STENCIL_FUNC_EQUAL,1,2,0,2); blending(&c,0); draw_prog(&c,2,af);
|
||||
return execute(&c,&a,&b,&out,&e,NULL);
|
||||
}
|
||||
static uint64_t query_case(int reordered, int mode) {
|
||||
tex_t a=texture(8,1,0),b=texture(4,1,0); chain c=make_chain(); uint64_t q[2]={UINT64_MAX,0}, type=NVN_COUNTER_TYPE_SAMPLES_PASSED;
|
||||
emit(&c,OP_RESET_COUNTER,&type,8); stencil(&c,0,8,1,255,255,0); blending(&c,0);
|
||||
if(!reordered) { clear(&c,&a,0,NULL,0,0,0); draw_prog(&c,0,0); }
|
||||
if(mode!=1) emit(&c,OP_RESET_COUNTER,&type,8);
|
||||
clear(&c,&b,0,NULL,0,0,0); draw_prog(&c,1,0);
|
||||
if(reordered) { clear(&c,&a,0,NULL,0,0,0); draw_prog(&c,0,0); }
|
||||
if(mode==2) { // 两块计数都在任何report之前被后继reset抹去;只报告新的4x4绘制。 | both blocks' counts are wiped by the subsequent reset before any report; only the new 4x4 draw is reported.
|
||||
emit(&c,OP_RESET_COUNTER,&type,8); clear(&c,&b,0,NULL,0,0,0); draw_prog(&c,1,0); }
|
||||
uint64_t report[2]={type,(uint64_t)q}; emit(&c,OP_REPORT_COUNTER,report,sizeof report); emit(&c,OP_END,NULL,0);
|
||||
state_reset(); memset(&R,0,sizeof R); vis_clear(); g_vis_on=g_vis_counting=0; mtl_sub_begin(); mtl_exec(c.p);
|
||||
EXPECT("查询完成",1,mtl_wait(mtl_sub_commit(),5000000000ull)); EXPECT("查询提交反馈无错误",0,mtl_last_commit_error());
|
||||
const char *names[]={"查询","同区间查询","后继reset覆盖查询"};
|
||||
save_raw(names[mode],reordered,q,sizeof q); mtl_pool_del(c.p); free(c.p); return q[0];
|
||||
}
|
||||
static void uniform_case(int reordered,uint8_t pixels[256]) {
|
||||
void *mem=NULL; if(posix_memalign(&mem,getpagesize(),getpagesize())) abort(); memset(mem,0,getpagesize());
|
||||
float red[4]={1,0,0,1},green[4]={0,1,0,1}; memcpy(mem,red,16); mtl_pool_add(mem,getpagesize());
|
||||
tex_t a=texture(8,1,0),b=texture(8,1,0),out=texture(8,1,0),e=texture(8,1,0); chain c=make_chain();
|
||||
clear(&c,&out,0,NULL,0,0,0); clear(&c,&e,0,NULL,0,0,0); stencil(&c,0,8,1,255,255,0); blending(&c,0);
|
||||
p_bind_buf ub={.stage=1,.index=0,.addr=(uint64_t)mem,.size=16}; emit(&c,OP_BIND_UBO,&ub,sizeof ub);
|
||||
if(!reordered) { clear(&c,&a,0,NULL,0,0,0); draw_prog(&c,4,0); }
|
||||
struct { uint64_t dst,n; float color[4]; } update={(uint64_t)mem,16,{0}}; memcpy(update.color,green,16); emit(&c,OP_UPDATE_UB,&update,sizeof update);
|
||||
if(reordered) { clear(&c,&a,0,NULL,0,0,0); draw_prog(&c,4,0); }
|
||||
clear(&c,&b,0,NULL,0,0,0); draw_prog(&c,4,0); result r=execute(&c,&a,&b,&out,&e,NULL); save_result("UB写",reordered,&r); memcpy(pixels,r.a,256);
|
||||
uniform_pixels("UB更新后的第二绘制始终绿色",r.b,0,255,0,255); mtl_pool_del(mem); free(mem);
|
||||
}
|
||||
// view的可访问区间不能只看base:shader读相对第二级/第二层,G写该子资源。
|
||||
// A view's accessible range cannot be judged by base alone: the shader reads relative to the second level/second layer, and G writes that subresource.
|
||||
static void slice_rt(chain *c,const tex_t *t,int lv,int sl) {
|
||||
p_set_rt r={.n=1}; r.color[0]=t; r.has_cview[0]=1;
|
||||
r.cview[0]=(view_t){.set_levels=1,.base_level=lv,.nlevels=1,.set_layers=1,.min_layer=sl,.nlayers=1};
|
||||
emit(c,OP_SET_RT,&r,sizeof r); p_viewports v={.n=1}; v.v[0][2]=v.v[0][3]=MAX(t->d.width>>lv,1u); emit(c,OP_VIEWPORTS,&v,sizeof v);
|
||||
c->width=(int)v.v[0][2]; p_scissor sc={0,0,(int)t->d.width,(int)t->d.height}; emit(c,OP_SCISSOR,&sc,sizeof sc);
|
||||
}
|
||||
static void slice_clear(chain *c,const tex_t *t,int lv,int sl,int green) {
|
||||
slice_rt(c,t,lv,sl); p_clear_color cc={.index=0,.mask=15,.rgba={0,green,0,1}}; emit(c,OP_CLEAR_COLOR,&cc,sizeof cc);
|
||||
}
|
||||
static void sample_block(chain *c,const tex_t *dst,int program,int tid) {
|
||||
rt(c,dst,0,NULL); stencil(c,0,8,1,255,255,0); blending(c,0); draw_prog(c,program,tid);
|
||||
}
|
||||
static result range_case(int array,int reordered) {
|
||||
tex_t a=texture(8,array?1:2,0),b=texture(8,1,0),out=texture(8,1,0),e=texture(8,1,0);
|
||||
if(array) { a.d.target=NVN_TEXTURE_TARGET_2D_ARRAY; a.d.depth=2; }
|
||||
int tid=bind_view_range(&a,0,array?1:2,0,array?2:0); chain c=make_chain();
|
||||
slice_clear(&c,&a,0,0,0); slice_clear(&c,&a,array?0:1,array?1:0,1);
|
||||
clear(&c,&b,0,NULL,0,0,0); clear(&c,&out,0,NULL,0,0,0); clear(&c,&e,0,NULL,0,0,0);
|
||||
if(reordered) sample_block(&c,&b,array?6:5,tid);
|
||||
slice_rt(&c,&a,array?0:1,array?1:0); stencil(&c,0,8,1,255,255,0); blending(&c,0); draw_prog(&c,1,0);
|
||||
if(!reordered) sample_block(&c,&b,array?6:5,tid);
|
||||
result r=execute(&c,&a,&b,&out,&e,NULL);
|
||||
NSUInteger w=array?8:4; id<MTLBuffer> buf=[g_dev newBufferWithLength:w*w*4 options:MTLResourceStorageModeShared];
|
||||
id<MTLCommandBuffer> cb=[g_q commandBuffer]; id<MTLBlitCommandEncoder> bl=[cb blitCommandEncoder];
|
||||
[bl copyFromTexture:tex_mtl(&a) sourceSlice:array?1:0 sourceLevel:array?0:1 sourceOrigin:MTLOriginMake(0,0,0) sourceSize:MTLSizeMake(w,w,1)
|
||||
toBuffer:buf destinationOffset:0 destinationBytesPerRow:w*4 destinationBytesPerImage:w*w*4]; [bl endEncoding]; [cb commit]; [cb waitUntilCompleted];
|
||||
EXPECT("第二子资源读回GPU完成",4,cb.status); uint8_t blue[4]={0,0,255,255}; unsigned bad=0;
|
||||
for(NSUInteger i=0;i<w*w;i++) bad+=memcmp((const uint8_t *)buf.contents+4*i,blue,4)!=0;
|
||||
EXPECT("G第二子资源逐像素蓝",0,bad); save_raw(array?"整slice写目标":"整mip写目标",reordered,buf.contents,w*w*4);
|
||||
return r;
|
||||
}
|
||||
// 附件不交仍会通过继承的程序产生依赖;只演示显式补齐program,不冒充完整S/R快照。
|
||||
// Disjoint attachments can still create a dependency through an inherited program; this only demonstrates explicitly filling in the program and does not pass itself off as a full S/R snapshot.
|
||||
static result state_case(int restored,int reordered) {
|
||||
tex_t a=texture(8,1,0),b=texture(8,1,0),out=texture(8,1,0),e=texture(8,1,0); chain c=make_chain();
|
||||
clear(&c,&a,0,NULL,0,0,0); clear(&c,&b,0,NULL,0,0,0); clear(&c,&out,0,NULL,0,0,0); clear(&c,&e,0,NULL,0,0,0);
|
||||
stencil(&c,0,8,1,255,255,0); blending(&c,0); p_bind_program seed={&pg[0],3}; emit(&c,OP_BIND_PROGRAM,&seed,sizeof seed);
|
||||
for(int k=0;k<2;k++) { int middle=reordered?k==0:k==1;
|
||||
rt(&c,middle?&b:&a,0,NULL);
|
||||
if(!middle) draw_prog(&c,1,0);
|
||||
else { if(restored) { p_bind_program p={&pg[1],3}; emit(&c,OP_BIND_PROGRAM,&p,sizeof p); }
|
||||
p_draw d={NVN_DRAW_PRIMITIVE_TRIANGLES,0,3}; emit(&c,OP_DRAW,&d,sizeof d); } }
|
||||
return execute(&c,&a,&b,&out,&e,NULL);
|
||||
}
|
||||
static result exit_state_case(int restored,int reordered) {
|
||||
tex_t a=texture(8,1,0),b=texture(8,1,0),out=texture(8,1,0),e=texture(8,1,0); chain c=make_chain();
|
||||
clear(&c,&a,0,NULL,0,0,0); clear(&c,&b,0,NULL,0,0,0); clear(&c,&out,0,NULL,0,0,0); clear(&c,&e,0,NULL,0,0,0);
|
||||
for(int k=0;k<2;k++) { int middle=reordered?k==0:k==1; sample_block(&c,middle?&b:&a,middle?1:0,0); }
|
||||
rt(&c,&out,0,NULL);
|
||||
if(restored) { p_bind_program p={&pg[1],3}; emit(&c,OP_BIND_PROGRAM,&p,sizeof p); }
|
||||
p_draw d={NVN_DRAW_PRIMITIVE_TRIANGLES,0,3}; emit(&c,OP_DRAW,&d,sizeof d);
|
||||
return execute(&c,&a,&b,&out,&e,NULL);
|
||||
}
|
||||
// 写掩码不交也不够:IncrementWrap的隐含读包含低位,低位清零会改变向bit1的进位。
|
||||
// Disjoint write masks are not enough either: the implicit read of IncrementWrap includes the low bits, and clearing the low bits changes the carry into bit1.
|
||||
static result stencil_carry_case(int reordered) {
|
||||
tex_t a=texture(8,1,0),b=texture(8,1,0),out=texture(8,1,0),e=texture(8,1,0),ds=texture(8,1,1); chain c=make_chain();
|
||||
clear(&c,&a,0,&ds,0,0,0); p_clear_ds init={.depth=1,.depth_mask=1,.stencil=1,.stencil_mask=255}; emit(&c,OP_CLEAR_DS,&init,sizeof init);
|
||||
clear(&c,&b,0,NULL,0,0,0); clear(&c,&out,0,NULL,0,0,0); clear(&c,&e,0,NULL,0,0,0); blending(&c,0);
|
||||
chmask_st mask={0}; state(&c,2,&mask,sizeof mask);
|
||||
for(int k=0;k<2;k++) { int inc=reordered?k==0:k==1; rt(&c,inc?&b:&a,0,&ds);
|
||||
stencil(&c,1,NVN_STENCIL_FUNC_ALWAYS,inc?NVN_STENCIL_OP_INCR_WRAP:NVN_STENCIL_OP_ZERO,0,inc?2:1,0); draw_prog(&c,0,0); }
|
||||
mask.mask=0xffffffffu; state(&c,2,&mask,sizeof mask); rt(&c,&out,0,&ds); stencil(&c,1,NVN_STENCIL_FUNC_EQUAL,1,2,0,2); draw_prog(&c,7,0);
|
||||
return execute(&c,&a,&b,&out,&e,NULL);
|
||||
}
|
||||
// G写入藏在真实CALL/JUMP目标;跳转列表用跳回地址保持原执行路径与块内顺序。
|
||||
// The G write is hidden in a real CALL/JUMP target; the jump list uses return addresses to preserve the original execution path and in-block order.
|
||||
static result control_case(int jump,int reordered) {
|
||||
tex_t a=texture(8,1,0),b=texture(8,1,0),out=texture(8,1,0),e=texture(8,1,0); int tid=bind_view(&a,0);
|
||||
chain c=make_chain(),child=make_chain();
|
||||
clear(&c,&a,0,NULL,0,0,0); clear(&c,&b,0,NULL,0,0,0); clear(&c,&out,0,NULL,0,0,0); clear(&c,&e,0,NULL,0,0,0);
|
||||
if(reordered) sample_block(&c,&b,2,tid);
|
||||
uint64_t ptr=(uint64_t)child.p; emit(&c,jump?OP_JUMP:OP_CALL,&ptr,8);
|
||||
uint64_t ret=(uint64_t)(c.p+c.n); sample_block(&child,&a,1,0);
|
||||
emit(&child,jump?OP_JUMP:OP_END,jump?&ret:NULL,jump?8:0);
|
||||
if(!reordered) sample_block(&c,&b,2,tid);
|
||||
result r=execute(&c,&a,&b,&out,&e,NULL); mtl_pool_del(child.p); free(child.p); return r;
|
||||
}
|
||||
static void compare_pair(const char *name,const result *o,const result *r,unsigned different) {
|
||||
save_result(name,0,o); save_result(name,1,r); unsigned bad=0;
|
||||
for(int k=0;k<1024;k+=4) bad+=memcmp((const uint8_t *)o+k,(const uint8_t *)r+k,4)!=0;
|
||||
EXPECT("完整区间/状态/控制流不同像素(256分母)",all_independent?0:different,bad);
|
||||
}
|
||||
int main(int argc,char **argv) { @autoreleasepool {
|
||||
setvbuf(stdout,NULL,_IONBF,0);
|
||||
all_independent=argc>1&&!strcmp(argv[1],"--all-independent"); setenv("DM_NVN_TBDR","0",1); mtl_init();
|
||||
NSError *err=nil; id<MTLLibrary> lib=[g_dev newLibraryWithSource:@"#include <metal_stdlib>\nusing namespace metal;\n"
|
||||
"vertex float4 v(uint n [[vertex_id]]){float2 p[3]={float2(-1,-1),float2(3,-1),float2(-1,3)};return float4(p[n],0,1);}\n"
|
||||
"fragment float4 red(){return float4(1,0,0,1);} fragment float4 blue(){return float4(0,0,1,1);} fragment float4 green(){return float4(0,1,0,1);}\n"
|
||||
"struct A{texture2d<float> t [[id(0)]];}; fragment float4 readtex(constant A&a [[buffer(0)]]){return a.t.read(uint2(0));}\n"
|
||||
"fragment float4 halftex(constant A&a [[buffer(0)]]){return float4(a.t.read(uint2(0)).rgb,0.5);}\n"
|
||||
"fragment float4 readlevel1(constant A&a [[buffer(0)]]){return a.t.read(uint2(0),1);}\n"
|
||||
"struct T{texture2d_array<float> t [[id(0)]];}; fragment float4 readslice1(constant T&a [[buffer(0)]]){return a.t.read(uint2(0),1);}\n"
|
||||
"struct U{constant float4 *c [[id(0)]];}; fragment float4 ub(constant U&a [[buffer(0)]]){return *a.c;}\n" options:nil error:&err];
|
||||
if(!lib) { fprintf(stderr,"%s\n",err.localizedDescription.UTF8String); return 2; }
|
||||
NSString *fn[8]={@"red",@"blue",@"readtex",@"halftex",@"ub",@"readlevel1",@"readslice1",@"green"};
|
||||
for(int i=0;i<8;i++) { NvProg *p=[NvProg new]; p->sh[0]=[NvShader new]; p->sh[0]->fn=[lib newFunctionWithName:@"v"];
|
||||
p->sh[1]=[NvShader new]; NvShader *f=p->sh[1]; f->fn=[lib newFunctionWithName:fn[i]]; f->stage=1;
|
||||
if(i>=2&&i!=7) { f->rf.nb=1; f->rf.b[0]=(nvn_rbind){.kind=i==4?NVN_RB_CBUF:NVN_RB_TEX,.dtt=i==6?3:2}; f->ae=[f->fn newArgumentEncoderWithBufferIndex:0]; }
|
||||
pg[i].serial=4000+i; serial_put(pg[i].serial,p); }
|
||||
const char *names[]={"独立mip复制","同mip反例","模板不交位","模板交位反例","复制读源反例","块内次序反例"};
|
||||
for(int mode=0;mode<6;mode++) { printf("CASE %s\n",names[mode]); result o=render_case(mode,0),r=render_case(mode,1);
|
||||
save_result(names[mode],0,&o); save_result(names[mode],1,&r);
|
||||
int same=mode==SAME_MIP; uniform_pixels("原序闭式resolve",o.c,0,same?0:128,same?255:128,128);
|
||||
uint8_t cr=mode==INTERNAL_ORDER?128:0,cg=mode==SAME_MIP||mode==STENCIL_DEPENDENT?0:128,cb=mode==INTERNAL_ORDER?0:128;
|
||||
uniform_pixels("候选闭式resolve",r.c,cr,cg,cb,128);
|
||||
uniform_pixels("原序独立/依赖复制结果",o.e,0,0,255,255);
|
||||
uniform_pixels("候选复制结果",r.e,0,0,mode==COPY_DEPENDENT?0:255,255);
|
||||
unsigned different=0; const uint8_t *x=(const uint8_t *)&o,*y=(const uint8_t *)&r;
|
||||
for(int k=0;k<1024;k+=4) different+=memcmp(x+k,y+k,4)!=0;
|
||||
EXPECT("重排不同像素(4附件256像素分母)",all_independent?0:mode==INDEPENDENT||mode==STENCIL_INDEPENDENT?0:mode==COPY_DEPENDENT?64:mode==INTERNAL_ORDER?128:192,different);
|
||||
}
|
||||
uint64_t q0=query_case(0,0),q1=query_case(1,0); EXPECT("reset原区间4x4通过采样",16,q0); EXPECT("跨reset反例4x4+8x8通过采样",80,q1);
|
||||
EXPECT("查询生命周期不能当独立",all_independent?1:0,q0==q1);
|
||||
uint8_t u0[256],u1[256]; uniform_case(0,u0); uniform_case(1,u1); uniform_pixels("UB原序首绘红",u0,255,0,0,255); uniform_pixels("跨UB写首绘绿",u1,0,255,0,255);
|
||||
EXPECT("UB写不能跨绘制搬动",all_independent?1:0,!memcmp(u0,u1,256));
|
||||
for(int array=0;array<2;array++) { const char *name=array?"整slice范围":"整mip范围"; printf("CASE %s\n",name);
|
||||
result o=range_case(array,0),r=range_case(array,1); uniform_pixels("范围原序第二子资源蓝",o.b,0,0,255,255);
|
||||
uniform_pixels("范围候选第二子资源绿",r.b,0,255,0,255); compare_pair(name,&o,&r,64); }
|
||||
for(int restored=0;restored<2;restored++) { const char *name=restored?"入口程序显式补齐":"入口程序继承"; printf("CASE %s\n",name);
|
||||
result o=state_case(restored,0),r=state_case(restored,1); uniform_pixels("继承原序蓝",o.b,0,0,255,255);
|
||||
uniform_pixels("候选显式补齐蓝/未补齐红",r.b,restored?0:255,0,restored?255:0,255); compare_pair(name,&o,&r,restored?0:64); }
|
||||
for(int restored=0;restored<2;restored++) { const char *name=restored?"出口程序显式补齐":"出口程序继承"; printf("CASE %s\n",name);
|
||||
result o=exit_state_case(restored,0),r=exit_state_case(restored,1); uniform_pixels("后续原序继承蓝",o.c,0,0,255,255);
|
||||
uniform_pixels("后续候选显式补齐蓝/未补齐红",r.c,restored?0:255,0,restored?255:0,255); compare_pair(name,&o,&r,restored?0:64); }
|
||||
for(int jump=0;jump<2;jump++) { const char *name=jump?"JUMP隐藏写":"CALL隐藏写"; printf("CASE %s\n",name);
|
||||
result o=control_case(jump,0),r=control_case(jump,1); uniform_pixels("控制原序蓝",o.b,0,0,255,255);
|
||||
uniform_pixels("控制候选先读黑",r.b,0,0,0,255); compare_pair(name,&o,&r,64); }
|
||||
q0=query_case(0,1); q1=query_case(1,1); EXPECT("同epoch原序通过采样64+16",80,q0); EXPECT("同epoch换序通过采样16+64",80,q1);
|
||||
EXPECT("同epoch固定两绘制换序保持报告80",1,q0==q1);
|
||||
q0=query_case(0,2); q1=query_case(1,2); EXPECT("后继reset覆盖原未报告计数",16,q0); EXPECT("后继reset覆盖候选未报告计数",16,q1);
|
||||
EXPECT("本固定后继reset支配report,交换前后所报16相同",1,q0==q1);
|
||||
printf("CASE 模板隐含进位读\n"); result co=stencil_carry_case(0),cr=stencil_carry_case(1);
|
||||
uniform_pixels("低位先清导致bit1为0",co.c,0,0,0,255); uniform_pixels("先增进位导致bit1为1",cr.c,0,255,0,255); compare_pair("模板隐含进位读",&co,&cr,64);
|
||||
printf("== %d 项,失败 %d ==\n",count,fail); return fail!=0;
|
||||
} }
|
||||
@@ -0,0 +1,25 @@
|
||||
// CPU资格反例:真实production rt_range_same,Metal对象由明确mock提供,不启GPU/不证明像素。
|
||||
// CPU eligibility counterexample: real production rt_range_same, Metal objects supplied by explicit mocks; no GPU is started and no pixels are proven.
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
void *front_metal_layer(void){return NULL;}
|
||||
module_t *module_of(const void *p){(void)p;return NULL;}
|
||||
module_t g_mod[MAX_MOD];int g_nmod;void svc_thread_dump(void){}uint64_t now_ns(void){return bp_now();}
|
||||
@interface MockTex:NSObject @end
|
||||
@implementation MockTex
|
||||
-(NSUInteger)width{return 8;}-(NSUInteger)height{return 8;}-(NSUInteger)sampleCount{return 1;}-(MTLTextureType)textureType{return MTLTextureType2D;}
|
||||
@end
|
||||
static int n,bad;
|
||||
#define E(s,w,a) do{int v=(a);n++;printf("%s 期望%d → 真结果%d\n",s,w,v);bad+=(w)!=v;}while(0)
|
||||
static void history(void){
|
||||
#ifdef NVN_RT_RANGE_DEPTH_IMPL
|
||||
rt_range_note_depth();
|
||||
#endif
|
||||
}
|
||||
int main(void){@autoreleasepool{setenv("DM_NVN_RT_RANGE","1",1);tex_t c={.serial=26},d={.serial=29};c.d.width=c.d.height=d.d.width=d.d.height=8;c.d.depth=d.d.depth=c.d.samples=d.d.samples=1;c.d.levels=4;d.d.levels=1;c.d.target=d.d.target=NVN_TEXTURE_TARGET_2D;c.d.format=NVN_FORMAT_RGBA8;d.d.format=NVN_FORMAT_DEPTH32F_STENCIL8;
|
||||
view_t cv={.set_levels=1,.nlevels=4};p_set_rt a={.n=1,.depth=&d};a.color[0]=&c;a.has_cview[0]=1;a.cview[0]=cv;p_set_rt b=a;b.cview[0].nlevels=1;
|
||||
id<MTLTexture> tc=(id)[MockTex new],td=(id)[MockTex new];serial_put(26,tc);serial_put(29,td);g_enc=(id)[NSObject new];g_enc_mode=4;g_pass.hd=1;g_pass.tw=g_pass.th=8;g_pass.range_color=tc;g_pass.range_depth=td;g_pass.reg_gen=g_reg_gen;g_pass.ser_gen=g_ser_gen;g_pass.range_dirty=nvn_dirty_now();S.ds.dt=1;
|
||||
E("原已证深度RO资格保持",1,rt_range_same(&a,&b));S.ds.dw=1;E("当前深度写拒绝",0,rt_range_same(&a,&b));history();S.ds.dw=0;E("曾写深度不能只看末态",0,rt_range_same(&a,&b));
|
||||
#ifdef NVN_RT_RANGE_DEPTH_IMPL
|
||||
g_pass.range_depth_nonro=0;
|
||||
#endif
|
||||
S.ds.dt=0;E("当前无depth读取不扩checker射程",0,rt_range_same(&a,&b));g_enc=nil;printf("RT_DEPTH_RO cases=%d failed=%d MOCK_METAL_NO_GPU\n",n,bad);return bad!=0;}}
|
||||
@@ -0,0 +1,52 @@
|
||||
// 实际RT单级选择不变,仅view范围4→1;同纹理同CB原guard参考与候选,手写常量shader不冒游戏shader。
|
||||
// The actual RT single-level selection is unchanged, only the view range goes 4→1; same texture and same CB for the original-guard reference and the candidate; hand-written constant shaders do not pass themselves off as game shaders.
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
void *front_metal_layer(void){return NULL;}
|
||||
module_t *module_of(const void *p){(void)p;return NULL;}
|
||||
module_t g_mod[MAX_MOD];int g_nmod;
|
||||
void svc_thread_dump(void){}
|
||||
uint64_t now_ns(void){return bp_now();}
|
||||
static int cases,bad,enabled,small_depth,force_invalid,sample_attachment,both_flags;
|
||||
#define E(n,w,a) do{uint64_t actual=(a),want=(w);cases++;printf("%s 期望%llu → 真结果%llu\n",n,(unsigned long long)want,(unsigned long long)actual);bad+=want!=actual;}while(0)
|
||||
typedef struct{uint8_t b[8192];size_t n;} code;
|
||||
static void emit(code *c,int op,const void *p,size_t n){size_t z=(8+n+7)&~7ull;op_hdr h={op,(uint32_t)z};memcpy(c->b+c->n,&h,8);if(n)memcpy(c->b+c->n+8,p,n);c->n+=z;}
|
||||
static void st(code *c,int k,const void *v,size_t n){p_bind_state b={.kind=k};memcpy(b.bytes,v,n);emit(c,OP_BIND_STATE,&b,sizeof b);}
|
||||
static tex_t color={.serial=52000},depth={.serial=52001};static prog_t pg[2]={{.serial=52002},{.serial=52003}};
|
||||
static p_set_rt rt(int levels){p_set_rt r={.n=1,.depth=&depth,.has_dview=1};r.color[0]=&color;r.has_cview[0]=1;
|
||||
r.cview[0]=(view_t){.set_levels=1,.set_layers=1,.set_format=1,.set_target=1,.nlevels=levels,.nlayers=1,.format=NVN_FORMAT_RGBA8,.target=NVN_TEXTURE_TARGET_2D};
|
||||
r.dview=r.cview[0];r.dview.nlevels=1;r.dview.base_level=small_depth?1:0;r.dview.format=NVN_FORMAT_DEPTH32F_STENCIL8;return r;}
|
||||
static void seed(void){MTL4RenderPassDescriptor *p=[MTL4RenderPassDescriptor new];p.colorAttachments[0].texture=tex_mtl(&color);p.colorAttachments[0].loadAction=MTLLoadActionClear;p.colorAttachments[0].storeAction=MTLStoreActionStore;p.colorAttachments[0].clearColor=MTLClearColorMake(0,0,0,1);
|
||||
p.depthAttachment.texture=p.stencilAttachment.texture=tex_mtl(&depth);p.depthAttachment.loadAction=p.stencilAttachment.loadAction=MTLLoadActionClear;p.depthAttachment.storeAction=p.stencilAttachment.storeAction=MTLStoreActionStore;p.depthAttachment.clearDepth=.75;p.stencilAttachment.clearStencil=0x2d;enc_r_end(enc_r_begin(p));
|
||||
if(sample_attachment){MTL4RenderPassDescriptor *q=[MTL4RenderPassDescriptor new];q.colorAttachments[0].texture=tex_mtl(&color);q.colorAttachments[0].level=1;q.colorAttachments[0].loadAction=MTLLoadActionClear;q.colorAttachments[0].storeAction=MTLStoreActionStore;q.colorAttachments[0].clearColor=MTLClearColorMake(0,1,0,0);enc_r_end(enc_r_begin(q));}
|
||||
if(small_depth){p.colorAttachments[0].texture=nil;p.depthAttachment.level=p.stencilAttachment.level=1;enc_r_end(enc_r_begin(p));}}
|
||||
static void rr_read_planes(id<MTLBuffer> __strong *b){id<MTLTexture> t=tex_mtl(&color),d=tex_mtl(&depth);[blit()copyFromTexture:t sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0,0,0)sourceSize:MTLSizeMake(8,8,1)toBuffer:b[0]destinationOffset:0 destinationBytesPerRow:32 destinationBytesPerImage:256];
|
||||
[blit()copyFromTexture:d sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0,0,0)sourceSize:MTLSizeMake(8,8,1)toBuffer:b[1]destinationOffset:0 destinationBytesPerRow:32 destinationBytesPerImage:256 options:MTLBlitOptionDepthFromDepthStencil];
|
||||
[blit()copyFromTexture:d sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0,0,0)sourceSize:MTLSizeMake(8,8,1)toBuffer:b[2]destinationOffset:0 destinationBytesPerRow:8 destinationBytesPerImage:64 options:MTLBlitOptionStencilFromDepthStencil];}
|
||||
int main(int argc,char **argv){@autoreleasepool{enabled=1;for(int i=1;i<argc;i++){if(!strcmp(argv[i],"--disabled"))enabled=0;else if(!strcmp(argv[i],"--small-depth"))small_depth=1;else if(!strcmp(argv[i],"--force-invalid"))force_invalid=1;else if(!strcmp(argv[i],"--sample-attachment"))sample_attachment=1;else if(!strcmp(argv[i],"--both-flags"))both_flags=1;}if(enabled)setenv("DM_NVN_RT_RANGE","1",1);else unsetenv("DM_NVN_RT_RANGE");if(both_flags)setenv("DM_NVN_VIEW_CONTINUE","1",1);else unsetenv("DM_NVN_VIEW_CONTINUE");mtl_init();NSError *err=nil;
|
||||
id<MTLLibrary> lib=[g_dev newLibraryWithSource:@"#include <metal_stdlib>\nusing namespace metal;vertex float4 v(uint n[[vertex_id]]){float2 p[3]={float2(-1,-1),float2(3,-1),float2(-1,3)};return float4(p[n],.5,1);}\nfragment float4 r(){return float4(1,0,0,1);}\nfragment float4 g(){return float4(0,1,0,0);}struct A{texture2d<float> t[[id(0)]];};fragment float4 s(constant A&a[[buffer(0)]]){return a.t.read(uint2(0));}\n"options:nil error:&err];if(!lib)abort();
|
||||
for(int i=0;i<2;i++){NvProg *p=[NvProg new];p->sh[0]=[NvShader new];p->sh[0]->fn=[lib newFunctionWithName:@"v"];p->sh[1]=[NvShader new];p->sh[1]->fn=[lib newFunctionWithName:i?(sample_attachment?@"s":@"g"):@"r"];p->sh[1]->stage=1;p->sh[1]->rf.color_mask=1;if(i&&sample_attachment){p->sh[1]->rf.nb=1;p->sh[1]->rf.b[0]=(nvn_rbind){.kind=NVN_RB_TEX,.dtt=MTLTextureType2D};p->sh[1]->ae=[p->sh[1]->fn newArgumentEncoderWithBufferIndex:0];}
|
||||
#ifdef NVN_RT_RANGE_RO_IMPL
|
||||
p->sh[0]->range_ro=p->sh[1]->range_ro=1; // 本测试手写constant shader,已直接查无外部写 | this test hand-writes constant shaders and has directly verified there are no external writes
|
||||
#endif
|
||||
serial_put(pg[i].serial,p);}
|
||||
color.d.width=color.d.height=depth.d.width=depth.d.height=8;color.d.depth=color.d.samples=depth.d.depth=depth.d.samples=1;color.d.levels=4;depth.d.levels=small_depth?2:1;color.d.target=depth.d.target=NVN_TEXTURE_TARGET_2D;color.d.format=NVN_FORMAT_RGBA8;depth.d.format=NVN_FORMAT_DEPTH32F_STENCIL8;
|
||||
(void)tex_mtl(&color);(void)tex_mtl(&depth);if(sample_attachment){view_t v={.set_levels=1,.base_level=1,.nlevels=1};mtl_reg_tex(1000,&color,&v);}
|
||||
uint16_t *ix;posix_memalign((void **)&ix,getpagesize(),getpagesize());for(int i=0;i<120;i++)ix[i]=i%3;mtl_pool_add(ix,getpagesize());
|
||||
code first={0},second={0};p_set_rt a=rt(4),b=rt(1);emit(&first,OP_SET_RT,&a,sizeof a);ds_st ds={.dt=1,.df=NVN_DEPTH_FUNC_LESS};st(&first,5,&ds,sizeof ds);
|
||||
color_st col={0,NVN_LOGIC_OP_COPY,NVN_ALPHA_FUNC_ALWAYS};st(&first,1,&col,sizeof col);p_bind_program pr={&pg[0],3};emit(&first,OP_BIND_PROGRAM,&pr,sizeof pr);uint64_t reset=NVN_COUNTER_TYPE_SAMPLES_PASSED;emit(&first,OP_RESET_COUNTER,&reset,8);p_draw dw={NVN_DRAW_PRIMITIVE_TRIANGLES,0,3};emit(&first,OP_DRAW,&dw,sizeof dw);emit(&first,OP_END,NULL,0);
|
||||
emit(&second,OP_RESET_COUNTER,&reset,8);emit(&second,OP_SET_RT,&b,sizeof b);if(small_depth){ds_st off={.df=NVN_DEPTH_FUNC_ALWAYS};st(&second,5,&off,sizeof off);}pr.prog=&pg[1];emit(&second,OP_BIND_PROGRAM,&pr,sizeof pr);if(sample_attachment){p_bind_handles h={.stage=1,.first=0,.n=1};h.h[0]=1000;emit(&second,OP_BIND_TEX,&h,sizeof h);}col.blend_en=1;st(&second,1,&col,sizeof col);blend_st blend={0,NVN_BLEND_FUNC_ONE,NVN_BLEND_FUNC_ONE,NVN_BLEND_FUNC_ONE,NVN_BLEND_FUNC_ZERO,NVN_BLEND_EQUATION_ADD,NVN_BLEND_EQUATION_ADD};st(&second,0,&blend,sizeof blend);p_draw_idx di={.prim=NVN_DRAW_PRIMITIVE_TRIANGLES,.count=120,.itype=1,.ibuf=(uint64_t)ix,.instances=1};emit(&second,OP_DRAW_IDX,&di,sizeof di);emit(&second,OP_END,NULL,0);
|
||||
id<MTLBuffer> buffers[2][3];for(int m=0;m<2;m++)for(int j=0;j<3;j++)buffers[m][j]=[g_dev newBufferWithLength:j==2?64:256 options:MTLResourceStorageModeShared];uint64_t passes[2],bytes[2],q[2][2]={{0}};
|
||||
mtl_sub_begin();
|
||||
for(int m=0;m<2;m++){state_reset();memset(&R,0,sizeof R);vis_clear();g_vis_on=g_vis_counting=0;seed();uint64_t p=g_stat_pass,l=g_bw_load,s=g_bw_store,draws=g_stat_draw;mtl_exec(first.b);E("首绘按深度只读模式",4,g_enc_mode);if(!m)rp_end();else if(force_invalid)R.rt.cview[0].nlevels=1; // 负控:错误地假设附件范围/目标始终等价 | negative control: wrongly assume the attachment range/target is always equivalent
|
||||
mtl_exec(second.b);rp_end();passes[m]=g_stat_pass-p;bytes[m]=g_bw_load-l+g_bw_store-s;E("真实draw次数不变",2,g_stat_draw-draws);post((post_op){3,NULL,0,0,(uint64_t)q[m],(uint32_t)reset,vis_snapshot()});rr_read_planes(buffers[m]);if(g_blit){[g_blit endEncoding];g_blit=nil;}}
|
||||
int done=mtl_wait(mtl_sub_commit(),5000000000ull);E("同纹理同CB完成",1,done);if(!done)abort();E("提交反馈无错误",0,mtl_last_commit_error());
|
||||
uint8_t yellow[4]={255,255,0,0},green[4]={0,255,0,0}; // alpha由第二draw ONE/ ZERO给0;整数闭式RGB黄色。 | alpha is given 0 by the second draw's ONE/ ZERO; integer closed-form RGB yellow.
|
||||
for(int m=0;m<2;m++){unsigned bc=0,bd=0,bs=0;for(int i=0;i<64;i++){bc+=memcmp((uint8_t *)buffers[m][0].contents+4*i,small_depth && (i%8>=4||i/8>=4)?green:yellow,4)!=0;bd+=((float *)buffers[m][1].contents)[i]!=.75f;bs+=((uint8_t *)buffers[m][2].contents)[i]!=0x2d;}E("各64纹素手算黄色",0,bc);E("depth .75种子保持",0,bd);E("stencil 0x2d种子保持",0,bs);E("Reset后120索引40三角采样数",2560,q[m][0]);}
|
||||
E("三平面原候选逐字节",0,memcmp(buffers[0][0].contents,buffers[1][0].contents,256)||memcmp(buffers[0][1].contents,buffers[1][1].contents,256)||memcmp(buffers[0][2].contents,buffers[1][2].contents,64));
|
||||
E("原guard两pass",2,passes[0]);E("候选一pass/默认两pass",enabled&&!small_depth&&!sample_attachment?1:2,passes[1]);{ // DontCare(本通道没写不写回):两个通道的深度状态都只开测试不开写,每个通道省一次深度模板写回 = 8×8×5 字节(Depth32F_S8 附件模型 5 B/像素) | DontCare (not stored if this pass did not write it): both passes' depth state enables only test, not write, so each pass saves one depth-stencil store = 8×8×5 bytes (Depth32F_S8 attachment model, 5 B/pixel)
|
||||
const char *u=getenv("DM_NVN_UNWRITTEN_DC"); int udc=!(u&&!strcmp(u,"0")); unsigned dsb=udc&&!small_depth&&!sample_attachment?8*8*5:0;
|
||||
E(udc?"原附件模型2048−2×320(DontCare)":"原附件模型2048",(small_depth?1152:2048)-2*dsb,bytes[0]);
|
||||
E(udc?"候选附件模型1024−320(DontCare)":"候选附件模型1024/默认2048",(small_depth?1152:enabled&&!sample_attachment?1024:2048)-(enabled&&!sample_attachment?1:2)*dsb,bytes[1]); }
|
||||
const char *dir=getenv("DM_GFX_FIXTURE_OUT");if(dir){char p[1024];for(int m=0;m<2;m++)for(int j=0;j<3;j++){snprintf(p,sizeof p,"%s/%s_%s.raw",dir,m?"candidate":"reference",j==0?"color":j==1?"depth":"stencil");FILE *f=fopen(p,"wb");if(!f||fwrite(buffers[m][j].contents,1,j==2?64:256,f)!=(j==2?64:256))abort();fclose(f);}}
|
||||
mtl_pool_del(ix);free(ix);printf("RT_RANGE_GPU cases=%d failed=%d\n",cases,bad);return bad!=0;
|
||||
}}
|
||||
@@ -0,0 +1,38 @@
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
void *front_metal_layer(void){return NULL;}
|
||||
module_t *module_of(const void *p){(void)p;return NULL;}
|
||||
module_t g_mod[MAX_MOD];int g_nmod;
|
||||
void svc_thread_dump(void){}
|
||||
uint64_t now_ns(void){return bp_now();}
|
||||
static int cases,bad;
|
||||
static int ro(NSDictionary *j){
|
||||
#ifdef NVN_RT_RANGE_RO_IMPL
|
||||
return rt_range_bindings_ro(j);
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
#define E(n,w,a) do{int v=(a);cases++;printf("%s 期望%d → 真结果%d\n",n,w,v);bad+=(w)!=v;}while(0)
|
||||
static NSDictionary *one(NSDictionary *b){return @{ @"route":@"B",@"drv_reads":@{},@"bindings":@[b] };}
|
||||
int main(void){@autoreleasepool{
|
||||
E("明确sbuf RO",1,ro(one(@{@"kind":@"sbuf",@"msl_type":@"const device _27*",@"rw":@NO})));
|
||||
E("缺rw不当默认0证明",0,ro(one(@{@"kind":@"sbuf",@"msl_type":@"const device _27*"})));
|
||||
E("rw写用途拒绝",0,ro(one(@{@"kind":@"sbuf",@"msl_type":@"device _27*",@"rw":@YES})));
|
||||
E("device缺const拒绝",0,ro(one(@{@"kind":@"sbuf",@"msl_type":@"device _27*",@"rw":@NO})));
|
||||
E("image未知用途拒绝",0,ro(one(@{@"kind":@"img",@"msl_type":@"texture2d<float, access::read>"})));
|
||||
E("sample纹理明确RO",1,ro(one(@{@"kind":@"tex",@"msl_type":@"texture2d<float>"})));
|
||||
E("tex显式rw拒绝",0,ro(one(@{@"kind":@"tex",@"msl_type":@"texture2d<float>",@"rw":@YES})));
|
||||
E("constant cbuf显式rw拒绝",0,ro(one(@{@"kind":@"cbuf",@"msl_type":@"constant _16*",@"rw":@YES})));
|
||||
E("rw类型未知拒绝",0,ro(one(@{@"kind":@"tex",@"msl_type":@"texture2d<float>",@"rw":@"false"})));
|
||||
E("driver间接地址不扩展",0,ro(one(@{@"kind":@"drv0",@"msl_type":@"constant _16*"})));
|
||||
E("texture read_write拒绝",0,ro(one(@{@"kind":@"tex",@"msl_type":@"texture2d<float, access::read_write>"})));
|
||||
E("texture write拒绝",0,ro(one(@{@"kind":@"tex",@"msl_type":@"texture2d<float, access::write>"})));
|
||||
E("cbuf constant明确RO",1,ro(one(@{@"kind":@"cbuf",@"msl_type":@"constant _16*"})));
|
||||
E("cbuf类型未知拒绝",0,ro(one(@{@"kind":@"cbuf",@"msl_type":@"device _16*"})));
|
||||
E("未知kind拒绝",0,ro(one(@{@"kind":@"opaque",@"msl_type":@"constant _16*"})));
|
||||
E("缺bindings拒绝",0,ro(@{@"route":@"B"}));
|
||||
E("缺driver语义信息拒绝",0,ro(@{@"route":@"B",@"bindings":@[]}));
|
||||
E("存在driver间接读取拒绝",0,ro(@{@"route":@"B",@"bindings":@[],@"drv_reads":@{@"0":@YES}}));
|
||||
NSString *d=[NSString stringWithFormat:@"%s%s/build/cache/metal_shader_cache/b-%s", getenv("DM_ROOT") ?: getenv("HOME"), getenv("DM_ROOT") ? "" : "/dm-work", DMSH_CHAIN];
|
||||
for(NSString *k in @[@"06ece8336c8c242c",@"6d19a794f1206668",@"fa27a102ecd14b3e",@"1bd6a72fa95c6a07"]){NSData *s=[NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/%@_b.json",d,k]];NSDictionary *j=[NSJSONSerialization JSONObjectWithData:s options:0 error:nil];E(k.UTF8String,1,ro(j));}
|
||||
printf("RT_RANGE_RO cases=%d failed=%d\n",cases,bad);return bad!=0;}}
|
||||
@@ -0,0 +1,32 @@
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
void *front_metal_layer(void){return NULL;}
|
||||
module_t *module_of(const void *p){(void)p;return NULL;}
|
||||
module_t g_mod[MAX_MOD];int g_nmod;
|
||||
void svc_thread_dump(void){}
|
||||
uint64_t now_ns(void){return bp_now();}
|
||||
static int cases,bad;
|
||||
#define E(label,w,a) do{int actual=(a);cases++;printf("%s 期望%d → 真结果%d\n",label,w,actual);bad+=(w)!=actual;}while(0)
|
||||
static int shape(const p_set_rt *a,const p_set_rt *b){
|
||||
#ifdef NVN_RT_RANGE_IMPL
|
||||
return rt_range_shape(a,b);
|
||||
#else
|
||||
return rt_same(a,b);
|
||||
#endif
|
||||
}
|
||||
int main(void){@autoreleasepool{
|
||||
tex_t c={.serial=26},d={.serial=29};c.d.width=c.d.height=8;c.d.depth=c.d.samples=1;c.d.levels=4;c.d.target=NVN_TEXTURE_TARGET_2D;c.d.format=NVN_FORMAT_RGBA8;d.d=c.d;d.d.levels=1;d.d.format=NVN_FORMAT_DEPTH32F_STENCIL8;
|
||||
view_t cv={.set_levels=1,.set_layers=1,.set_format=1,.set_target=1,.base_level=0,.nlevels=4,.min_layer=0,.nlayers=1,.format=NVN_FORMAT_RGBA8,.target=NVN_TEXTURE_TARGET_2D};view_t dv=cv;dv.nlevels=1;dv.format=d.d.format;
|
||||
p_set_rt a={.n=1,.depth=&d,.has_dview=1,.dview=dv};a.color[0]=&c;a.has_cview[0]=1;a.cview[0]=cv;p_set_rt b=a;b.cview[0].nlevels=1;
|
||||
E("实际level0同层仅级数变化",1,shape(&a,&b));
|
||||
tex_t small=d;small.d.levels=2;p_set_rt sa=a,sb=b;sa.depth=sb.depth=&small;sa.dview.base_level=sb.dview.base_level=1;E("深度尺寸收窄颜色时仍切",0,shape(&sa,&sb));
|
||||
p_set_rt x=b;x.cview[0].base_level=1;E("level变化仍切",0,shape(&a,&x));x=b;x.cview[0].min_layer=1;E("层变化仍切",0,shape(&a,&x));
|
||||
x=b;x.cview[0].nlevels=0;E("未知零级数仍切",0,shape(&a,&x));x=b;x.cview[0].nlevels=5;E("越界级数仍切",0,shape(&a,&x));
|
||||
x=b;x.cview[0].format=NVN_FORMAT_RGBA16F;E("格式变化仍切",0,shape(&a,&x));x=b;x.cview[0].target=NVN_TEXTURE_TARGET_2D_ARRAY;E("target变化仍切",0,shape(&a,&x));
|
||||
x=b;x.has_cview[0]=0;E("未知view仍切",0,shape(&a,&x));x=b;x.cview[0].set_levels=0;E("无明确level仍切",0,shape(&a,&x));
|
||||
x=b;x.cview[0].nlayers=2;E("未知层范围仍切",0,shape(&a,&x));x=b;x.dview.nlevels=0;E("深度view变化仍切",0,shape(&a,&x));x=b;x.depth=NULL;E("深度附件变化仍切",0,shape(&a,&x));
|
||||
tex_t other=c;other.serial++;x=b;x.color[0]=&other;E("对象序号变化仍切",0,shape(&a,&x));other=c;other.d.width=16;x.color[0]=&other;E("同序号元数据变化仍切",0,shape(&a,&x));
|
||||
other=c;other.has_layout=1;other.mem=(uint8_t *)1;x=b;x.color[0]=&other;E("packaged未知版本仍切",0,shape(&a,&x));
|
||||
other=c;other.d.target=NVN_TEXTURE_TARGET_2D_ARRAY;x=b;x.color[0]=&other;E("数组目标仍切",0,shape(&a,&x));other=c;other.d.samples=4;x.color[0]=&other;E("多采样仍切",0,shape(&a,&x));
|
||||
x=b;x.n=2;x.color[1]=&c;E("多颜色不扩展",0,shape(&a,&x));
|
||||
printf("RT_RANGE_SHAPE cases=%d failed=%d\n",cases,bad);return bad!=0;
|
||||
}}
|
||||
@@ -0,0 +1,43 @@
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
void *front_metal_layer(void) { return NULL; }
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
module_t g_mod[MAX_MOD]; int g_nmod;
|
||||
void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { return bp_now(); }
|
||||
static int fail, count;
|
||||
#define EXPECT(name, want, got) do { long long w=(want), g=(got); count++; printf("%s 期望 %lld → 真结果 %lld %s\n", name, w, g, w==g?"OK":"FAIL"); if(w!=g) fail++; } while(0)
|
||||
int g_t_ub_var = 7, g_t_ub_var2 = -3; // 被 @set 按符号名找到的全局变量 | global variables found by @set via symbol name
|
||||
// 同进程交替测量(DM_NVN_UB)的相位逻辑单测:不起渲染,只按帧号推进。
|
||||
// 配置:两类,每相 60 帧。相序 = 基准, a, 基准, b, 基准, a, …;a = 设 g_t_ub_var=5 且丢键 abcd…;b = 设 g_t_ub_var2=9 且丢全部(*)。
|
||||
// Unit tests for the phase logic of same-process alternating measurement (DM_NVN_UB): no rendering is started, it only advances by frame number.
|
||||
// Configuration: two classes, 60 frames per phase. Phase order = baseline, a, baseline, b, baseline, a, ...; a = set g_t_ub_var=5 and drop keys abcd...; b = set g_t_ub_var2=9 and drop everything (*).
|
||||
int main(void) {
|
||||
setenv("DM_NVN_UB", "a=@set:g_t_ub_var=5,abcd;b=@set:g_t_ub_var2=9,*;c=@set:g_no_such_var=1", 1); setenv("DM_NVN_UB_N", "60", 1);
|
||||
struct { int f, v1, v2, skip_abcd, skip_other; const char *what; } T[] = {
|
||||
{0, 7, -3, 0, 0, "相 0 基准"}, {59, 7, -3, 0, 0, "相 0 末帧"},
|
||||
{60, 5, -3, 1, 0, "相 1 = a:变量 1 被设、丢 abcd"}, {119, 5, -3, 1, 0, "相 1 末帧"},
|
||||
{120, 7, -3, 0, 0, "相 2 基准:变量 1 还原"},
|
||||
{180, 7, 9, 1, 1, "相 3 = b:变量 2 被设、全丢"},
|
||||
{240, 7, -3, 0, 0, "相 4 基准:变量 2 还原"},
|
||||
{300, 7, -3, 0, 0, "相 5 = c:变量不存在,什么都不改"},
|
||||
{360, 7, -3, 0, 0, "相 6 基准"},
|
||||
{420, 5, -3, 1, 0, "相 7 = a(第二圈)"},
|
||||
};
|
||||
int ti = 0, n = (int)(sizeof T / sizeof T[0]);
|
||||
for (int f = 0; f <= 420 && ti < n; f++) { mtl_set_frame((uint64_t)f);
|
||||
if (f != T[ti].f) continue;
|
||||
char nm[96]; snprintf(nm, sizeof nm, "%s 变量1", T[ti].what); EXPECT(nm, T[ti].v1, g_t_ub_var);
|
||||
snprintf(nm, sizeof nm, "%s 变量2", T[ti].what); EXPECT(nm, T[ti].v2, g_t_ub_var2);
|
||||
snprintf(nm, sizeof nm, "%s 丢 abcd0123", T[ti].what); EXPECT(nm, T[ti].skip_abcd, ub_skip("abcd0123ffff0000"));
|
||||
snprintf(nm, sizeof nm, "%s 丢别的键", T[ti].what); EXPECT(nm, T[ti].skip_other, ub_skip("9999888877776666"));
|
||||
ti++; }
|
||||
EXPECT("走完的检查点数", n, ti);
|
||||
// 上屏间隔按相统计:相内第 45 帧起才计;三档界线 20.8 / 29.2 ms;−1 记丢弃
|
||||
// On-screen present intervals are tallied per phase: counted only from frame 45 of the phase on; boundaries of the three bands are 20.8 / 29.2 ms; −1 is recorded as discarded
|
||||
for (int f = 480; f < 480 + 45; f++) { mtl_set_frame((uint64_t)f); mtl_ub_present(16.7); } // 过渡段:不计 | transition segment: not counted
|
||||
EXPECT("过渡段不计", 0, atomic_load(&g_ubp_c[0]));
|
||||
mtl_set_frame(480 + 45); mtl_ub_present(16.7); mtl_ub_present(25.0); mtl_ub_present(25.0); mtl_ub_present(33.3); mtl_ub_present(-1); mtl_ub_present(0);
|
||||
EXPECT("16.7 ms 档", 1, atomic_load(&g_ubp_c[0])); EXPECT("25 ms 档", 2, atomic_load(&g_ubp_c[1])); EXPECT("≥33 ms 档", 1, atomic_load(&g_ubp_c[2])); EXPECT("丢弃", 1, atomic_load(&g_ubp_c[3]));
|
||||
EXPECT("间隔和(微秒)", 16700 + 25000 + 25000 + 33300, (long long)atomic_load(&g_ubp_sum_us));
|
||||
printf("t_ub:%d 项,失败 %d\n", count, fail); return fail != 0;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
void *front_metal_layer(void) { return NULL; }
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
module_t g_mod[MAX_MOD]; int g_nmod;
|
||||
void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { return bp_now(); }
|
||||
static int fail, count;
|
||||
#define EXPECT(name, want, got) do { uint64_t w=(want), g=(got); count++; printf("%s 期望 %llu → 真结果 %llu %s\n", name, (unsigned long long)w, (unsigned long long)g, w==g?"✓":"✗"); fail += w != g; } while (0)
|
||||
typedef struct { uint8_t *p; size_t n; } chain;
|
||||
static chain chain_new(void) { chain c={0}; if (posix_memalign((void **)&c.p,getpagesize(),65536)) abort(); memset(c.p,0,65536); mtl_pool_add(c.p,65536); return c; }
|
||||
static void emit(chain *c, unsigned op, const void *a, size_t n) { size_t z=(8+n+7)&~7ull; op_hdr h={op,(uint32_t)z}; memcpy(c->p+c->n,&h,8); if(n) memcpy(c->p+c->n+8,a,n); c->n+=z; }
|
||||
static tex_t tex(unsigned w) { static uint64_t s=9000; tex_t t={.serial=s++}; t.d.width=t.d.height=w; t.d.depth=t.d.samples=1; t.d.levels=2; t.d.target=NVN_TEXTURE_TARGET_2D; t.d.format=NVN_FORMAT_RGBA8; return t; }
|
||||
static int view(const tex_t *t, int lv) { static int id=1200; view_t v={.set_levels=1,.base_level=lv,.nlevels=1}; mtl_reg_tex(id,t,&v); return id++; }
|
||||
static void set_rt(chain *c, const tex_t *a, const tex_t *b, int alv) { p_set_rt r={.n=b?2:1}; r.color[0]=a; r.color[1]=b; for(int i=0;i<r.n;i++){r.has_cview[i]=1;r.cview[i].set_levels=1;r.cview[i].base_level=i?0:alv;r.cview[i].nlevels=1;} emit(c,OP_SET_RT,&r,sizeof r); p_viewports v={.n=1};v.v[0][2]=v.v[0][3]=8;emit(c,OP_VIEWPORTS,&v,sizeof v);p_scissor sc={0,0,8,8};emit(c,OP_SCISSOR,&sc,sizeof sc); }
|
||||
static void clear_color(chain *c, int i, float r, float g, float b) { p_clear_color x={.index=i,.mask=15,.rgba={r,g,b,1}}; emit(c,OP_CLEAR_COLOR,&x,sizeof x); }
|
||||
static void bind_prog(chain *c, prog_t *p) { p_bind_program b={p,3}; emit(c,OP_BIND_PROGRAM,&b,sizeof b); }
|
||||
static void bind_tex(chain *c, int id) { p_bind_handles b={.stage=1,.first=0,.n=1};b.h[0]=id;emit(c,OP_BIND_TEX,&b,sizeof b); }
|
||||
static void draw_cmd(chain *c) { p_draw d={NVN_DRAW_PRIMITIVE_TRIANGLES,0,3}; emit(c,OP_DRAW,&d,sizeof d); }
|
||||
static void blend(chain *c) { color_st col={1,NVN_LOGIC_OP_COPY,NVN_ALPHA_FUNC_ALWAYS}; p_bind_state x={.kind=1};memcpy(x.bytes,&col,sizeof col);emit(c,OP_BIND_STATE,&x,sizeof x); blend_st b={0,NVN_BLEND_FUNC_SRC_ALPHA,NVN_BLEND_FUNC_ONE_MINUS_SRC_ALPHA,NVN_BLEND_FUNC_ONE,NVN_BLEND_FUNC_ZERO,NVN_BLEND_EQUATION_ADD,NVN_BLEND_EQUATION_ADD};x.kind=0;memcpy(x.bytes,&b,sizeof b);emit(c,OP_BIND_STATE,&x,sizeof x); }
|
||||
static void ds_off(chain *c) { ds_st d={0,0,NVN_DEPTH_FUNC_ALWAYS,0,NVN_STENCIL_FUNC_ALWAYS,NVN_STENCIL_FUNC_ALWAYS,NVN_STENCIL_OP_KEEP,NVN_STENCIL_OP_KEEP,NVN_STENCIL_OP_KEEP,NVN_STENCIL_OP_KEEP,NVN_STENCIL_OP_KEEP,NVN_STENCIL_OP_KEEP}; p_bind_state x={.kind=5}; memcpy(x.bytes,&d,sizeof d); emit(c,OP_BIND_STATE,&x,sizeof x); }
|
||||
static void readback(const tex_t *t, uint8_t out[256]) { id<MTLBuffer> b=[g_dev newBufferWithLength:256 options:MTLResourceStorageModeShared]; [blit() copyFromTexture:tex_mtl(t) sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0,0,0) sourceSize:MTLSizeMake(8,8,1) toBuffer:b destinationOffset:0 destinationBytesPerRow:32 destinationBytesPerImage:256]; uint64_t f=mtl_sub_commit(); EXPECT("提交完成",1,mtl_wait(f,5000000000ull)); EXPECT("提交反馈无错误",0,mtl_last_commit_error()); memcpy(out,b.contents,256); }
|
||||
static NvProg *g_tkeep[256]; static int g_tnkeep; /* 测试里的程序对象常驻:释放后新对象可能落在同一地址,管线缓存按对象地址认会取到旧管线(生产里程序对象不释放) | Program objects in the tests are permanent: after a free, a new object may land at the same address, and the pipeline cache, keyed by object address, would return the old pipeline (in production program objects are never freed) */
|
||||
static void setup_prog(prog_t *pg) { NSError *e=nil; id<MTLLibrary> l=[g_dev newLibraryWithSource:@"#include <metal_stdlib>\nusing namespace metal; vertex float4 v(uint n[[vertex_id]]){float2 p[3]={float2(-1,-1),float2(3,-1),float2(-1,3)};return float4(p[n],0,1);}\nfragment float4 red(){return float4(1,0,0,0.5);}\nstruct A{texture2d<float> t[[id(0)]];}; fragment float4 sample(constant A&a[[buffer(0)]]){return a.t.read(uint2(0));}\n" options:nil error:&e]; if(!l){fprintf(stderr,"%s\n",e.localizedDescription.UTF8String);abort();} for(int i=0;i<2;i++)pg[i].serial=8000+i; for(int i=0;i<2;i++){NvProg *p=[NvProg new];p->sh[0]=[NvShader new];p->sh[0]->fn=[l newFunctionWithName:@"v"];p->sh[1]=[NvShader new];p->sh[1]->stage=1;p->sh[1]->fn=[l newFunctionWithName:i?@"sample":@"red"];if(i){p->sh[1]->rf.nb=1;p->sh[1]->rf.b[0]=(nvn_rbind){.kind=NVN_RB_TEX,.reg=0,.dtt=2};p->sh[1]->ae=[p->sh[1]->fn newArgumentEncoderWithBufferIndex:0];}if(g_tnkeep<256)g_tkeep[g_tnkeep++]=p;serial_put(pg[i].serial,p);} }
|
||||
// 跨提交附件有效性账本单测:每个「周期」是一次提交。A 每周期先清再画(提交末尾没人再碰它)→ 试用期满后不写回。
|
||||
// Unit tests for the cross-submit attachment validity ledger: each "cycle" is one submit. A is cleared then drawn every cycle (nobody touches it again at the end of the submit) → not stored once the trial period is over.
|
||||
static void commit(void) { id<MTLCommandBuffer> cb=g_cb; uint64_t f=mtl_sub_commit(); mtl_wait(f,5000000000ull); (void)cb; }
|
||||
static prog_t t_pg[2];
|
||||
// kind:0 = 清 A、画 A(合规周期);1 = 清 A、画 A、再用 B 采样 A 并读回 B(A 提交内被读 → 照常写回;验证重置后的内容);2 = 不清 A,直接 B 采样 A(读旧内容 = 违规)
|
||||
// kind: 0 = clear A, draw A (compliant cycle); 1 = clear A, draw A, then B samples A and B is read back (A is read within the submit → stored as usual; verifies the contents after reset); 2 = do not clear A, B samples A directly (reading old contents = violation)
|
||||
static tex_t t_mid, t_x; static int t_two; // t_two:A 的通道多挂一张(换一个通道签名 = 换一个键) | t_two: A's pass has one more attachment (a different pass signature = a different key)
|
||||
static void cycle(const tex_t *a, const tex_t *b, int aid, int kind, uint8_t px[256]) {
|
||||
chain c=chain_new();
|
||||
if (kind!=2) { set_rt(&c,a,t_two?&t_x:NULL,0); clear_color(&c,0,0,0,0); if (t_two) clear_color(&c,1,0,0,0); ds_off(&c); bind_prog(&c,&t_pg[0]); blend(&c); draw_cmd(&c);
|
||||
set_rt(&c,&t_mid,NULL,0); clear_color(&c,0,0,0,0); draw_cmd(&c); } /* A 的通道在命令流里结束(下一个 SetRenderTargets),和游戏里一样;最后这个通道在提交结束时才结束(一律写回) | A's pass ends in the command stream (at the next SetRenderTargets), as in the game; this last pass only ends when the submit ends (always stored) */
|
||||
if (kind) { set_rt(&c,b,NULL,0); clear_color(&c,0,0,0,0); ds_off(&c); bind_prog(&c,&t_pg[1]); bind_tex(&c,aid); draw_cmd(&c); }
|
||||
emit(&c,OP_END,NULL,0); state_reset(); memset(&R,0,sizeof R); vis_clear(); g_vis_on=g_vis_counting=0;
|
||||
mtl_sub_begin(); uint64_t hh=(uint64_t)c.p; mtl_sub_index(&hh,1); mtl_exec(c.p);
|
||||
if (kind) readback(b,px); else commit();
|
||||
}
|
||||
int main(void){@autoreleasepool{setvbuf(stdout,NULL,_IONBF,0);setenv("DM_NVN_TBDR","1",1);
|
||||
char path[256]; snprintf(path,sizeof path,"/tmp/t_xv_%d.txt",(int)getpid()); unlink(path); setenv("DM_XV_FILE",path,1);
|
||||
mtl_init(); setup_prog(t_pg); t_mid=tex(8); t_x=tex(8); uint8_t ref[256],px[256]; int dc=0,viol=0,dc0,viol0;
|
||||
// ① 正例:试用期(XV_TRIAL 个合规周期)内照常写回,之后才不写回;被作废后重新清、画,内容与最初一致
|
||||
// ① Positive case: during the trial period (XV_TRIAL compliant cycles) it is stored as usual, and only afterwards is it not stored; after being invalidated it is cleared and drawn again, and the contents match the original
|
||||
{ tex_t a=tex(8),b=tex(8); int aid=view(&a,0);
|
||||
cycle(&a,&b,aid,1,ref);
|
||||
xv_test_counts(&dc0,&viol0);
|
||||
/* 计数按键(格式 / 尺寸 / 通道签名 / 附件序号)累计,同键的别的贴图也会推进试用期——所以断言看 A 自己在账本里的状态 | Counts accumulate per key (format / size / pass signature / attachment index), and other textures with the same key also advance the trial period - so the assertions look at A's own state in the ledger */
|
||||
#define ST(t) (xv_find((t).serial,0,0) ? xv_find((t).serial,0,0)->state : 0)
|
||||
cycle(&a,&b,aid,0,NULL);
|
||||
EXPECT("首个合规周期:A 在试用期(照常写回)",XV_PROBE,(uint64_t)ST(a)); xv_test_counts(&dc,&viol); EXPECT("首个合规周期:不写回次数 0",0,(uint64_t)(dc-dc0));
|
||||
for(int k=0;k<XV_TRIAL+2;k++) cycle(&a,&b,aid,0,NULL);
|
||||
EXPECT("试用期满:A 已作废(不写回)",XV_INVALID,(uint64_t)ST(a)); xv_test_counts(&dc,&viol); EXPECT("试用期满后不写回次数 ≥ 1",1,(uint64_t)(dc-dc0>=1)); EXPECT("合规周期无违规",0,(uint64_t)(viol-viol0));
|
||||
cycle(&a,&b,aid,1,px); xv_test_counts(&dc0,&viol); EXPECT("作废后重置再用:内容与最初逐字节相同",0,(uint64_t)(memcmp(px,ref,256)!=0)); EXPECT("重置再用无违规",0,(uint64_t)(viol-viol0));
|
||||
// ② 违规:先让 A 再次被作废,然后不清就读
|
||||
// ② Violation: first let A be invalidated again, then read without clearing
|
||||
for(int k=0;k<2;k++) cycle(&a,&b,aid,0,NULL);
|
||||
xv_test_counts(&dc0,&viol0); cycle(&a,&b,aid,2,px); xv_test_counts(&dc,&viol); EXPECT("作废后被读:违规 +1",1,(uint64_t)(viol-viol0));
|
||||
for(int k=0;k<XV_TRIAL+3;k++) cycle(&a,&b,aid,0,NULL); EXPECT("违规后该键永久不做(A 不再进账本)",0,(uint64_t)ST(a));
|
||||
FILE *f=fopen(path,"r"); char line[256]; int nl=0; while(f&&fgets(line,sizeof line,f)) nl++; if(f) fclose(f); EXPECT("违规落盘 1 行",1,(uint64_t)nl);
|
||||
int nd=g_xv_ndis; g_xv_init=0; g_xv_ndis=0; xv_init(); EXPECT("重读文件后禁用集合恢复(模拟下次启动)",1,(uint64_t)(g_xv_ndis>=1 && nd>=1)); }
|
||||
// ③ 试用期里见读者:不报红、不落盘、该键不做(不同尺寸 = 不同键)
|
||||
// ③ A reader seen during the trial period: no failure reported, nothing written to disk, that key is not done (different size = different key)
|
||||
{ tex_t a=tex(8),b=tex(8); int aid=view(&a,0); t_two=1;
|
||||
xv_test_counts(&dc0,&viol0); cycle(&a,&b,aid,0,NULL); cycle(&a,&b,aid,2,px); for(int k=0;k<6;k++) cycle(&a,&b,aid,0,NULL);
|
||||
xv_test_counts(&dc,&viol); EXPECT("试用期见读者:不算违规",0,(uint64_t)(viol-viol0)); EXPECT("试用期见读者:A 的键不做(A 不进账本)",0,(uint64_t)ST(a)); }
|
||||
unlink(path); printf("== %d 项,失败 %d ==\n",count,fail); return fail!=0; }}
|
||||
@@ -0,0 +1,50 @@
|
||||
#include "../nvn/nvn_mtl.m"
|
||||
void *front_metal_layer(void) { return NULL; }
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
module_t g_mod[MAX_MOD]; int g_nmod;
|
||||
void svc_thread_dump(void) {}
|
||||
uint64_t now_ns(void) { return bp_now(); }
|
||||
static int fail, count;
|
||||
#define EXPECT(name, want, got) do { uint64_t w=(want), g=(got); count++; printf("%s 期望 %llu → 真结果 %llu %s\n", name, (unsigned long long)w, (unsigned long long)g, w==g?"✓":"✗"); fail += w != g; } while (0)
|
||||
typedef struct { uint8_t *p; size_t n; } chain;
|
||||
static chain chain_new(void) { chain c={0}; if (posix_memalign((void **)&c.p,getpagesize(),65536)) abort(); memset(c.p,0,65536); mtl_pool_add(c.p,65536); return c; }
|
||||
static void emit(chain *c, unsigned op, const void *a, size_t n) { size_t z=(8+n+7)&~7ull; op_hdr h={op,(uint32_t)z}; memcpy(c->p+c->n,&h,8); if(n) memcpy(c->p+c->n+8,a,n); c->n+=z; }
|
||||
static tex_t tex(unsigned w) { static uint64_t s=9000; tex_t t={.serial=s++}; t.d.width=t.d.height=w; t.d.depth=t.d.samples=1; t.d.levels=2; t.d.target=NVN_TEXTURE_TARGET_2D; t.d.format=NVN_FORMAT_RGBA8; return t; }
|
||||
static int view(const tex_t *t, int lv) { static int id=1200; view_t v={.set_levels=1,.base_level=lv,.nlevels=1}; mtl_reg_tex(id,t,&v); return id++; }
|
||||
static void set_rt(chain *c, const tex_t *a, const tex_t *b, int alv) { p_set_rt r={.n=b?2:1}; r.color[0]=a; r.color[1]=b; for(int i=0;i<r.n;i++){r.has_cview[i]=1;r.cview[i].set_levels=1;r.cview[i].base_level=i?0:alv;r.cview[i].nlevels=1;} emit(c,OP_SET_RT,&r,sizeof r); p_viewports v={.n=1};v.v[0][2]=v.v[0][3]=8;emit(c,OP_VIEWPORTS,&v,sizeof v);p_scissor sc={0,0,8,8};emit(c,OP_SCISSOR,&sc,sizeof sc); }
|
||||
static void clear_color(chain *c, int i, float r, float g, float b) { p_clear_color x={.index=i,.mask=15,.rgba={r,g,b,1}}; emit(c,OP_CLEAR_COLOR,&x,sizeof x); }
|
||||
static void bind_prog(chain *c, prog_t *p) { p_bind_program b={p,3}; emit(c,OP_BIND_PROGRAM,&b,sizeof b); }
|
||||
static void bind_tex(chain *c, int id) { p_bind_handles b={.stage=1,.first=0,.n=1};b.h[0]=id;emit(c,OP_BIND_TEX,&b,sizeof b); }
|
||||
static void draw_cmd(chain *c) { p_draw d={NVN_DRAW_PRIMITIVE_TRIANGLES,0,3}; emit(c,OP_DRAW,&d,sizeof d); }
|
||||
static void blend(chain *c) { color_st col={1,NVN_LOGIC_OP_COPY,NVN_ALPHA_FUNC_ALWAYS}; p_bind_state x={.kind=1};memcpy(x.bytes,&col,sizeof col);emit(c,OP_BIND_STATE,&x,sizeof x); blend_st b={0,NVN_BLEND_FUNC_SRC_ALPHA,NVN_BLEND_FUNC_ONE_MINUS_SRC_ALPHA,NVN_BLEND_FUNC_ONE,NVN_BLEND_FUNC_ZERO,NVN_BLEND_EQUATION_ADD,NVN_BLEND_EQUATION_ADD};x.kind=0;memcpy(x.bytes,&b,sizeof b);emit(c,OP_BIND_STATE,&x,sizeof x); }
|
||||
static void ds_off(chain *c) { ds_st d={0,0,NVN_DEPTH_FUNC_ALWAYS,0,NVN_STENCIL_FUNC_ALWAYS,NVN_STENCIL_FUNC_ALWAYS,NVN_STENCIL_OP_KEEP,NVN_STENCIL_OP_KEEP,NVN_STENCIL_OP_KEEP,NVN_STENCIL_OP_KEEP,NVN_STENCIL_OP_KEEP,NVN_STENCIL_OP_KEEP}; p_bind_state x={.kind=5}; memcpy(x.bytes,&d,sizeof d); emit(c,OP_BIND_STATE,&x,sizeof x); }
|
||||
static void readback(const tex_t *t, uint8_t out[256]) { id<MTLBuffer> b=[g_dev newBufferWithLength:256 options:MTLResourceStorageModeShared]; [blit() copyFromTexture:tex_mtl(t) sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0,0,0) sourceSize:MTLSizeMake(8,8,1) toBuffer:b destinationOffset:0 destinationBytesPerRow:32 destinationBytesPerImage:256]; uint64_t f=mtl_sub_commit(); EXPECT("提交完成",1,mtl_wait(f,5000000000ull)); EXPECT("提交反馈无错误",0,mtl_last_commit_error()); memcpy(out,b.contents,256); }
|
||||
static NvProg *g_tkeep[256]; static int g_tnkeep; /* 测试里的程序对象常驻:释放后新对象可能落在同一地址,管线缓存按对象地址认会取到旧管线(生产里程序对象不释放) | Program objects in the tests are permanent: after a free, a new object may land at the same address, and the pipeline cache, keyed by object address, would return the old pipeline (in production program objects are never freed) */
|
||||
static void setup_prog(prog_t *pg) { NSError *e=nil; id<MTLLibrary> l=[g_dev newLibraryWithSource:@"#include <metal_stdlib>\nusing namespace metal; vertex float4 v(uint n[[vertex_id]]){float2 p[3]={float2(-1,-1),float2(3,-1),float2(-1,3)};return float4(p[n],0,1);}\nfragment float4 red(){return float4(1,0,0,0.5);}\nstruct A{texture2d<float> t[[id(0)]];}; fragment float4 sample(constant A&a[[buffer(0)]]){return a.t.read(uint2(0));}\n" options:nil error:&e]; if(!l){fprintf(stderr,"%s\n",e.localizedDescription.UTF8String);abort();} for(int i=0;i<2;i++)pg[i].serial=8000+i; for(int i=0;i<2;i++){NvProg *p=[NvProg new];p->sh[0]=[NvShader new];p->sh[0]->fn=[l newFunctionWithName:@"v"];p->sh[1]=[NvShader new];p->sh[1]->stage=1;p->sh[1]->fn=[l newFunctionWithName:i?@"sample":@"red"];if(i){p->sh[1]->rf.nb=1;p->sh[1]->rf.b[0]=(nvn_rbind){.kind=NVN_RB_TEX,.reg=0,.dtt=2};p->sh[1]->ae=[p->sh[1]->fn newArgumentEncoderWithBufferIndex:0];}if(g_tnkeep<256)g_tkeep[g_tnkeep++]=p;serial_put(pg[i].serial,p);} }
|
||||
// 零源跳过单测(生产 mtl_exec + 手写着色器):sample 着色器输出 = 被采样贴图的 (0,0) 纹素——对采样值齐次线性,测试里注入事实表
|
||||
// Zero-source skip unit tests (production mtl_exec + hand-written shaders): the sample shader's output = texel (0,0) of the sampled texture - homogeneous linear in the sampled value; the fact table is injected in the test
|
||||
static void copy_cmd(chain *c, const tex_t *s, const tex_t *d) { p_copy_t2t x={.src=s,.dst=d}; x.sr=(NVNcopyRegion){0,0,0,8,8,1}; x.dr=x.sr; emit(c,OP_COPY_T2T,&x,sizeof x); }
|
||||
// mode:0 正例(A 清 0 → B 清 0 后采样 A);1 传播(A 清 0 → 整张拷 A→C → B 采样 C);2 A 清成非 0;3 A 清 0 后被画过;4 B 的清除值非 0
|
||||
// mode: 0 positive case (A cleared to 0 → B cleared to 0 then samples A); 1 propagation (A cleared to 0 → whole-texture copy A→C → B samples C); 2 A cleared to non-zero; 3 A drawn to after being cleared to 0; 4 B's clear value is non-zero
|
||||
static int run(int mode, int enabled, uint8_t px[256]) {
|
||||
tex_t a=tex(8),b=tex(8),c2=tex(8); int aid=view(&a,0), cid=view(&c2,0); chain c=chain_new(); static prog_t pg[2]; memset(pg,0,sizeof pg); setup_prog(pg);
|
||||
strcpy(g_tkeep[g_tnkeep-1]->sh[1]->key, "feedfacefeedface_b");
|
||||
float av = mode==2 ? 0.5f : 0.0f;
|
||||
set_rt(&c,&a,NULL,0); clear_color(&c,0,av,av,av); c.n -= 0;
|
||||
{ p_clear_color *last=(p_clear_color *)(c.p + c.n - ((8+sizeof(p_clear_color)+7)&~7ull) + 8); last->rgba[3] = av; } /* clear_color 帮手把 alpha 固定成 1:这里改成与 rgb 一致(0 = 全零) | The clear_color helper fixes alpha at 1: here it is changed to match rgb (0 = all zeros) */
|
||||
if (mode==3) { ds_off(&c); bind_prog(&c,&pg[0]); draw_cmd(&c); }
|
||||
if (mode==1) copy_cmd(&c,&a,&c2);
|
||||
float bv = mode==4 ? 0.25f : 0.0f;
|
||||
set_rt(&c,&b,NULL,0); clear_color(&c,0,bv,bv,bv);
|
||||
{ p_clear_color *last=(p_clear_color *)(c.p + c.n - ((8+sizeof(p_clear_color)+7)&~7ull) + 8); last->rgba[3] = bv; }
|
||||
ds_off(&c); bind_prog(&c,&pg[1]); bind_tex(&c,mode==1?cid:aid); draw_cmd(&c); emit(&c,OP_END,NULL,0);
|
||||
state_reset(); memset(&R,0,sizeof R); vis_clear(); g_vis_on=g_vis_counting=0; setenv("DM_NVN_ZSKIP",enabled?"1":"0",1); g_zskip_env=-1;
|
||||
mtl_sub_begin(); uint64_t hh=(uint64_t)c.p; mtl_sub_index(&hh,1); mtl_exec(c.p); int n=zskip_test_count(); readback(&b,px); return n;
|
||||
}
|
||||
int main(void){@autoreleasepool{setvbuf(stdout,NULL,_IONBF,0);setenv("DM_NVN_TBDR","1",1);mtl_init();uint8_t on[256],off[256];
|
||||
run(0,0,off); int n=run(0,1,on); EXPECT("不在事实表:不跳过",0,n); EXPECT("不在事实表:开关逐字节相同",0,(uint64_t)(memcmp(on,off,256)!=0));
|
||||
zskip_test_add("feedfacefeedface",-1,0,0);
|
||||
static const char *nm[5]={"正例(A 清 0)","传播(A 清 0 → 拷到 C)","反例 A 清成非 0","反例 A 清 0 后被画过","反例 B 清除值非 0"}; static const int want[5]={1,1,0,0,0};
|
||||
for(int m=0;m<5;m++){ run(m,0,off); n=run(m,1,on); char t1[96],t2[96]; snprintf(t1,sizeof t1,"%s:跳过次数",nm[m]); snprintf(t2,sizeof t2,"%s:开关逐字节相同",nm[m]);
|
||||
EXPECT(t1,want[m],n); EXPECT(t2,0,(uint64_t)(memcmp(on,off,256)!=0)); if(m==2) EXPECT("反例 A 非 0:B 读回非 0",1,on[0]!=0); if(m==0) EXPECT("正例:B 读回全 0",0,on[0]|on[1]|on[2]|on[3]); }
|
||||
printf("== %d 项,失败 %d ==\n",count,fail); return fail!=0; }}
|
||||
@@ -0,0 +1,87 @@
|
||||
"""预算表导出回归:小日志闭式期望,不需要游戏或 GPU;临时文件只放 run/gfx。 | Budget table export regression: small logs with closed-form expectations, no game or GPU needed; temp files go only under run/gfx."""
|
||||
import csv
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # 工作区根目录(游戏文件、产物、运行现场都在它下面) | Workspace root (game files, build outputs and run artifacts are all under it)
|
||||
|
||||
TOOL = Path(os.environ.get('TBDR_BUDGET_TOOL', Path(__file__).resolve().parents[1] / 'tools/tbdr_budget.py'))
|
||||
|
||||
class BudgetExport(unittest.TestCase):
|
||||
def export(self, text):
|
||||
root = Path(DM_ROOT) / 'run/gfx'
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix='budget_test_', dir=root) as tmp:
|
||||
log, out = Path(tmp) / 'pass.log', Path(tmp) / 'pass.tsv'
|
||||
log.write_text(text)
|
||||
p = subprocess.run([sys.executable, str(TOOL), str(log), '700', '170', '--tsv=' + str(out)], capture_output=True, text=True)
|
||||
self.assertEqual(p.returncode, 0, p.stderr)
|
||||
self.assertTrue(out.exists(), '全量通道 TSV 未导出')
|
||||
with out.open() as f:
|
||||
return list(csv.DictReader(f, delimiter='\t'))
|
||||
|
||||
def test_all_passes_not_only_console_top25(self):
|
||||
# 30 个独立 4×4 RGBA8 clear:每个写回 4×4×4=64 字节。
|
||||
# 30 independent 4×4 RGBA8 clears: each stores 4×4×4=64 bytes.
|
||||
rows = self.export(''.join(f'[pass] F700 P {p} c0 ser={p} fmt=70 4x4 ms1 lv0 sl0 clear\n' for p in range(1, 31)))
|
||||
self.assertEqual(len(rows), 30)
|
||||
self.assertEqual([int(x['pass']) for x in rows], list(range(1, 31)))
|
||||
self.assertEqual(sum(int(x['store_bytes']) for x in rows), 1920)
|
||||
self.assertTrue(all(x['draw_source'] == 'clear_only' for x in rows))
|
||||
|
||||
def test_draws_attachment_bytes_and_untruncated_shader_keys(self):
|
||||
key = '0123456789abcdef'
|
||||
rows = self.export(f'''[pass] F700 P 501 c0 ser=1 fmt=70 4x4 ms1 lv0 sl0 load
|
||||
[pass] F700 Z 501 c ser=1 lv0 sl0 dontcare why=0
|
||||
[pass] F700 P 502 c0 ser=2 fmt=70 8x4 ms1 lv0 sl0 clear
|
||||
[pass] F700 K 502 st1 key={key}_b nb=1
|
||||
[pass] F700 B 502 st1 tex reg0 tid=1 实 ser=12 fmt=70 8x4x1
|
||||
[pass] F700 R 502 st1 ser=12
|
||||
[pass] F700 d 502 fs={key}_b vc=3
|
||||
[pass] F700 d 502 fs={key}_b vc=3
|
||||
''')
|
||||
self.assertEqual((rows[0]['load_bytes'], rows[0]['store_bytes']), ('64', '0'))
|
||||
self.assertEqual((rows[1]['draws'], rows[1]['draw_source']), ('2', 'PASSDUMP_ALL'))
|
||||
self.assertEqual(rows[1]['fragment_keys'], key)
|
||||
self.assertEqual(rows[1]['texture_est_bytes'], '128')
|
||||
self.assertEqual(rows[1]['unknown_textures'], '0')
|
||||
|
||||
def test_unknown_texture_metadata_is_reported(self):
|
||||
rows = self.export('''[pass] F700 P 1 c0 ser=1 fmt=70 4x4 ms1 lv0 sl0 clear
|
||||
[pass] F700 R 1 st1 ser=99
|
||||
[pass] F700 d 1 fs=unknown_b vc=3
|
||||
''')
|
||||
self.assertEqual(rows[0]['unknown_textures'], '1')
|
||||
self.assertEqual(rows[0]['texture_est_bytes'], '64')
|
||||
|
||||
def test_texture_views_do_not_leak_between_passes(self):
|
||||
# 两通道均 8×4 输出;同 ser=99 的实际绑定视图分别 8×4、4×4。
|
||||
# RGBA8:独立期望 128 / 64 字节,不能让后通道尺寸覆盖前通道。
|
||||
# Both passes output 8×4; the actual bound views of the same ser=99 are 8×4 and 4×4 respectively.
|
||||
# RGBA8: independent expectations of 128 / 64 bytes; the later pass's size must not overwrite the earlier pass's.
|
||||
rows = self.export('''[pass] F700 P 1 c0 ser=1 fmt=70 8x4 ms1 lv0 sl0 clear
|
||||
[pass] F700 B 1 st1 tex reg0 tid=1 实 ser=99 fmt=70 8x4x1
|
||||
[pass] F700 R 1 st1 ser=99
|
||||
[pass] F700 d 1 fs=unknown_b vc=3
|
||||
[pass] F700 P 2 c0 ser=2 fmt=70 8x4 ms1 lv0 sl0 clear
|
||||
[pass] F700 B 2 st1 tex reg0 tid=2 实 ser=99 fmt=70 4x4x1
|
||||
[pass] F700 R 2 st1 ser=99
|
||||
[pass] F700 d 2 fs=unknown_b vc=3
|
||||
''')
|
||||
self.assertEqual([x['texture_est_bytes'] for x in rows], ['128', '64'])
|
||||
|
||||
def test_distinct_views_within_same_pass_are_kept(self):
|
||||
rows = self.export('''[pass] F700 P 1 c0 ser=1 fmt=70 8x4 ms1 lv0 sl0 clear
|
||||
[pass] F700 B 1 st1 tex reg0 tid=1 实 ser=99 fmt=70 8x4x1
|
||||
[pass] F700 R 1 st1 ser=99
|
||||
[pass] F700 B 1 st1 tex reg1 tid=2 实 ser=99 fmt=70 4x4x1
|
||||
[pass] F700 R 1 st1 ser=99
|
||||
[pass] F700 d 1 fs=unknown_b vc=3
|
||||
''')
|
||||
self.assertEqual(rows[0]['texture_est_bytes'], '192')
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user