245 lines
13 KiB
Python
245 lines
13 KiB
Python
"""Offline, read-only mounted ATS extraction for a local authored lane graph.
|
|
|
|
All generated files live under diagnostics/native-lanes. Installed archives,
|
|
the original road-control cache and the running game are never written.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import math
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT))
|
|
from telemetry.native_lanes import (authored_prefab_lanes, build_lane_graph, NativeLaneGraph,
|
|
merge_native_lane_graphs)
|
|
from telemetry.road_geometry import BUILD_SHA256
|
|
from ui.map_background import MountedDisplayMap, _Archive, loaded_sources, PARSER, PARSER_HASHES
|
|
|
|
PPD_HASHES = {
|
|
'read-prefab.cjs': '0707fd88194773ae04e2815e59b0af04f1bff22470adc8286bcbe55ec040d8fa',
|
|
'prefab-ppd-parser.js': 'f7f855332f6279b1ff6d9836c6c175f26ac43844af6fb039a65f676d5ebdd874',
|
|
}
|
|
|
|
|
|
def parse_units(text, unit_type):
|
|
result = {}
|
|
pattern = r'(?ms)^\s*' + re.escape(unit_type) + r'\s*:\s*([\w.]+)\s*\{(.*?)^\s*\}'
|
|
for unit in re.finditer(pattern, text):
|
|
fields = {}
|
|
for line in unit[2].splitlines():
|
|
field = re.match(r'^\s*(\w+)(\[\d*\])?\s*:\s*(.*?)\s*(?:#.*)?$', line)
|
|
if field:
|
|
name, array, value = field.groups()
|
|
if array:
|
|
if not isinstance(fields.get(name), list):
|
|
fields[name] = []
|
|
fields[name].append(value)
|
|
else:
|
|
fields[name] = value
|
|
result[unit[1]] = fields
|
|
return result
|
|
|
|
|
|
def merge_sector_nodes(sectors):
|
|
"""Cross-sector duplicates must agree before any road receives a pose."""
|
|
nodes, conflicts = {}, set()
|
|
for sector in sectors:
|
|
for node in sector.get('nodes', []):
|
|
uid = str(node['uid'])
|
|
old = nodes.get(uid)
|
|
if old and (any(abs(old[k] - node[k]) > .01 for k in ('x', 'y', 'z'))
|
|
or abs(math.atan2(math.sin(old['rotation'] - node['rotation']),
|
|
math.cos(old['rotation'] - node['rotation']))) > .0001):
|
|
conflicts.add(uid)
|
|
nodes[uid] = node
|
|
for uid in conflicts:
|
|
nodes.pop(uid, None)
|
|
return nodes, sorted(conflicts)
|
|
|
|
|
|
def build(pose, output, max_prefabs=256, accumulate=True):
|
|
output = Path(output).resolve()
|
|
output.mkdir(parents=True, exist_ok=True)
|
|
started = time.monotonic()
|
|
for name, digest in PPD_HASHES.items():
|
|
if hashlib.sha256((PARSER / name).read_bytes()).hexdigest() != digest:
|
|
raise ValueError('Pinned prefab decoder changed: ' + name)
|
|
backend = MountedDisplayMap(output / 'sectors', 9)
|
|
archives, extra = list(backend.archives), []
|
|
try:
|
|
mounts, executable = loaded_sources()
|
|
available = {str(a.path.resolve()): a for a in archives}
|
|
# Unlike the display reader, prefab extraction must inspect base.scs
|
|
# and every mounted DLC for exact asset overrides as well.
|
|
for mount in mounts:
|
|
if str(Path(mount['path']).resolve()) not in available:
|
|
archive = _Archive(mount['path'])
|
|
extra.append(archive)
|
|
available[str(archive.path.resolve())] = archive
|
|
archives = [available[str(Path(m['path']).resolve())] for m in mounts]
|
|
assets = {}
|
|
def resolve(name):
|
|
if name.startswith('/') or '..' in Path(name).parts:
|
|
raise ValueError('Invalid mounted asset path')
|
|
for archive in reversed(archives):
|
|
if archive.has(name):
|
|
payload = archive.read(name)
|
|
if payload is None:
|
|
raise ValueError('Asset metadata is not a supported plain file: ' + name)
|
|
assets[name] = dict(archive=str(archive.path), sha256=hashlib.sha256(payload).hexdigest(),
|
|
size=len(payload))
|
|
return payload
|
|
return None
|
|
cx, cz = math.floor(pose[0]/4000), math.floor(pose[2]/4000)
|
|
cells = [(cx+dx, cz+dz) for dx in (-1, 0, 1) for dz in (-1, 0, 1)]
|
|
sectors = [backend._load_sector(cell) for cell in cells]
|
|
nodes, conflicting_nodes = merge_sector_nodes(sectors)
|
|
items = {}
|
|
for sector in sectors:
|
|
items.update({str(item['uid']): item for item in sector.get('items', [])})
|
|
definition_names = set()
|
|
for archive in archives:
|
|
definition_names.update('def/world/' + name for name in archive.files('def/world')
|
|
if re.fullmatch(r'(?:road_look|prefab)(?:\.[\w-]+)?\.sii', name))
|
|
looks, prefab_bindings = {}, {}
|
|
for name in sorted(definition_names):
|
|
payload = resolve(name)
|
|
if not payload:
|
|
continue
|
|
text = payload.decode('utf-8-sig')
|
|
if Path(name).name.startswith('road_look'):
|
|
for token, fields in parse_units(text, 'road_look').items():
|
|
token = token.removeprefix('road.')
|
|
looks[token] = dict(token=token, name=fields.get('name', '').strip('"'),
|
|
lanes_left=fields.get('lanes_left', []),
|
|
lanes_right=fields.get('lanes_right', []), raw_fields=fields,
|
|
source_file=name, source_sha256=assets[name]['sha256'])
|
|
else:
|
|
for token, fields in parse_units(text, 'prefab_model').items():
|
|
if fields.get('prefab_desc'):
|
|
prefab_bindings[token.removeprefix('prefab.')] = fields['prefab_desc'].strip('"').lstrip('/')
|
|
roads, unresolved_roads, prefabs = [], {}, []
|
|
for uid, item in items.items():
|
|
if 'roadLookToken' in item:
|
|
try:
|
|
roads.append(dict(item, start=nodes[str(item['startNodeUid'])],
|
|
end=nodes[str(item['endNodeUid'])], road_look=looks[item['roadLookToken']]))
|
|
except KeyError as exc:
|
|
unresolved_roads[uid] = str(exc)
|
|
elif 'originNodeIndex' in item:
|
|
prefabs.append(item)
|
|
requested = sorted({p['token'] for p in prefabs if not p.get('hidden')})
|
|
if len(requested) > max_prefabs:
|
|
raise ValueError('Local prefab population exceeds bounded extraction limit')
|
|
definitions, missing = {}, {}
|
|
asset_dir = output / 'prefabs'
|
|
asset_dir.mkdir(exist_ok=True)
|
|
for token in requested:
|
|
path = prefab_bindings.get(token)
|
|
if not path:
|
|
missing[token] = 'Missing installed prefab definition binding'
|
|
continue
|
|
try:
|
|
payload = resolve(path)
|
|
if not payload:
|
|
raise ValueError('Bound prefab asset not found in mounted archives')
|
|
digest = hashlib.sha256(payload).hexdigest()
|
|
ppd, parsed = asset_dir / (token + '.ppd'), asset_dir / (token + '.json')
|
|
decoded = json.loads(parsed.read_text()) if parsed.exists() else {}
|
|
if decoded.get('asset_sha256') != digest or decoded.get('parser_hashes') != PPD_HASHES:
|
|
ppd.write_bytes(payload)
|
|
result = subprocess.run([backend.node, str(PARSER / 'read-prefab.cjs'), str(ppd), str(parsed)],
|
|
capture_output=True, text=True, timeout=20,
|
|
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
|
if result.returncode:
|
|
raise ValueError(result.stderr.strip().splitlines()[0][:200])
|
|
decoded = json.loads(parsed.read_text())
|
|
decoded.update(asset_sha256=digest, parser_hashes=PPD_HASHES)
|
|
parsed.write_text(json.dumps(decoded, separators=(',', ':')), encoding='utf-8')
|
|
definitions[token] = dict(asset_path=path, asset_sha256=digest,
|
|
description=decoded['description'], ppd_version=decoded['ppd_version'])
|
|
except (ValueError, OSError, subprocess.SubprocessError) as exc:
|
|
missing[token] = str(exc)
|
|
prefab_lanes, failed_placements = authored_prefab_lanes(roads, prefabs, definitions, nodes)
|
|
graph = build_lane_graph(roads, prefab_lanes)
|
|
# All source populations must still match after extraction.
|
|
final_mounts, _ = loaded_sources()
|
|
if [m['path'] for m in final_mounts] != [m['path'] for m in mounts] or any(not a.unchanged() for a in archives):
|
|
raise ValueError('Mounted sources changed during native lane extraction')
|
|
provenance = dict(loaded_archive_order=[m['path'] for m in mounts],
|
|
archives=[a.fingerprint for a in archives],
|
|
assets=assets, game_executable=str(executable),
|
|
sector_sources=[dict(cell=cell, asset_sha256=sector.get('asset_sha256'),
|
|
archive=sector.get('archive'), absent=sector.get('absent', False))
|
|
for cell, sector in zip(cells, sectors)],
|
|
parser_hashes=dict(PARSER_HASHES, **PPD_HASHES),
|
|
decoder_commit='e853797bec3620659f14811d70ceea213399b83d')
|
|
graph.update(schema_version=1, game_build_sha256=BUILD_SHA256, usable_for_control=False,
|
|
interpolation_verified=False, source='ATS installed sectors and authored PPD lane endpoints',
|
|
built_at_unix=time.time(), pose_at_build=pose, provenance=provenance,
|
|
missing_prefab_assets=missing, failed_prefab_placements=failed_placements,
|
|
unresolved_roads=unresolved_roads, conflicting_sector_nodes=conflicting_nodes)
|
|
graph['coverage'].update(sectors=len(sectors), prefab_tokens_requested=len(requested),
|
|
prefab_tokens_decoded=len(definitions), placed_prefabs=len({l['prefab_uid'] for l in prefab_lanes}),
|
|
failed_placements=len(failed_placements), missing_prefab_assets=len(missing),
|
|
road_looks_with_lanes=len({l['road_look_token'] for l in graph['lanes'] if l['kind'] == 'road'}))
|
|
destination = output / 'lane-graph.json'
|
|
if accumulate and destination.exists():
|
|
try:
|
|
existing = json.loads(destination.read_text(encoding='utf-8'))
|
|
graph = merge_native_lane_graphs(existing, graph)
|
|
except (OSError, ValueError, TypeError, KeyError, json.JSONDecodeError):
|
|
# A stale or interrupted artifact is replaced by the freshly
|
|
# verified source set; never mix an unreadable graph.
|
|
pass
|
|
pending = destination.with_suffix('.pending.json')
|
|
pending.write_text(json.dumps(graph, separators=(',', ':')), encoding='utf-8')
|
|
pending.replace(destination)
|
|
reader = NativeLaneGraph(destination)
|
|
snapshot = reader.snapshot(dict(valid=True, position_valid=True, paused=False, world_position=pose))
|
|
if reader.reason:
|
|
raise ValueError('Built lane graph failed current source verification: ' + reader.reason)
|
|
(output / 'current-pose-snapshot.json').write_text(json.dumps(snapshot, separators=(',', ':')), encoding='utf-8')
|
|
summary = dict(path=str(destination), elapsed_s=round(time.monotonic()-started, 2),
|
|
pose=pose, **graph['coverage'], graph_connections=len(graph['connections']),
|
|
local_lanes=len(snapshot['lanes']), local_connections=len(snapshot['connections']),
|
|
available=snapshot['available'], reason=snapshot['reason'], usable_for_control=False)
|
|
(output / 'build-summary.json').write_text(json.dumps(summary, indent=2), encoding='utf-8')
|
|
return summary
|
|
finally:
|
|
backend.close()
|
|
for archive in extra:
|
|
archive.close()
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--pose', type=float, nargs=3, metavar=('X', 'HEIGHT', 'Z'))
|
|
parser.add_argument('--output', type=Path, default=ROOT / 'diagnostics/native-lanes')
|
|
parser.add_argument('--fresh', action='store_true',
|
|
help='Discard any existing graph in --output instead of accumulating sectors')
|
|
args = parser.parse_args()
|
|
pose = args.pose
|
|
if pose is None:
|
|
from telemetry.ats_telemetry import ATSTelemetry
|
|
sdk = ATSTelemetry()
|
|
try:
|
|
sdk.get_data()
|
|
time.sleep(.2)
|
|
data = sdk.get_data()
|
|
if not data.get('valid') or not data.get('position_valid'):
|
|
raise ValueError('Current SDK pose unavailable; supply an offline --pose')
|
|
pose = data['world_position']
|
|
finally:
|
|
sdk.close()
|
|
print(json.dumps(build(pose, args.output, accumulate=not args.fresh), indent=2))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|