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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 25 additions & 7 deletions dm/gfx/tools/shader_split.py
Original file line number Diff line number Diff line change
Expand Up @@ -1421,15 +1421,24 @@ def program(x, at, label):
VIPER_GLSLC = b'\x91\x68\x86\x19'
VIPER_CHUNK = 0x10000

def viper_zip_member(z, info):
# PEANUTS begin(upstream-candidate): share the raw stored-member read with the ZIP padding probe.
def zip_stored_bytes(z, info):
z.fp.seek(info.header_offset); h = z.fp.read(30)
if len(h) != 30 or h[:4] != ZIP: red(f'{z.filename or "zip"}/{info.filename}: no local header at {info.header_offset:#x}')
nlen, xlen = struct.unpack_from('<HH', h, 26)
z.fp.seek(info.header_offset + 30 + nlen + xlen)
data = z.fp.read(info.compress_size)
if len(data) != info.compress_size: red(f'{info.filename}: truncated stored ZIP member')
return data
# PEANUTS end(upstream-candidate)


def viper_zip_member(d, info): # PEANUTS(upstream-candidate): its caller supplies the stored bytes.
"""A member of Star Fox's data.zip (its engine's vfs.zip.c): the central directory calls it stored, but a member whose size on disk differs from its file size is a chain of 64 KB chunks,
each a u32 length and an LZ4 block of that length, compressed against the previous chunk's output as its dictionary (a chunk whose length equals what is left is stored raw).
The CRC the directory keeps is the decoded data's, so zipfile's own read stops on it; 114,154 members, 33 GB, all check"""
import lz4.block
z.fp.seek(info.header_offset); h = z.fp.read(30)
if h[:4] != ZIP: red(f'{z.filename or "zip"}/{info.filename}: no local header at {info.header_offset:#x}')
nlen, xlen = struct.unpack_from('<HH', h, 26)
z.fp.seek(info.header_offset + 30 + nlen + xlen); d = z.fp.read(info.compress_size); u = info.file_size
u = info.file_size
out, off = bytearray(), 0
while off + 4 <= len(d) and len(out) < u:
n = struct.unpack_from('<I', d, off)[0]; off += 4; want = min(VIPER_CHUNK, u - len(out))
Expand All @@ -1443,11 +1452,20 @@ def viper_zip_member(z, info):
if zlib.crc32(out) & 0xFFFFFFFF != info.CRC: red(f'{info.filename}: CRC mismatch after the LZ4 chunks')
return bytes(out)

# PEANUTS begin(upstream-candidate): stored ZIP members can have alignment padding.
def zip_member(z, name):
"""A zip member's data: zipfile's, or viper_zip_member's for a member the directory calls stored at another size than its file size (Star Fox)"""
"""Read a standard member, a padded stored member, or a Viper LZ4 chain."""
info = z.getinfo(name)
if info.compress_type == 0 and info.compress_size != info.file_size: return viper_zip_member(z, info)
if info.compress_type == 0 and info.compress_size != info.file_size:
raw = zip_stored_bytes(z, info)
if info.compress_size > info.file_size:
prefix = memoryview(raw)[:info.file_size]
if zlib.crc32(prefix) == info.CRC:
return bytes(prefix)
return viper_zip_member(raw, info)
return z.read(name)
# PEANUTS end(upstream-candidate)


def viper_shader(d, label):
"""Star Fox's shader binaries (its engine's _vrender_shader_binary_t, one per data.zip member): the GLSLC output magic, u32 code length, u32 control length, u32 0, a 64-bit hash, then the
Expand Down
44 changes: 44 additions & 0 deletions dm/tools/tests/test_split_zip_padding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import io
import struct
import sys
import unittest
import zipfile
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'gfx/tools'))
from shader_split import zip_member


class ZipPadding(unittest.TestCase):
def stored(self, payload, stored):
stream = io.BytesIO()
with zipfile.ZipFile(stream, 'w') as archive:
archive.writestr('shader.bin', payload)
data = bytearray(stream.getvalue())
central = data.index(b'PK\x01\x02')
end = data.index(b'PK\x05\x06')
struct.pack_into('<I', data, 18, len(stored))
struct.pack_into('<I', data, central + 20, len(stored))
offset = 30 + len('shader.bin')
struct.pack_into('<I', data, end + 16, offset + len(stored))
data[offset:central] = stored
return data

def test_stored_prefix_must_match_crc(self):
payload = b'shader'
data = self.stored(payload, payload + b'\0' * 8)
with zipfile.ZipFile(io.BytesIO(data)) as archive:
self.assertEqual(zip_member(archive, 'shader.bin'), payload)
data[30 + len('shader.bin')] ^= 1
with zipfile.ZipFile(io.BytesIO(data)) as archive:
with self.assertRaisesRegex(SystemExit, 'LZ4 chunk'):
zip_member(archive, 'shader.bin')

def test_viper_chunk_fallback(self):
import lz4.block

payload = b'shader' * 64
compressed = lz4.block.compress(payload, store_size=False)
member = self.stored(payload, struct.pack('<I', len(compressed)) + compressed)
with zipfile.ZipFile(io.BytesIO(member)) as archive:
self.assertEqual(zip_member(archive, 'shader.bin'), payload)
1 change: 1 addition & 0 deletions docs/agents/symptoms.md
Original file line number Diff line number Diff line change
Expand Up @@ -1043,6 +1043,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- `vkCreateComputePipelines` returns `-13` on a module that passes `spirv-val --target-env vulkan1.3`. The compute dispatch cannot run. → [Valid compute SPIR-V rejected by Qualcomm's pipeline compiler](../reference/shaders.md#valid-compute-spir-v-rejected-by-qualcomms-pipeline-compiler)
- ground or other surfaces that pick their texture by a value the shader computes draw flat, in one placeholder colour or in tile-shaped blocks. No `[RED]` line names it, or only `has no view of shape` lines of a placeholder texture. → [Textures picked from the records of a table all read as one texture](../reference/shaders.md#textures-picked-from-the-records-of-a-table-all-read-as-one-texture)
- dashed or blocky edges, two pixels wide, along the line where a surface changes from one texture of an array to another (the border between two ground types). → [A texture array indexed per pixel draws broken edges where the index changes](../reference/shaders.md#a-texture-array-indexed-per-pixel-draws-broken-edges-where-the-index-changes)
- a stored ZIP member fails to open during shader splitting because the member's sizes differ. → [Stored ZIP shader members with trailing alignment padding](../reference/shaders.md#stored-zip-shader-members-with-trailing-alignment-padding)

## Game state

Expand Down
8 changes: 8 additions & 0 deletions docs/reference/shaders.md
Original file line number Diff line number Diff line change
Expand Up @@ -2011,3 +2011,11 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
- **Cause:** keeping the last pool and adding coarse hints does not index smaller placed ranges. This is software address translation, not a measurement of hardware GMEM cache misses.
- **Fix (opt-in experiment):** `vk_android_mesh.py cache --page-index <keys>` replaces only the generated cold hint lookup with a 4 KiB page-to-pool candidate, preserving the hot helper path, all word loads/stores and the complete search. The host tables (switch DM_VK_PIDX) are not in this tree: without them the cache keeps the exact search. Missing/partial/out-of-window pages, invalid candidates and unavailable snapshots retain exact search. Candidates are range-checked; unordered or overlapping host intervals produce no candidates. Snapshots stay immutable until all recording and submitted uses retire. The four snapshot buffers do not add frames to the queue; pressure falls back without waiting. The mesh chain includes both the shader rewrite and host header contract, so sidecars require the matching APK. The design reference is [Anka Native](https://github.com/EddizEge/AnkaNative/blob/main/CHANGELOG_ANKA_NATIVE.md) (MIT); no implementation was copied. Its in-place reuse of a recording snapshot is unsuitable for this backend's partial submissions and is not used.
- **Found on:** [Ocarina of Time](../../dm/games/0400486024DEC000/README.md), three heavy mesh modules on Adreno 830 / Qualcomm 891.14. Synthetic SPIR-V differential tests compare every output word and physical store against the original lookup, including fallback and boundary addresses; host tests cover page windows, overlap rejection and open/fence reuse under ASan/UBSan. Performance acceptance is recorded in the game note; default remains off.

<!-- PEANUTS(upstream-candidate) -->
### Stored ZIP shader members with trailing alignment padding

- **Symptom:** a stored ZIP member fails to open during shader splitting because the member's sizes differ.
- **Cause:** the stored extent includes alignment bytes beyond the declared size. A size mismatch can also signal a Viper LZ4 member.
- **Fix:** accept the declared-size prefix when its CRC matches the directory entry. Otherwise pass the stored bytes to the Viper decoder.
- **Found on:** World War Z (`010099F013898000`).