Files
mandy/tools/live_prompt_glyphs.py
ubiquitarianism 69454e705a Live prompts: call lnInit from each symbol class's constructor
In the second run in the title, Main's initialiser ran (the run-time
sentinels were found, four copies) but lnMade stayed 0: the hook in
mx.core.SpriteAsset never ran. The three movies that load the glyph movie
each define mx.core.SpriteAsset too, and theirs is the one used. The 38
Main_Button_N classes and platform_xbsx.input_icons.Main are defined only
in the glyph movie (the loaders' document classes are generic_movie.Main,
hud.Main and map_scripted_movie.Main), so each Main_Button_N constructor
now calls Main.lnInit(this) in a try block and SpriteAsset is left as it
is. 459 bytes to spare.
2026-11-29 23:20:51 -05:00

586 lines
28 KiB
Python

#!/usr/bin/env python3
"""Builds the button prompt movie that follows the device in use during play: a pad set and the keyboard set in one
movie, and a few lines of ActionScript that show the one the runtime asks for. Standard library only.
The title draws its prompts from one Scaleform movie of 38 sprites ``platform_xbsx.input_icons.Main_Button_<N>``
(docs/prompt_glyphs.md) that it reads once, a few seconds after it starts. Serving a movie of one family
(tools/ps_prompt_glyphs.py, tools/pc_prompt_glyphs.py) fixes the prompts to the device in use at that moment. This
movie carries two:
* each ``Main_Button_<N>`` sprite places the keyboard picture (tools/pc_prompt_glyphs.py's built-in key caps, or
the player's pictures) and then, on top, the pad picture (tools/ps_prompt_glyphs.py's PlayStation set), the first
pad piece named ``p``; one invisible rectangle of the Xbox glyph's bounds under both keeps the sprite's size. If
the added code never runs, the PlayStation discs are drawn over the key caps and the prompts look PlayStation,
whatever the device: that is told apart from prompts stuck on the start family;
* the title's own ActionScript block is kept and three things are added to it, on the player's PC from the player's
movie (nothing of it is in the repository):
- on the document class ``Main``, five static ``Number`` slots in a row: ``lnLo`` and ``lnHi`` hold two sentinels
(`SENTINEL_LOW`, `SENTINEL_HIGH`, made of the letters ``LEONIDA``), ``lnFamily`` between them the family to show
(the runtime's `Family` code: 2 is the keyboard and mouse, anything else the pad), then ``lnMade`` (prompts made)
and ``lnShown`` (pictures switched), which the runtime reads to log that the code runs. ``lnFamily``'s default in
the file is `FAMILY_UNSET`, which the runtime replaces with the family in use when it serves the movie. The
sentinels are not in the file: ``Main``'s static initialiser computes them first thing (half of each, times 2),
so only the class's live slots ever hold them, never a copy of the movie or of a slot default;
- static methods on ``Main``: ``lnShow(sprite)`` makes the keyboard pieces (children 1 .. before ``p``) or the pad
pieces (``p`` onwards) visible; ``lnInit(sprite)`` counts, shows and listens for ``enterFrame``, ``lnTick`` shows again
on each frame while the sprite is on the stage (a prompt already on screen follows a switch) and otherwise trades
the frame listener for an ``addedToStage`` one, ``lnAdded``, so a prompt taken off the stage costs nothing;
- the constructor of each of the 38 ``Main_Button_<N>`` classes calls ``Main.lnInit(this)`` after its own work,
inside a try block: whatever goes wrong there, the prompt is made as before. Each of the four methods is a try
block too. (A first version hooked their base, ``mx.core.SpriteAsset``, once: but the three movies that load this
one define ``mx.core.SpriteAsset`` too, the loader's definition is the one used, and in the title the hook never
ran: ``lnMade`` stayed 0, 2026-11-29. ``Main_Button_<N>`` and ``platform_xbsx.input_icons.Main`` are defined only
here; the other movies' document classes are ``platform_xbsx.generic_movie.Main``, ``...hud.Main`` and
``...map_scripted_movie.Main``.)
* the runtime (leonida-hle, ``modules/glyphs.rs`` and ``glyphs/live.rs``) finds ``lnLo, lnFamily, lnHi`` in the
title's memory by the sentinels, a few seconds after it served the movie, and writes ``lnFamily`` whenever the
device in use changes.
An earlier version stored the sentinels as the slots' defaults; in the title the runtime then found four copies of
the three defaults eight bytes apart, wrote them on every switch, and nothing on screen changed (2026-11-29).
python -I tools/live_prompt_glyphs.py --from-archive "<package>/data.rpf" --out ps_live_prompt_glyphs.gfx
python -I tools/live_prompt_glyphs.py --base <inflated movie> --pc-glyphs <folder> --out <file>
python -I tools/live_prompt_glyphs.py --describe --from-archive "<package>/data.rpf" # names and sizes only
The output holds the title's tags (its ActionScript included): keep it on your PC and never commit it.
tools/prompt_glyph_movies.py builds it where the runtime looks.
"""
import argparse
import os
import struct
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import abc_file # noqa: E402
import pc_prompt_glyphs as pc # noqa: E402
import ps_prompt_glyphs as swf # noqa: E402
MOVIE_SIZE = 28148
# The bits of the three doubles (see the docstring); glyphs.rs has the same numbers.
SENTINEL_LOW = 0x4C454F4E49444131 # "LEONIDA1"
SENTINEL_HIGH = 0x4C454F4E49444132 # "LEONIDA2"
FAMILY_UNSET = 0x4C454F4E49444146 # "LEONIDAF"
KEYBOARD = 2 # Family::KeyboardMouse
MAIN = "platform_xbsx.input_icons:Main"
ASSET = "mx.core:SpriteAsset"
BUTTON = "platform_xbsx.input_icons:Main_Button_"
FIRST_PAD = "p" # the name of the first pad piece in each sprite (drawn over the keyboard pieces)
# The title's symbol class constructor: getlocal0, pushscope, getlocal0, constructsuper 0, returnvoid.
PLAIN_CONSTRUCTOR = bytes.fromhex("d030d0490047")
# ---------------------------------------------------------------- AVM2 instructions used here
GETLOCAL0, GETLOCAL1, GETLOCAL2, GETLOCAL3 = 0xD0, 0xD1, 0xD2, 0xD3
SETLOCAL2, SETLOCAL3 = 0xD6, 0xD7
GETLOCAL, SETLOCAL, INCLOCAL_I = 0x62, 0x63, 0xC2
PUSHSCOPE, CONSTRUCTSUPER, RETURNVOID, POP, LABEL = 0x30, 0x49, 0x47, 0x29, 0x09
GETLEX, GETPROPERTY, SETPROPERTY, CALLPROPERTY, CALLPROPVOID = 0x60, 0x66, 0x61, 0x46, 0x4F
PUSHBYTE, PUSHSTRING = 0x24, 0x2C
EQUALS, GREATEREQUALS = 0xAB, 0xB0
NOT, PUSHDOUBLE, MULTIPLY, INCREMENT = 0x96, 0x2F, 0xA2, 0x91
JUMP, IFTRUE, IFFALSE, IFEQ, IFNE, IFLT = 0x10, 0x11, 0x12, 0x13, 0x14, 0x15
# opcode -> (operands: "u" a u30, "b" a byte, "s" an s24 branch offset; stack change, or None when it depends on
# an argument count; scope change)
OPS = {
GETLOCAL0: ("", 1, 0), GETLOCAL1: ("", 1, 0), GETLOCAL2: ("", 1, 0), GETLOCAL3: ("", 1, 0),
SETLOCAL2: ("", -1, 0), SETLOCAL3: ("", -1, 0),
GETLOCAL: ("u", 1, 0), SETLOCAL: ("u", -1, 0), INCLOCAL_I: ("u", 0, 0),
PUSHSCOPE: ("", -1, 1), CONSTRUCTSUPER: ("u", None, 0), RETURNVOID: ("", 0, 0), POP: ("", -1, 0),
LABEL: ("", 0, 0),
GETLEX: ("u", 1, 0), GETPROPERTY: ("u", 0, 0), SETPROPERTY: ("u", -2, 0),
CALLPROPERTY: ("uu", None, 0), CALLPROPVOID: ("uu", None, 0),
PUSHBYTE: ("b", 1, 0), PUSHSTRING: ("u", 1, 0), EQUALS: ("", -1, 0), GREATEREQUALS: ("", -1, 0),
NOT: ("", 0, 0), PUSHDOUBLE: ("u", 1, 0), MULTIPLY: ("", -1, 0), INCREMENT: ("", 0, 0),
JUMP: ("s", 0, 0), IFTRUE: ("s", -1, 0), IFFALSE: ("s", -1, 0),
IFEQ: ("s", -2, 0), IFNE: ("s", -2, 0), IFLT: ("s", -2, 0),
}
ENDS = (RETURNVOID, JUMP) # no fall-through
class Asm:
"""Writes instructions; branches name labels, resolved by `code`."""
def __init__(self):
self.out = bytearray()
self.labels = {}
self.fixups = []
def op(self, opcode, *args):
kinds = OPS[opcode][0]
if len(args) != len(kinds):
raise ValueError("opcode %#x takes %d operands" % (opcode, len(kinds)))
self.out.append(opcode)
for kind, arg in zip(kinds, args):
if kind == "u":
self.out += abc_file.u30(arg)
elif kind == "b":
self.out.append(arg & 0xFF)
else:
self.fixups.append((len(self.out), arg))
self.out += b"\0\0\0"
return self
def label(self, name, mark=False):
"""`name` is here; `mark` writes the `label` instruction a backward branch must land on."""
self.labels[name] = len(self.out)
if mark:
self.out.append(LABEL)
return self
def here(self):
return len(self.out)
def code(self):
out = bytearray(self.out)
for at, name in self.fixups:
offset = self.labels[name] - (at + 3)
out[at:at + 3] = struct.pack("<i", offset)[:3]
return bytes(out)
def walk(code):
"""[(offset, opcode, operands, next offset)] of a body's code; refuses an instruction not in `OPS`."""
r, out = abc_file.Reader(code), []
while r.at < len(code):
at, opcode = r.at, r.u8()
if opcode not in OPS:
raise ValueError("instruction %#x at %d is not one this tool writes" % (opcode, at))
args = []
for kind in OPS[opcode][0]:
if kind == "u":
args.append(r.u30())
elif kind == "b":
args.append(r.u8())
else:
raw = r.raw(3)
args.append(struct.unpack("<i", raw + (b"\xff" if raw[2] & 0x80 else b"\0"))[0])
out.append((at, opcode, args, r.at))
return out
def check_body(abc, body):
"""Follows every path through a body written here, with the stack and scope depth on each, as the AVM2 verifier
does: the same depth wherever paths meet, never below zero, at most `max_stack` and `max_scope - init_scope`,
branches onto instructions (backward ones onto a `label`), locals below `locals`, operands in their pools, and
no path running off the end. Raises ValueError; returns (stack, scope) high-water marks."""
steps = walk(body.code)
index = {at: i for i, (at, _, _, _) in enumerate(steps)}
depth = {0: (0, 0)}
for _, _, target, _, _ in body.exceptions:
depth[target] = (1, 0)
work = list(depth)
high = [0, 0]
while work:
at = work.pop()
if at not in index:
raise ValueError("a path reaches %d, not an instruction" % at)
stack, scope = depth[at]
_, opcode, args, nxt = steps[index[at]]
kinds, change, scope_change = OPS[opcode]
if change is None:
change = {CONSTRUCTSUPER: lambda: -(args[0] + 1), CALLPROPERTY: lambda: -args[1],
CALLPROPVOID: lambda: -(args[1] + 1)}[opcode]()
if opcode in (CONSTRUCTSUPER, CALLPROPERTY, CALLPROPVOID):
need = args[-1] + 1 # the receiver and the arguments
else:
need = {SETPROPERTY: 2, IFEQ: 2, IFNE: 2, IFLT: 2, EQUALS: 2, GREATEREQUALS: 2, IFTRUE: 1, IFFALSE: 1,
POP: 1, PUSHSCOPE: 1, SETLOCAL2: 1, SETLOCAL3: 1, SETLOCAL: 1, GETPROPERTY: 1,
NOT: 1, INCREMENT: 1, MULTIPLY: 2}.get(opcode, 0)
if stack < need:
raise ValueError("stack underflow at %d" % at)
stack, scope = stack + change, scope + scope_change
high = [max(high[0], stack), max(high[1], scope)]
if opcode in (GETLOCAL, SETLOCAL, INCLOCAL_I) and args[0] >= body.locals:
raise ValueError("local %d at %d, the body has %d" % (args[0], at, body.locals))
if opcode in (GETLOCAL2, SETLOCAL2) and body.locals < 3 or opcode in (GETLOCAL3, SETLOCAL3) and body.locals < 4:
raise ValueError("a local the body does not have at %d" % at)
if opcode in (GETLEX, GETPROPERTY, SETPROPERTY, CALLPROPERTY, CALLPROPVOID) and \
not 0 < args[0] < len(abc.multinames):
raise ValueError("multiname %d at %d" % (args[0], at))
if opcode == PUSHSTRING and not 0 < args[0] < len(abc.strings):
raise ValueError("string %d at %d" % (args[0], at))
if opcode == PUSHDOUBLE and not 0 < args[0] < len(abc.doubles):
raise ValueError("double %d at %d" % (args[0], at))
nexts = []
if opcode not in ENDS:
nexts.append(nxt)
if "s" in kinds:
target = nxt + args[-1]
if target <= at and (target not in index or steps[index[target]][1] != LABEL):
raise ValueError("a backward branch at %d lands on %d, not a label" % (at, target))
nexts.append(target)
for n in nexts:
if n >= len(body.code):
raise ValueError("a path runs off the end after %d" % at)
if n in depth:
if depth[n] != (stack, scope):
raise ValueError("paths meet at %d with depths %s and %s" % (n, depth[n], (stack, scope)))
else:
depth[n] = (stack, scope)
work.append(n)
if high[0] > body.max_stack:
raise ValueError("stack reaches %d, max_stack is %d" % (high[0], body.max_stack))
if high[1] > body.max_scope - body.init_scope:
raise ValueError("scope reaches %d, the body allows %d" % (high[1], body.max_scope - body.init_scope))
return tuple(high)
# ---------------------------------------------------------------- the ActionScript added to the title's block
class Hooked:
"""What `hook` added: method and body indices for the checks, and the double the runtime patches."""
def __init__(self):
self.bodies = []
self.slots = {}
def hook(abc):
"""Adds the slots, the four methods and the constructor call (see the docstring) to the title's ABC, in place.
Refuses a block that is not the one measured: the classes, their base and the plain constructor must be there."""
main = abc.find_class(MAIN)
asset = abc.find_class(ASSET)
buttons = [i for i, inst in enumerate(abc.instances) if abc.name(inst.name).startswith(BUTTON)]
subclasses = [i for i, inst in enumerate(abc.instances) if inst.super_name == abc.instances[asset].name]
if not buttons or sorted(buttons) != sorted(subclasses):
raise ValueError("the symbol classes are not exactly the subclasses of %s" % ASSET)
for name in (b"lnFamily", b"lnShow"):
if name in abc.strings[1:]:
raise ValueError("the block already has the live prompt code")
ctors = [abc.body_of(abc.instances[i].iinit) for i in buttons]
if any(ctor.code != PLAIN_CONSTRUCTOR or ctor.exceptions for ctor in ctors):
raise ValueError("a symbol class's constructor is not the plain one this tool extends")
for raw in (SENTINEL_LOW, SENTINEL_HIGH, FAMILY_UNSET):
if struct.pack("<Q", raw) in abc.doubles[1:]:
raise ValueError("the block already holds a sentinel")
public = abc.namespace(abc_file.NS_PACKAGE, "")
mn = lambda name: abc.qname(public, name) # noqa: E731
main_mn = abc.instances[main].name
cinit = abc.body_of(abc.classes[main][0])
scope = cinit.init_scope
if cinit.code[:2] != bytes([GETLOCAL0, PUSHSCOPE]) or cinit.code[2] == LABEL:
raise ValueError("Main's static initialiser does not start as this tool expects")
# The unset family, and half of each sentinel (the sentinels themselves are made at run time).
pool = {}
for key, bits in (("unset", FAMILY_UNSET), ("low/2", half(SENTINEL_LOW)), ("high/2", half(SENTINEL_HIGH))):
abc.doubles.append(struct.pack("<Q", bits))
pool[key] = len(abc.doubles) - 1
traits = abc.classes[main][1]
slot = 1 + max([t.data[0] for t in traits if t.kind in (abc_file.TRAIT_SLOT, abc_file.TRAIT_CONST)] + [0])
number = mn("Number")
out = Hooked()
zero = abc.double(0.0)
for name, value in (("lnLo", 0), ("lnFamily", pool["unset"]), ("lnHi", 0), ("lnMade", zero), ("lnShown", zero)):
data = [slot, number, value, abc_file.CONST_DOUBLE] if value else [slot, number, 0]
traits.append(abc_file.Trait(mn(name), abc_file.TRAIT_SLOT, data))
out.slots[name] = slot
slot += 1
for name in ("lnTickFn", "lnAddedFn"):
traits.append(abc_file.Trait(mn(name), abc_file.TRAIT_SLOT, [slot, 0, 0]))
out.slots[name] = slot
slot += 1
family, tick_fn, added_fn = mn("lnFamily"), mn("lnTickFn"), mn("lnAddedFn")
made, shown = mn("lnMade"), mn("lnShown")
show, init, tick, added = mn("lnShow"), mn("lnInit"), mn("lnTick"), mn("lnAdded")
visible, child_at = mn("visible"), mn("getChildAt")
enter_frame, added_to_stage = abc.string("enterFrame"), abc.string("addedToStage")
def method(trait, locals_, max_stack, write):
index = abc.method(params=1, name=abc.string(abc.text(abc.multinames[trait][2])))
a = Asm()
a.op(GETLOCAL0).op(PUSHSCOPE)
write(a)
end = a.here()
a.op(POP).op(RETURNVOID) # the catch: whatever was thrown is dropped
body = abc_file.Body(index, max_stack, locals_, scope, scope + 1, a.code(), [(0, end, end, 0, 0)])
abc.bodies.append(body)
traits.append(abc_file.Trait(trait, abc_file.TRAIT_METHOD, [0, index]))
out.bodies.append(body)
return index
def write_show(a):
# locals: 0 Main, 1 the sprite, 2 the first pad piece then its index, 3 pad wanted?, 4 i, 5 children
a.op(GETLOCAL1).op(PUSHSTRING, abc.string(FIRST_PAD)).op(CALLPROPERTY, mn("getChildByName"), 1)
a.op(SETLOCAL2).op(GETLOCAL2).op(IFFALSE, "end")
a.op(GETLOCAL0).op(GETPROPERTY, family).op(PUSHBYTE, KEYBOARD).op(EQUALS).op(NOT).op(SETLOCAL3)
# Nothing to do when the first key piece is hidden exactly when the pad shows, and the pad shows.
a.op(GETLOCAL1).op(PUSHBYTE, 1).op(CALLPROPERTY, child_at, 1).op(GETPROPERTY, visible)
a.op(GETLOCAL3).op(IFEQ, "pass")
a.op(GETLOCAL2).op(GETPROPERTY, visible).op(GETLOCAL3).op(IFNE, "pass")
a.op(RETURNVOID)
a.label("pass")
a.op(GETLOCAL0).op(GETLOCAL0).op(GETPROPERTY, shown).op(INCREMENT).op(SETPROPERTY, shown)
a.op(GETLOCAL1).op(GETLOCAL2).op(CALLPROPERTY, mn("getChildIndex"), 1).op(SETLOCAL2)
a.op(GETLOCAL1).op(GETPROPERTY, mn("numChildren")).op(SETLOCAL, 5)
a.op(PUSHBYTE, 1).op(SETLOCAL, 4).op(JUMP, "test")
a.label("loop", mark=True)
a.op(GETLOCAL1).op(GETLOCAL, 4).op(CALLPROPERTY, child_at, 1)
a.op(GETLOCAL, 4).op(GETLOCAL2).op(GREATEREQUALS).op(GETLOCAL3).op(EQUALS).op(SETPROPERTY, visible)
a.op(INCLOCAL_I, 4)
a.label("test")
a.op(GETLOCAL, 4).op(GETLOCAL, 5).op(IFLT, "loop")
a.label("end")
a.op(RETURNVOID)
def write_init(a):
a.op(GETLOCAL0).op(GETLOCAL0).op(GETPROPERTY, made).op(INCREMENT).op(SETPROPERTY, made)
a.op(GETLOCAL0).op(GETLOCAL1).op(CALLPROPVOID, show, 1)
a.op(GETLOCAL0).op(GETPROPERTY, tick_fn).op(IFTRUE, "have")
a.op(GETLOCAL0).op(GETLOCAL0).op(GETPROPERTY, tick).op(SETPROPERTY, tick_fn)
a.op(GETLOCAL0).op(GETLOCAL0).op(GETPROPERTY, added).op(SETPROPERTY, added_fn)
a.label("have")
a.op(GETLOCAL1).op(PUSHSTRING, enter_frame).op(GETLOCAL0).op(GETPROPERTY, tick_fn)
a.op(CALLPROPVOID, mn("addEventListener"), 2)
a.op(RETURNVOID)
def write_tick(a):
a.op(GETLOCAL1).op(GETPROPERTY, mn("currentTarget")).op(SETLOCAL2)
a.op(GETLOCAL2).op(GETPROPERTY, mn("stage")).op(IFTRUE, "live")
a.op(GETLOCAL2).op(PUSHSTRING, enter_frame).op(GETLOCAL0).op(GETPROPERTY, tick_fn)
a.op(CALLPROPVOID, mn("removeEventListener"), 2)
a.op(GETLOCAL2).op(PUSHSTRING, added_to_stage).op(GETLOCAL0).op(GETPROPERTY, added_fn)
a.op(CALLPROPVOID, mn("addEventListener"), 2)
a.op(RETURNVOID)
a.label("live")
a.op(GETLOCAL0).op(GETLOCAL2).op(CALLPROPVOID, show, 1)
a.op(RETURNVOID)
def write_added(a):
a.op(GETLOCAL1).op(GETPROPERTY, mn("currentTarget")).op(SETLOCAL2)
a.op(GETLOCAL2).op(PUSHSTRING, added_to_stage).op(GETLOCAL0).op(GETPROPERTY, added_fn)
a.op(CALLPROPVOID, mn("removeEventListener"), 2)
a.op(GETLOCAL0).op(GETLOCAL2).op(CALLPROPVOID, init, 1)
a.op(RETURNVOID)
method(show, 6, 4, write_show)
method(init, 2, 4, write_init)
method(tick, 3, 4, write_tick)
method(added, 3, 4, write_added)
# Each symbol class's constructor: its own work, then Main.lnInit(this) in a try block.
a = Asm()
a.out += PLAIN_CONSTRUCTOR[:-1]
start = a.here()
a.op(GETLEX, main_mn).op(GETLOCAL0).op(CALLPROPVOID, init, 1)
end = a.here()
a.op(RETURNVOID)
handler = a.here()
a.op(POP).op(RETURNVOID)
code = a.code()
for ctor in ctors:
ctor.code = code
ctor.exceptions = [(start, end, handler, 0, 0)]
ctor.max_stack = max(ctor.max_stack, 2)
out.bodies.append(ctor)
# Main's static initialiser: the sentinels first, made from their halves, then the title's own code.
a = Asm()
for name, key in (("lnLo", "low/2"), ("lnHi", "high/2")):
a.op(GETLOCAL0).op(PUSHDOUBLE, pool[key]).op(PUSHBYTE, 2).op(MULTIPLY).op(SETPROPERTY, mn(name))
added_code = a.code()
check_body(abc, abc_file.Body(0, 3, 1, 0, 1, bytes([GETLOCAL0, PUSHSCOPE]) + added_code + bytes([RETURNVOID])))
cinit.code = cinit.code[:2] + added_code + cinit.code[2:]
cinit.exceptions = [(f + len(added_code) if f >= 2 else f, t + len(added_code), g + len(added_code), k, v)
for f, t, g, k, v in cinit.exceptions]
cinit.max_stack = max(cinit.max_stack, 3)
out.cinit_added = added_code
for body in out.bodies:
check_body(abc, body)
return out
def half(bits):
"""The bits of half the double `bits` (exact: one less in the exponent)."""
value = struct.unpack("<d", struct.pack("<Q", bits))[0] / 2
out = struct.unpack("<Q", struct.pack("<d", value))[0]
assert struct.unpack("<d", struct.pack("<Q", out))[0] * 2 == struct.unpack("<d", struct.pack("<Q", bits))[0]
return out
def hook_block(body):
"""A DoABC tag body (flags, name, ABC) with the live prompt code added."""
end = body.index(b"\0", 4)
abc = abc_file.parse(body[end + 1:])
hook(abc)
return body[:end + 1] + abc.serialize()
# ---------------------------------------------------------------- the sprites
def place(depth, cid, tx, ty, name=None):
"""PlaceObject2 of a shape at a translation, with a name if given."""
b = swf.Bits()
b.ub(0, 2) # no scale, no rotate
nb = swf.sbits(tx, ty)
b.ub(nb, 5)
b.sb(tx, nb)
b.sb(ty, nb)
flags = 0x06 | (0x20 if name else 0)
body = bytes([flags]) + struct.pack("<HH", depth, cid) + b.bytes()
if name:
body += swf.cstr(name)
return swf.tag(26, body)
def sprite_tag(sid, pad_items, key_items):
"""DefineSprite `sid`: the bounds rectangle (the pad's first item), the keyboard pieces, then the other pad pieces
on top, the first of them named."""
body = struct.pack("<HH", sid, 1)
items = list(pad_items[:1]) + list(key_items) + list(pad_items[1:])
for depth, (cid, tx, ty) in enumerate(items, 1):
name = FIRST_PAD if depth == len(key_items) + 2 else None
body += place(depth, cid, tx, ty, name)
body += swf.tag(1, b"") + swf.tag(0, b"")
return swf.tag(39, body)
def bounds_shape(movie, n):
x0, y0, x1, y1 = swf.BOUNDS.get(n, (0, 0, swf.BOX, swf.BOX))
return movie.shape([swf.poly_contour(swf.clockwise([(x0, y0), (x1, y0), (x1, y1), (x0, y1)]))], swf.CLEAR)
def bounds_shape_pc(movie, n):
"""The rectangle as tools/pc_prompt_glyphs.py writes it (its corners in the other order)."""
x0, y0, x1, y1 = swf.BOUNDS.get(n, (0, 0, swf.BOX, swf.BOX))
return movie.shape([swf.poly_contour([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])], swf.CLEAR)
def sprites(movie, ids, glyphs, pad_sprite=swf.build_sprite):
"""{character id: DefineSprite tag} of both sets, sharing `movie`'s shapes."""
out = {}
for cid, n in ids.items():
pad = pad_sprite(movie, n).items
if pad[:1] != [bounds_shape(movie, n)]:
raise ValueError("the pad picture of %d does not start with its bounds" % n)
keys = [item for item in glyphs.sprite(movie, n).items if item != bounds_shape_pc(movie, n)]
if not keys:
raise ValueError("the keyboard picture of %d is empty" % n)
out[cid] = sprite_tag(cid, pad, keys)
return out
# ---------------------------------------------------------------- the movie
def build_over(base, glyphs=None, pad_sprite=swf.build_sprite):
"""The title's movie `base` with both sets drawn into its sprites and the live code in its ActionScript block,
padded to its length. `glyphs` is a traced keyboard set (pc_prompt_glyphs.trace), the built-in one if None.
Raises ValueError when something does not match or the two sets do not fit."""
if base[:3] not in (b"GFX", b"FWS"):
raise ValueError("not an uncompressed movie")
tags, start = swf.read_tags(base)
ids = swf.exports_of(tags)
unknown = sorted(n for n in ids.values() if n not in swf.GLYPHS)
if unknown or sorted(ids.values()) != sorted(swf.GLYPHS):
raise ValueError("the movie's exports are not the 38 this tool draws: %s" % (unknown or sorted(ids.values())))
if sum(1 for code, _ in tags if code == 82) != 1:
raise ValueError("the movie does not have exactly one ActionScript block")
glyphs = glyphs or pc.trace(pc.builtin())
movie = swf.Movie(compact=True)
movie.next_id = 1 + max(struct.unpack_from("<H", body, 0)[0] for code, body in tags if code in (2, 22, 32, 39, 83))
drawn = sprites(movie, ids, glyphs, pad_sprite)
out, placed = [], False
for code, body in tags:
if code in (32, 39) and not placed:
out.extend(swf.tag(32, movie.shapes[key][1]) for key in movie.order)
placed = True
if code in (32, 77):
continue # the title's shapes, and any padding, give their room to ours
if code == 39:
cid = struct.unpack_from("<H", body, 0)[0]
if cid not in drawn:
raise ValueError("a sprite (%d) that is not one of the exports" % cid)
out.append(drawn[cid])
continue
if code == 82:
body = hook_block(body)
out.append(swf.tag(code, body))
data = base[:4] + struct.pack("<I", 0) + base[8:start] + b"".join(out)
if len(data) > len(base):
raise ValueError("both sets and the code take %d bytes, %d over the title's %d"
% (len(data), len(data) - len(base), len(base)))
data = swf.pad_movie(data, len(base))
if data.count(struct.pack("<Q", FAMILY_UNSET)) != 1:
raise ValueError("the unset family is not in the movie exactly once")
for bits in (SENTINEL_LOW, SENTINEL_HIGH):
if struct.pack("<Q", bits) in data:
raise ValueError("a sentinel is in the movie's bytes")
return data
def family_offset(movie):
"""Where the runtime writes the family in use into the served movie: the one copy of `FAMILY_UNSET`."""
raw = struct.pack("<Q", FAMILY_UNSET)
at = movie.find(raw)
if at < 0 or movie.find(raw, at + 1) >= 0:
raise ValueError("the movie does not hold the unset family exactly once")
return at
def room(data, base):
"""(bytes the sets and code took beyond the title's own tags, bytes left as padding) of a built movie."""
pad = sum((2 if len(b) < 63 else 6) + len(b) for code, b in swf.read_tags(data)[0] if code == 77)
return len(base) - pad, pad
def describe(base, out=sys.stdout):
"""Names, counts and sizes of the title's movie and its ActionScript block: nothing of their content."""
tags, _ = swf.read_tags(base)
counts = {}
for code, body in tags:
n, size = counts.get(code, (0, 0))
counts[code] = (n + 1, size + len(body))
out.write("tags: %s\n" % ", ".join("%d x%d (%d bytes)" % (c, n, s) for c, (n, s) in sorted(counts.items())))
for code, body in tags:
if code == 82:
end = body.index(b"\0", 4)
abc_file.describe(abc_file.parse(body[end + 1:]), out)
def main(argv):
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--from-archive", help="the title's movie from this data.rpf (read-only)")
ap.add_argument("--base", help="the title's movie from this inflated file instead")
ap.add_argument("--pc-glyphs", help="your own keyboard pictures (see tools/pc_prompt_glyphs.py); default built-in")
ap.add_argument("--out", help="write the movie here")
ap.add_argument("--describe", action="store_true", help="print names, counts and sizes of the title's movie")
args = ap.parse_args(argv)
if not (args.from_archive or args.base):
ap.error("name the title's movie: --from-archive or --base")
if args.base:
with open(args.base, "rb") as f:
base = f.read()
else:
base = swf.read_archive_movie(args.from_archive)
if args.describe:
describe(base)
if args.out:
glyphs = pc.trace(pc.read_folder(args.pc_glyphs) if args.pc_glyphs else pc.builtin())
try:
data = build_over(base, glyphs)
except ValueError as error:
sys.exit("the live movie was not built: %s" % error)
used, spare = room(data, base)
print("%d bytes, %d to spare; the family is written at %d" % (len(data), spare, family_offset(data)))
with open(args.out, "wb") as f:
f.write(data)
elif not args.describe:
ap.print_help()
if __name__ == "__main__":
sys.stdout.reconfigure(errors="replace")
main(sys.argv[1:])