Android port (Adreno): Vulkan backend, GameActivity app, touch HUD, lifecycle, minimap quest goals
- host/android: Vulkan replay backend (nvn_vk.c) with pipeline/descriptor caching, ADPF, AChoreographer present link; Linux compat layer; Makefile.android (headless dmhost + APK lib) - android/app: GameActivity shell without Gradle (build_apk.sh), AAudio output, touch HUD port (touch_app.c + TouchOverlay.java, three layers: body / joystick / minimap goals), lifecycle save-on-background like iOS, art_from_ipa.py for touch / HUD / mapgoal art - touch: shared touch controls moved from ios/Sources to dm/touch - patch_nso.py Android ruleset, dmsh_vk.py shader pack, DM_TOUCH_PRODUCT defaults - hle_audio: AAudio resume waits through STARTING and reopens once on failure - .gitignore: local resources/ (original game data) never committed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
5bc5a01087
commit
4d91f80bae
@@ -1,3 +1,3 @@
|
||||
// 生成文件(dm/gfx/tools/dmsh_chain.py --header):本源码树期望的 B 着色器库翻译链版本(缺省选项);宿主只加载 <库目录>/b-<V>/
|
||||
// Generated file (dm/gfx/tools/dmsh_chain.py --header): the translation chain version of the B shader library expected by this source tree (default options); the host only loads <library dir>/b-<V>/
|
||||
#define DMSH_CHAIN "15cf7ca29eaf"
|
||||
#define DMSH_CHAIN "f0d74f7f12a9"
|
||||
|
||||
+46
-4
@@ -66,13 +66,13 @@ typedef struct { const char *name; void *fn; } nvn_impl;
|
||||
#define NVN(name, ret, ...) \
|
||||
static ret h_##name(__VA_ARGS__); \
|
||||
static const NVNT_##name chk_##name __attribute__((unused)) = h_##name; \
|
||||
__attribute__((used, section("__DATA,swnvn"))) static const nvn_impl e_##name = {#name, (void *)h_##name}; \
|
||||
__attribute__((used, DM_SECT("swnvn"))) static const nvn_impl e_##name = {#name, (void *)h_##name}; \
|
||||
static ret h_##name(__VA_ARGS__)
|
||||
// 无原型的新版接口:不做签名检查
|
||||
// Newer interfaces without prototypes: no signature check
|
||||
#define NVN_NOPROTO(name, ret, ...) \
|
||||
static ret h_##name(__VA_ARGS__); \
|
||||
__attribute__((used, section("__DATA,swnvn"))) static const nvn_impl e_##name = {#name, (void *)h_##name}; \
|
||||
__attribute__((used, DM_SECT("swnvn"))) static const nvn_impl e_##name = {#name, (void *)h_##name}; \
|
||||
static ret h_##name(__VA_ARGS__)
|
||||
|
||||
static int g_log;
|
||||
@@ -164,7 +164,12 @@ NVN(nvnDeviceGetSeparateSamplerHandle, NVNseparateSamplerHandle, const NVNdevice
|
||||
NVN(nvnDeviceInstallDebugCallback, void, NVNdevice *d, const PFNNVNDEBUGCALLBACKPROC cb, void *data, uint32_t enable) {
|
||||
dev_t_ *o = (dev_t_ *)d; o->dbg_cb = B(enable) ? (void *)cb : NULL; o->dbg_data = data;
|
||||
}
|
||||
NVN(nvnDeviceSetWindowOriginMode, void, NVNdevice *d, NVNwindowOriginMode m) { ((dev_t_ *)d)->origin = m; LOG("[nvn] 窗口原点 %s", m ? "左上(同 D3D / Metal)" : "左下(GL)"); }
|
||||
NVN(nvnDeviceSetWindowOriginMode, void, NVNdevice *d, NVNwindowOriginMode m) {
|
||||
((dev_t_ *)d)->origin = m;
|
||||
#ifdef __ANDROID__
|
||||
mtl_set_window_origin_mode(m); // Vulkan 后端按原点选负高视口 | the Vulkan backend picks a negative-height viewport by origin
|
||||
#endif
|
||||
LOG("[nvn] 窗口原点 %s", m ? "左上(同 D3D / Metal)" : "左下(GL)"); }
|
||||
NVN(nvnDeviceSetDepthMode, void, NVNdevice *d, NVNdepthMode m) { ((dev_t_ *)d)->depth_mode = m; LOG("[nvn] 深度模式 %s", m ? "近=0(同 D3D / Metal)" : "近=-w(GL)"); }
|
||||
NVN(nvnDeviceFinalizeCommandHandle, void, NVNdevice *d, NVNcommandHandle h) { (void)d; (void)h; }
|
||||
|
||||
@@ -399,7 +404,11 @@ NVN(nvnQueueFinalize, void, NVNqueue *q) { ((queue_t *)q)->magic = 0; }
|
||||
NVN(nvnQueueGetError, NVNqueueGetErrorResult, NVNqueue *q, NVNqueueErrorInfo *info) {
|
||||
(void)q; if (info) memset(info, 0, sizeof *info); return NVN_QUEUE_GET_ERROR_RESULT_GPU_NO_ERROR;
|
||||
}
|
||||
NVN(nvnQueueFlush, void, NVNqueue *q) { (void)q; }
|
||||
NVN(nvnQueueFlush, void, NVNqueue *q) { (void)q;
|
||||
#ifdef __ANDROID__
|
||||
mtl_queue_flush();
|
||||
#endif
|
||||
}
|
||||
NVN(nvnQueueFinish, void, NVNqueue *q) { (void)q; mtl_finish(); }
|
||||
|
||||
// ---------- 命令缓冲:录进游戏的命令内存,提交时执行 CPU 可见副作用 ----------
|
||||
@@ -535,6 +544,30 @@ static void *rec(NVNcommandBuffer *c, uint32_t op, size_t payload) {
|
||||
return p + 8;
|
||||
}
|
||||
#define REC(c, OP, T) ((T *)rec((c), (OP), sizeof(T)))
|
||||
#ifdef __ANDROID__
|
||||
// Vulkan 后端要按命令序处理的同步命令(Metal 端仍当空操作,见 g_nops);格式与 dodola/d2r-mobile 的 nvn_vk.c 一致
|
||||
// Sync commands the Vulkan backend handles in command order (still no-ops on Metal, see g_nops); format matches nvn_vk.c of dodola/d2r-mobile
|
||||
NVN(nvnCommandBufferSetShaderScratchMemory, void, NVNcommandBuffer *c, const NVNmemoryPool *p, ptrdiff_t off, size_t size) {
|
||||
const pool_t *pool = (const pool_t *)p;
|
||||
if (!pool || pool->magic != MAGIC('P', 'O', 'O', 'L') || !pool->mem || off < 0 || (uint64_t)off > pool->size || size > pool->size - (uint64_t)off)
|
||||
die("ShaderScratchMemory 范围非法 off=%lld size=%llu", (long long)off, (unsigned long long)size);
|
||||
*REC(c, OP_SHADER_SCRATCH, p_bind_buf) = (p_bind_buf){.addr = (uint64_t)(uintptr_t)(pool->mem + off), .size = size};
|
||||
}
|
||||
NVN(nvnCommandBufferWaitSync, void, NVNcommandBuffer *c, const NVNsync *s) {
|
||||
if (!s || ((const sync_t *)s)->magic != MAGIC('S', 'Y', 'N', 'C')) die("CommandBufferWaitSync 同步对象非法");
|
||||
*REC(c, OP_WAIT_SYNC, p_sync) = (p_sync){(sync_t *)s, 0, 0};
|
||||
}
|
||||
NVN(nvnCommandBufferFenceSync, void, NVNcommandBuffer *c, NVNsync *s, NVNsyncCondition cond, int flags) {
|
||||
if (!s || ((sync_t *)s)->magic != MAGIC('S', 'Y', 'N', 'C') || cond < 0 || cond > 1 || (flags & ~1)) die("CommandBufferFenceSync 参数非法");
|
||||
*REC(c, OP_FENCE_SYNC, p_sync) = (p_sync){(sync_t *)s, cond, flags};
|
||||
}
|
||||
NVN(nvnCommandBufferWaitEvent, void, NVNcommandBuffer *c, const NVNevent *e, NVNeventWaitMode mode, uint32_t v) {
|
||||
const ev_t *ev = (const ev_t *)e;
|
||||
if (!ev || ev->magic != MAGIC('E', 'V', 'N', 'T') || !ev->val || mode < 0 || mode > 1) die("CommandBufferWaitEvent 参数非法");
|
||||
uint8_t *p = rec(c, OP_WAIT_EVENT, 16); uint64_t a = (uint64_t)(uintptr_t)ev->val; uint32_t mm = mode;
|
||||
memcpy(p, &a, 8); memcpy(p + 8, &mm, 4); memcpy(p + 12, &v, 4);
|
||||
}
|
||||
#endif
|
||||
// 带数组的绑定记录按实际个数分配:前缀字段 + n 个元素(回放端只读前 n 个)。原先按最大个数定长记(绑顶点缓冲 272 字节、绑贴图 / 采样器 280 字节,
|
||||
// 实际常只有 1–2 个),空尾占每帧命令字节的四到五成;88 级法师的高级属性页每帧录 12.5 MB,把游戏自己的命令内存池(约每帧 105 段 × 128 KB)用空
|
||||
// Binding records with arrays are allocated by the actual count: prefix fields + n elements (the replay side reads only the first n). Previously they were recorded at fixed length for the maximum count (bind vertex buffers 272 bytes, bind textures / samplers 280 bytes,
|
||||
@@ -777,12 +810,18 @@ static const char *const g_nops[] = {
|
||||
"nvnCommandBufferDispatchComputeIndirect",
|
||||
"nvnCommandBufferSetDepthBounds",
|
||||
"nvnCommandBufferDownsampleTextureView",
|
||||
#ifndef __ANDROID__
|
||||
"nvnCommandBufferWaitSync",
|
||||
#endif
|
||||
#ifndef __ANDROID__
|
||||
"nvnCommandBufferSetShaderScratchMemory",
|
||||
#endif
|
||||
"nvnCommandBufferPushDebugGroupDynamic",
|
||||
"nvnCommandBufferPopDebugGroup",
|
||||
"nvnCommandBufferInsertDebugMarkerDynamic",
|
||||
#ifndef __ANDROID__
|
||||
"nvnCommandBufferWaitEvent",
|
||||
#endif
|
||||
"nvnWindowFinalize",
|
||||
};
|
||||
__attribute__((constructor)) static void nvn_nops_register(void) {
|
||||
@@ -840,6 +879,7 @@ static double g_rt_period_ms;
|
||||
static void sleep_until_ns(uint64_t dl);
|
||||
static uint64_t present_period(const win_t *o);
|
||||
__attribute__((weak)) void dm_main_yield_stats(uint64_t *n, uint64_t *ns) { *n = 0; *ns = 0; } // 宿主 hle_thread.c 提供真值;图形单测里为 0 | The host's hle_thread.c provides the ground truth; 0 in graphics unit tests
|
||||
__attribute__((weak)) void mtl_pace_slept(uint64_t ns) { (void)ns; } // 取图里节拍等待的墙钟;安卓后端(nvn_vk.c)据此算每帧真实工作时长报给 ADPF | Wall time spent in the acquire pacing wait; the Android backend (nvn_vk.c) uses it to derive each frame's real work time for ADPF
|
||||
__attribute__((weak)) uint32_t dm_guest_work_qos(unsigned *count) { if (count) *count = 0; return QOS_CLASS_UNSPECIFIED; }
|
||||
extern uint32_t mtl_present_qos(void);
|
||||
static uint64_t g_frame;
|
||||
@@ -856,8 +896,10 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn
|
||||
static uint64_t rt_period; uint64_t period = present_period(o);
|
||||
if (period && rt_period != period) { rt_period = period; set_time_constraint(period); }
|
||||
rt_comp_tick(period);
|
||||
uint64_t pace_t0 = now_ns();
|
||||
if (mtl_link_active()) { if (!mtl_link_wait_tick(period ? 2 * period : 33333333ull) && wait) sleep_until_ns(at); } // DM_PRESENT_LINK:节拍完全跟显示节拍(跑得快就等下一拍,落后立刻走);自己的 60 Hz 时钟只作等不到节拍时的兜底 | DM_PRESENT_LINK: pacing fully follows the display link (wait for the next display-link tick when running fast, go immediately when behind); our own 60 Hz clock is only the fallback when no display-link tick arrives
|
||||
else if (wait) sleep_until_ns(at);
|
||||
mtl_pace_slept(now_ns() - pace_t0);
|
||||
} else { // DM_DETCLOCK_PACE=1(画面闸门用):客体时钟按帧走的同时,每帧墙钟不短于一个步长——帧数与游戏内时间确定,后台加载线程每帧至少有一个步长的墙钟可用; | DM_DETCLOCK_PACE=1 (used by the screenshot gate): while the guest clock advances per frame, each frame's wall clock is no shorter than one step -- frame count and in-game time are deterministic, and the background loading thread has at least one step of wall clock available per frame;
|
||||
// 机器满载时帧只会更慢、后台得到的墙钟只会更多,所以「消息后第 N 帧」截到的画面与负载无关
|
||||
// When the machine is fully loaded frames only get slower and the background only gets more wall clock, so the picture captured at "the Nth frame after the message" is independent of load
|
||||
|
||||
@@ -37,6 +37,9 @@ uint64_t mtl_sub_commit(void);
|
||||
|
||||
uint64_t mtl_last_fence(void); // 最近一次提交的栅栏值(0 = 从未提交) | Fence value of the most recent submit (0 = never submitted)
|
||||
int mtl_wait(uint64_t fence, uint64_t timeout_ns); // GPU 完成到 fence 返回 1,超时 0 | Returns 1 when the GPU has completed up to fence, 0 on timeout
|
||||
#ifdef __ANDROID__
|
||||
void mtl_queue_flush(void); // Submit deferred Vulkan work without waiting.
|
||||
#endif
|
||||
void mtl_finish(void); // 等所有已提交的命令完成 | Wait for all submitted commands to complete
|
||||
void mtl_drain(void); // 等队列上全部命令(含出图)完成:提交空命令缓冲并等它 | Wait for all commands on the queue (including presents) to complete: submit an empty command buffer and wait for it
|
||||
void mtl_xv_window_tex(uint64_t serial); // 登记窗口(交换链)贴图:跨提交有效性账本永不收它 | Register a window (swapchain) texture: the cross-submit validity ledger never collects it
|
||||
|
||||
@@ -92,7 +92,7 @@ enum {
|
||||
OP_BIND_PROGRAM, OP_BIND_STATE, OP_BIND_VATTR, OP_BIND_VSTREAM, OP_BIND_VBUF,
|
||||
OP_BIND_UBO, OP_BIND_SSBO, OP_BIND_TEX, OP_BIND_SAMP,
|
||||
OP_STENCIL, OP_POLY_OFFSET, OP_DRAW, OP_DRAW_IDX, OP_DISPATCH, OP_BARRIER,
|
||||
OP_SET_TEX_POOL, OP_SET_SAMP_POOL, OP_COPY_B2T, OP_COPY_STRIDE, OP_BLEND_COLOR, OP_COPY_T2B, OP_BIND_IMG, OP_COPY_T2T, OP_RESET_COUNTER, OP_CLEAR_TEX, OP_COUNT_
|
||||
OP_SET_TEX_POOL, OP_SET_SAMP_POOL, OP_COPY_B2T, OP_COPY_STRIDE, OP_BLEND_COLOR, OP_COPY_T2B, OP_BIND_IMG, OP_COPY_T2T, OP_RESET_COUNTER, OP_CLEAR_TEX, OP_SHADER_SCRATCH, OP_WAIT_SYNC, OP_FENCE_SYNC, OP_WAIT_EVENT, OP_COUNT_
|
||||
};
|
||||
// 载荷(紧跟 op_hdr)
|
||||
// Payload (immediately follows op_hdr)
|
||||
@@ -120,6 +120,7 @@ typedef struct { const tex_t *src, *dst; view_t sv, dv; uint8_t has_sv, has_dv;
|
||||
typedef struct { const tex_t *tex; view_t view; uint8_t has_view, is_uint; NVNcopyRegion r; int32_t mask; union { float f[4]; uint32_t u[4]; } c; } p_clear_tex;
|
||||
typedef struct { int64_t stride; } p_copy_stride;
|
||||
typedef struct { float rgba[4]; } p_blend_color;
|
||||
typedef struct { sync_t *sync; int32_t condition, flags; } p_sync; // OP_WAIT_SYNC / OP_FENCE_SYNC(仅 Android 录制) | OP_WAIT_SYNC / OP_FENCE_SYNC (recorded on Android only)
|
||||
|
||||
// Metal 回放层入口(nvn_mtl.m):把一组命令句柄回放进当前提交
|
||||
// Entry point of the Metal replay layer (nvn_mtl.m): replays a set of command handles into the current submission
|
||||
@@ -171,6 +172,9 @@ void mtl_read_texels(const tex_t *t, unsigned level, unsigned layer0, const NVNc
|
||||
void mtl_reg_tex(int id, const tex_t *t, const view_t *v);
|
||||
void mtl_reg_samp(int id, const samp_par *p);
|
||||
void mtl_prog_release(prog_t *p);
|
||||
#ifdef __ANDROID__
|
||||
void mtl_set_window_origin_mode(int mode);
|
||||
#endif
|
||||
// 新序号(> 0,全局递增)
|
||||
// New serial (> 0, globally increasing)
|
||||
uint64_t nvn_new_serial(void);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
dmsh_xlate.dll aff3b70cff6bf29e
|
||||
Ryujinx.Graphics.Shader.dll 72886c0b30bc0016
|
||||
Ryujinx.Common.dll 614dced78b44547d
|
||||
xlate_source 1cc46907ca1ee8d0
|
||||
xlate_source d379d76ef969729f
|
||||
spirv-cross c95d3fc88f6ae5f5
|
||||
metal_macosx Apple metal version 32023.883 (metalfe-32023.883)
|
||||
metal_iphoneos Apple metal version 32023.883 (metalfe-32023.883)
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
#!/usr/bin/env python3
|
||||
# Vulkan 路线离线出包(Android):Switch 原版着色器 → SPIR-V(dmsh_xlate,Ryujinx 翻译器)→ 直接给 Vulkan 用,不经 spirv-cross / Metal。
|
||||
# 与 dmsh_build.py 共用作业构造(作答表 nvn/shader_facts.tsv、映射表 nvn/shader_map.tsv、c1、内嵌着色器);反射直接从 SPIR-V 的名字与修饰里读,
|
||||
# 资源分类与 dmsh_build.reflect 同口径(Ryujinx 的资源名 spirv-cross 原样保留进 MSL,所以同一套名字规则在 SPIR-V 上同样成立)。
|
||||
# 改写:描述符组号按阶段分开——顶点 / 计算 = 0,像素 = 1(Ryujinx 一律放进第 0 组,绑定号各阶段都从 1 起,同一管线里会撞)。
|
||||
# 用法:dmsh_vk.py <Switch 着色器包目录> <输出目录> [键…](不给键 = 全部) 环境:XLATE=翻译工具,MAIN=Switch main NSO(内嵌着色器),J=并发,SPIRV_VAL=校验工具
|
||||
# 产物:<输出目录>/<键>.spv(已改组号)、<输出目录>/<键>.vk.json(反射)、<输出目录>/_vk_build.json(逐键结果);
|
||||
# <输出目录>/rt/:设备端运行时缓存(nvn_vk.c 读)= shader_index.bin(控制段 → 键)+ <键>.vkmeta(绑定表)+ <键>.spv.gz
|
||||
# PACK_ONLY=1 只按已有 .spv / .vk.json 重出 rt/;GLSLC=glslc 时一并编译 main 内嵌的 4 个计数报告内核(nvn_builtin.h)
|
||||
# SB_ALIGN=宿主存储缓冲偏移对齐(缺省 64 = Adreno):翻译器按 base & -SB_ALIGN 求 SSBO 偏移,vkmeta 绑定标志位 1 告诉宿主可下对齐绑定、免拷贝;16 = 与 iOS 同样的翻译
|
||||
# Vulkan-route offline build (Android): original Switch shaders → SPIR-V (dmsh_xlate, the Ryujinx translator) → used by Vulkan directly, no spirv-cross / Metal.
|
||||
# Shares job construction with dmsh_build.py (answer table nvn/shader_facts.tsv, mapping table nvn/shader_map.tsv, c1, embedded shaders); reflection is read straight from SPIR-V names and decorations,
|
||||
# resource classification follows dmsh_build.reflect (spirv-cross keeps Ryujinx's resource names in the MSL unchanged, so the same naming rules hold on SPIR-V).
|
||||
# Rewrite: descriptor set numbers are split by stage - vertex / compute = 0, pixel = 1 (Ryujinx puts everything in set 0 with binding numbers starting at 1 in every stage, which collide within one pipeline).
|
||||
# Usage: dmsh_vk.py <Switch shader package dir> <output dir> [key...] (no keys = all) Environment: XLATE=translator, MAIN=Switch main NSO (embedded shaders), J=concurrency, SPIRV_VAL=validator
|
||||
# Output: <output dir>/<key>.spv (set numbers rewritten), <output dir>/<key>.vk.json (reflection), <output dir>/_vk_build.json (per-key results);
|
||||
# <output dir>/rt/: the on-device runtime cache (read by nvn_vk.c) = shader_index.bin (control segment → key) + <key>.vkmeta (binding table) + <key>.spv.gz
|
||||
# PACK_ONLY=1 only re-emits rt/ from the existing .spv / .vk.json; with GLSLC=glslc the 4 counter-report kernels embedded in main (nvn_builtin.h) are compiled too
|
||||
# SB_ALIGN=host storage buffer offset alignment (default 64 = Adreno): the translator takes SSBO offsets from base & -SB_ALIGN, and vkmeta binding flag bit 1 tells the host it may bind aligned down without copying; 16 = the same translation as iOS
|
||||
import os, sys, re, json, struct, gzip, hashlib, shutil, subprocess, tempfile, collections, concurrent.futures as cf
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE); import dmsh_facts
|
||||
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work')
|
||||
dm_dir, out = sys.argv[1:3]; want = set(sys.argv[3:])
|
||||
XLATE = os.environ.get('XLATE', f'{DM_ROOT}/build/gfx/dmsh_xlate/dmsh_xlate')
|
||||
MAIN = os.environ.get('MAIN', f'{DM_ROOT}/data/switch/3.3.94012/Update/ExeFS/main')
|
||||
SPIRV_VAL = os.environ.get('SPIRV_VAL', shutil.which('spirv-val') or '')
|
||||
MAP = os.path.join(HERE, '../nvn/shader_map.tsv')
|
||||
FACTS = dmsh_facts.load()
|
||||
if not FACTS: sys.exit('【红】没有作答表 nvn/shader_facts.tsv')
|
||||
TEX_BASE, SAMP_BASE, IMG_BASE = 0x168, 0x568, 0x120
|
||||
SET_OF = {'vs': 0, 'cs': 0, 'ps': 1}
|
||||
|
||||
def records(d):
|
||||
r = [m.start() for m in re.finditer(b'BTCDBTCD', d)]
|
||||
return [d[x:(r[k + 1] if k + 1 < len(r) else len(d))] for k, x in enumerate(r)]
|
||||
|
||||
loc, stage_of = {}, {}
|
||||
for ln in open(MAP):
|
||||
c = ln.rstrip('\n').split('\t')
|
||||
if len(c) > 4 and c[0].endswith('.bin'): loc.setdefault(c[3], (c[0], int(c[1])))
|
||||
if len(c) > 4 and c[0].startswith('main.rodata@'):
|
||||
loc.setdefault(c[3], (c[0], int(c[0].split('@')[1], 16))); stage_of[c[3]] = {'顶点': 'vs', '像素': 'ps'}[c[2]]
|
||||
|
||||
def main_rec(mi, o):
|
||||
# 同 dmsh_build.main_rec:内嵌代码区紧贴控制段之前 | same as dmsh_build.main_rec: the embedded code area sits right before the control segment
|
||||
g = mi.rfind(bytes.fromhex('78563412'), o - 0x1000, o)
|
||||
if g < 0 or mi[o:o + 4] != bytes.fromhex('34127698'): sys.exit(f'【红】main 映像 @{o:#x} 不是内嵌着色器控制段(MAIN={MAIN})')
|
||||
return bytes(0x38) + mi[g:o + 0x880]
|
||||
|
||||
def job_for(key, name, rec, w):
|
||||
# 同 dmsh_build.job_for | same as dmsh_build.job_for
|
||||
ci = rec.find(bytes.fromhex('34127698')); code = rec[0x38:ci]; stage = stage_of.get(key, name[:2])
|
||||
c1o, c1t = struct.unpack_from('<2I', rec, ci + 0x700)
|
||||
c1 = rec[0x38 + c1o:0x38 + c1t]
|
||||
if stage != 'cs': code = code[0x30:]
|
||||
cp = os.path.join(w, key + '.bin'); open(cp, 'wb').write(code)
|
||||
j = {'key': key, 'stage': stage, 'code': cp, 'tex': {}, 'img': {}, 'attr': {}, 'fout': {}, 'c1': c1.hex(),
|
||||
'debug': os.environ.get('XLATE_DEBUG', '1') != '0', 'reduced': os.environ.get('XLATE_REDUCED', '1') == '1',
|
||||
'sb_align': int(os.environ.get('SB_ALIGN', '64'))} # Adreno minStorageBufferOffsetAlignment;翻译器按 base & -64 求偏移 | translator takes offsets from base & -64
|
||||
if key not in FACTS: j['pc_missing'] = True; return j, c1
|
||||
j.update(FACTS[key])
|
||||
return j, c1
|
||||
|
||||
def decode_tex(name):
|
||||
# 同 dmsh_build.decode_tex | same as dmsh_build.decode_tex
|
||||
m = re.match(r'[a-z]+_[ti]\w*?_(?:cb(\d+)|tcb)_([0-9A-F]+)', name)
|
||||
if not m: return None
|
||||
slots = int(m.group(1)) if m.group(1) else -1; h = int(m.group(2), 16)
|
||||
tb = (slots & 0xffff) if slots >= 0 else 2; sb = ((slots >> 16) - 1) if slots >= 0 and (slots >> 16) else tb
|
||||
o0, o1, ty = h & 0x3fff, (h >> 14) & 0x3fff, h >> 28
|
||||
def slot(word, base, cb): return (word * 4 - base) // 8 if cb == 2 and word * 4 >= base and (word * 4 - base) % 8 == 0 else None
|
||||
words = [o0] + ([o1] if ty else [])
|
||||
if re.match(r'[a-z]+_i', name):
|
||||
return next((slot(x, IMG_BASE, tb) for x in words if IMG_BASE <= x * 4 < TEX_BASE and slot(x, IMG_BASE, tb) is not None), None), None, ty
|
||||
t = next((slot(x, TEX_BASE, tb) for x in words if slot(x, TEX_BASE, tb) is not None and x * 4 < SAMP_BASE), None)
|
||||
s = next((slot(x, SAMP_BASE, sb) for x in words if x * 4 >= SAMP_BASE and slot(x, SAMP_BASE, sb) is not None), None)
|
||||
return t, s, ty
|
||||
|
||||
# ---- SPIR-V 解析 | SPIR-V parsing ----
|
||||
OP_NAME, OP_DECORATE, OP_VARIABLE, OP_TYPE_POINTER, OP_ENTRY, OP_EXEC_MODE = 5, 71, 59, 32, 15, 16
|
||||
OP_TYPE_IMAGE, OP_TYPE_SAMPLER, OP_TYPE_SAMPLED_IMAGE, OP_TYPE_ARRAY, OP_TYPE_RUNTIME_ARRAY, OP_TYPE_STRUCT = 25, 26, 27, 28, 29, 30
|
||||
DEC_BINDING, DEC_SET, DEC_LOCATION, DEC_BUILTIN = 33, 34, 30, 11
|
||||
SC_UNIFORM_CONSTANT, SC_INPUT, SC_UNIFORM, SC_OUTPUT, SC_STORAGE_BUFFER = 0, 1, 2, 3, 12
|
||||
|
||||
def spv_insts(words):
|
||||
o = 5
|
||||
while o < len(words):
|
||||
n, op = words[o] >> 16, words[o] & 0xffff
|
||||
if not n or o + n > len(words): raise ValueError(f'SPIR-V 指令越界 @{o}')
|
||||
yield o, op, words[o + 1:o + n]; o += n
|
||||
|
||||
def spv_str(ops):
|
||||
b = struct.pack(f'<{len(ops)}I', *ops); return b[:b.index(0)].decode()
|
||||
|
||||
def reflect_spv(key, stage, words, res):
|
||||
names, deco, types, var = {}, collections.defaultdict(dict), {}, {}
|
||||
for o, op, a in spv_insts(words):
|
||||
if op == OP_NAME: names[a[0]] = spv_str(a[1:])
|
||||
elif op == OP_DECORATE and len(a) >= 2: deco[a[0]][a[1]] = a[2] if len(a) > 2 else 1
|
||||
elif 19 <= op <= 39: types[a[0]] = (op, a[1:])
|
||||
elif op == OP_VARIABLE: var[a[1]] = (a[0], a[2])
|
||||
def pointee(tid):
|
||||
t = types.get(tid); return t[1][1] if t and t[0] == OP_TYPE_POINTER else None
|
||||
def base(tid):
|
||||
while tid in types and types[tid][0] in (OP_TYPE_ARRAY, OP_TYPE_RUNTIME_ARRAY): tid = types[tid][1][0]
|
||||
return tid
|
||||
def desc_type(sc, tid):
|
||||
"""VkDescriptorType:0 采样器、1 组合、2 采样图像、3 存储图像、4 uniform 纹素缓冲、5 存储纹素缓冲、6 uniform 缓冲、7 存储缓冲 | VkDescriptorType numbering"""
|
||||
t = types.get(base(tid))
|
||||
if sc == SC_UNIFORM: return 7 if deco[base(tid)].get(3) else 6 # BufferBlock(3) 旧式存储缓冲 | BufferBlock (3) is the legacy storage buffer form
|
||||
if sc == SC_STORAGE_BUFFER: return 7
|
||||
if not t: return None
|
||||
if t[0] == OP_TYPE_SAMPLER: return 0
|
||||
if t[0] == OP_TYPE_SAMPLED_IMAGE:
|
||||
im = types[t[1][0]]; return 4 if im[1][1] == 5 else 1 # Dim Buffer = 5
|
||||
if t[0] == OP_TYPE_IMAGE:
|
||||
dim, sampled = t[1][1], t[1][5]
|
||||
if dim == 5: return 4 if sampled == 1 else 5
|
||||
return 2 if sampled == 1 else 3
|
||||
return None
|
||||
binds = []
|
||||
sb_sorted = sorted(res['sbufs'], key=lambda b: b['binding'])
|
||||
sb_by_binding = {b['binding']: (i, b) for i, b in enumerate(sb_sorted)}
|
||||
sbase = {'vs': 0x110, 'cs': 0x310, 'ps': 0x510}[stage]
|
||||
for vid, (ptype, sc) in var.items():
|
||||
if sc not in (SC_UNIFORM_CONSTANT, SC_UNIFORM, SC_STORAGE_BUFFER) or DEC_BINDING not in deco[vid]: continue
|
||||
nm = names.get(vid, ''); ty = desc_type(sc, pointee(ptype))
|
||||
tdef = types.get(pointee(ptype)); count = 1
|
||||
if tdef and tdef[0] == OP_TYPE_ARRAY: count = -1 # 描述符数组:Ryujinx 只在无绑定贴图时出,这里不支持 | descriptor array: Ryujinx only emits it for bindless textures; unsupported here
|
||||
e = {'name': nm, 'binding': deco[vid][DEC_BINDING], 'set': deco[vid].get(DEC_SET, 0), 'vk_type': ty, 'count': count, 'var': vid}
|
||||
if nm == 'support_buffer': e['kind'] = 'support'
|
||||
elif re.fullmatch(r'[a-z]+_c(\d+)', nm):
|
||||
n = int(re.fullmatch(r'[a-z]+_c(\d+)', nm).group(1))
|
||||
e.update(kind='cbuf', reg=n - 3) if 3 <= n <= 16 else e.update(kind='c1' if n == 1 else 'drvcb', bank=n)
|
||||
elif re.fullmatch(r'[a-z]+_s(\d+)', nm):
|
||||
idx, b = sb_by_binding.get(e['binding'], (None, None))
|
||||
e.update(kind='sbuf', index=idx)
|
||||
off = b['cb_offset'] * 4 if b and b['cb_slot'] == 0 else None
|
||||
if stage == 'cs' and off is not None and 0x210 <= off < 0x310 and (off - 0x210) % 16 == 0:
|
||||
e.update(kind='ubo_ptr', reg=(off - 0x210) // 16)
|
||||
else: e['reg'] = (off - sbase) // 16 if off is not None and 0 <= off - sbase < 0x100 and (off - sbase) % 16 == 0 else None
|
||||
e['rw'] = bool(b and b['flags'] & 2)
|
||||
elif ty == 0:
|
||||
t, s, hty = decode_tex(nm[:-5] if nm.endswith('Smplr') else nm) or (None, None, 0)
|
||||
e.update(kind='samp', reg=s) if hty else e.update(kind='samp_tex', reg=t)
|
||||
else:
|
||||
d = decode_tex(nm)
|
||||
if not d: e['kind'] = '?'
|
||||
else:
|
||||
img = bool(re.match(r'[a-z]+_i', nm))
|
||||
e.update(kind='img' if img else ('tbuf' if ty in (4, 5) else 'tex'), reg=d[0])
|
||||
if not img and ty == 1: # 组合采样:采样器号取同一句柄(类型 0 = 贴图槽句柄高位) | combined: sampler from the same handle (type 0 = high bits of the texture slot's handle)
|
||||
e['samp'] = d[1] if d[2] else None; e['samp_from_tex'] = not d[2]
|
||||
binds.append(e)
|
||||
binds.sort(key=lambda b: b['binding'])
|
||||
inputs = sorted(deco[v][DEC_LOCATION] for v, (_, sc) in var.items() if sc == SC_INPUT and DEC_LOCATION in deco[v] and DEC_BUILTIN not in deco[v])
|
||||
outputs = sorted(deco[v][DEC_LOCATION] for v, (_, sc) in var.items() if sc == SC_OUTPUT and DEC_LOCATION in deco[v] and DEC_BUILTIN not in deco[v])
|
||||
return binds, inputs, outputs
|
||||
|
||||
def drv_reads(words, binds):
|
||||
"""对驱动段 c0 / c2 的访问:OpAccessChain(var, 0, 常量 vec4 下标, 常量分量) → 字节偏移;非常量 → 动态 | accesses to driver segments c0 / c2"""
|
||||
consts, out = {}, {}
|
||||
for o, op, a in spv_insts(words):
|
||||
if op == 43 and len(a) == 3: consts[a[1]] = a[2]
|
||||
drv = {b['var']: b['bank'] for b in binds if b['kind'] == 'drvcb'}
|
||||
for o, op, a in spv_insts(words):
|
||||
if op in (65, 66) and len(a) >= 3 and a[2] in drv:
|
||||
d = out.setdefault(str(drv[a[2]]), {'offsets': set(), 'dynamic': False})
|
||||
idx = a[3:]
|
||||
if len(idx) >= 2 and all(i in consts for i in idx[:3]): d['offsets'].add(consts[idx[1]] * 16 + (consts[idx[2]] * 4 if len(idx) > 2 else 0))
|
||||
else: d['dynamic'] = True
|
||||
return {k: {'offsets': sorted(v['offsets']), 'dynamic': v['dynamic']} for k, v in out.items()}
|
||||
|
||||
def set_rewrite(words, stage):
|
||||
"""组号按阶段改写;去掉 Ryujinx 无条件声明、实际没用到的能力(Float64 / Int64 / 像素互锁 / 绘制参数),免得驱动按缺特性拒收
|
||||
Rewrite set numbers per stage; drop capabilities Ryujinx declares unconditionally but never uses (Float64 / Int64 / pixel interlock / draw parameters), so drivers lacking the feature do not reject the module"""
|
||||
s = SET_OF[stage]; used = set(); keep = []
|
||||
for o, op, a in spv_insts(words):
|
||||
if op == 22 and a[1] == 64: used.add(10) # OpTypeFloat 64 → Float64
|
||||
if op == 21 and a[1] == 64: used.add(11) # OpTypeInt 64 → Int64
|
||||
if op in (5364, 5365): used.add(5378) # Begin / EndInvocationInterlockEXT
|
||||
if op == OP_DECORATE and len(a) == 3 and a[1] == DEC_BUILTIN and a[2] in (4424, 4425, 4426): used.add(4427) # BaseVertex / BaseInstance / DrawIndex
|
||||
drop = {10, 11, 5378, 4427} - used
|
||||
have = {a[0] for o, op, a in spv_insts(words) if op == 17}
|
||||
unk = any(op == OP_TYPE_IMAGE and a[6] == 2 and a[7] == 0 for o, op, a in spv_insts(words)) # 无格式存储图像 | storage image with Unknown format
|
||||
add = [c for c in (55, 56) if unk and c not in have] # Storage Image Read / WriteWithoutFormat(Adreno 两个特性都有 | Adreno has both features)
|
||||
for o, op, a in spv_insts(words):
|
||||
if op == 17 and add:
|
||||
for c in add: keep.extend([2 << 16 | 17, c])
|
||||
add = []
|
||||
ins = list(words[o:o + 1 + len(a)])
|
||||
if op == 17 and a[0] in drop: continue
|
||||
if op == 10 and spv_str(a) == 'SPV_EXT_fragment_shader_interlock' and 5378 in drop: continue
|
||||
if op == 16 and a[1] in (5366, 5367, 5368, 5369, 5370, 5371) and 5378 in drop: continue # 互锁执行模式 | interlock execution modes
|
||||
if op == OP_DECORATE and len(a) == 3 and a[1] == DEC_SET: ins[3] = s
|
||||
keep.extend(ins)
|
||||
return list(words[:5]) + keep
|
||||
|
||||
# 翻译器对每个着色器都声明 GroupNonUniform{Vote,Ballot,Shuffle}(cap 62/64/65),实际只有少数 ps / cs 用到;
|
||||
# Adreno 的 subgroup 只支持 fragment / compute,顶点着色器带着这些声明会被拒,所以没用到 subgroup 指令 / 内建量的就把声明去掉
|
||||
# The translator declares GroupNonUniform{Vote,Ballot,Shuffle} (cap 62/64/65) on every shader but only a few ps / cs use them;
|
||||
# Adreno supports subgroups only in fragment / compute and a vertex shader carrying them is rejected, so drop the declarations when no subgroup instruction / builtin is used
|
||||
SUBGROUP_CAPS = set(range(61, 69))
|
||||
SUBGROUP_BUILTINS = {36, 37, 38, 39, 40, 41, 4416, 4417, 4418, 4419, 4420}
|
||||
def strip_subgroup(words):
|
||||
used = False
|
||||
for o, op, a in spv_insts(words):
|
||||
if 333 <= op <= 366 or op in (4421, 4422, 4428, 4429, 4430, 4431, 4432) or \
|
||||
(op == 71 and len(a) >= 3 and a[1] == DEC_BUILTIN and a[2] in SUBGROUP_BUILTINS): used = True; break
|
||||
if used: return words
|
||||
keep = [x for o, op, a in spv_insts(words) for x in words[o:o + (words[o] >> 16)] if not (op == 17 and a[0] in SUBGROUP_CAPS)]
|
||||
return list(words[:5]) + keep
|
||||
|
||||
def finish(key, w, j, c1, name, k):
|
||||
if j['stage'] not in SET_OF: return 'skip stage ' + j['stage'], None # 外壳 / 域各 1 个,Metal 回放层同样不用 | one hull / one domain shader; the Metal replay does not use them either
|
||||
spv = os.path.join(w, key + '.spv')
|
||||
if not os.path.exists(spv): return 'no spv', None
|
||||
res = json.load(open(os.path.join(w, key + '.res.json')))
|
||||
data = open(spv, 'rb').read(); words = list(struct.unpack(f'<{len(data) // 4}I', data))
|
||||
if words[0] != 0x07230203: return 'bad magic', None
|
||||
binds, inputs, outputs = reflect_spv(key, j['stage'], words, res)
|
||||
words = set_rewrite(words, j['stage'])
|
||||
words = strip_subgroup(words)
|
||||
open(os.path.join(out, key + '.spv'), 'wb').write(struct.pack(f'<{len(words)}I', *words))
|
||||
caps = sorted({a[0] for o, op, a in spv_insts(words) if op == 17})
|
||||
exts = sorted({spv_str(a) for o, op, a in spv_insts(words) if op == 10})
|
||||
refl = {'key': key, 'stage': j['stage'], 'set': SET_OF[j['stage']], 'source': f'{name}#{k}', 'c1': c1.hex(),
|
||||
'local': j.get('local'), 'shared': j.get('shared', 0), 'notes': res['notes'] + (['pc_missing'] if j.get('pc_missing') else []),
|
||||
'bindings': [{x: v for x, v in b.items() if x not in ('var', 'set')} for b in binds], 'inputs': inputs, 'outputs': outputs,
|
||||
'sb_align': res.get('sb_align', 16), 'frag_out_map': res.get('frag_out_map'), 'uses_frag_coord': res.get('uses_frag_coord'),
|
||||
'drv_reads': drv_reads(words, binds), 'caps': caps, 'exts': exts}
|
||||
bad = [b for b in binds if b['kind'] == '?' or b['vk_type'] is None or b['count'] != 1 or
|
||||
(b['kind'] in ('cbuf', 'samp', 'samp_tex', 'tex', 'img', 'tbuf', 'sbuf', 'ubo_ptr') and b.get('reg') is None)]
|
||||
if bad: refl['unresolved'] = [b['name'] for b in bad]
|
||||
json.dump(refl, open(os.path.join(out, key + '.vk.json'), 'w'), ensure_ascii=False, indent=1)
|
||||
if SPIRV_VAL:
|
||||
r = subprocess.run([SPIRV_VAL, '--target-env', 'vulkan1.1', os.path.join(out, key + '.spv')], capture_output=True, text=True)
|
||||
if r.returncode: return 'spirv-val: ' + (r.stdout + r.stderr).strip().splitlines()[0][:140], refl
|
||||
return ('unresolved' if bad else 'ok'), refl
|
||||
|
||||
# ---- 设备端运行时缓存(nvn_vk.c 的 RHeader / RBinding 布局) | on-device runtime cache (RHeader / RBinding layout of nvn_vk.c) ----
|
||||
STAGE_NO = {'vs': 0, 'ps': 1, 'cs': 5}
|
||||
# 资源种类码 | resource kind codes: 1 support 2 uniform 3 storage 4 texture 6 image 7 c1 8 driver table 9 uniform via storage 10 texel buffer
|
||||
KIND_NO = {'support': 1, 'cbuf': 2, 'sbuf': 3, 'tex': 4, 'img': 6, 'c1': 7, 'drvcb': 8, 'ubo_ptr': 9, 'tbuf': 10}
|
||||
# 计数报告内核(nvn_builtin.h 的 Vulkan 版):u64 用 uvec2 进位算,免 Int64 | counter-report kernels (Vulkan form of nvn_builtin.h): u64 as uvec2 with carry, no Int64
|
||||
BUILTIN = {'d0f769bb916bbba9': (0x1df10e8, 'ST(LD(id * 4u));'),
|
||||
'16479cc6d75c2b28': (0x1df1a94, 'ST(LD(id * 4u + 2u));'),
|
||||
'0687e2ef95133577': (0x1df2440, 'ST(SUB(LD(id * 8u + 4u), LD(id * 8u)));'),
|
||||
'4df5909e6dabee05': (0x1df2dec, 'ST(SUB(LD(id * 8u + 6u), LD(id * 8u + 2u)));')}
|
||||
BUILTIN_GLSL = """#version 450
|
||||
layout(local_size_x = 32) in;
|
||||
layout(set = 0, binding = 0) uniform U { uint n; } u;
|
||||
layout(set = 0, binding = 1) readonly buffer S { uint s[]; };
|
||||
layout(set = 0, binding = 2) writeonly buffer D { uint d[]; };
|
||||
#define LD(w) uvec2(s[w], s[(w) + 1u])
|
||||
#define ST(v) { uvec2 v_ = v; d[id * 2u] = v_.x; d[id * 2u + 1u] = v_.y; }
|
||||
uvec2 SUB(uvec2 a, uvec2 b) { uint borrow; uint lo = usubBorrow(a.x, b.x, borrow); return uvec2(lo, a.y - b.y - borrow); }
|
||||
void main() { uint id = (gl_WorkGroupID.x << 5) + gl_LocalInvocationID.x; if (id >= u.n) return; BODY }
|
||||
"""
|
||||
|
||||
def vkmeta(refl, spv_size):
|
||||
st = STAGE_NO[refl['stage']]; bs = refl['bindings']
|
||||
attrs = [(l, 0) for l in refl['inputs']] if refl['stage'] == 'vs' else []
|
||||
c1 = bytes.fromhex(refl['c1']).rstrip(b'\0')
|
||||
c1 += bytes(-len(c1) % 4)
|
||||
caps = refl['caps']; local = refl.get('local') or [0, 0, 0]
|
||||
fout = refl.get('frag_out_map'); fout = 0 if fout is None else fout
|
||||
if len(bs) > 64 or len(attrs) > 32 or len(caps) > 32 or len(c1) > 4096: raise ValueError(f"{refl['key']} 超出 vkmeta 上限")
|
||||
h = struct.pack('<11I', 0x4d4b5644, 1, st, len(bs), len(attrs), len(c1), len(caps), *local[:3], fout) + struct.pack('<I', spv_size)
|
||||
for b in bs:
|
||||
k = KIND_NO[b['kind']]
|
||||
slot = 0 if k in (1, 7) else b['bank'] if k == 8 else b['reg']
|
||||
samp = b['samp'] if k == 4 and b.get('samp') is not None else -1
|
||||
# 位 0 可写;位 1 着色器偏移相对 base & -64(翻译器实际答的对齐),宿主可下对齐绑定 | bit 0 writable; bit 1 shader offsets are relative to base & -64 (the alignment the translator actually used), so the host may bind aligned down
|
||||
flags = (int(bool(b.get('rw'))) | (2 if refl.get('sb_align', 16) == 64 else 0)) if k == 3 else 0
|
||||
h += struct.pack('<4I2i2I', SET_OF[refl['stage']], b['binding'], b['vk_type'], k, slot, samp, 1, flags)
|
||||
for a in attrs: h += struct.pack('<2I', *a)
|
||||
h += struct.pack(f'<{len(caps)}I', *caps) + c1
|
||||
return h
|
||||
|
||||
def emit_runtime(entries):
|
||||
"""entries: [(键, 控制段 0x880 字节, 反射, SPIR-V 字节)] → <out>/rt | entries: [(key, 0x880-byte control segment, reflection, SPIR-V bytes)] → <out>/rt"""
|
||||
rt = os.path.join(out, 'rt'); os.makedirs(rt, exist_ok=True)
|
||||
idx = [struct.pack('<3I', 0x494b5644, 1, len(entries))]
|
||||
for key, ctl, refl, spv in entries:
|
||||
assert len(ctl) == 0x880 and len(key) == 16
|
||||
words = strip_subgroup(list(struct.unpack(f'<{len(spv) // 4}I', spv))) # PACK_ONLY 读的旧产物也要剔 | old outputs read by PACK_ONLY need it too
|
||||
spv = struct.pack(f'<{len(words)}I', *words); refl = dict(refl, caps=sorted({a[0] for o, op, a in spv_insts(words) if op == 17}))
|
||||
idx.append(key.encode() + struct.pack('<I', STAGE_NO[refl['stage']]) + ctl)
|
||||
open(os.path.join(rt, key + '.vkmeta'), 'wb').write(vkmeta(refl, len(spv)))
|
||||
open(os.path.join(rt, key + '.spv.gz'), 'wb').write(gzip.compress(spv, 9, mtime=0))
|
||||
open(os.path.join(rt, 'shader_index.bin'), 'wb').write(b''.join(idx))
|
||||
print(f'运行时缓存:{len(entries)} 条 → {rt}')
|
||||
|
||||
def builtin_entries(mi):
|
||||
glslc = os.environ.get('GLSLC')
|
||||
if not glslc: print('【黄】没给 GLSLC,跳过 4 个内嵌计数报告内核'); return []
|
||||
res = []
|
||||
for key, (o, body) in BUILTIN.items():
|
||||
ctl = mi[o:o + 0x880]
|
||||
if hashlib.sha256(ctl).hexdigest()[:16] != key: sys.exit(f'【红】main @{o:#x} 控制段哈希与内嵌内核键 {key} 不符')
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
src = os.path.join(t, 'k.comp'); open(src, 'w').write(BUILTIN_GLSL.replace('BODY', body))
|
||||
r = subprocess.run([glslc, '--target-env=vulkan1.1', '-O', src, '-o', os.path.join(t, 'k.spv')], capture_output=True, text=True)
|
||||
if r.returncode: sys.exit('【红】内嵌内核编译失败:' + r.stderr)
|
||||
spv = open(os.path.join(t, 'k.spv'), 'rb').read()
|
||||
refl = {'key': key, 'stage': 'cs', 'c1': '', 'local': [32, 1, 1], 'inputs': [], 'caps': [1], 'frag_out_map': 0,
|
||||
'bindings': [{'binding': 0, 'vk_type': 6, 'kind': 'cbuf', 'reg': 0},
|
||||
{'binding': 1, 'vk_type': 7, 'kind': 'sbuf', 'reg': 0, 'rw': False},
|
||||
{'binding': 2, 'vk_type': 7, 'kind': 'sbuf', 'reg': 1, 'rw': True}]}
|
||||
res.append((key, ctl, refl, spv))
|
||||
return res
|
||||
|
||||
def main():
|
||||
keys = sorted(want) if want else sorted(loc)
|
||||
NJ = int(os.environ.get('J', '8'))
|
||||
os.makedirs(out, exist_ok=True)
|
||||
w = tempfile.mkdtemp(prefix='dmsh_vk_', dir=os.environ.get('WORK'))
|
||||
packs, jobs, c1s, ctls = {}, {}, {}, {}
|
||||
pack_only = os.environ.get('PACK_ONLY') == '1'
|
||||
for key in keys:
|
||||
name, k = loc[key]
|
||||
if name.startswith('main.rodata@'):
|
||||
if 'main' not in packs:
|
||||
sys.path.insert(0, os.path.join(HERE, '../../verify')); import nsoimg
|
||||
packs['main'] = nsoimg.load(MAIN)
|
||||
rec = main_rec(packs['main'], k)
|
||||
else:
|
||||
if name not in packs: packs[name] = records(open(os.path.join(dm_dir, name), 'rb').read())
|
||||
rec = packs[name][k]
|
||||
ci = rec.find(bytes.fromhex('34127698'))
|
||||
if hashlib.sha256(rec[ci:ci + 0x880]).hexdigest()[:16] != key: sys.exit(f'【红】{name}#{k} 控制段哈希与键 {key} 不符')
|
||||
ctls[key] = rec[ci:ci + 0x880]
|
||||
if not pack_only: jobs[key], c1s[key] = job_for(key, name, rec, w)
|
||||
if 'main' not in packs and os.environ.get('GLSLC'):
|
||||
sys.path.insert(0, os.path.join(HERE, '../../verify')); import nsoimg
|
||||
packs['main'] = nsoimg.load(MAIN)
|
||||
if pack_only:
|
||||
shutil.rmtree(w, ignore_errors=True)
|
||||
st = {r['key']: r['st'] for r in json.load(open(os.path.join(out, '_vk_build.json')))}
|
||||
ents = [(k, ctls[k], json.load(open(os.path.join(out, k + '.vk.json'))), open(os.path.join(out, k + '.spv'), 'rb').read())
|
||||
for k in keys if st.get(k) == 'ok']
|
||||
emit_runtime(ents + builtin_entries(packs.get('main', b''))); return
|
||||
chunks = [c for c in (keys[i::NJ] for i in range(NJ)) if c]
|
||||
def xl(ch):
|
||||
jp = os.path.join(w, f'job_{ch[0]}.json'); json.dump([jobs[k] for k in ch], open(jp, 'w'))
|
||||
return subprocess.run([XLATE, jp, w], capture_output=True, text=True)
|
||||
with cf.ThreadPoolExecutor(NJ) as ex: xr = list(ex.map(xl, chunks))
|
||||
xerr = {}
|
||||
for r in xr:
|
||||
for ln in r.stderr.splitlines():
|
||||
m = re.match(r'【红】(\w+):(.*)', ln)
|
||||
if m: xerr[m.group(1)] = m.group(2)[:160]
|
||||
def fin(key):
|
||||
if key in xerr: return key, 'xlate: ' + xerr[key], None
|
||||
st, refl = finish(key, w, jobs[key], c1s[key], *loc[key])
|
||||
return key, st, refl
|
||||
with cf.ThreadPoolExecutor(NJ) as ex: res = list(ex.map(fin, keys))
|
||||
shutil.rmtree(w, ignore_errors=True)
|
||||
st = collections.Counter(r[1].split(':')[0] for r in res)
|
||||
print(f'着色器 {len(res)}:' + ','.join(f'{k} {v}' for k, v in st.most_common()))
|
||||
for e, n in collections.Counter(r[1] for r in res if r[1] != 'ok').most_common(12): print(f' {n:5d} {e}')
|
||||
ok = [r[2] for r in res if r[2]]
|
||||
for e, n in collections.Counter(u for x in ok for u in x.get('unresolved', [])).most_common(8): print(f' 未解绑定 {n:5d} {e}')
|
||||
for e, n in collections.Counter(c for x in ok for c in x['caps']).most_common(): print(f' cap {e}: {n}')
|
||||
for e, n in collections.Counter(c for x in ok for c in x['exts']).most_common(): print(f' ext {e}: {n}')
|
||||
dr = collections.Counter()
|
||||
for x in ok:
|
||||
for bank, d in x['drv_reads'].items():
|
||||
dr[f'c{bank} dyn'] += d['dynamic']
|
||||
for o in d['offsets']: dr[f'c{bank}+{o:#x}'] += 1
|
||||
print('驱动段读取(前 20):', ', '.join(f'{k}×{v}' for k, v in dr.most_common(20)))
|
||||
json.dump([{'key': r[0], 'st': r[1]} for r in res], open(os.path.join(out, '_vk_build.json'), 'w'), ensure_ascii=False)
|
||||
emit_runtime([(r[0], ctls[r[0]], r[2], open(os.path.join(out, r[0] + '.spv'), 'rb').read()) for r in res if r[1] == 'ok']
|
||||
+ builtin_entries(packs.get('main', b'')))
|
||||
|
||||
if __name__ == '__main__': main()
|
||||
@@ -93,6 +93,10 @@ static class SwshXlate
|
||||
false /* 不做 Y 取反 | no Y flip */, true /* 原点左上 | origin upper-left */, false);
|
||||
}
|
||||
public bool QueryHostSupportsTextureShadowLod() => true;
|
||||
// 作业 sb_align:宿主存储缓冲偏移对齐(Adreno 64)。大于 NVN 的 16 时,着色器按 base & -sb_align 求偏移,宿主下对齐绑定、不再拷贝
|
||||
// Job sb_align: host storage buffer offset alignment (Adreno 64). Above NVN's 16, shaders take offsets from base & -sb_align, so the host binds aligned down without copying
|
||||
public int QueryHostStorageBufferOffsetAlignment() => _job["sb_align"] is JsonNode n ? (int)n : 16;
|
||||
public bool QueryHasUnalignedStorageBuffer() => QueryHostStorageBufferOffsetAlignment() > 16;
|
||||
// 作业 reduced = true:放宽精度——翻译器只给强制精确的运算打 NoContraction(缺省全部打:保持 Maxwell 分开舍入的逐位结果,代价是 MSL 里大量禁优化的 spvFMul 等)
|
||||
// Job reduced = true: relaxed precision - the translator marks NoContraction only on operations that must be exact (the default marks all: keeps the bit-exact results of Maxwell's separate rounding, at the cost of many optimization-disabled spvFMul etc. in the MSL)
|
||||
public bool QueryHostReducedPrecision() => _job["reduced"] is JsonNode n && (bool)n;
|
||||
@@ -126,7 +130,7 @@ static class SwshXlate
|
||||
{
|
||||
["key"] = key, ["stage"] = (string)job["stage"], ["notes"] = new JsonArray(acc.Notes.ConvertAll(n => (JsonNode)n).ToArray()),
|
||||
["cbufs"] = new JsonArray(), ["sbufs"] = new JsonArray(), ["textures"] = new JsonArray(), ["images"] = new JsonArray(),
|
||||
["uses_frag_coord"] = p.Info.UsesFragCoord, ["frag_out_map"] = p.Info.FragmentOutputMap,
|
||||
["sb_align"] = acc.QueryHostStorageBufferOffsetAlignment(), ["uses_frag_coord"] = p.Info.UsesFragCoord, ["frag_out_map"] = p.Info.FragmentOutputMap,
|
||||
};
|
||||
foreach (var b in p.Info.CBuffers) res["cbufs"].AsArray().Add(new JsonObject { ["binding"] = b.Binding, ["slot"] = b.Slot });
|
||||
foreach (var b in p.Info.SBuffers) res["sbufs"].AsArray().Add(new JsonObject { ["binding"] = b.Binding, ["slot"] = b.Slot, ["cb_slot"] = b.SbCbSlot, ["cb_offset"] = b.SbCbOffset, ["flags"] = (int)b.Flags });
|
||||
|
||||
Reference in New Issue
Block a user