mirror of
https://github.com/seedds/nxnative.git
synced 2026-11-23 11:39:42 -10:00
vulkan/shaders: repair RenderDragon bone inputs before translation
Trace Minecraft 1.26.62's remaining native vertex layouts and capability writes. Every affected a_indices input binds R16_UINT; deferred layouts copy the legacy format, while the debug and chunk paths have no affected bone input. Record the construction and format mappings in the game note. Repair the material's signed scalar input in SPIR-V before translation. Load unsigned values and bitcast them under the original signed result IDs so high-bit indices widen correctly and signed consumers remain intact. Keep the original shader keys and remove the Metal variant and selector. Build all 1,828 Mac shaders and validate the 133 repaired modules. Pass 55 focused tests and Metal-validation readback for 0x8000 and 0xffff on Apple M6. Rebuild the host and refresh the signed Mac app. Gameplay was skipped at the user's request; iOS remains untested. Existing ForwardPBR resource limits and unrelated Python lint findings are unchanged. Preserve the viewport lowering added on main; all 51 Vulkan command GPU checks pass, and every Minecraft SPIR-V and selected Metal source matches the validated build after rebasing. Follow up the RenderDragon support from PR #1652. Co-authored-by: Aoba_d1snet <[email protected]>
This commit is contained in:
1 parent
ee998ae6d7
commit
b526a50b85
7 files changed
+186
-74
No files matched your search
@@ -19,6 +19,16 @@ The Mac brings up the title panorama, the first-run dialog and a local world. Pr
|
||||
- [RenderDragon's unsigned bone indices](../../../docs/reference/rendering.md#renderdragons-unsigned-bone-indices).
|
||||
- [Distributing branch hops between patch areas](../../../docs/reference/rewriter.md#distributing-branch-hops-between-patch-areas).
|
||||
|
||||
## Bone-index layout
|
||||
|
||||
Resolved on main build `84306c1f3543e39becef959079766644` (1.26.62). All 133 affected shaders have a scalar signed `a_indices` input, mapped by their BGFX attribute IDs to bone semantic 8. The legacy layout builder (`main+0xe4299a0`) constructs one non-normalized component for that field. Its type selector (`+0xe513bfc`) uses a cached capability initialized from context byte `+0x28`, which the constructor (`+0xe51551c`) sets to 1. The singleton's direct and GOT users contain no subsequent capability writer or setter-call escape; the guarded cache has one initialization store. Engine type 4 maps to backend type 3 in `+0xe815260`, then to `VK_FORMAT_R16_UINT` in both Vulkan pipeline format tables.
|
||||
|
||||
The other layout paths were traced before replacing the Metal variant. Three deferred callbacks copy the legacy builder's layout unchanged. The remaining debug callback uses the fixed `Debug/ImGui` material, whose inputs contain no bone index. Chunk layouts come from `+0x54d7590` through `+0xe8f7680`: their nine packed descriptors have semantics 0, 4, 10, 11, 12, 1, 2, 14 and 13, and their eight chunk materials have no bone-index inputs in any of 260 Vulkan vertex records. Mask enumeration, descriptor merging and the final six-byte layout copy preserve those semantics. Neither native path introduces an affected bone-index binding.
|
||||
|
||||
The [shader repair](../../../docs/reference/rendering.md#renderdragons-unsigned-bone-indices) therefore corrects the unsigned input before translation and keeps the original signed consumers. No per-build addresses enter the repair. SPIR-V validation covers all 133 repaired modules; synthetic cases cover shared signed pointer types, repeated loads and existing unsigned declarations. The Mac GPU test checks unsigned widening at `0x8000` and `0xffff`. Gameplay was not repeated for this change at the user's request.
|
||||
|
||||
## Open
|
||||
|
||||
Online services and graphics modes beyond the default renderer remain unverified. Clear rectangles smaller than an attachment still report unsupported operations.
|
||||
|
||||
The complete shader-table load reports 198 ForwardPBR shader rows with more than the host's 24 resource entries. The rows are unchanged by the bone-index repair; this existing limit remains separate from the default-renderer gameplay result.
|
||||
@@ -106,20 +106,13 @@ static void check_bone_index(uint16_t index) {
|
||||
NSError *err = nil;
|
||||
id<MTLLibrary> lib = [g_dev newLibraryWithSource:msl options:nil error:&err];
|
||||
assert(lib);
|
||||
shinfo info = {.bone_index = 0};
|
||||
struct VkShaderModule_T vert = {.si = &info, .fn_u = [lib newFunctionWithName:@"bone"]};
|
||||
struct VkShaderModule_T vert = {.fn = [lib newFunctionWithName:@"bone"]};
|
||||
struct VkShaderModule_T frag = {.fn = [lib newFunctionWithName:@"result"]};
|
||||
VkPipelineShaderStageCreateInfo stages[] = {{.stage = VK_SHADER_STAGE_VERTEX_BIT, .module = &vert}, {.stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = &frag}};
|
||||
VkVertexInputAttributeDescription attr = {0, 0, VK_FORMAT_R16_UINT, 0};
|
||||
VkVertexInputBindingDescription bind = {0, 4, VK_VERTEX_INPUT_RATE_VERTEX};
|
||||
VkPipelineVertexInputStateCreateInfo vi = {.vertexBindingDescriptionCount = 1, .pVertexBindingDescriptions = &bind,
|
||||
.vertexAttributeDescriptionCount = 1, .pVertexAttributeDescriptions = &attr};
|
||||
attr.location = 1;
|
||||
assert(vertex_function(&vert, &vi) == vert.fn);
|
||||
attr.location = 0;
|
||||
attr.format = VK_FORMAT_R16_SINT;
|
||||
assert(vertex_function(&vert, &vi) == vert.fn);
|
||||
attr.format = VK_FORMAT_R16_UINT;
|
||||
struct VkRenderPass_T rp = {.natt = 1, .ncol = 1, .depth = -1, .col = {0}, .res = {-1},
|
||||
.att = {{.fmt = VK_FORMAT_R32_UINT, .load = VK_ATTACHMENT_LOAD_OP_CLEAR, .store = VK_ATTACHMENT_STORE_OP_STORE}}};
|
||||
VkGraphicsPipelineCreateInfo gi = {.stageCount = 2, .pStages = stages, .pVertexInputState = &vi, .renderPass = &rp};
|
||||
|
||||
+70
-31
@@ -24,7 +24,7 @@
|
||||
# Table rows: key <TAB> stage (vert / frag / comp:x,y,z / geomvp:location) <TAB> resources, space-separated kind:set.binding=slot[*count]; lower-case u/b/t/s/c/p bind discrete buffers, textures, samplers and push constants;
|
||||
# upper-case U/B/T/S are argument-buffer members, with @id after the slot and count for the first element's Metal ID;
|
||||
# o maps a dynamic buffer's set.binding to an offset index, and q gives that offset buffer's Metal slot
|
||||
# a RenderDragon vertex shader with an unsigned bone-index variant vk_<key>_u adds the input location in column 5
|
||||
# RenderDragon material bone-index inputs are repaired in SPIR-V before translation; keys still identify the game's original words.
|
||||
# Usage: vk_shaders.py <SPIR-V dir | NSO>... <out dir> [--ios <dir>]
|
||||
import concurrent.futures as cf, hashlib, json, os, re, struct, subprocess, sys, tempfile
|
||||
from typing import NoReturn
|
||||
@@ -153,16 +153,65 @@ def fix_strides(words):
|
||||
if not add: return words
|
||||
return words[:at] + [w for t, s in add.items() for w in ((4 << 16) | OP_DECORATE, t, DEC_ARRAY_STRIDE, s)] + words[at:]
|
||||
|
||||
def unsigned_bone_indices(src):
|
||||
"""RenderDragon's scalar a_indices as an unsigned fetch, widened to int before the shader uses it."""
|
||||
attribute = re.search(r'\bint(\s+a_indices\s*\[\[attribute\((\d+)\)\]\];)', src)
|
||||
stage_in = re.search(r'\b(\w+)\s*\[\[stage_in\]\]', src)
|
||||
if not attribute or not stage_in: return None
|
||||
value = re.escape(stage_in[1]) + r'\.a_indices\b'
|
||||
src = src[:attribute.start()] + 'uint' + src[attribute.start() + 3:]
|
||||
variant, uses = re.subn(r'\b' + value, lambda m: f'int({m[0]})', src)
|
||||
if not uses: return None
|
||||
return attribute[2], variant
|
||||
def unsigned_bone_indices(words):
|
||||
"""Repair RenderDragon's R16_UINT bone input, preserving signed values/arithmetic after each load.
|
||||
|
||||
Its material compiler declares scalar a_indices as int. The engine's bone layout supplies an unsigned
|
||||
short (the binary trace and the other layout paths are recorded in Minecraft's game note).
|
||||
"""
|
||||
instructions, names, ints, pointers, variables, models = [], set(), {}, {}, {}, []
|
||||
locations, interface = set(), set()
|
||||
i = 5
|
||||
while i < len(words):
|
||||
n, op = words[i] >> 16, words[i] & 0xffff
|
||||
if not n: red('SPIR-V instruction length 0')
|
||||
ins = words[i:i + n]; instructions.append(ins)
|
||||
if op == 5 and struct.pack(f'<{n - 2}I', *ins[2:]).split(b'\0', 1)[0] == b'a_indices': names.add(ins[1]) # OpName
|
||||
elif op == 15: # OpEntryPoint: interfaces follow the nul-terminated entry name
|
||||
models.append(ins[1])
|
||||
end = next(j for j in range(3, n) if b'\0' in struct.pack('<I', ins[j]))
|
||||
interface.update(ins[end + 1:])
|
||||
elif op == 21: ints[ins[1]] = tuple(ins[2:]) # OpTypeInt
|
||||
elif op == 32: pointers[ins[1]] = tuple(ins[2:]) # OpTypePointer
|
||||
elif op == 59: variables[ins[2]] = (ins[1], ins[3]) # OpVariable
|
||||
elif op == OP_DECORATE and n >= 4 and ins[2] == 30: locations.add(ins[1]) # Location
|
||||
i += n
|
||||
if models != [0]: return words # vertex entry point only
|
||||
targets = {v for v in names & locations & interface if v in variables and variables[v][1] == 1
|
||||
and pointers.get(variables[v][0], ())[:1] == (1,)
|
||||
and ints.get(pointers[variables[v][0]][1]) == (32, 1)}
|
||||
if not targets: return words
|
||||
# Only direct loads occur in this asset contract. Reject a changed pointer-use shape before changing its type.
|
||||
in_function = False
|
||||
for ins in instructions:
|
||||
op = ins[0] & 0xffff
|
||||
if op == 54: in_function = True # OpFunction
|
||||
if op in (8, 317): continue # OpLine / OpNoLine contain debug literals, not input-pointer uses
|
||||
if in_function and targets.intersection(ins[1:]) and not (op == 61 and ins[3] in targets):
|
||||
red('RenderDragon a_indices input has a use other than OpLoad')
|
||||
targets &= {ins[3] for ins in instructions if ins[0] & 0xffff == 61} # ignore declared but unread inputs
|
||||
if not targets: return words
|
||||
bound = words[3]
|
||||
uint = next((t for t, shape in ints.items() if shape == (32, 0)), None)
|
||||
if uint is None: uint, bound = bound, bound + 1
|
||||
pointer = next((t for t, shape in pointers.items() if shape == (1, uint)), None)
|
||||
if pointer is None: pointer, bound = bound, bound + 1
|
||||
# Put the unsigned scalar/pointer declarations before the first integer type. Moving existing definitions
|
||||
# earlier also handles a module whose uint type was originally declared after its signed input variable.
|
||||
out, inserted = list(words[:5]), False
|
||||
for ins in instructions:
|
||||
op = ins[0] & 0xffff
|
||||
if op == 21 and not inserted:
|
||||
out += [(4 << 16) | 21, uint, 32, 0, (4 << 16) | 32, pointer, 1, uint]
|
||||
inserted = True
|
||||
if op in (21, 32) and ins[1] in (uint, pointer): continue
|
||||
if op == 59 and ins[2] in targets: ins = [ins[0], pointer, *ins[2:]]
|
||||
if op == 61 and ins[3] in targets: # OpLoad, then OpBitcast under the original signed result ID
|
||||
out += [ins[0], uint, bound, *ins[3:], (4 << 16) | 124, ins[1], ins[2], bound]
|
||||
bound += 1
|
||||
else: out += ins
|
||||
out[3] = bound
|
||||
return out
|
||||
|
||||
|
||||
def entry_args(src, key, path):
|
||||
@@ -347,6 +396,7 @@ def one(source, tmp):
|
||||
key, path, data = source
|
||||
if len(data) % 4: red(f'{path}: SPIR-V length {len(data)} is not a multiple of 4')
|
||||
words = fix_strides(list(struct.unpack(f'<{len(data) // 4}I', data)))
|
||||
if '.material.bin@' in path: words = unsigned_bone_indices(words)
|
||||
src_spv = os.path.join(tmp, key + '.in.spv')
|
||||
with open(src_spv, 'wb') as f: f.write(struct.pack(f'<{len(words)}I', *words))
|
||||
refl = json.loads(subprocess.run([SPIRV_CROSS, src_spv, '--reflect'], capture_output=True, text=True, check=True).stdout)
|
||||
@@ -355,7 +405,7 @@ def one(source, tmp):
|
||||
stage = eps[0]['mode']
|
||||
if stage == 'geom':
|
||||
location = geometry_viewport(words)
|
||||
if location is not None: return key, f'geomvp:{location}', [], [], path, ''
|
||||
if location is not None: return key, f'geomvp:{location}', [], [], path
|
||||
if stage not in ('vert', 'frag', 'comp'): return stage # skipped (main counts them)
|
||||
field = stage
|
||||
if stage == 'comp':
|
||||
@@ -495,7 +545,6 @@ def one(source, tmp):
|
||||
src = PRECISE.sub(r'precise::\1(', src)
|
||||
with open(msl, 'w') as f: f.write(src)
|
||||
msls = [msl]
|
||||
bone_index = ''
|
||||
if stage == 'frag':
|
||||
# Metal requires two outputs of the same type for the dual-source variant.
|
||||
outs = {int(i): t for t, i in re.findall(r'(\w+)\s+\w+\s+\[\[color\((\d+)\)\]\]', src)}
|
||||
@@ -503,21 +552,12 @@ def one(source, tmp):
|
||||
msl_d = os.path.join(tmp, key + '_d.metal'); msls.append(msl_d)
|
||||
with open(msl_d, 'w') as f: f.write(src.replace(f'vk_{key}', f'vk_{key}_d').replace('[[color(1)]]', '[[color(0), index(1)]]'))
|
||||
elif stage == 'vert':
|
||||
vertex_sources = [(key, src)]
|
||||
if '.material.bin@' in path and (unsigned := unsigned_bone_indices(src)):
|
||||
bone_index, variant = unsigned
|
||||
name = f'{key}_u'
|
||||
variant = variant.replace(f'vk_{key}', f'vk_{name}')
|
||||
msl_u = os.path.join(tmp, name + '.metal'); msls.append(msl_u)
|
||||
with open(msl_u, 'w') as f: f.write(variant)
|
||||
vertex_sources.append((name, variant))
|
||||
for location in instance_locations(words):
|
||||
for name, vertex_source in vertex_sources:
|
||||
variant = viewport_variant(vertex_source, name, location)
|
||||
if variant is None: continue
|
||||
msl_vp = os.path.join(tmp, f'{name}_vp{location}.metal'); msls.append(msl_vp)
|
||||
with open(msl_vp, 'w') as f: f.write(variant)
|
||||
return key, field, res, msls, path, bone_index
|
||||
variant = viewport_variant(src, key, location)
|
||||
if variant is None: continue
|
||||
msl_vp = os.path.join(tmp, f'{key}_vp{location}.metal'); msls.append(msl_vp)
|
||||
with open(msl_vp, 'w') as f: f.write(variant)
|
||||
return key, field, res, msls, path
|
||||
|
||||
def metallib(msls, out, sdk, extra):
|
||||
os.makedirs(out, exist_ok=True)
|
||||
@@ -548,15 +588,14 @@ def main():
|
||||
seen, skipped = {}, {}
|
||||
for row in rows:
|
||||
if isinstance(row, str): skipped[row] = skipped.get(row, 0) + 1; continue
|
||||
key, stage, res, msl, src, info = row
|
||||
seen[key] = (stage, res, msl, src, info)
|
||||
key, stage, res, msl, src = row
|
||||
seen[key] = (stage, res, msl, src)
|
||||
if skipped: print('[RED] skipped unsupported shader stages: ' + ', '.join(f'{k} {v}' for k, v in sorted(skipped.items())))
|
||||
viewport_suffixes = {f'_vp{v[0].split(":")[1]}.metal' for v in seen.values() if v[0].startswith('geomvp:')}
|
||||
msls = [m for v in seen.values() for m in v[2] if '_vp' not in os.path.basename(m) or any(m.endswith(s) for s in viewport_suffixes)]
|
||||
tsv = ['# Vulkan shaders (dm/gfx/tools/vk_shaders.py): key = sha256(SPIR-V)[:16], Metal function vk_<key>; stage vert/frag/comp:x,y,z/geomvp:location; resource kinds u/b/t/s/c/p and argument-buffer U/B/T/S/o/q',
|
||||
'# spirv-cross ' + ' '.join((lambda r: r.stdout + r.stderr)(subprocess.run([SPIRV_CROSS, '--revision'], capture_output=True, text=True)).split())]
|
||||
tsv += [f'{k}\t{stage}\t{" ".join(res)}\t{src}' + (f'\t{info}' if info else '')
|
||||
for k, (stage, res, _, src, info) in sorted(seen.items())]
|
||||
tsv += [f'{k}\t{stage}\t{" ".join(res)}\t{src}' for k, (stage, res, _, src) in sorted(seen.items())]
|
||||
dirs = [(os.path.join(out, 'vk'), 'macosx', [MAC_MIN_FLAG])] # the Mac host's minimum macOS, as the NVN chain's libraries (dmsh_chain.py MAC_MIN)
|
||||
# The iPhone library is compiled with -fmetal-math-mode=relaxed, as the NVN chain's (dm/ios/tools/ios_metal.py): the default fast mode lets the GPU compiler assume there is
|
||||
# no NaN / Inf, which would let it drop the NaN handling of the precise:: functions above
|
||||
|
||||
+5
-19
@@ -190,7 +190,7 @@ static id<MTLSamplerState> ab_sampler_fail(void) {
|
||||
// p is the push-constant block; U / B / T / S are members of a set's argument buffer at buffer slot `slot`, with a separate Metal ID (+ element);
|
||||
// o is a dynamic offset's index in q, and q is the slot of that offset buffer
|
||||
typedef struct { char kind; uint8_t set, slot; uint16_t count, binding, arg_id; } shres;
|
||||
typedef struct { char key[17]; int frag, comp, nres, bone_index, geom_vp; uint16_t wg[3]; shres res[24]; } shinfo; // geom_vp: location + 1, zero for shaders without viewport lowering
|
||||
typedef struct { char key[17]; int frag, comp, nres, geom_vp; uint16_t wg[3]; shres res[24]; } shinfo; // geom_vp: location + 1, zero for shaders without viewport lowering
|
||||
enum { ST_VERT, ST_FRAG, ST_COMP };
|
||||
static int is_arg(char k) { return k && strchr("UBTS", k); }
|
||||
static shinfo *g_sh; static int g_nsh;
|
||||
@@ -227,9 +227,6 @@ static void sh_load(void) {
|
||||
LOG("[vk] [RED] shader table %s: compute stage without a local size (%s)", s->key, stage); s->comp = 0;
|
||||
}
|
||||
}
|
||||
s->bone_index = -1;
|
||||
char *extra = rest ? strchr(rest, '\t') : NULL;
|
||||
if (!strcmp(stage, "vert") && extra) sscanf(extra + 1, "%d", &s->bone_index);
|
||||
if (!strncmp(stage, "geomvp:", 7)) {
|
||||
unsigned loc;
|
||||
if (sscanf(stage + 7, "%u", &loc) == 1 && loc < 32) s->geom_vp = (int)loc + 1;
|
||||
@@ -283,7 +280,7 @@ struct VkImage_T { __strong id<MTLTexture> tex; const fmt_t *f; VkFormat fmt; Vk
|
||||
int swap; }; // one of a swap chain's images: the swap chain owns it
|
||||
struct VkImageView_T { __strong id<MTLTexture> tex; VkImage img; };
|
||||
struct VkSampler_T { __strong id<MTLSamplerState> s; __strong VkSamplerMetal *ref; };
|
||||
struct VkShaderModule_T { const shinfo *si; __strong id<MTLFunction> fn, fn_d, fn_u; char key[17]; int tried_d; }; // fn_d: the dual-source variant vk_<key>_d, looked up on first use
|
||||
struct VkShaderModule_T { const shinfo *si; __strong id<MTLFunction> fn, fn_d; char key[17]; int tried_d; }; // fn_d: the dual-source variant vk_<key>_d, looked up on first use
|
||||
struct VkPipelineCache_T { int unused; };
|
||||
// A result is valid once the Metal command buffer that wrote it has completed (g_done >= ticket).
|
||||
// Timestamps use that command buffer's completion time in ns (timestampPeriod 1).
|
||||
@@ -1098,14 +1095,13 @@ VKB(vkCreateShaderModule, VkResult, VkDevice d, const VkShaderModuleCreateInfo *
|
||||
@autoreleasepool {
|
||||
if (m->si && !m->si->geom_vp && g_lib) {
|
||||
m->fn = [g_lib newFunctionWithName:[NSString stringWithFormat:@"vk_%s", m->key]];
|
||||
if (m->si->bone_index >= 0) m->fn_u = [g_lib newFunctionWithName:[NSString stringWithFormat:@"vk_%s_u", m->key]];
|
||||
}
|
||||
}
|
||||
if (!m->fn && !(m->si && m->si->geom_vp)) LOG("[vk] [RED] shader %s (%zu bytes of SPIR-V) is not in the library", m->key, ci->codeSize);
|
||||
else OLOG("CreateShaderModule %s", m->key);
|
||||
*out = m; return VK_SUCCESS;
|
||||
}
|
||||
VKB(vkDestroyShaderModule, void, VkDevice d, VkShaderModule m, const VkAllocationCallbacks *a) { (void)d; (void)a; if (m) { m->fn = m->fn_d = m->fn_u = nil; free(m); } }
|
||||
VKB(vkDestroyShaderModule, void, VkDevice d, VkShaderModule m, const VkAllocationCallbacks *a) { (void)d; (void)a; if (m) { m->fn = m->fn_d = nil; free(m); } }
|
||||
// Pipeline caches hold nothing: the game's initial data is NVIDIA's binary cache (Super Mario Galaxy's data/database/vulkan/*.cache), and Metal keeps its own
|
||||
VK(vkCreatePipelineCache, VkResult, VkDevice d, const VkPipelineCacheCreateInfo *ci, const VkAllocationCallbacks *a, VkPipelineCache *out) {
|
||||
(void)d; (void)ci; (void)a; *out = zalloc(sizeof **out); return VK_SUCCESS;
|
||||
@@ -1165,15 +1161,6 @@ static void pipe_layout_hold(VkPipeline p, VkPipelineLayout layout) {
|
||||
p->pc_size = layout->pc_size; p->nset = layout->nset;
|
||||
for (uint32_t i = 0; i < p->nset; i++) if ((p->set[i] = layout->set[i])) atomic_fetch_add(&p->set[i]->refs, 1);
|
||||
}
|
||||
static id<MTLFunction> vertex_function(VkShaderModule m, const VkPipelineVertexInputStateCreateInfo *vi) {
|
||||
if (m->fn_u && vi) {
|
||||
for (uint32_t i = 0; i < vi->vertexAttributeDescriptionCount; i++) {
|
||||
const VkVertexInputAttributeDescription *a = &vi->pVertexAttributeDescriptions[i];
|
||||
if (a->location == (uint32_t)m->si->bone_index && a->format == VK_FORMAT_R16_UINT) return m->fn_u;
|
||||
}
|
||||
}
|
||||
return m->fn;
|
||||
}
|
||||
static VkPipeline pipe_make(const VkGraphicsPipelineCreateInfo *ci) {
|
||||
VkPipeline p = zalloc(sizeof *p);
|
||||
pipe_layout_hold(p, ci->layout);
|
||||
@@ -1189,11 +1176,10 @@ static VkPipeline pipe_make(const VkGraphicsPipelineCreateInfo *ci) {
|
||||
for (uint32_t s = 0; s < ci->stageCount; s++) {
|
||||
const VkPipelineShaderStageCreateInfo *st = &ci->pStages[s]; VkShaderModule m = st->module;
|
||||
if (st->stage == VK_SHADER_STAGE_VERTEX_BIT) {
|
||||
id<MTLFunction> fn = vertex_function(m, ci->pVertexInputState);
|
||||
id<MTLFunction> fn = m->fn;
|
||||
if (geom_vp) {
|
||||
const char *suffix = fn && fn == m->fn_u ? "_u" : "";
|
||||
fn = fn && topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST && max_viewports() > 1
|
||||
? [g_lib newFunctionWithName:[NSString stringWithFormat:@"vk_%s%s_vp%d", m->key, suffix, geom_vp - 1]] : nil;
|
||||
? [g_lib newFunctionWithName:[NSString stringWithFormat:@"vk_%s_vp%d", m->key, geom_vp - 1]] : nil;
|
||||
if (!fn) LOG("[vk] [RED] geometry viewport lowering unavailable for vertex shader %s at location %d (topology %d)", m->key, geom_vp - 1, topology);
|
||||
}
|
||||
pd.vertexFunction = spec_fn(fn, st->pSpecializationInfo); p->vs = m->si;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"""Test named Vulkan detection and shader framing without game assets."""
|
||||
"""Test named Vulkan detection, shader framing and RenderDragon SPIR-V repair without game assets."""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -19,6 +21,44 @@ def bgfx(code):
|
||||
return b'VSH\x05' + struct.pack('<IH', 0, 1) + uniform + struct.pack('<I', len(code)) + code + b'\0'
|
||||
|
||||
|
||||
def bone_shader(uint='late', alias=False):
|
||||
"""The signed input shares its pointer type with another input and has two loads with signed consumers."""
|
||||
unsigned = '%uint = OpTypeInt 32 0\n' if uint != 'absent' else ''
|
||||
return '''OpCapability Shader
|
||||
OpMemoryModel Logical GLSL450
|
||||
OpEntryPoint Vertex %main "main" %bone %other %position
|
||||
OpName %bone "a_indices"
|
||||
OpName %other "other"
|
||||
OpDecorate %bone Location 1
|
||||
OpDecorate %other Location 2
|
||||
OpDecorate %position BuiltIn Position
|
||||
%void = OpTypeVoid
|
||||
%fn = OpTypeFunction %void
|
||||
%int = OpTypeInt 32 1
|
||||
''' + (unsigned if uint == 'early' else '') + '''%float = OpTypeFloat 32
|
||||
%vec4 = OpTypeVector %float 4
|
||||
%zero = OpConstant %float 0
|
||||
%one = OpConstant %float 1
|
||||
%input = OpTypePointer Input %int
|
||||
%output = OpTypePointer Output %vec4
|
||||
%bone = OpVariable %input Input
|
||||
%other = OpVariable %input Input
|
||||
%position = OpVariable %output Output
|
||||
''' + (unsigned if uint == 'late' else '%uint_input = OpTypePointer Input %uint\n' if uint == 'early' else '') + '''%main = OpFunction %void None %fn
|
||||
%entry = OpLabel
|
||||
''' + ('%alias = OpCopyObject %input %bone\n' if alias else '') + f'''%a = OpLoad %int {"%alias" if alias else "%bone"}
|
||||
%b = OpLoad %int %bone
|
||||
%c = OpLoad %int %other
|
||||
%sum = OpIAdd %int %a %b
|
||||
%result = OpISub %int %sum %c
|
||||
%x = OpConvertSToF %float %result
|
||||
%pos = OpCompositeConstruct %vec4 %x %zero %zero %one
|
||||
OpStore %position %pos
|
||||
OpReturn
|
||||
OpFunctionEnd
|
||||
'''
|
||||
|
||||
|
||||
class RenderDragon(unittest.TestCase):
|
||||
def test_payload_has_shader_header_and_exact_instruction_span(self):
|
||||
good = spirv(1)
|
||||
@@ -40,15 +80,60 @@ class RenderDragon(unittest.TestCase):
|
||||
self.assertEqual([data for _, _, data in modules], [spirv(2), spirv(1)])
|
||||
self.assertTrue(modules[1][1].startswith('/shader.material.bin@'))
|
||||
|
||||
def test_unsigned_variant_preserves_signed_uses(self):
|
||||
shader = 'struct V { int a_indices [[attribute(1)]]; }; vertex float4 f(V in [[stage_in]]) { return bones[in.a_indices]; }'
|
||||
result = vk.unsigned_bone_indices(shader)
|
||||
assert result is not None
|
||||
location, variant = result
|
||||
self.assertEqual(location, '1')
|
||||
self.assertIn('uint a_indices [[attribute(1)]]', variant)
|
||||
self.assertIn('bones[int(in.a_indices)]', variant)
|
||||
self.assertIsNone(vk.unsigned_bone_indices(shader.replace('a_indices', 'other')))
|
||||
def test_spirv_unsigned_fetch_preserves_other_inputs_and_signed_consumers(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
original, fixed = Path(d) / 'original.spv', Path(d) / 'fixed.spv'
|
||||
for uint in ('absent', 'late', 'early'):
|
||||
with self.subTest(uint=uint):
|
||||
subprocess.run(['spirv-as', '--target-env', 'vulkan1.0', '-o', str(original), '-'], input=bone_shader(uint), text=True, check=True)
|
||||
subprocess.run(['spirv-val', '--target-env', 'vulkan1.0', str(original)], check=True)
|
||||
data = original.read_bytes()
|
||||
words = list(struct.unpack(f'<{len(data) // 4}I', data))
|
||||
result = vk.unsigned_bone_indices(words)
|
||||
fixed.write_bytes(struct.pack(f'<{len(result)}I', *result))
|
||||
subprocess.run(['spirv-val', '--target-env', 'vulkan1.0', str(fixed)], check=True)
|
||||
src = subprocess.run(['spirv-dis', str(fixed)], capture_output=True, text=True, check=True).stdout
|
||||
self.assertEqual(src.count('OpLoad %uint %a_indices'), 2)
|
||||
self.assertEqual(src.count('OpBitcast %int'), 2)
|
||||
self.assertIn('OpLoad %int %other', src)
|
||||
self.assertIn('OpIAdd %int', src)
|
||||
self.assertIn('OpISub %int', src)
|
||||
self.assertEqual(vk.unsigned_bone_indices(result), result)
|
||||
|
||||
def test_material_repair_keeps_original_key_and_one_function(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
original = Path(d) / 'shader.spv'
|
||||
subprocess.run(['spirv-as', '--target-env', 'vulkan1.0', '-o', str(original), '-'], input=bone_shader(), text=True, check=True)
|
||||
data = original.read_bytes(); key = hashlib.sha256(data).hexdigest()[:16]
|
||||
row = vk.one((key, '/Actor.material.bin@0x20', data), d)
|
||||
self.assertEqual(row[:3], (key, 'vert', []))
|
||||
self.assertEqual(len(row[3]), 1)
|
||||
src = Path(row[3][0]).read_text()
|
||||
self.assertIn(f'vk_{key}(', src)
|
||||
self.assertIn('uint a_indices [[attribute(1)]]', src)
|
||||
self.assertIn('int other [[attribute(2)]]', src)
|
||||
self.assertNotIn(f'vk_{key}_u', src)
|
||||
vk.one((key, '/ordinary.vert', data), d)
|
||||
self.assertIn('int a_indices [[attribute(1)]]', Path(row[3][0]).read_text())
|
||||
|
||||
def test_changed_input_pointer_contract_is_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
original = Path(d) / 'shader.spv'
|
||||
for asm in (bone_shader(alias=True), bone_shader(alias=True).replace('OpLoad %int %bone', 'OpLoad %int %alias')):
|
||||
subprocess.run(['spirv-as', '--target-env', 'vulkan1.0', '-o', str(original), '-'], input=asm, text=True, check=True)
|
||||
data = original.read_bytes()
|
||||
with self.assertRaisesRegex(SystemExit, 'use other than OpLoad'):
|
||||
vk.unsigned_bone_indices(list(struct.unpack(f'<{len(data) // 4}I', data)))
|
||||
|
||||
def test_unread_or_builtin_input_is_unchanged(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
original = Path(d) / 'shader.spv'
|
||||
for asm in (bone_shader().replace('OpLoad %int %bone', 'OpLoad %int %other'),
|
||||
bone_shader().replace('OpDecorate %bone Location 1', 'OpDecorate %bone BuiltIn VertexIndex')):
|
||||
subprocess.run(['spirv-as', '--target-env', 'vulkan1.0', '-o', str(original), '-'], input=asm, text=True, check=True)
|
||||
subprocess.run(['spirv-val', '--target-env', 'vulkan1.0', str(original)], check=True)
|
||||
data = original.read_bytes(); words = list(struct.unpack(f'<{len(data) // 4}I', data))
|
||||
self.assertEqual(vk.unsigned_bone_indices(words), words)
|
||||
|
||||
def test_named_vulkan_has_instance_and_device_evidence(self):
|
||||
imports = {pg.RO_LOOKUP}
|
||||
|
||||
@@ -173,7 +173,7 @@ class VkShaders(unittest.TestCase):
|
||||
out = self.tmp / 'out'; out.mkdir(exist_ok=True)
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter('ignore', ResourceWarning) # the tool leaves its files to be closed at collection
|
||||
key, stage, res, msls, _, _ = translate_file(spv, str(out))
|
||||
key, stage, res, msls, _ = translate_file(spv, str(out))
|
||||
self.assertEqual(key, hashlib.sha256(spv.read_bytes()).hexdigest()[:16])
|
||||
return key, stage, res, [Path(m).read_text() for m in msls]
|
||||
|
||||
@@ -200,10 +200,9 @@ class VkShaders(unittest.TestCase):
|
||||
'%pos = OpCompositeConstruct %vec %x %zero %zero %one\nOpStore %position %pos')
|
||||
data = self.assemble(asm).read_bytes()
|
||||
key = hashlib.sha256(data).hexdigest()[:16]
|
||||
_, _, _, msls, _, info = vs.one((key, '/synthetic.material.bin@0x0', data), str(self.tmp))
|
||||
self.assertEqual(info, '2')
|
||||
self.assertEqual(len(msls), 4)
|
||||
combined = (self.tmp / f'{key}_u_vp1.metal').read_text()
|
||||
_, _, _, msls, _ = vs.one((key, '/synthetic.material.bin@0x0', data), str(self.tmp))
|
||||
self.assertEqual(len(msls), 2)
|
||||
combined = (self.tmp / f'{key}_vp1.metal').read_text()
|
||||
self.assertIn('uint a_indices [[attribute(2)]]', combined)
|
||||
self.assertIn('int(in.a_indices)', combined)
|
||||
self.assertIn('[[viewport_array_index]]', combined)
|
||||
|
||||
@@ -1901,7 +1901,7 @@ The Vulkan layer (`dm/gfx/vk/hle_vk.m`) was written for Hades. Super Mario Galax
|
||||
|
||||
- **Symptom:** Metal rejects a pipeline with `Vertex attribute a_indices(1) of type int cannot be read using MTLAttributeFormatUShort`. The title can continue drawing while an actor's pipeline is missing.
|
||||
- **Cause:** RenderDragon's skinning shaders declare a scalar `int` input which the game supplies as `R16_UINT`. The Switch driver accepts that pairing. Reading the bytes as `Short` would sign-extend values with bit 15 set.
|
||||
- **Fix:** material vertex shaders that use `a_indices` also get a variant with an unsigned stage input and an explicit conversion to `int` at its uses. The Vulkan layer chooses it only when that location is bound as `R16_UINT`. `t_vk_renderdragon` reads back 32-bit values for inputs `0x8000` and `0xffff` under Metal validation.
|
||||
- **Fix:** `vk_shaders.py` repairs the material's scalar `a_indices` input to unsigned in SPIR-V before translation. Each unsigned load feeds an `OpBitcast` under the original signed result ID, preserving the shader's signed arithmetic. The key still hashes the original game bytes. This follows the [traced engine layout contract](../../dm/games/0100D71004694000/README.md#bone-index-layout), rather than changing Vulkan vertex-format semantics. One ordinary Metal function is built per vertex shader. `t_vk_renderdragon` reads back 32-bit values for inputs `0x8000` and `0xffff` under Metal validation.
|
||||
- **Found on:** [Minecraft for Nintendo Switch](../../dm/games/0100D71004694000/README.md) 1.26.62.
|
||||
|
||||
### Vulkan triangle fans
|
||||
|
||||
Reference in new issue
Block a user