Files
ats-native-fsd/tools/build_local_road_context.py
2026-10-06 18:11:59 +00:00

129 lines
6.5 KiB
Python

"""Create a small passive map cache from already extracted, verified game files.
This uses the isolated ETS2LA/maps GPL-3.0 sector decoder. It never extracts
archives itself, writes game files, scans process memory or opens actuators.
"""
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.ats_telemetry import ATSTelemetry
CACHE = ROOT/'diagnostics/map-cache'
GAME = Path(r'C:\Program Files (x86)\DODI-Repacks\American Truck Simulator')
PARSER = ROOT/'diagnostics/map-tools/parser'
def fingerprint(path):
digest = hashlib.sha256()
with path.open('rb') as stream:
for chunk in iter(lambda: stream.read(1024*1024), b''):
digest.update(chunk)
return dict(path=str(path), sha256=digest.hexdigest(), size=path.stat().st_size,
mtime_ns=path.stat().st_mtime_ns)
def road_definitions():
results = {}
for origin in ('def', 'arizona', 'tesla-mod'):
for file in sorted((CACHE/origin/'def/world').glob('road_look*.sii')):
text = file.read_text(encoding='utf-8-sig')
for match in re.finditer(r'(?ms)^road_look\s*:\s*road\.(\w+)\s*\n\s*\{(.*?)^\}', text):
token, body = match.groups()
fields = {}
for line in body.splitlines():
field = re.match(r'^\s*(\w+)(\[\d*\])?\s*:\s*(.*?)\s*$', line)
if not field:
continue
name, array, value = field.groups()
if array:
fields.setdefault(name, []).append(value)
else:
fields[name] = value
# No missing-array inference: absent left/right means zero by
# road_look contract, but preserve all raw fields for review.
results[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=str(file),
source_sha256=hashlib.sha256(file.read_bytes()).hexdigest())
return results
def main():
telemetry = ATSTelemetry()
try:
time.sleep(.1)
data = telemetry.get_data()
finally:
telemetry.close()
if not data.get('position_valid'):
raise ValueError('SDK world pose required')
px, _, pz = data['world_position']
sx, sz = math.floor(px/4000), math.floor(pz/4000)
subprocess.run(['node', str(PARSER/'compile.cjs')], check=True, cwd=ROOT)
nodes, roads, prefabs, sources = {}, {}, {}, []
for x in range(sx-1, sx+2):
for z in range(sz-1, sz+2):
name = f'sec{x:+05d}{z:+05d}.base'
# Extraction only includes base map and the verified current Arizona DLC.
candidates = [CACHE/origin/'map/usa'/name for origin in ('base-map', 'arizona', 'tesla-mod')]
source = next((file for file in reversed(candidates) if file.exists()), None)
if not source or source.stat().st_size < 100:
continue
output = CACHE/(name+'.json')
result = subprocess.run(['node', str(PARSER/'read-sector.cjs'), str(source), str(output)],
check=False, cwd=ROOT, capture_output=True, text=True)
if result.returncode:
raise ValueError(f'Sector decoder failed {name}: {result.stderr[-500:]}')
parsed = json.loads(output.read_text(encoding='utf-8'))
sources.append(dict(**fingerprint(source), map_format=parsed['map_format']))
nodes.update({node['uid']: node for node in parsed['nodes']})
roads.update({item['uid']: item for item in parsed['items'] if 'roadLookToken' in item})
prefabs.update({item['uid']: item for item in parsed['items'] if 'originNodeIndex' in item})
if not roads:
raise ValueError('No successfully parsed road items around SDK pose')
definition = road_definitions()
matched_roads = []
missing_nodes = []
for road in roads.values():
if road['startNodeUid'] not in nodes or road['endNodeUid'] not in nodes:
missing_nodes.append(road['uid'])
continue
if road['roadLookToken'] not in definition:
continue
matched_roads.append(dict(road, start=nodes[road['startNodeUid']], end=nodes[road['endNodeUid']],
road_look=definition[road['roadLookToken']]))
mod = CACHE/'tesla-mod'
mod_overrides = [str(file) for file in mod.glob('map/**/*') if file.is_file()]
mod_overrides += [str(file) for file in (mod/'def/world').glob('road_look*')]
if mod_overrides:
raise ValueError('Active Tesla mod contains map overrides requiring load-order handling')
metadata = dict(schema_version=1, usable_for_control=False, source='ATS installed map definitions',
map='usa', game_version='1.61.2.0', decoder_commit='e853797bec3620659f14811d70ceea213399b83d',
world_pose_at_build=data['world_position'], sector_center=[sx, sz],
sectors=sources, roads=matched_roads, prefabs=list(prefabs.values()),
missing_endpoint_roads=missing_nodes, lane_boundaries_available=False,
lane_boundary_reason='Road-template mesh/width geometry is not decoded; no guessed widths',
archives=[fingerprint(GAME/name) for name in ('base_map.scs', 'def.scs', 'dlc_arizona.scs')],
game_executable=fingerprint(GAME/'bin/win_x64/amtrucks.exe'),
active_mod_archive=fingerprint(Path.home()/'Documents/American Truck Simulator/mod/ATS_1.61_TRUCK_TESLA_SEMI_TRUCK_2019__TRAILER_v3.0_LITE__by_CyrusTheVirus.scs'),
mod_order=['ATS_1.61_TRUCK_TESLA_SEMI_TRUCK_2019__TRAILER_v3.0_LITE__by_CyrusTheVirus'],
active_mod_map_overrides=False)
destination = CACHE/'local-road-context.json'
destination.write_text(json.dumps(metadata, indent=2), encoding='utf-8')
print(json.dumps(dict(path=str(destination), sectors=len(sources), roads=len(matched_roads),
prefabs=len(prefabs), formats=sorted(set(source['map_format'] for source in sources)),
world_pose=data['world_position'])))
if __name__ == '__main__':
main()