mirror of
https://github.com/valentderah/totk-pc-recomp.git
synced 2026-11-22 21:15:57 +00:00
Draw Xbox button icons into the prompts overlay with make_romfs_patches.py --prompts
tools/button_icons.py, adapted from MacNativeGames' make_button_icons.py, draws LB, RB, LT, RT, Menu, View and a d-pad cross into the button font of every font archive and into the button guide's L and ZL images, with the letters cut out in the game's own text fonts, and raises the resource size table for the archives that grow. --prompts xbox swaps the face buttons as --xbox-prompts did (now its older name); --prompts xbox-label keeps their letters for the xbox and auto pad layouts. The plain overlay is unchanged. tests/romfs_prompts_test.py runs both on a RomFS it builds itself. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0aa529b4ce
commit
f7d563db05
6 files changed
+944
-151
No files matched your search
@@ -0,0 +1,319 @@
|
||||
# Adapted from MacNativeGames games/totk/scripts/make_button_icons.py @ 933b6a0 (MIT, Copyright (c) 2026
|
||||
# MacNativeGames contributors).
|
||||
"""Xbox button icons for the game's prompts, drawn on the player's machine for tools/make_romfs_patches.py --prompts.
|
||||
The outlines are our own shapes with letters cut out of them in the game's own text fonts: nothing of the game is in
|
||||
the repository.
|
||||
|
||||
Every prompt except the button guide in play is text in the button font, scft/External.bfotf of each
|
||||
Font/Font*.Nin_NX_NVN.bfarc.zs: private-use code points from U+E040 (A, B, X, Y, then L, R, ZL, ZR, the d-pad, Plus and
|
||||
Minus, the sticks). A .bfotf is an OpenType (CFF) font after an 8-byte header; from offset 4 on, every byte is XORed
|
||||
with a 4-byte key, which the size in the header's second word gives away (bfotf_decode). redraw_font draws the shoulder
|
||||
buttons, the triggers, Plus, Minus and the d-pad as an Xbox controller names them (LB RB, LT RT, Menu and View, a
|
||||
cross), can swap the glyphs of the face buttons (A with B, X with Y), and has fontTools write the font again. The
|
||||
archive then grows by a kilobyte or two, more than the game's resource size table allows it: grow_restbl raises those
|
||||
entries (without it the game stops at start, MacNativeGames found).
|
||||
|
||||
The button guide in play (bottom right) draws L and ZL from images of the common layout archive instead
|
||||
(timg/__Combined.bntx, Nt_KeyTexL_00 and Nt_KeyTexZL_00): bntx_redraw paints the same icons into them, the size
|
||||
unchanged. The sticks keep the Switch icons, and so do prompts drawn as fixed images (some tutorial animations).
|
||||
|
||||
Needs fontTools (tools/requirements-installer.txt, tools/requirements-py314.txt).
|
||||
"""
|
||||
import io
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
from fontTools.pens.basePen import BasePen
|
||||
from fontTools.pens.boundsPen import BoundsPen
|
||||
from fontTools.pens.recordingPen import RecordingPen
|
||||
from fontTools.pens.reverseContourPen import ReverseContourPen
|
||||
from fontTools.pens.t2CharStringPen import T2CharStringPen
|
||||
from fontTools.pens.transformPen import TransformPen
|
||||
from fontTools.ttLib import TTFont
|
||||
|
||||
FONT = 'scft/External.bfotf'
|
||||
# The letters on the keys come from the text fonts of the default archive; the regional archives lack them.
|
||||
TEXT_ARCHIVE = 'Font/Font.Nin_NX_NVN.bfarc.zs'
|
||||
TEXT_FONTS = ('scft/ninP_RodinNTLG-B_DH_003_subset.bfotf', 'scft/nintendo_NTLG-DB_DH_002.bfotf')
|
||||
# The button guide's images and the glyph each one shows.
|
||||
HUD_TEXTURES = {'Nt_KeyTexL_00': 0xE044, 'Nt_KeyTexZL_00': 0xE046}
|
||||
|
||||
|
||||
def xor(data, key):
|
||||
"""data with byte i XORed with key[i % 4]."""
|
||||
pad = (key * (len(data) // 4 + 1))[:len(data)]
|
||||
return (int.from_bytes(data, 'little') ^ int.from_bytes(pad, 'little')).to_bytes(len(data), 'little')
|
||||
|
||||
|
||||
def bfotf_decode(blob):
|
||||
"""(OpenType font, key) of a .bfotf (the module docstring). The font fills the rest of the file."""
|
||||
key = xor(blob[4:8], struct.pack('>I', len(blob) - 8))
|
||||
otf = xor(blob[8:], key)
|
||||
assert otf[:4] == b'OTTO', 'not a CFF OpenType font'
|
||||
return otf, key
|
||||
|
||||
|
||||
def bfotf_encode(otf, key, head):
|
||||
"""The .bfotf of otf: head (the original's first word) and the size, the rest XORed with key as bfotf_decode reads
|
||||
it. The size field holds the whole font, so its length has to be a multiple of 4 (fontTools pads its tables)."""
|
||||
assert len(otf) % 4 == 0, len(otf)
|
||||
return head[:4] + xor(struct.pack('>I', len(otf)) + otf, key)
|
||||
|
||||
|
||||
# ---- drawing, in units of the font's 1000-unit em; the round A/B/X/Y icons fill y 20..585
|
||||
Y0, Y1 = 20, 585
|
||||
CY, R = (Y0 + Y1) / 2, (Y1 - Y0) / 2
|
||||
K = 0.5523 # control point distance of a quarter circle drawn with one cubic curve, per unit of radius
|
||||
|
||||
|
||||
class Glyphs:
|
||||
"""Outlines of letters from the game's own text fonts, drawn as holes in a shape."""
|
||||
def __init__(self, fonts):
|
||||
self.fonts = fonts
|
||||
|
||||
def outline(self, ch):
|
||||
for font in self.fonts:
|
||||
cmap = font.getBestCmap()
|
||||
if ord(ch) in cmap:
|
||||
glyphs = font.getGlyphSet(); g = glyphs[cmap[ord(ch)]]
|
||||
rec = RecordingPen(); g.draw(rec); box = BoundsPen(glyphs); g.draw(box)
|
||||
return rec, box.bounds, font['head'].unitsPerEm, g.width
|
||||
raise KeyError(f'no text font has {ch!r}')
|
||||
|
||||
def hole(self, pen, text, cx, cy, cap, max_width):
|
||||
"""text centred on (cx, cy), at most cap high and max_width wide, its contours reversed so they cut holes."""
|
||||
parts, x, ink = [], 0.0, [1e9, 1e9, -1e9, -1e9]
|
||||
for ch in text:
|
||||
rec, b, upm, advance = self.outline(ch); k = 1000 / upm
|
||||
parts.append((rec, k, x))
|
||||
ink = [min(ink[0], x + b[0] * k), min(ink[1], b[1] * k), max(ink[2], x + b[2] * k), max(ink[3], b[3] * k)]
|
||||
x += advance * k * 0.96
|
||||
width, height = ink[2] - ink[0], ink[3] - ink[1]
|
||||
scale = min(cap / height, max_width / width)
|
||||
ox, oy = cx - (ink[0] + width / 2) * scale, cy - (ink[1] + height / 2) * scale
|
||||
reverse = ReverseContourPen(pen)
|
||||
for rec, k, x in parts:
|
||||
rec.replay(TransformPen(reverse, (scale * k, 0, 0, scale * k, ox + x * scale, oy)))
|
||||
|
||||
|
||||
def text_glyphs(blobs):
|
||||
"""Glyphs over the text fonts in blobs (.bfotf files), the first that has a letter giving it."""
|
||||
return Glyphs([TTFont(io.BytesIO(bfotf_decode(blob)[0])) for blob in blobs])
|
||||
|
||||
|
||||
def circle(pen, cx, cy, r):
|
||||
k = K * r
|
||||
pen.moveTo((cx + r, cy))
|
||||
pen.curveTo((cx + r, cy + k), (cx + k, cy + r), (cx, cy + r))
|
||||
pen.curveTo((cx - k, cy + r), (cx - r, cy + k), (cx - r, cy))
|
||||
pen.curveTo((cx - r, cy - k), (cx - k, cy - r), (cx, cy - r))
|
||||
pen.curveTo((cx + k, cy - r), (cx + r, cy - k), (cx + r, cy))
|
||||
pen.closePath()
|
||||
|
||||
|
||||
def rounded(pen, x0, y0, x1, y1, bottom, top=None):
|
||||
"""Counter-clockwise rounded rectangle (bottom and top corner radii)."""
|
||||
top = bottom if top is None else top
|
||||
kb, kt = K * bottom, K * top
|
||||
pen.moveTo((x0 + bottom, y0)); pen.lineTo((x1 - bottom, y0))
|
||||
pen.curveTo((x1 - bottom + kb, y0), (x1, y0 + bottom - kb), (x1, y0 + bottom)); pen.lineTo((x1, y1 - top))
|
||||
pen.curveTo((x1, y1 - top + kt), (x1 - top + kt, y1), (x1 - top, y1)); pen.lineTo((x0 + top, y1))
|
||||
pen.curveTo((x0 + top - kt, y1), (x0, y1 - top + kt), (x0, y1 - top)); pen.lineTo((x0, y0 + bottom))
|
||||
pen.curveTo((x0, y0 + bottom - kb), (x0 + bottom - kb, y0), (x0 + bottom, y0)); pen.closePath()
|
||||
|
||||
|
||||
def polygon(pen, points):
|
||||
pen.moveTo(points[0])
|
||||
for p in points[1:]:
|
||||
pen.lineTo(p)
|
||||
pen.closePath()
|
||||
|
||||
|
||||
def xbox_icons(g):
|
||||
"""Code point -> (advance, draw(pen)) for the buttons an Xbox controller names differently from a Switch: L R = LB
|
||||
RB, ZL ZR = LT RT, Plus and Minus = Menu and View, the d-pad as a cross. g: Glyphs for the letters. The face
|
||||
buttons keep the game's own glyphs (redraw_font swaps them for the Nintendo layout)."""
|
||||
def bumper(label, advance=820):
|
||||
def draw(pen):
|
||||
rounded(pen, 40, Y0 + 70, advance - 40, Y1 - 70, 70, 150); g.hole(pen, label, advance / 2, CY, 230, advance - 200)
|
||||
return advance, draw
|
||||
|
||||
def trigger(label, advance=760):
|
||||
def draw(pen):
|
||||
rounded(pen, 60, Y0, advance - 60, Y1, 60, 230); g.hole(pen, label, advance / 2, CY - 20, 230, advance - 220)
|
||||
return advance, draw
|
||||
|
||||
def menu(advance=640): # three bars, as on the Menu button
|
||||
def draw(pen):
|
||||
circle(pen, advance / 2, CY, R); reverse = ReverseContourPen(pen)
|
||||
for dy in (-115, 0, 115):
|
||||
rounded(reverse, advance / 2 - 150, CY + dy - 38, advance / 2 + 150, CY + dy + 38, 38)
|
||||
return advance, draw
|
||||
|
||||
def view(advance=640): # two overlapping windows, as on the View button
|
||||
def draw(pen):
|
||||
circle(pen, advance / 2, CY, R); reverse = ReverseContourPen(pen); s = 150
|
||||
rounded(reverse, advance / 2 - s - 15, CY + 15, advance / 2 - 15, CY + s + 15, 16)
|
||||
rounded(reverse, advance / 2 + 15, CY - s - 15, advance / 2 + s + 15, CY - 15, 16)
|
||||
return advance, draw
|
||||
|
||||
def dpad(*lit, advance=640): # a cross with an arrow cut into each direction the prompt means
|
||||
def draw(pen):
|
||||
cx, length, arm = advance / 2, R, R * 0.40
|
||||
polygon(pen, [(cx + length, CY - arm), (cx + length, CY + arm), (cx + arm, CY + arm), (cx + arm, CY + length),
|
||||
(cx - arm, CY + length), (cx - arm, CY + arm), (cx - length, CY + arm), (cx - length, CY - arm),
|
||||
(cx - arm, CY - arm), (cx - arm, CY - length), (cx + arm, CY - length), (cx + arm, CY - arm)])
|
||||
m, t, h = (length + arm) / 2, arm * 0.72, arm * 0.80 # arm centre, half base and height of the arrow
|
||||
heads = {'up': [(cx - t, CY + m - h / 2), (cx, CY + m + h / 2), (cx + t, CY + m - h / 2)],
|
||||
'down': [(cx + t, CY - m + h / 2), (cx, CY - m - h / 2), (cx - t, CY - m + h / 2)],
|
||||
'left': [(cx - m + h / 2, CY - t), (cx - m - h / 2, CY), (cx - m + h / 2, CY + t)],
|
||||
'right': [(cx + m - h / 2, CY + t), (cx + m + h / 2, CY), (cx + m - h / 2, CY - t)]}
|
||||
for d in lit:
|
||||
polygon(pen, heads[d]) # already clockwise: a hole
|
||||
return advance, draw
|
||||
|
||||
return {
|
||||
0xE044: bumper('LB'), 0xE045: bumper('RB'), 0xE046: trigger('LT'), 0xE047: trigger('RT'),
|
||||
0xE04B: menu(), 0xE04C: view(),
|
||||
0xE049: dpad('up', 'down', 'left', 'right'), 0xE060: dpad('up'), 0xE061: dpad('down'),
|
||||
0xE062: dpad('left'), 0xE063: dpad('right'), 0xE064: dpad('up', 'down'), 0xE065: dpad('left', 'right'),
|
||||
}
|
||||
|
||||
|
||||
def redraw_font(otf, icons, swaps=()):
|
||||
"""The OpenType font otf with the glyphs of each (code point, code point) pair of swaps trading places (outlines and
|
||||
horizontal metrics), then every code point of icons (code point -> (advance, draw)) drawn anew, written again by
|
||||
fontTools. The timestamps stay, so the same input gives the same bytes."""
|
||||
font = TTFont(io.BytesIO(otf), recalcTimestamp=False)
|
||||
assert font['head'].unitsPerEm == 1000, f'em of {font["head"].unitsPerEm} units, the drawings assume 1000'
|
||||
cff = font['CFF '].cff
|
||||
top = cff.topDictIndex[0]
|
||||
assert not hasattr(top, 'ROS'), 'CID-keyed CFF' # its glyphs can use different private dictionaries
|
||||
charstrings, private, hmtx, cmap = top.CharStrings, top.Private, font['hmtx'], font.getBestCmap()
|
||||
nominal = getattr(private, 'nominalWidthX', 0)
|
||||
for a, b in swaps:
|
||||
ga, gb = cmap[a], cmap[b]
|
||||
outline_a, outline_b = charstrings[ga], charstrings[gb]
|
||||
charstrings[ga], charstrings[gb] = outline_b, outline_a
|
||||
hmtx[ga], hmtx[gb] = hmtx[gb], hmtx[ga]
|
||||
for cp, (advance, draw) in icons.items():
|
||||
pen = T2CharStringPen(advance - nominal, None); draw(pen) # the width operand is relative to nominalWidthX
|
||||
charstrings[cmap[cp]] = pen.getCharString(private=private, globalSubrs=cff.GlobalSubrs)
|
||||
glyphs = font.getGlyphSet()
|
||||
for cp, (advance, _) in icons.items():
|
||||
box = BoundsPen(glyphs); glyphs[cmap[cp]].draw(box)
|
||||
hmtx[cmap[cp]] = (advance, int(round(box.bounds[0])))
|
||||
out = io.BytesIO(); font.save(out)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
# ---- the button guide's images: square R8_UNORM masks (white key, black letter), one mip, block-linear, 72x72 up to
|
||||
# 1.2.1 and 108x108 in 1.4.3. Each is drawn from the icon of the same Switch button, fitted into the square.
|
||||
R8_UNORM, HUD_MARGIN, SUPERSAMPLE = 0x201, 4, 4
|
||||
|
||||
|
||||
def gob_offset(x, y, width_gobs, block_height):
|
||||
"""Byte offset of (x, y) in a Tegra block-linear surface of 1 byte per pixel (GOBs of 64 bytes x 8 rows)."""
|
||||
return ((y // (8 * block_height)) * 512 * block_height * width_gobs + (x // 64) * 512 * block_height
|
||||
+ ((y % (8 * block_height)) // 8) * 512 + ((x % 64) // 32) * 256 + ((y % 8) // 2) * 64
|
||||
+ ((x % 32) // 16) * 32 + (y % 2) * 16 + (x % 16))
|
||||
|
||||
|
||||
class PolygonPen(BasePen):
|
||||
"""Outlines flattened to closed polygons."""
|
||||
def __init__(self):
|
||||
super().__init__(None); self.polygons = []
|
||||
|
||||
def _moveTo(self, pt):
|
||||
self.polygons.append([pt])
|
||||
|
||||
def _lineTo(self, pt):
|
||||
self.polygons[-1].append(pt)
|
||||
|
||||
def _curveToOne(self, pt1, pt2, pt3):
|
||||
p0 = self.polygons[-1][-1]
|
||||
for i in range(1, 17):
|
||||
t = i / 16; u = 1 - t
|
||||
self.polygons[-1].append(tuple(u ** 3 * p0[k] + 3 * u * u * t * pt1[k] + 3 * u * t * t * pt2[k] + t ** 3 * pt3[k]
|
||||
for k in (0, 1)))
|
||||
|
||||
def _qCurveToOne(self, pt1, pt2):
|
||||
p0 = self.polygons[-1][-1]
|
||||
for i in range(1, 17):
|
||||
t = i / 16; u = 1 - t
|
||||
self.polygons[-1].append(tuple(u * u * p0[k] + 2 * u * t * pt1[k] + t * t * pt2[k] for k in (0, 1)))
|
||||
|
||||
|
||||
def rasterize(draw, size):
|
||||
"""A size x size coverage mask (0..255, rows top down) of draw's outline, fitted into the square, nonzero winding."""
|
||||
rec = RecordingPen(); draw(rec)
|
||||
box = BoundsPen(None); rec.replay(box); x0, y0, x1, y1 = box.bounds
|
||||
inner = size - 2 * HUD_MARGIN; scale = inner / max(x1 - x0, y1 - y0)
|
||||
ox = HUD_MARGIN + (inner - (x1 - x0) * scale) / 2 - x0 * scale
|
||||
oy = HUD_MARGIN + (inner - (y1 - y0) * scale) / 2 - y0 * scale
|
||||
flat = PolygonPen(); rec.replay(TransformPen(flat, (scale, 0, 0, -scale, ox, size - oy))) # font y up -> rows down
|
||||
edges = [(a, b) for poly in flat.polygons for a, b in zip(poly, poly[1:] + poly[:1]) if a[1] != b[1]]
|
||||
n = size * SUPERSAMPLE; cover = [0] * (size * size)
|
||||
for row in range(n):
|
||||
y = (row + 0.5) / SUPERSAMPLE
|
||||
crossings = sorted((a[0] + (y - a[1]) * (b[0] - a[0]) / (b[1] - a[1]), 1 if b[1] > a[1] else -1)
|
||||
for a, b in edges if min(a[1], b[1]) <= y < max(a[1], b[1]))
|
||||
winding, start = 0, None
|
||||
for x, d in crossings:
|
||||
if winding == 0:
|
||||
start = x
|
||||
winding += d
|
||||
if winding == 0:
|
||||
for col in range(max(0, round(start * SUPERSAMPLE)), min(n, round(x * SUPERSAMPLE))):
|
||||
cover[(row // SUPERSAMPLE) * size + col // SUPERSAMPLE] += 1
|
||||
return bytes(min(255, c * 255 // (SUPERSAMPLE * SUPERSAMPLE)) for c in cover)
|
||||
|
||||
|
||||
def bntx_redraw(data, base, textures, icons):
|
||||
"""Paint the icon of each texture of textures (name without the ^ suffix -> code point; icons: code point ->
|
||||
(advance, draw)) over its image in the BNTX at data[base:] (a bytearray), in place. Returns the names painted."""
|
||||
assert data[base:base + 4] == b'BNTX' and data[base + 0x20:base + 0x24] == b'NX '
|
||||
count, table = struct.unpack_from('<IQ', data, base + 0x24)
|
||||
done = []
|
||||
for k in range(count):
|
||||
info = base + struct.unpack_from('<Q', data, base + table + 8 * k)[0]
|
||||
assert data[info:info + 4] == b'BRTI'
|
||||
at = base + struct.unpack_from('<Q', data, info + 0x60)[0]
|
||||
name = data[at + 2:at + 2 + struct.unpack_from('<H', data, at)[0]].decode().split('^')[0]
|
||||
if name not in textures:
|
||||
continue
|
||||
mips, fmt = struct.unpack_from('<H', data, info + 0x16)[0], struct.unpack_from('<I', data, info + 0x1c)[0]
|
||||
(w, h), layout = struct.unpack_from('<II', data, info + 0x24), struct.unpack_from('<I', data, info + 0x34)[0]
|
||||
assert fmt == R8_UNORM and w == h and mips == 1, f'{name}: format {fmt:#x}, {w}x{h}, {mips} mips'
|
||||
start = base + struct.unpack_from('<Q', data, base + struct.unpack_from('<Q', data, info + 0x70)[0])[0]
|
||||
size, block = struct.unpack_from('<I', data, info + 0x50)[0], 1 << (layout & 7)
|
||||
mask = rasterize(icons[textures[name]][1], w)
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
at = gob_offset(x, y, (w + 63) // 64, block)
|
||||
assert at < size, f'{name}: pixel ({x}, {y}) past the image'
|
||||
data[start + at] = mask[y * w + x]
|
||||
done.append(name)
|
||||
missing = sorted(set(textures) - set(done))
|
||||
assert not missing, f'not in the texture list: {", ".join(missing)}'
|
||||
return done
|
||||
|
||||
|
||||
# ---- the resource size table: System/Resource/ResourceSizeTable.Product.<n>.Nin_NX_NVN.rsizetable.zs, a RESTBL whose
|
||||
# entries are keyed by the CRC32 of the RomFS path without .zs. The game sizes the buffer it loads a file into from its
|
||||
# entry, so an archive that grew needs its entry raised by as much.
|
||||
def restbl_offsets(table):
|
||||
"""CRC32 of a path -> offset of its size in the RESTBL table."""
|
||||
assert table[:6] == b'RESTBL', 'not a RESTBL'
|
||||
count = struct.unpack_from('<I', table, 14)[0]
|
||||
return {struct.unpack_from('<I', table, 22 + i * 8)[0]: 22 + i * 8 + 4 for i in range(count)}
|
||||
|
||||
|
||||
def grow_restbl(table, growth):
|
||||
"""table with the entry of each RomFS path of growth (path -> bytes it grew) raised by that much."""
|
||||
at, out = restbl_offsets(table), bytearray(table)
|
||||
for path, extra in growth.items():
|
||||
h = zlib.crc32(path.removesuffix('.zs').encode())
|
||||
assert h in at, f'{path} has no entry in the resource size table'
|
||||
struct.pack_into('<I', out, at[h], struct.unpack_from('<I', out, at[h])[0] + extra)
|
||||
return bytes(out)
|
||||
+83
-150
@@ -16,21 +16,30 @@ left out.
|
||||
to the screen's corners. totk.exe loads that overlay from romfs-patches-<w>x<h> when the game resolution is that size
|
||||
(runtime/romfs.c overlay_init); the camera's side of it is the patch set aspect (recomp/patches-v143.txt).
|
||||
|
||||
--xbox-prompts: the same overlay with the A and B, and the X and Y button prompts swapped, for pad_layout = xbox_prompts
|
||||
(runtime/romfs.c overlay_init loads romfs-patches-xbox in place of romfs-patches). That layout plays an Xbox pad by
|
||||
position, as nintendo does: the button that does Switch A is labelled B, and the prompts then name the label. Built from
|
||||
the game's own images and glyphs, nothing added:
|
||||
- the action prompt (blyt/DoCommand_00.bflyt) draws the letter images Nt_KeyTexA/B/X/Y_00 of timg/__Combined.bntx in
|
||||
the Common archive: their image data is swapped (same format, size and tiling). Around it, a diamond names the
|
||||
other face buttons with one-letter text panes (T_B_00, T_X_00, ...). The game fills them from the messages of the
|
||||
same name in LayoutMsg/DoCommand_00.msbt of each Mals/<language> archive, over the layout's own text: both have
|
||||
their letters swapped the same way. The diamond's shape (Nt_KeyBtnSubBase*) shows the button's position, which
|
||||
stays right.
|
||||
- every other prompt is text: the button glyphs U+E040 A, U+E041 B, U+E042 X, U+E043 Y of scft/External.bfotf, the
|
||||
same font in each Font/Font*.Nin_NX_NVN.bfarc.zs. Their CFF outlines and horizontal metrics are swapped.
|
||||
--prompts xbox | xbox-label: the same overlay with Xbox button icons in the game's prompts, for prompts = xbox
|
||||
(runtime/romfs.c overlay_init loads romfs-patches-xbox or romfs-patches-xbox-label in place of romfs-patches). Drawn
|
||||
from the game's own files on the player's machine, nothing added (tools/button_icons.py, which needs fontTools):
|
||||
- both: L, R, ZL, ZR, Plus, Minus and the d-pad become LB, RB, LT, RT, Menu, View and a cross in the button font
|
||||
(scft/External.bfotf, the same font in each Font/Font*.Nin_NX_NVN.bfarc.zs), and L and ZL in the button guide's images
|
||||
(Nt_KeyTexL_00 and Nt_KeyTexZL_00 of timg/__Combined.bntx in the Common archive). The fonts grow, so the overlay also
|
||||
carries the resource size table (System/Resource/ResourceSizeTable.Product.<n>...rsizetable.zs) with their entries
|
||||
raised by as much.
|
||||
- xbox, for pad_layout = nintendo. That layout plays an Xbox pad by position: the button that does Switch A is
|
||||
labelled B, so the face buttons' prompts are swapped to name the labels, A with B and X with Y:
|
||||
- the action prompt (blyt/DoCommand_00.bflyt) draws the letter images Nt_KeyTexA/B/X/Y_00 of timg/__Combined.bntx in
|
||||
the Common archive: their image data is swapped (same format, size and tiling). Around it, a diamond names the
|
||||
other face buttons with one-letter text panes (T_B_00, T_X_00, ...). The game fills them from the messages of the
|
||||
same name in LayoutMsg/DoCommand_00.msbt of each Mals/<language> archive, over the layout's own text: both have
|
||||
their letters swapped the same way. The diamond's shape (Nt_KeyBtnSubBase*) shows the button's position, which
|
||||
stays right.
|
||||
- every other prompt: the glyphs U+E040 A, U+E041 B, U+E042 X, U+E043 Y of the button font trade places.
|
||||
- xbox-label, for pad_layout = xbox and auto. Those layouts put Switch A on the button labelled A (auto picks xbox for
|
||||
every pad not labelled the Nintendo way), so the face buttons keep their letters; the action prompt's diamond keeps
|
||||
the Switch positions (A on the right).
|
||||
--xbox-prompts is the older name of --prompts xbox.
|
||||
|
||||
Input: build/extracted/<version>/romfs (romfs.bin and index.json, verified by tools/extract.py). Output:
|
||||
build/<version>/romfs-patches/<path> by default (romfs-patches-xbox with --xbox-prompts), and <out>/manifest.tsv (path, size, SHA-256 of the overlay, SHA-256 of the original). Run with .venv-py314.
|
||||
build/<version>/romfs-patches/<path> by default (romfs-patches-<style> with --prompts), and <out>/manifest.tsv (path, size, SHA-256 of the overlay, SHA-256 of the original). Run with .venv-py314.
|
||||
"""
|
||||
import argparse
|
||||
import compression.zstd as zstd
|
||||
@@ -46,12 +55,15 @@ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
ap.add_argument('--version', choices=('v121', 'v143'), default='v121')
|
||||
ap.add_argument('--romfs', type=Path, help='default build/extracted/<version>/romfs')
|
||||
ap.add_argument('--out', type=Path,
|
||||
help='default build/<version>/romfs-patches (romfs-patches-xbox with --xbox-prompts)')
|
||||
help='default build/<version>/romfs-patches (romfs-patches-<style> with --prompts)')
|
||||
ap.add_argument('--aspect', help='<w>x<h> of a game resolution wider than 16:9: also lay the UI out for it')
|
||||
ap.add_argument('--xbox-prompts', action='store_true', help='swap the A/B and X/Y button prompts as well')
|
||||
ap.add_argument('--prompts', choices=('xbox', 'xbox-label'),
|
||||
help='Xbox button icons in the prompts: xbox for pad_layout = nintendo (A shown as B, X as Y), '
|
||||
'xbox-label for pad_layout = xbox or auto (the face buttons keep their letters)')
|
||||
ap.add_argument('--xbox-prompts', dest='prompts', action='store_const', const='xbox', help='the same as --prompts xbox')
|
||||
args = ap.parse_args()
|
||||
args.romfs = args.romfs or root / 'build/extracted' / args.version / 'romfs'
|
||||
args.out = args.out or root / 'build' / args.version / ('romfs-patches-xbox' if args.xbox_prompts else 'romfs-patches')
|
||||
args.out = args.out or root / 'build' / args.version / (f'romfs-patches-{args.prompts}' if args.prompts else 'romfs-patches')
|
||||
index = json.loads((args.romfs / 'index.json').read_text())
|
||||
assert index['status'] == 'pass'
|
||||
files = {f['path']: f for f in index['files']}
|
||||
@@ -180,119 +192,6 @@ def msbt_letters(data, swap):
|
||||
return changed
|
||||
|
||||
|
||||
def cff_index(data, pos):
|
||||
"""([(start, end)] of every item, offSize, end) of the CFF INDEX at data[pos:]."""
|
||||
count = struct.unpack_from('>H', data, pos)[0]
|
||||
if not count:
|
||||
return [], 0, pos + 2
|
||||
size = data[pos + 2]
|
||||
offsets = [int.from_bytes(data[pos + 3 + i * size:pos + 3 + (i + 1) * size], 'big') for i in range(count + 1)]
|
||||
first = pos + 2 + (count + 1) * size
|
||||
return [(first + offsets[i], first + offsets[i + 1]) for i in range(count)], size, first + offsets[-1]
|
||||
|
||||
|
||||
def cff_charstrings(data, cff):
|
||||
"""The offset (from the CFF table) of the CharStrings INDEX: operator 17 of the Top DICT. CID-keyed fonts (ROS,
|
||||
operator 12 30) are refused: their glyphs can use different private dictionaries."""
|
||||
_, _, pos = cff_index(data, cff + data[cff + 2]) # Name INDEX after the header
|
||||
top, _, _ = cff_index(data, pos)
|
||||
(pos, end), operands, found = top[0], [], None
|
||||
while pos < end:
|
||||
b = data[pos]
|
||||
if b <= 21:
|
||||
op = (12, data[pos + 1]) if b == 12 else b
|
||||
pos += 2 if b == 12 else 1
|
||||
assert op != (12, 30), 'CID-keyed CFF'
|
||||
if op == 17:
|
||||
found = operands[-1]
|
||||
operands = []
|
||||
elif b == 28:
|
||||
operands.append(struct.unpack_from('>h', data, pos + 1)[0]); pos += 3
|
||||
elif b == 29:
|
||||
operands.append(struct.unpack_from('>i', data, pos + 1)[0]); pos += 5
|
||||
elif b == 30: # real number: nibbles up to an 0xf
|
||||
pos += 1
|
||||
while data[pos] & 0x0f != 0x0f and data[pos] & 0xf0 != 0xf0:
|
||||
pos += 1
|
||||
pos += 1
|
||||
operands.append(0)
|
||||
elif b <= 246:
|
||||
operands.append(b - 139); pos += 1
|
||||
elif b <= 250:
|
||||
operands.append((b - 247) * 256 + data[pos + 1] + 108); pos += 2
|
||||
else:
|
||||
operands.append(-(b - 251) * 256 - data[pos + 1] - 108); pos += 2
|
||||
assert found is not None, 'no CharStrings in the Top DICT'
|
||||
return found
|
||||
|
||||
|
||||
def otf_glyph(data, cmap, code):
|
||||
"""The glyph id of a code point in the format 4 (platform 3 encoding 1) subtable of the cmap at data[cmap:]."""
|
||||
for k in range(struct.unpack_from('>H', data, cmap + 2)[0]):
|
||||
platform, encoding, offset = struct.unpack_from('>HHI', data, cmap + 4 + 8 * k)
|
||||
p = cmap + offset
|
||||
if (platform, encoding) != (3, 1) or struct.unpack_from('>H', data, p)[0] != 4:
|
||||
continue
|
||||
seg = struct.unpack_from('>H', data, p + 6)[0] // 2
|
||||
for s in range(seg):
|
||||
end = struct.unpack_from('>H', data, p + 14 + 2 * s)[0]
|
||||
start = struct.unpack_from('>H', data, p + 16 + 2 * seg + 2 * s)[0]
|
||||
if not start <= code <= end:
|
||||
continue
|
||||
delta = struct.unpack_from('>h', data, p + 16 + 4 * seg + 2 * s)[0]
|
||||
at = p + 16 + 6 * seg + 2 * s
|
||||
ro = struct.unpack_from('>H', data, at)[0]
|
||||
glyph = code if not ro else struct.unpack_from('>H', data, at + ro + 2 * (code - start))[0]
|
||||
return (glyph + delta) & 0xffff if glyph else 0
|
||||
raise AssertionError(f'U+{code:04X} is not in the font')
|
||||
|
||||
|
||||
def otf_checksum(data):
|
||||
data = bytes(data) + bytes(-len(data) % 4)
|
||||
return sum(struct.unpack(f'>{len(data) // 4}I', data)) & 0xffffffff
|
||||
|
||||
|
||||
def bfotf_swap(data, pairs):
|
||||
"""The BFOTF data with the glyphs of each (code point, code point) pair swapped: CFF outlines and horizontal
|
||||
metrics, then the table checksums. A BFOTF is an OpenType font after an 8-byte header; from offset 4 on, every
|
||||
4-byte word is XORed with one key, which the size field gives away (it holds the font's length)."""
|
||||
key = bytes(x ^ y for x, y in zip(data[4:8], struct.pack('>I', len(data) - 8)))
|
||||
plain = bytearray(data[:4]) + bytearray(x ^ key[i % 4] for i, x in enumerate(data[4:]))
|
||||
font = plain[8:]
|
||||
assert font[:4] == b'OTTO', 'not a CFF OpenType font'
|
||||
tables = {}
|
||||
for k in range(struct.unpack_from('>H', font, 4)[0]):
|
||||
tag, _, offset, length = struct.unpack_from('>4sIII', font, 12 + 16 * k)
|
||||
tables[tag] = (12 + 16 * k, offset, length)
|
||||
cff = tables[b'CFF '][1]
|
||||
strings, size, end = cff_index(font, cff + cff_charstrings(font, cff))
|
||||
hmtx, metrics = tables[b'hmtx'][1], struct.unpack_from('>H', font, tables[b'hhea'][1] + 34)[0]
|
||||
order = list(range(len(strings)))
|
||||
for a, b in pairs:
|
||||
ga, gb = otf_glyph(font, tables[b'cmap'][1], a), otf_glyph(font, tables[b'cmap'][1], b)
|
||||
assert 0 < ga < len(strings) and 0 < gb < len(strings) and ga < metrics and gb < metrics, (a, b, ga, gb)
|
||||
order[ga], order[gb] = order[gb], order[ga]
|
||||
ma, mb = hmtx + 4 * ga, hmtx + 4 * gb
|
||||
font[ma:ma + 4], font[mb:mb + 4] = font[mb:mb + 4], font[ma:ma + 4]
|
||||
# The CharStrings INDEX again with the items in the new order: the same length, so nothing after it moves.
|
||||
body = b''.join(bytes(font[slice(*strings[g])]) for g in order)
|
||||
first = strings[0][0]
|
||||
assert first + len(body) == end
|
||||
font[first:end] = body
|
||||
at, base = first - (len(strings) + 1) * size, 1 # the offset array ends where the first item starts
|
||||
for i, g in enumerate(order + [None]):
|
||||
font[at + i * size:at + (i + 1) * size] = base.to_bytes(size, 'big')
|
||||
if g is not None:
|
||||
base += strings[g][1] - strings[g][0]
|
||||
head = tables[b'head'][1]
|
||||
struct.pack_into('>I', font, head + 8, 0)
|
||||
for entry, offset, length in tables.values():
|
||||
struct.pack_into('>I', font, entry + 4, otf_checksum(font[offset:offset + length]))
|
||||
struct.pack_into('>I', font, head + 8, (0xb1b0afba - otf_checksum(font)) & 0xffffffff)
|
||||
plain[8:] = font
|
||||
return bytes(plain[:4]) + bytes(x ^ key[i % 4] for i, x in enumerate(plain[4:]))
|
||||
|
||||
|
||||
def sarc_replace(data, new):
|
||||
"""The SARC data with the members named in new (name -> bytes) replaced. The header, SFAT and SFNT stay; the
|
||||
members are laid out again in their old order, each at an offset with at least the alignment its old one had."""
|
||||
@@ -326,6 +225,18 @@ for p in files:
|
||||
MALS[m[1]] = (int(m[2]), p)
|
||||
MALS = sorted(p for _, p in MALS.values())
|
||||
LAYOUT_MSG = 'LayoutMsg/DoCommand_00.msbt'
|
||||
# The resource size table, likewise the newest version in the RomFS.
|
||||
RESTBL = max((p for p in files if re.fullmatch(r'System/Resource/ResourceSizeTable\.Product\.\d+\.[\w.]*rsizetable\.zs', p)),
|
||||
key=lambda p: int(re.search(r'\.Product\.(\d+)\.', p)[1]), default=None)
|
||||
by_position = args.prompts == 'xbox' # the face buttons' prompts swapped to the labels (pad_layout = nintendo)
|
||||
if args.prompts:
|
||||
assert FONTS, 'no Font/Font*.Nin_NX_NVN.bfarc.zs in the RomFS'
|
||||
assert MALS or not by_position, 'no Mals/<language>.Product.<version>.sarc.zs in the RomFS'
|
||||
assert RESTBL, 'no System/Resource/ResourceSizeTable.Product.<n>...rsizetable.zs in the RomFS'
|
||||
spec = importlib.util.spec_from_file_location('button_icons', Path(__file__).with_name('button_icons.py'))
|
||||
icons = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(icons)
|
||||
assert icons.TEXT_ARCHIVE in FONTS, f'no {icons.TEXT_ARCHIVE} in the RomFS'
|
||||
|
||||
with (args.romfs / 'romfs.bin').open('rb') as image:
|
||||
def read(path):
|
||||
@@ -339,7 +250,8 @@ with (args.romfs / 'romfs.bin').open('rb') as image:
|
||||
for name, (lo, hi) in sarc_members(pack).items():
|
||||
d = zstd.ZstdDict(pack[lo:hi])
|
||||
dictionaries[d.dict_id] = d
|
||||
originals = {path: read(path) for path in [ARCHIVE] + (FONTS + MALS if args.xbox_prompts else [])}
|
||||
prompt_files = (FONTS + (MALS if by_position else []) + [RESTBL]) if args.prompts else []
|
||||
originals = {path: read(path) for path in [ARCHIVE] + prompt_files}
|
||||
raw = originals[ARCHIVE]
|
||||
info = zstd.get_frame_info(raw)
|
||||
dictionary = dictionaries[info.dictionary_id]
|
||||
@@ -370,27 +282,43 @@ diff = [i for i in range(len(original)) if original[i] != blarc[i]]
|
||||
touched = [members[m] for m in (*MEMBERS, *layout)]
|
||||
assert diff and all(any(lo <= i < hi for lo, hi in touched) for i in diff), diff
|
||||
outputs = {ARCHIVE: bytes(blarc)} # RomFS path -> new contents (before compression)
|
||||
if args.xbox_prompts:
|
||||
bntx_swap(blarc, members['timg/__Combined.bntx'][0], KEY_TEXTURES)
|
||||
prompts = None
|
||||
if args.prompts:
|
||||
sizes = {ARCHIVE: len(original)} # RomFS path -> size of the original's contents
|
||||
|
||||
def unpack(path):
|
||||
frame = zstd.get_frame_info(originals[path])
|
||||
data = zstd.decompress(originals[path], zstd_dict=dictionaries.get(frame.dictionary_id))
|
||||
sizes[path] = len(data)
|
||||
return data
|
||||
archives = {path: unpack(path) for path in FONTS}
|
||||
text = sarc_members(archives[icons.TEXT_ARCHIVE])
|
||||
missing = [name for name in icons.TEXT_FONTS if name not in text]
|
||||
assert not missing, f'no {", ".join(missing)} in {icons.TEXT_ARCHIVE}'
|
||||
drawn = icons.xbox_icons(icons.text_glyphs(archives[icons.TEXT_ARCHIVE][slice(*text[name])]
|
||||
for name in icons.TEXT_FONTS))
|
||||
bntx = members['timg/__Combined.bntx'][0]
|
||||
letters = {}
|
||||
for member, (lo, hi) in members.items():
|
||||
if member.endswith('.bflyt'):
|
||||
changed = bflyt_letters(blarc, lo, hi, KEY_LETTERS)
|
||||
if changed:
|
||||
letters[member] = changed
|
||||
assert 'blyt/DoCommand_00.bflyt' in letters, 'no letter panes in blyt/DoCommand_00.bflyt'
|
||||
if by_position:
|
||||
bntx_swap(blarc, bntx, KEY_TEXTURES)
|
||||
for member, (lo, hi) in members.items():
|
||||
if member.endswith('.bflyt'):
|
||||
changed = bflyt_letters(blarc, lo, hi, KEY_LETTERS)
|
||||
if changed:
|
||||
letters[member] = changed
|
||||
assert 'blyt/DoCommand_00.bflyt' in letters, 'no letter panes in blyt/DoCommand_00.bflyt'
|
||||
hud = icons.bntx_redraw(blarc, bntx, icons.HUD_TEXTURES, drawn)
|
||||
outputs[ARCHIVE] = bytes(blarc)
|
||||
assert FONTS, 'no Font/Font*.Nin_NX_NVN.bfarc.zs in the RomFS'
|
||||
for path in FONTS:
|
||||
frame = zstd.get_frame_info(originals[path])
|
||||
bfarc = zstd.decompress(originals[path], zstd_dict=dictionaries.get(frame.dictionary_id))
|
||||
lo, hi = sarc_members(bfarc)['scft/External.bfotf']
|
||||
outputs[path] = sarc_replace(bfarc, {'scft/External.bfotf': bfotf_swap(bfarc[lo:hi], KEY_GLYPHS)})
|
||||
assert MALS, 'no Mals/<language>.Product.<version>.sarc.zs in the RomFS'
|
||||
fonts = {} # each distinct font is drawn once (1.4.3's four archives hold the same one)
|
||||
for path, bfarc in archives.items():
|
||||
lo, hi = sarc_members(bfarc)[icons.FONT]
|
||||
otf, key = icons.bfotf_decode(bfarc[lo:hi])
|
||||
if otf not in fonts:
|
||||
fonts[otf] = icons.redraw_font(otf, drawn, KEY_GLYPHS if by_position else ())
|
||||
outputs[path] = sarc_replace(bfarc, {icons.FONT: icons.bfotf_encode(fonts[otf], key, bfarc[lo:hi])})
|
||||
messages = {}
|
||||
for path in MALS:
|
||||
frame = zstd.get_frame_info(originals[path])
|
||||
mals = bytearray(zstd.decompress(originals[path], zstd_dict=dictionaries.get(frame.dictionary_id)))
|
||||
for path in MALS if by_position else []:
|
||||
mals = bytearray(unpack(path))
|
||||
lo, hi = sarc_members(mals)[LAYOUT_MSG]
|
||||
msbt = bytearray(mals[lo:hi])
|
||||
changed = msbt_letters(msbt, KEY_LETTERS)
|
||||
@@ -398,6 +326,12 @@ if args.xbox_prompts:
|
||||
mals[lo:hi] = msbt
|
||||
outputs[path] = bytes(mals)
|
||||
messages[path] = len(changed)
|
||||
# An archive that grew needs as much more room in the resource size table, or the game stops when it loads it.
|
||||
grown = {path: len(data) - sizes[path] for path, data in outputs.items() if len(data) > sizes[path]}
|
||||
if grown:
|
||||
outputs[RESTBL] = icons.grow_restbl(unpack(RESTBL), grown)
|
||||
prompts = dict(style=args.prompts, textures=KEY_TEXTURES if by_position else [], letters=letters,
|
||||
messages=messages, hud=hud, icons=len(drawn), fonts=FONTS, grown=grown)
|
||||
|
||||
lines = []
|
||||
for path, contents in outputs.items():
|
||||
@@ -414,5 +348,4 @@ for path, contents in outputs.items():
|
||||
+ ''.join(line + '\n' for line in lines))
|
||||
print(json.dumps(dict(status='pass', path=ARCHIVE, members=patched, changed_bytes=len(diff),
|
||||
ultrawide_layout=dict(aspect=args.aspect, members=len(layout)) if args.aspect else None,
|
||||
xbox_prompts=dict(textures=KEY_TEXTURES, letters=letters, messages=messages, fonts=FONTS)
|
||||
if args.xbox_prompts else None)))
|
||||
prompts=prompts)))
|
||||
@@ -1,7 +1,9 @@
|
||||
# Packages of the release's bundled Python 3.14.9 (tools/make_release.py): what the installer steps import.
|
||||
# numpy: recomp/gen.py. lz4: recomp/nso.py, tools/shader_census.py. cryptography, cffi, pycparser: tools/extract.py and the vendored extract scripts.
|
||||
# fonttools: tools/button_icons.py (make_romfs_patches.py --prompts).
|
||||
numpy==2.5.4
|
||||
lz4==4.4.5
|
||||
cryptography==50.0.2
|
||||
fonttools==4.68.0
|
||||
cffi==2.1.1
|
||||
pycparser==3.11
|
||||
@@ -7,6 +7,7 @@ capstone==5.0.9
|
||||
cffi==2.1.1
|
||||
cryptography==50.0.2
|
||||
enlighten==1.14.1
|
||||
fonttools==4.68.0
|
||||
jinxed==2.1.0
|
||||
lz4==4.4.5
|
||||
nsz==5.0.0
|
||||
|
||||
Reference in new issue
Block a user