diff --git a/Makefile b/Makefile index db3683de..7feb0534 100644 --- a/Makefile +++ b/Makefile @@ -735,6 +735,12 @@ test-save-convert: $(B)/test_save_convert .PHONY: test-save-convert +# The texture pack converter (tools/hdpack_convert.py) on a synthetic game and pack (no game files needed) +test-hdpack-convert: + python3 tools/test_hdpack_convert.py + +.PHONY: test-hdpack-convert + # Save profiles (runtime/services/save_profiles.c): names, create / copy / rename / delete, the active profile and the # legacy `save` folder, on tiny fake folders in a temporary directory (no game files, no real saves) $(B)/test_save_profiles: tools/test_save_profiles.c runtime/services/save_profiles.c runtime/services/save_profiles.h runtime/services/save_convert.c runtime/services/save_convert.h runtime/services/archive.c runtime/services/archive.h diff --git a/docs/FAQ.md b/docs/FAQ.md index fadb290c..6c314dcd 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -537,6 +537,11 @@ on the start screen, or F1 in game) and restart. The tab also sets the load orde the Switch version 1.9.0 fit best; Wii U and Cemu packs need adapting, because the file formats differ. On Alpha 6 (0.6.0), a mod's `romfs` folder can be loaded with the launch option `SAVAGEWIND_ROMFS_OVERLAY=`. +Texture packs made for the game's 1.6.0 update, such as HDPacks.com's 4K pack, crash or never finish loading on +1.9.0 as they are. `python3 tools/hdpack_convert.py mods/` makes +a 1.9.0 mod of only their textures from your own game files. Packs this big also need more game memory: +`game_memory_mb = 6144` in `savagewind.ini`. The mod holds parts of your game files, so don't share it. + **Mods are other people's work.** Savage Wind doesn't check, test or support them, and isn't responsible for what they do, including if they break the game or your saves. Back up your saves before trying one. `savagewind.log` lists the mods each run loads, so a bug report with mods on first gets asked to try again with every mod off. If the bug is still diff --git a/tools/hdpack_convert.py b/tools/hdpack_convert.py new file mode 100644 index 00000000..af4da58b --- /dev/null +++ b/tools/hdpack_convert.py @@ -0,0 +1,348 @@ +#!/usr/bin/env python3 +"""Make a texture pack made for the game's 1.6.0 update into a Savage Wind mod for 1.9.0, from your own game files. + + python3 tools/hdpack_convert.py [--no-terrain] [--no-fonts] + [--copy] + + the folder with romfs/ (and the DLC's aoc1/ if you have it): the one Savage Wind uses + the pack's RomFS folder (Model/, Pack/, Terrain/, ...) + where the mod is made, for example mods/HDPack in Savage Wind's data folder; it gets a + romfs/ folder. An existing romfs/ in it is replaced. + +A texture pack made for 1.6.0 (such as HDPacks.com's 4K pack) can't be loaded on 1.9.0 as it is: next to its +textures it has 1.6.0 copies of whole packs (the title screen, the Divine Beasts, actors), Pack/Bootup.pack and a +1.6.0 ResourceSizeTable, and the game crashes or never finishes loading. This makes a mod of only its textures, on +top of your 1.9.0 files: + +- loose files (Model/*.Tex*.sbfres, UI/StockItem/..., Terrain/...) that 1.9.0 or its DLC also has: linked (hard links + on the same drive, copies otherwise or with --copy); files 1.9.0 doesn't have are left out +- Pack/*.pack: your 1.9.0 pack with only its texture files (*.Tex*.sbfres) taken from the pack's copy. The DLC's + packs (the shrines of The Master Trials and The Champions' Ballad) go under aoc/0010/. Pack/Bootup.pack is left + out (1.6.0 game data; Savage Wind patches its own) +- Font/Font_US.sbfarc: your 1.9.0 archive with the pack's fonts, except External_00.bffnt (the button icons, which + Savage Wind draws itself). --no-fonts leaves the fonts out +- System/Resource/ResourceSizeTable.product.srsizetable: your 1.9.0 table with the entries of the files that grew + made bigger: the largest of the 1.9.0 size, the pack's own table's size, and the 1.9.0 size plus what the file grew + by. The game sets aside memory by this table, and Savage Wind's own growing does not reach the files inside packs + +A pack this big needs more game memory than the game's own: set game_memory_mb = 6144 in savagewind.ini. Without it the +textures overflow the game's texture pool (walls and floors missing in shrines), and the 4K terrain (Terrain/ and +Model/Terrain.Tex*.sbfres, which make Pack/TitleBG.pack 80 -> 287 MB) crashes the title screen. --no-terrain leaves the +terrain out. Textures this big also need a GPU with enough memory. + +The mod is made from your game files: it holds parts of them (the packs) and must not be shared. Nothing is +downloaded and nothing outside /romfs is written. +""" +import os +import shutil +import struct +import sys +import zlib + +RSTB_PATH = 'System/Resource/ResourceSizeTable.product.srsizetable' +RSTB_MARGIN = 0x1000 # (room on top of what a file grew by, as the pack's own table leaves) +SKIP_DIRS = ('Pack', 'System', 'Font') # (handled on their own) + + +# ---- Yaz0 ------------------------------------------------------------------------------------------------------- + +def yaz0_size(head): + """The decompressed size of a file from its first 16 bytes (its own size when it isn't Yaz0).""" + return struct.unpack_from('>I', head, 4)[0] if head[:4] == b'Yaz0' else None + + +def yaz0_decompress(d): + if d[:4] != b'Yaz0': + return d + size, = struct.unpack_from('>I', d, 4) + out = bytearray(size) + i, o = 16, 0 + while o < size: + code = d[i] + i += 1 + for bit in range(8): + if o >= size: + break + if code & (0x80 >> bit): + out[o] = d[i] + i += 1 + o += 1 + else: + b1, b2 = d[i], d[i + 1] + i += 2 + dist = ((b1 & 0xF) << 8 | b2) + 1 + n = b1 >> 4 + if n == 0: + n = d[i] + 0x12 + i += 1 + else: + n += 2 + s = o - dist + if dist >= n: + out[o:o + n] = out[s:s + n] + else: # (overlapping: a run) + for k in range(n): + out[o + k] = out[s + k] + o += n + return bytes(out) + + +def yaz0_store(d): + """Yaz0 without compression (every byte a literal): the game reads it like any other.""" + out = bytearray(b'Yaz0' + struct.pack('>I', len(d)) + bytes(8)) + for i in range(0, len(d), 8): + chunk = d[i:i + 8] + out.append((0xFF00 >> len(chunk)) & 0xFF) + out += chunk + return bytes(out) + + +# ---- SARC (little endian, as on the Switch) ---------------------------------------------------------------------- + +def _sarc_entries(d): + if d[:4] != b'SARC' or d[6:8] != b'\xff\xfe': + raise ValueError('not a little-endian SARC archive') + hdr_len, = struct.unpack_from(' 1 and (data_off + s) % align: + align >>= 1 + blob = new.get(name, d[data_off + s:data_off + e]) + body += bytes(-(data_off + len(body)) % align) + start = len(body) + body += blob + struct.pack_into(' 0 else 0) + if want > tab[key]: + tab[key] = want + self.grown += 1 + + +# ---- the mod --------------------------------------------------------------------------------------------------- + +def head16(path): + with open(path, 'rb') as f: + return f.read(16) + + +def unpacked_size(path): + s = yaz0_size(head16(path)) + return os.path.getsize(path) if s is None else s + + +def place(src, dst, copy): + os.makedirs(os.path.dirname(dst), exist_ok=True) + if not copy: + try: + os.link(src, dst) + return + except OSError: + pass # (another drive, or no hard links there) + shutil.copyfile(src, dst) + + +def is_terrain(rel): + return rel.startswith('Terrain/') or rel.startswith('Model/Terrain.Tex') + + +def convert(game, pack, mod, terrain=True, fonts=True, copy=False, log=print): + romfs, aoc = os.path.join(game, 'romfs'), os.path.join(game, 'aoc1') + if not os.path.isfile(os.path.join(romfs, RSTB_PATH)): + raise SystemExit(f'{game}: no romfs/{RSTB_PATH} (the folder with your romfs/ and aoc1/)') + out = os.path.join(mod, 'romfs') + if os.path.isdir(out): + shutil.rmtree(out) + pack_rstb = os.path.join(pack, RSTB_PATH) + with open(os.path.join(romfs, RSTB_PATH), 'rb') as f: + game_rstb = f.read() + table = SizeTable(game_rstb, open(pack_rstb, 'rb').read() if os.path.isfile(pack_rstb) else None) + + def base_of(rel): + """(1.9.0 file, its path in the mod) for a RomFS path, from the game or its DLC; None if neither has it.""" + if os.path.isfile(os.path.join(romfs, rel)): + return os.path.join(romfs, rel), rel + if os.path.isfile(os.path.join(aoc, rel)): + return os.path.join(aoc, rel), 'aoc/0010/' + rel + return None + + # loose files + linked = left = 0 + for top in sorted(os.listdir(pack)): + if top in SKIP_DIRS or not os.path.isdir(os.path.join(pack, top)): + continue + for dp, _, fs in os.walk(os.path.join(pack, top)): + for f in sorted(fs): + src = os.path.join(dp, f) + rel = os.path.relpath(src, pack).replace(os.sep, '/') + base = base_of(rel) + if base is None or (not terrain and is_terrain(rel)): + left += 1 + continue + place(src, os.path.join(out, base[1]), copy) + table.grow(base[1], unpacked_size(src) - unpacked_size(base[0])) + linked += 1 + log(f'loose files: {linked} linked, {left} left out (not in 1.9.0{"" if terrain else ", or terrain"})') + + # packs + n_packs = n_tex = 0 + pack_dir = os.path.join(pack, 'Pack') + for f in sorted(os.listdir(pack_dir)) if os.path.isdir(pack_dir) else (): + rel = 'Pack/' + f + base = base_of(rel) + if f == 'Bootup.pack' or base is None: + continue + with open(base[0], 'rb') as fh: + a_raw = fh.read() + with open(os.path.join(pack_dir, f), 'rb') as fh: + b = sarc_files(yaz0_decompress(fh.read())) + a_arc = yaz0_decompress(a_raw) + a = sarc_files(a_arc) + new = {k: v for k, v in b.items() if k in a and a[k] != v and '.Tex' in k and k.endswith('.sbfres') and + (terrain or not k.startswith('Model/Terrain.Tex'))} + if not new: + continue + for k, v in new.items(): + table.grow(k, (yaz0_size(v[:16]) or len(v)) - (yaz0_size(a[k][:16]) or len(a[k]))) + built = sarc_replace(a_arc, new) + dst = os.path.join(out, base[1]) + os.makedirs(os.path.dirname(dst), exist_ok=True) + with open(dst, 'wb') as fh: + fh.write(built if a_raw[:4] != b'Yaz0' else yaz0_store(built)) + table.grow(base[1], len(built) - len(a_arc)) + n_packs += 1 + n_tex += len(new) + log(f'packs: {n_packs} of your 1.9.0 packs with {n_tex} of the pack\'s textures') + + # fonts + rel = 'Font/Font_US.sbfarc' + if fonts and os.path.isfile(os.path.join(pack, rel)) and os.path.isfile(os.path.join(romfs, rel)): + with open(os.path.join(romfs, rel), 'rb') as fh: + a_raw = fh.read() + a_arc = yaz0_decompress(a_raw) + a = sarc_files(a_arc) + with open(os.path.join(pack, rel), 'rb') as fh: + b = sarc_files(yaz0_decompress(fh.read())) + new = {k: v for k, v in b.items() if k in a and a[k] != v and k != 'External_00.bffnt'} + if new: + built = sarc_replace(a_arc, new) + os.makedirs(os.path.join(out, 'Font'), exist_ok=True) + with open(os.path.join(out, rel), 'wb') as fh: + fh.write(yaz0_store(built)) + table.grow(rel, len(built) - len(a_arc)) + for k, v in new.items(): + table.grow('Font/' + k, len(v) - len(a[k])) + log(f'fonts: {", ".join(sorted(new))} (External_00.bffnt kept)') + + os.makedirs(os.path.dirname(os.path.join(out, RSTB_PATH)), exist_ok=True) + with open(os.path.join(out, RSTB_PATH), 'wb') as fh: + fh.write(rstb_write(table.crc, table.names)) + log(f'ResourceSizeTable: {table.grown} entries grown') + return table.grown + + +def main(argv): + flags = {a for a in argv if a.startswith('--')} + args = [a for a in argv if not a.startswith('--')] + unknown = flags - {'--no-terrain', '--no-fonts', '--copy'} + if len(args) != 3 or unknown: + sys.exit(__doc__) + game, pack, mod = args + convert(game, pack, mod, terrain='--no-terrain' not in flags, fonts='--no-fonts' not in flags, + copy='--copy' in flags) + print(f'made {os.path.join(mod, "romfs")}. Turn it on in the Mods tab, and set game_memory_mb = 6144 in ' + 'savagewind.ini.') + + +if __name__ == '__main__': + main(sys.argv[1:]) diff --git a/tools/test_hdpack_convert.py b/tools/test_hdpack_convert.py new file mode 100644 index 00000000..ec0396aa --- /dev/null +++ b/tools/test_hdpack_convert.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +"""Tests tools/hdpack_convert.py on a synthetic game and pack (no game files needed): small SARC archives, Yaz0 files +and a ResourceSizeTable made here, laid out like a 1.9.0 romfs/ + aoc1/ and a 1.6.0 texture pack. + + python3 tools/test_hdpack_convert.py + +One PASS / FAIL line per check; the exit status is 1 when anything failed. +""" +import os +import struct +import sys +import tempfile +import zlib + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import hdpack_convert as hc # noqa: E402 + +failed = 0 + + +def check(name, ok): + global failed + print(('PASS ' if ok else 'FAIL ') + name) + failed += not ok + + +def sarc(files, align=0x80): + """A little-endian SARC of {name: bytes}, names sorted by hash as the game's are, each file aligned.""" + def h(n): + v = 0 + for c in n.encode(): + v = (v * 0x65 + c) & 0xFFFFFFFF + return v + items = sorted(files.items(), key=lambda kv: h(kv[0])) + names = b'' + offs = [] + for n, _ in items: + offs.append(len(names) // 4) + names += n.encode() + b'\0' + names += bytes(-len(names) % 4) + nodes = b'' + data = b'' + for (n, d), o in zip(items, offs): + data += bytes(-len(data) % align) + nodes += struct.pack('I', 14) + bytes(8) + bytes([0b11000000]) + b'ab' + bytes([0xA0, 0x01]) + check('Yaz0 back-references (overlapping run)', hc.yaz0_decompress(packed) == b'ab' * 7) + arc = sarc({'a.bin': b'x' * 3, 'b.bin': b'y' * 5}) + rep = hc.sarc_replace(arc, {'a.bin': b'z' * 300}) + check('SARC replace keeps the other files', hc.sarc_files(rep) == {'a.bin': b'z' * 300, 'b.bin': b'y' * 5}) + off, _, ents = hc._sarc_entries(rep) + check('SARC replace keeps each file\'s alignment', all((off + s) % 0x80 == 0 for _, _, s, _ in ents)) + check('ResourceSizeTable names', (hc.rstb_name('Model/X.Tex1.sbfres'), hc.rstb_name('Pack/X.pack'), + hc.rstb_name('Foo/x.sarc'), hc.rstb_name('aoc/0010/Pack/X.pack')) == + ('Model/X.Tex1.bfres', 'Pack/X.pack', 'Foo/x.sarc', 'Aoc/0010/Pack/X.pack')) + + with tempfile.TemporaryDirectory() as t: + game, pack = make(t) + mod = os.path.join(t, 'mods', 'HD') + os.makedirs(os.path.join(mod, 'romfs', 'stale')) + before = tree(t) + hc.convert(game, pack, mod, log=lambda s: None) + out = os.path.join(mod, 'romfs') + files = tree(out) + check('only the mod\'s romfs/ is written', [p for p in tree(t) if p not in before and + not p.startswith('mods/HD/romfs/')] == []) + check('an old romfs/ in the mod is replaced', not any(p.startswith('stale') for p in files)) + check('the mod\'s files', files == sorted([ + 'Font/Font_US.sbfarc', 'Model/Rock.Tex1.sbfres', 'Model/Terrain.Tex1.sbfres', 'Pack/Dungeon000.pack', + 'Terrain/A/MainField.tscb', hc.RSTB_PATH, 'aoc/0010/Pack/RemainsElectric.pack'])) + check('Bootup.pack and files 1.9.0 hasn\'t got are left out', + 'Pack/Bootup.pack' not in files and 'Model/OnlyIn160.Tex1.sbfres' not in files) + d = hc.sarc_files(open(os.path.join(out, 'Pack/Dungeon000.pack'), 'rb').read()) + check('a pack: the pack\'s texture, 1.9.0\'s other files', + d['Model/DgnMrgPrt_Dungeon000.Tex1.sbfres'] == tex(14, 4000) and + d['Actor/ActorLink/Dungeon000.bxml'] == b'1.9.0 actor') + d = hc.sarc_files(open(os.path.join(out, 'aoc/0010/Pack/RemainsElectric.pack'), 'rb').read()) + check('a DLC pack goes under aoc/0010/', d['Model/Remains.Tex1.sbfres'] == tex(15, 6400)) + f = hc.sarc_files(hc.yaz0_decompress(open(os.path.join(out, 'Font/Font_US.sbfarc'), 'rb').read())) + check('fonts: the pack\'s, External_00.bffnt kept', f == {'Normal_00.bffnt': b'N' * 256, + 'External_00.bffnt': b'e' * 64}) + c, n = hc.rstb_read(open(os.path.join(out, hc.RSTB_PATH), 'rb').read()) + check('table: the pack\'s own size where it is bigger', c[crc('Model/Rock.Tex1.bfres')] == 50000) + check('table: 1.9.0 size + growth + margin', c[crc('Model/Terrain.Tex1.bfres')] == 2000 + 8000 + hc.RSTB_MARGIN) + check('table: a texture inside a pack', c[crc('Model/DgnMrgPrt_Dungeon000.Tex1.bfres')] == + 900 + 3520 + hc.RSTB_MARGIN) # (growth rounded up to 32) + dgn = len(hc.sarc_replace(sarc({'Model/DgnMrgPrt_Dungeon000.Tex1.sbfres': tex(3, 500), + 'Actor/ActorLink/Dungeon000.bxml': b'1.9.0 actor'}), + {'Model/DgnMrgPrt_Dungeon000.Tex1.sbfres': tex(14, 4000)})) + check('table: a pack by name', n['Pack/Dungeon000.pack'] >= dgn) + check('table: a DLC pack by its Aoc/0010/ name', n['Aoc/0010/Pack/RemainsElectric.pack'] > 2000) + check('table: a file that did not grow stays', c[crc('Terrain/A/MainField.tscb')] == 100) + + hc.convert(game, pack, mod, terrain=False, fonts=False, log=lambda s: None) + files = tree(out) + check('--no-terrain leaves the terrain out', 'Terrain/A/MainField.tscb' not in files and + 'Model/Terrain.Tex1.sbfres' not in files and 'Model/Rock.Tex1.sbfres' in files) + check('--no-fonts leaves the fonts out', 'Font/Font_US.sbfarc' not in files) + c, _ = hc.rstb_read(open(os.path.join(out, hc.RSTB_PATH), 'rb').read()) + check('--no-terrain: its entries stay', c[crc('Model/Terrain.Tex1.bfres')] == 2000) + + hc.convert(game, pack, mod, copy=True, log=lambda s: None) + src, dst = os.path.join(pack, 'Model/Rock.Tex1.sbfres'), os.path.join(out, 'Model/Rock.Tex1.sbfres') + check('--copy copies instead of linking', not os.path.samefile(src, dst) and + open(src, 'rb').read() == open(dst, 'rb').read()) + + print('ok' if not failed else f'{failed} failed') + return 1 if failed else 0 + + +if __name__ == '__main__': + sys.exit(main())