Files
firestorm/MW4COMPARE/tools/decompile/contents.py
T
83478b7666 Add MW4COMPARE: .mw4 decompiler toolchain and V4H comparison harness
Tooling built to recover editable source for six 'Mech chassis that exist
in the parallel FS_Build_V4H build but not in this repo. Reverse-engineers
every compiled record type in the .mw4 package format back to the .data /
.instance / .subsystems / .damage / .contents / .torso / .engine /
.armature sources the content pipeline consumes.

Nothing here is wired into the game build. It is a standalone analysis
harness run from Linux.

Package format
--------------
"#VBD" container. Directory records are [len][name][FILETIME][origSize]
[storedSize][offset], payload base at dword 0x0C. A record is stored raw
when storedSize == origSize, otherwise LZW (9->12-bit LSB-first codes,
256=clear, 257=EOF, dict from 258), per Database.cpp:451.

GameModel records are flat /Zp4 structs following the C++ inheritance
chain Entity(0) -> Mover(28) -> MWObject(80) -> Vehicle(664) -> Mech(756),
1636 bytes total. CreateMessage records follow Replicator -> Entity ->
Mover -> MWMover -> MWObject -> Vehicle -> Mech from start=16 (the
undeclared Connection__Message header), ending at 341 and padded to 344.

tools/decompile/
----------------
  datamap.py        header-driven layout engine; CHAIN + ANCHORS
                    {Vehicle:664, Mech:756} assert the struct offsets
  mw4msg.py         CreateMessage reader/walker
  data.py           .data      constants.py  define/table symbol resolution
  damage.py         .damage    contents.py   .contents
  smallmodel.py     .torso + .engine         instance.py  .instance
  armature.py / armature_parts.py  .armature + armaturedata/armaturevideo
  assembly.py       joint hierarchy renderer
  make_generic_doll.py  builds generic MFD/Radar damage dolls
  verify_*.py       per-type round-trip verifiers

Verified round-trip across all 64 shared chassis:
  .armature      2938/2976 pages     .subsystems  7579/7585 keys
  .data map      6071/6071 values    .data trip   8291/8306 keys
  .damage        6605/6605 keys      .contents    7480/7480 keys
  .torso+.engine 1280/1280 keys      .instance     896/896 keys, 64/64 pages
  armature_parts 1202/1202 .data, 1149/1202 .video

Layout-discovery lessons (documented in DECOMPILING.md)
-------------------------------------------------------
- Never let a field map be discovered by the values that verify it. A
  value-matching pass reported 4288/4288 while mis-assigning 34 keys. The
  map was rebuilt from header declaration order, anchored on uniquely
  resolved fields.
- Read the factory, not the data. 12 .data fields and 5 Torso fields are
  declared plain Stuff::Scalar but multiplied by Radians_Per_Degree in
  Mech_Tool.cpp:889 / Torso_Tool.cpp.
- Strip typedefs before walking a header. A stray `typedef int AttributeID;`
  masked a missing ClassID - two 4-byte errors cancelling out, caught only
  by the ANCHORS assertion.
- A verifier that silently narrows its own input reports success. Braced
  blocks must be hidden before splitting pages, replacing both CR and LF,
  because a `Shadow={...}` block contains a line reading `[shadow]` and
  splitlines() also splits on bare CR.
- NSWIZZLE is undefined, so the #else branch is live and orders members
  differently. bool is 1 byte; char x[MaxStringLength] is 256.
- V4H carries stale Mech IDs (their Atlas is 5, ours 6), so 64 of 65 shared
  chassis are off by one; --retarget-ids emits $(M_<Chassis>)/$(IDS_<Chassis>).

reports/ holds generated diffs. The two ~5 MB manifest-*.tsv intermediates
are gitignored; regenerate everything with run-comparison.sh.

Co-authored-by: Claude Opus 5 (Anthropic) <noreply@anthropic.com>
Co-authored-by: GitHub Copilot <copilot@github.com>
2026-08-08 16:47:57 -05:00

126 lines
4.7 KiB
Python

#!/usr/bin/env python3
"""
contents.py - decompiler for a mech `<chassis>.contents` file.
`.contents` is the thin half of the pair `armature.py` already handles. It
`!include`s `<chassis>.armature` and then gives every joint and site exactly two
entries:
[joint_torso]
Model=basic.data
ExecutionState=AlwaysExecuteState
Both values ride in the same CreateMessages `armature.py` walks -- the `.armature`
source contributes a page's geometry, the `.contents` source contributes its
Model and ExecutionState, and the packer merges them into one message per page.
So nothing new has to be located: `Model` is `dataListID` (record id in the HIGH
word) and `ExecutionState` is the enum at offset 76.
Site pages are the exception. `{sites}` records store only name, rotation and
translation, so a site's Model and ExecutionState are not in the package at all.
They do not need to be: all **2926** site pages across the 89 mech `.contents`
files carry the identical pair `basic.data` / `AlwaysExecuteState`, so they are
emitted as constants rather than guessed per mech.
python3 contents.py <chassis-record-dir> [-o out.contents]
python3 contents.py --verify
"""
import argparse, collections, glob, os, re, struct, subprocess, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import mw4msg, subsystems
MANIFEST = "/home/rich/Repositories/FS_Ours_extracted/_manifest.tsv"
REC_RE = re.compile(r'^(?P<chassis>.+?)\.contents\[(?P<parent>[^\]]+)\]\{(?P<kind>armature|sites)\}$',
re.I)
EXEC_STATE = {1: "NeverExecuteState", 2: "AlwaysExecuteState", 6: "ActiveState"}
SITE_DEFAULTS = [("Model", "basic.data"), ("ExecutionState", "AlwaysExecuteState")]
EXEC_OFF = 76
DATALIST_OFF = 84
def relative(path, chassis, folder=None):
"""Model= is written relative to the mech folder, not from the package root.
The package path uses the FOLDER name, which need not match the record stem
(V4H's jenner2c/ holds jenner_2c.* records), so both are tried.
"""
if not path:
return path
for name in (chassis, folder):
if name:
path = re.sub(rf'^mechs[\\/]{re.escape(name)}[\\/]', '', path, flags=re.I)
return path
def decompile(mech_dir, manifest=None):
"""-> (chassis, [(pageName, [(key, value)])])"""
manifest = manifest if manifest is not None else subsystems.load_manifest(MANIFEST)
chassis = None
folder = os.path.basename(mech_dir.rstrip("/"))
pages = collections.OrderedDict()
root = [p for p in glob.glob(os.path.join(mech_dir, "*.contents"))
if not re.search(r'[\[\{]', os.path.basename(p))]
for path in sorted(glob.glob(os.path.join(mech_dir, "*{armature}"))) + root:
base = os.path.basename(path)
m = REC_RE.match(base)
if m:
chassis = chassis or m.group("chassis")
else:
chassis = chassis or base[:-len(".contents")]
with open(path, "rb") as fh:
data = fh.read()
for _off, msg in mw4msg.walk(data):
name = mw4msg.joint_name(msg)
if not name:
continue
model = manifest.get(mw4msg.record_id(msg, DATALIST_OFF))
state = EXEC_STATE.get(struct.unpack_from("<i", msg, EXEC_OFF)[0])
pages.setdefault(name, [("Model", relative(model, chassis, folder)),
("ExecutionState", state)])
for path in sorted(glob.glob(os.path.join(mech_dir, "*{sites}"))):
with open(path, "rb") as fh:
for name, _rot, _trans in mw4msg.read_sites(fh.read()):
pages.setdefault(name, list(SITE_DEFAULTS))
return chassis, list(pages.items())
def emit(chassis, pages):
lines = ["[includes]", f"!include={chassis}.armature", ""]
for name, kv in pages:
lines.append(f"[{name}]")
lines.extend(f"{k}={v}" for k, v in kv)
lines.append("")
return "\r\n".join(lines)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("mech_dir", nargs="?")
ap.add_argument("-o", "--output")
ap.add_argument("-m", "--manifest", default=MANIFEST)
ap.add_argument("--verify", action="store_true")
args = ap.parse_args()
if args.verify:
here = os.path.dirname(os.path.abspath(__file__))
raise SystemExit(subprocess.call([sys.executable,
os.path.join(here, "verify_contents.py")]))
if not args.mech_dir:
ap.error("mech_dir required")
chassis, pages = decompile(args.mech_dir, subsystems.load_manifest(args.manifest))
text = emit(chassis, pages)
if args.output:
with open(args.output, "wb") as fh:
fh.write(text.encode("latin-1"))
print(f"wrote {args.output}")
else:
sys.stdout.write(text)
if __name__ == "__main__":
main()