From c1aa89e0ffa89b88ca3e7dafb77bc87e71eb9ff2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kacper=20Serewi=C5=9B?= Date: Mon, 23 Nov 2026 16:37:15 +0100 Subject: [PATCH] BUILD-2389: verify keyed drawable offset predictions against exported models (#6900) Squash-merged after diff review of PR #6900 - BUILD-2389: verify keyed drawable offset predictions against exported models --- docs/models.md | 29 ++++++++ tests/test_world_drawable_lookup.py | 43 +++++++++++ tests/test_world_drawable_verify.py | 60 +++++++++++++++ tools/world_drawable_lookup.py | 100 +++++++++++++++++++++++++ tools/world_drawable_verify.py | 109 ++++++++++++++++++++++++++++ 5 files changed, 341 insertions(+) create mode 100644 tests/test_world_drawable_lookup.py create mode 100644 tests/test_world_drawable_verify.py create mode 100644 tools/world_drawable_lookup.py create mode 100644 tools/world_drawable_verify.py diff --git a/docs/models.md b/docs/models.md index fd783dd36..5c29b2332 100644 --- a/docs/models.md +++ b/docs/models.md @@ -829,3 +829,32 @@ geometry from the BIN chunk. Standard library only; no game files. `levels.rpf` has the same 343,327 rows in a full export (50,731 fragments, 2,509,947,536 triangles). 4. Keep the README and issue #29 in sync with the new counts. + +### Predict model offsets for placements + +Run `python -I tools/world_drawable_lookup.py entities.jsonl archetypes.json names.json` +with the placement rows from `world_index.py --entities-out`, the definitions from +`world_archetypes.py`, and a bounded `rpf9_names.py --types dr,ft` report. The command +prints local scratch JSON. Supply `--manifest path/to/models/manifest.json` for each +existing export whose listed identities should be excluded. + +The lookup requires agreement between the placement archetype, the definition's name and +assetName, the resource stem's joaat and its 64-bit placement key. It considers type 1 +fragments and type 2 drawables at page offset +16. Multiple offsets for an identity in +the indexed window are marked ambiguous. Even a single hit is a prediction: a stream +can mention another model. Export a window around the predicted offset with +`rpf9dump models --start BYTES --length BYTES`, compare the manifest offset and +model identity and run `world_build.py --placements` with the exported geometry. + +Save the lookup JSON and run +`python -I tools/world_drawable_verify.py lookup.json first/models/manifest.json second/models/manifest.json` +to verify single-offset predictions. Supply completed normal model manifests from the +same source archive. The verifier reads cached JSON only. It uses the world builder's +name hashes and counts each identity and its placements once. A matching offset and both +hashes confirm an observation, including dictionary children sharing an offset. The local +report counts repeat exact observations and lists other offsets for the same identity. +Without an exact match, a different name at the offset takes precedence over a matching +identity elsewhere. The coverage flag independently records whether the predicted offset +falls in a supplied scan (start inclusive, end exclusive). A full scan covers all offsets. +A covered prediction with no named evidence remains missing. Geometry loadability is +checked separately by running the normal world builder on confirmed placement rows. diff --git a/tests/test_world_drawable_lookup.py b/tests/test_world_drawable_lookup.py new file mode 100644 index 000000000..fa4558257 --- /dev/null +++ b/tests/test_world_drawable_lookup.py @@ -0,0 +1,43 @@ +"""Synthetic coverage of the report join and its ambiguous/missing evidence.""" +import json +from pathlib import Path +import sys +import tempfile +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +import world_drawable_lookup as lookup +import world_names + + +class DrawableLookupTest(unittest.TestCase): + def test_only_export_candidates_with_consistent_evidence(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + names = ["one", "many", "conflict", "wrong_key", "unaligned", "cached", "missing_key"] + definitions, streams, placements = [], [], [] + for i, name in enumerate(names): + h = world_names.joaat(name) + definitions.append({"name": h, "asset_name": h, "asset_type": 2}) + key = world_names.hash64(name) + placements.append({"archetype": f"{h:x}", "key": f"{key:x}", "position": [0, 0, 0], + "rotation": [0, 0, 0, 1], "lod_level": 6}) + streams.append({"offset": 4096 * i + 16, "names": [name + ".#dr"]}) + streams.append({"offset": 4096 * 8 + 16, "names": ["many.#dr"]}) + definitions.append(dict(definitions[2], asset_type=1)) + placements[3]["key"] = "0" + streams[4]["offset"] += 1 + placements[-1].pop("key") + for file, data in [("defs", {"archetypes": definitions}), + ("names", {"summary": {"archive": "test.rpf"}, "files": streams}), + ("manifest", {"Items": [{"Name": "cached"}]})]: + (root / file).write_text(json.dumps(data), encoding="utf-8", newline="\n") + (root / "entities").write_text("\n".join(map(json.dumps, placements)), encoding="utf-8", newline="\n") + result = lookup.lookup(root / "entities", root / "defs", root / "names", [root / "manifest"]) + self.assertEqual(result["outcomes"], {"candidate": 1, "ambiguous": 1, "unresolved": 3, + "listed_in_manifest": 1, "missing_or_invalid_key": 1}) + self.assertEqual(sorted(r["offsets"] for r in result["candidates"]), [[16], [4112, 32784]]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_world_drawable_verify.py b/tests/test_world_drawable_verify.py new file mode 100644 index 000000000..af5882d04 --- /dev/null +++ b/tests/test_world_drawable_verify.py @@ -0,0 +1,60 @@ +"""Synthetic export windows and keyed model observations.""" +import json +from pathlib import Path +import sys +import tempfile +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +import world_drawable_verify as verifier +import world_names + + +class VerifyTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + + def write(self, name, data): + path = self.root / name + path.write_text(json.dumps(data), encoding="utf-8", newline="\n") + return path + + def test_join_counts_and_window_edges(self): + candidates = [] + for name, offset in [("one", 10), ("two", 12), ("three", 13), ("four", 14), ("five", 20)]: + candidates.append({"archetype": format(world_names.joaat(name), "x"), + "key": format(world_names.hash64(name), "x"), "offsets": [offset], + "status": "candidate", "placements": 3}) + # A 32-bit match alone cannot confirm the prediction. + candidates[1]["archetype"] = candidates[0]["archetype"] + candidates.append(dict(candidates[0], status="ambiguous", offsets=[10, 15])) + predictions = self.write("lookup", {"archive": "source.rpf", "candidates": candidates}) + export = {"src": "source.rpf", "Scan": {"Start": 10, "Length": 10}, + "Items": [{"Name": "one.#dr", "Offset": 10}, {"Name": "one", "Offset": 12}, + {"Name": "three", "Offset": 18}, {"Name": "", "Offset": 14}]} + first = self.write("first", export) + second = self.write("second", dict(export, Items=export["Items"][:1])) + result = verifier.verify(predictions, [first, second, first]) + self.assertEqual([r["status"] for r in result["rows"]], + ["confirmed", "conflicting_name", "conflicting_offset", "missing_evidence", + "outside_windows"]) + self.assertEqual(result["placements"], {s: 3 for s in result["identities"]}) + self.assertEqual(result["rows"][0]["duplicate_observations"], 1) + self.assertEqual(result["rows"][0]["other_identity_offsets"], [12]) + full = self.write("full", dict(export, Scan={})) + self.assertEqual(verifier.verify(predictions, [full])["identities"]["missing_evidence"], 2) + + def test_reject_unrelated_archive_and_bad_bounds(self): + predictions = self.write("lookup", {"archive": "source.rpf", "candidates": []}) + for source, scan in [("elsewhere/source.rpf", {}), ("source.rpf", {"Start": 0}), + ("source.rpf", {"Start": True, "Length": 5}), + ("source.rpf", {"Start": 0, "Length": 2})]: + manifest = self.write("manifest", {"src": source, "Scan": scan, "Items": [{"Offset": 2}]}) + with self.subTest(source=source, scan=scan), self.assertRaises(ValueError): + verifier.verify(predictions, [manifest]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/world_drawable_lookup.py b/tools/world_drawable_lookup.py new file mode 100644 index 000000000..0d25d9e19 --- /dev/null +++ b/tools/world_drawable_lookup.py @@ -0,0 +1,100 @@ +"""Predict model export offsets from local world_archetypes and rpf9_names reports.""" +import argparse +from collections import Counter, defaultdict +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import world_build +import world_names + + +def report_rows(path, field): + with open(path, encoding="utf-8-sig") as handle: + report = json.load(handle) + if not isinstance(report, dict) or not isinstance(report.get(field), list): + raise ValueError(f"{path}: expected a {field} array") + if any(not isinstance(row, dict) for row in report[field]): + raise ValueError(f"{path}: non-object in {field}") + return report + + +def lookup(placements, archetypes, names, manifests): + definitions = defaultdict(set) + for row in report_rows(archetypes, "archetypes")["archetypes"]: + definitions[row.get("name")].add((row.get("asset_name"), row.get("asset_type"))) + + counts = world_build._placement_counts() + wanted = Counter() + outcomes = Counter() + for row in world_build.iter_placements(placements, counts, world_build.ALL_LOD_LEVELS): + try: + key = int(row.get("key"), 16) + except (TypeError, ValueError): + outcomes["missing_or_invalid_key"] += 1 + continue + wanted[row["_arch"], key] += 1 + + listed = set() + for path in manifests: + entries = report_rows(path, "Items")["Items"] + index = world_build.model_name_index([("", item) for item in entries], world_names) + listed.update((h, key) for h, items in index.items() for _, _, key in items) + + offsets = defaultdict(set) + index = report_rows(names, "files") + summary = index.get("summary") + archive = summary.get("archive") if isinstance(summary, dict) else None + if not isinstance(archive, str) or not archive: + raise ValueError(f"{names}: missing archive in summary") + for row in index["files"]: + offset = row.get("offset") + if type(offset) is not int or offset < 0 or not isinstance(row.get("names"), list): + raise ValueError(f"{names}: invalid resource name index row") + if offset % 4096 != 16: + continue + for name in row["names"]: + if not isinstance(name, str): + raise ValueError(f"{names}: expected a resource name string") + stem, _, suffix = name.rpartition(".#") + asset_type = {"ft": 1, "dr": 2}.get(suffix.lower()) + if not stem or asset_type is None: + continue + h = world_names.joaat(stem) + identity = h, world_names.hash64(stem) + if identity in wanted and definitions.get(h) == {(h, asset_type)}: + offsets[identity].add(offset) + + candidates = [] + for identity, n in sorted(wanted.items()): + h, key = identity + hits = sorted(offsets.get(identity, ())) + if identity in listed: + outcomes["listed_in_manifest"] += n + elif hits: + status = "candidate" if len(hits) == 1 else "ambiguous" + outcomes[status] += n + candidates.append({"archetype": f"{h:08x}", "key": f"{key:016x}", "offsets": hits, + "placements": n, "status": status}) + else: + outcomes["unresolved"] += n + return {"archive": archive, "placements": counts, "outcomes": outcomes, "candidates": candidates} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("placements", help="world_index entity JSONL") + parser.add_argument("archetypes", help="world_archetypes JSON") + parser.add_argument("names", help="rpf9_names JSON for the source archive") + parser.add_argument("--manifest", action="append", default=[], help="exclude identities already listed (repeatable)") + args = parser.parse_args() + try: + result = lookup(args.placements, args.archetypes, args.names, args.manifest) + except (OSError, ValueError, TypeError) as exc: + parser.exit(1, f"{parser.prog}: {exc}\n") + print(json.dumps(result, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/tools/world_drawable_verify.py b/tools/world_drawable_verify.py new file mode 100644 index 000000000..2addfd274 --- /dev/null +++ b/tools/world_drawable_verify.py @@ -0,0 +1,109 @@ +"""Verify single-offset world_drawable_lookup predictions against normal model exports.""" +import argparse +from collections import Counter, defaultdict +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from world_drawable_lookup import report_rows +import world_build +import world_names + + +def archive_path(value): + if not isinstance(value, str) or not value.strip(): + raise ValueError("expected a source archive path") + return os.path.normcase(os.path.abspath(value)) + + +def verify(predictions, manifests): + report = report_rows(predictions, "candidates") + archive = archive_path(report.get("archive")) + windows = [] + full_scan = False + observations = Counter() + named_offsets = set() + by_identity = defaultdict(set) + paths = dict.fromkeys(os.path.normcase(os.path.realpath(path)) for path in manifests) + for path in paths: + export = report_rows(path, "Items") + if archive_path(export.get("src")) != archive: + raise ValueError(f"{path}: different source archive from predictions") + scan = export.get("Scan") + if not isinstance(scan, dict): + raise ValueError(f"{path}: missing Scan metadata") + bounded = "Start" in scan or "Length" in scan + if bounded: + start, length = scan.get("Start"), scan.get("Length") + if any(type(n) is not int or n < 0 for n in (start, length)): + raise ValueError(f"{path}: invalid Scan.Start or Scan.Length") + windows.append((start, start + length)) + else: + full_scan = True + for item in export["Items"]: + offset = item.get("Offset") + if type(offset) is not int or offset < 0 or (bounded and not start <= offset < start + length): + raise ValueError(f"{path}: invalid item offset for scan") + index = world_build.model_name_index([("", item) for item in export["Items"]], world_names) + for h, entries in index.items(): + for _, item, key in entries: + offset = item["Offset"] + observations[h, key, offset] += 1 + named_offsets.add(offset) + by_identity[h, key].add(offset) + + identities, placements = Counter(), Counter() + rows = [] + seen = set() + for row in report["candidates"]: + if row.get("status") == "ambiguous": + continue + offsets = row.get("offsets") + if (row.get("status") != "candidate" or not isinstance(offsets, list) or len(offsets) != 1 + or type(offsets[0]) is not int or offsets[0] < 0): + raise ValueError("expected single-offset candidate") + offset = offsets[0] + h, key = int(row["archetype"], 16), int(row["key"], 16) + if (h, key) in seen: + raise ValueError("duplicate candidate identity") + seen.add((h, key)) + n = row["placements"] + if type(n) is not int or n < 1: + raise ValueError("expected positive placement count") + covered = full_scan or any(start <= offset < end for start, end in windows) + exact = observations[h, key, offset] + elsewhere = sorted(by_identity[h, key] - {offset}) + if exact: + status = "confirmed" + elif offset in named_offsets: + status = "conflicting_name" + elif elsewhere: + status = "conflicting_offset" + elif covered: + status = "missing_evidence" + else: + status = "outside_windows" + identities[status] += 1 + placements[status] += n + rows.append({"archetype": row["archetype"], "key": row["key"], "offset": offset, + "placements": n, "status": status, "covered": covered, + "exact_observations": exact, "duplicate_observations": max(0, exact - 1), + "other_identity_offsets": elsewhere}) + return {"identities": identities, "placements": placements, "rows": rows} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("predictions", help="local world_drawable_lookup JSON") + parser.add_argument("manifest", nargs="+", help="rpf9dump models manifest.json from the same archive") + args = parser.parse_args() + try: + result = verify(args.predictions, args.manifest) + except (KeyError, OSError, TypeError, ValueError) as exc: + parser.exit(1, f"{parser.prog}: {exc}\n") + print(json.dumps(result, indent=1)) + + +if __name__ == "__main__": + main()