Files
ats-native-fsd/tools/build_tesla_screen_addon.py
2026-10-06 18:28:45 +00:00

279 lines
18 KiB
Python

"""Build a reversible private Tesla-only screen addon without installing it.
The caller supplies an extracted original mod. Original files stay unchanged.
Both exact marked textures are display-only. Native ATS gauges remain on the
left screen independently of the application and its optional status tile.
"""
import argparse
import hashlib
import json
from pathlib import Path
import re
import struct
import zipfile
import cv2
import numpy as np
# Direct script execution starts with tools/ on sys.path, rather than repo root.
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from ui.dashboard_stream import orient_tesla_screen
from tools.patch_tesla_left_screen import (MODEL, DESCRIPTOR, patch_left_screen,
ANIM_MODEL, ANIM_DESCRIPTOR, patch_duplicate_symbols)
ROOT = Path(__file__).resolve().parents[1]
WIDTH, HEIGHT = 1024, 512
MARKER = b'ATSOPHUD-V1-RIGHT-SCREEN-1024x512'
LEFT_MARKER = b'ATSOPHUD-V1-LEFT-SCREEN-1024x512'
RIGHT_MATERIAL = 'vehicle/truck/tesla_2019/interior/materials/4957b521406c39eeb910a76172a675730cfd4b.mat'
INTERIOR_DEF = 'def/vehicle/truck/tesla.2019/interior/standard.sii'
RIGHT_TEXTURE = 'vehicle/truck/tesla_2019/interior/atsop_live_hud.tobj'
PLACEHOLDER = RIGHT_TEXTURE.removesuffix('.tobj') + '.dds'
LEFT_MATERIAL = 'material/ui/dashboard/atsop_tesla/left_status.mat'
LEFT_TEXTURE = LEFT_MATERIAL.removesuffix('.mat') + '.tobj'
LEFT_PLACEHOLDER = LEFT_MATERIAL.removesuffix('.mat') + '.dds'
NATIVE_UI_TOBJ = 'material/ui/dashboard/peterbilt_579/display.tobj'
# Copied from both display.tobj and pict.tobj in the inspected original mod.
# Native UI uses different sampling/address flags from the right 3D material.
UI_TOBJ_PREFIX = bytes.fromhex('010ab170000000000000000000000000000000000100000002000101020002020000000000010000')
SOURCE_MOD_SHA256 = 'fe68506b2d3b528abab34b662e08b2401e9d8de29df2dc54d4c4b185d22184af'
def validate_unit_names(text, filename):
"""Validate engine token rules for declarations and UI pointer references.
SCS units comprise lowercase alphanumeric/underscore tokens of at most
twelve characters, separated by dots. The leading nameless dot is allowed.
See https://modding.scssoft.com/wiki/Documentation/Engine/Units .
"""
# Strings contain resource paths and markup; they are not unit identifiers.
plain = re.sub(r'"(?:\\.|[^"\\])*"', '""', text)
names = re.findall(r'^\s*[a-zA-Z_][a-zA-Z0-9_:]*\s*:\s*([^\s{}]+)\s*\{', plain, re.M)
names += re.findall(r'^\s*(?:my_parent|my_children\[\d+\]|look_template)\s*:\s*([^\s{}]+)', plain, re.M)
for name in names:
if name == 'null':continue
parts=(name[1:] if name.startswith('.') else name).split('.')
if len(parts)>10 or any(not re.fullmatch(r'[a-z0-9_]{1,12}',part) for part in parts):
raise ValueError(f'{filename}: invalid SCS unit identifier {name!r}')
def validate_dashboard_hierarchy(text):
"""Reject missing native pages and dangling/nonreciprocal UI pointers.
ATS selects dashboard pages by numeric ID, including warning page 900.
Those containers must exist even when the normal content is shared.
"""
blocks = re.findall(r'(ui::\w+)\s*:\s*([^\s{}]+)\s*\{([^{}]*)\}',text)
units = {name:(kind,body) for kind,name,body in blocks}
if len(units)!=len(blocks):raise ValueError('Duplicate dashboard unit')
root = units.get('.opsemi.window')
if not root or root[0]!='ui::window':raise ValueError('Missing dashboard window')
root_children=[]
for name,(kind,body) in units.items():
children = re.findall(r'\bmy_children\[(\d+)\]\s*:\s*([^\s{}]+)',body)
count = re.search(r'\bmy_children\s*:\s*(\d+)',body)
if kind in ('ui::window','ui::group'):
if not count or [int(i) for i,_ in children]!=list(range(int(count[1]))):
raise ValueError(f'Invalid dashboard child array: {name}')
parent = re.search(r'\bmy_parent\s*:\s*([^\s{}]+)',body)
if not parent or (name=='.opsemi.window' and parent[1]!='null'):
raise ValueError(f'Invalid dashboard parent: {name}')
if name!='.opsemi.window' and parent[1] not in units:
raise ValueError(f'Dangling dashboard parent: {name}')
for _,child in children:
if child not in units or not re.search(r'\bmy_parent\s*:\s*'+re.escape(name)+r'\s',units[child][1]):
raise ValueError(f'Dangling/nonreciprocal dashboard child: {child}')
if name=='.opsemi.window':root_children=[child for _,child in children]
root_ids={int(re.search(r'\bid\s*:\s*(\d+)',units[child][1])[1]) for child in root_children}
if root_ids!={10,20,100,200,300,400,900,950}:
raise ValueError(f'Missing native dashboard page/background: {sorted(root_ids)}')
def placeholder_dds(screen='right'):
# The temporary surface is deliberately opaque and text-free. A resource
# can be rebound while ATS rebuilds its cabin materials; showing status
# lettering here makes that short handoff look like a second panel behind
# the live image. Native code holds the last live frame after first bind.
bgra = np.full((HEIGHT, WIDTH, 4), (32, 30, 27, 255), np.uint8)
if screen not in ('right','left'):
raise ValueError('Unknown Tesla display')
identity=MARKER if screen=='right' else LEFT_MARKER
if screen=='right':
bgra = orient_tesla_screen(bgra)
else:
# This texture is an ordinary image in the native dashboard UI; the UI
# handles the dashboard mesh mapping. Do not apply the right GPS UV fix.
cv2.putText(bgra,'APP OFFLINE',(282,231),cv2.FONT_HERSHEY_SIMPLEX,
1.8,(185,187,190,255),3,cv2.LINE_AA)
cv2.putText(bgra,'Native truck instruments remain active',(145,297),
cv2.FONT_HERSHEY_SIMPLEX,.95,(130,134,138,255),2,cv2.LINE_AA)
# Marker remains in the GPU's first row after the image orientation fix.
# Tiny identification bytes are carried in color bytes of the first row.
# An injected texture bridge must check these in addition to dimensions.
bgra[0, :len(identity), 0] = np.frombuffer(identity, np.uint8)
bgra[0, :len(identity), 1] = 0xA7
bgra[0, :len(identity), 2] = 0x51
header = bytearray(128)
header[:4] = b'DDS '
struct.pack_into('<IIIIIII', header, 4, 124, 0x100F, HEIGHT, WIDTH, WIDTH*4, 0, 1)
struct.pack_into('<II4sIIIII', header, 76, 32, 0x41, b'\0\0\0\0', 32,
0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000)
struct.pack_into('<I', header, 108, 0x1000)
return bytes(header) + bgra.tobytes()
def tobj(texture_path, *, ui_texture=False):
# Existing validated legacy TOBJ layout, with a new absolute DDS path.
prefix = (UI_TOBJ_PREFIX if ui_texture else
bytes.fromhex('010ab170000000000000000000000000000000000100000002000101010000000000000000010000'))
name = ('/' + texture_path).encode('ascii')
return bytes(prefix) + struct.pack('<II', len(name), 0) + name
def dashboard_ui():
nodes = []
names = []
warning_names=[]
background_names=[]
def element(name, coords, *, text=None, element_id=0, template=None, value='0', parent='.opsemi.shared', layer=2):
identity = '.opsemi.' + name
(names if parent=='.opsemi.shared' else warning_names if parent=='.opsemi.warning' else background_names).append(identity)
kind = 'ui::text_common' if template else 'ui::text'
body = f' value: "{value}"\n look_template: {template}\n text: ""\n' if template else f' text: "{text}"\n'
left, right, top, bottom = coords
nodes.append(f'{kind} : {identity} {{\n{body} coords_l: {left}\n coords_r: {right}\n coords_t: {top}\n coords_b: {bottom}\n area_l: 1\n area_r: 0\n area_t: 0\n area_b: 1\n id: {element_id}\n layer: {layer}\n tab: -1\n pointer: -1\n my_parent: {parent}\n}}\n')
def label(name, text, coords):
scale=1.4 if len(text)>7 else 1.8
element(name, coords, text=f'<align hstyle=center><color value=ffaaaaaa><font face=/font/big.font xscale={scale} yscale={scale}>{text}</font></align>')
# Match the original native dashboard's image cursor/reset convention.
# Image tint must be explicit: inheriting the default text colour can make
# a correctly bound live SRV invisible. Give all paint stages unique layers.
background='<ret><offset hshift=0 vshift=0><img src=/material/ui/white.mat color=ff181818 height=770 width=990>'
element('background', (0,990,770,0), layer=0,text=background)
# A 2:1 image at native aspect ratio fills the lower area. It is separate
# from all game-driven instruments; producer failure cannot freeze them.
element('app_status',(20,970,495,20),layer=1,
text=f'<color value=ffffffff><ret><offset hshift=0 vshift=0><img src=/{LEFT_MATERIAL} color=ffffffff height=475 width=950>')
element('speed', (80,390,760,585), element_id=1020, template='txt.atsop_tesla.speed')
# Leave a clear vertical gap below the large speed value. The ATS text
# renderer includes font descent outside the nominal value rectangle, so
# the former two-unit gap still drew the MPH label through the digits.
label('mph', 'MPH', (80,390,550,510))
# Native detailed transmission mode reports D/N/R/M, rather than A5 etc.
# The original duplicate animated PARK quad is hidden by the mesh override.
element('gear', (350,490,725,610), element_id=1380, template='txt.atsop_tesla.value', value='N')
label('gear_label', 'GEAR', (350,490,600,550))
for name, identity, title, left, right in [('limit',1610,'LIMIT',600,770),('cruise',1100,'ATS CRUISE',785,980)]:
label(name+'_label', title, (left,right,742,695))
element(name, (left,right,690,590), element_id=identity, template='txt.atsop_tesla.value')
label('clock_label','TIME',(600,720,553,503))
element('clock',(720,980,564,504),element_id=1050,template='txt.atsop_tesla.clock')
element('park', (100,555,540,500), element_id=1270,
text='<align hstyle=center><color value=ff8888ff><font face=/font/big.font xscale=1.5 yscale=1.5>PARKING BRAKE</font></align>')
for name, identity, arrow, left, right in [('left',1570,'&lt;',5,75),('right',1580,'&gt;',495,570)]:
element(name,(left,right,760,710),element_id=identity,
text=f'<align hstyle=center><color value=ff88dd88><font face=/font/big.font xscale=2.5 yscale=2.5>{arrow}</font></align>')
# These are native page lookup IDs, not optional decorations. In particular
# warning900 is selected alone when ATS detects a service warning. Retain
# all four ordinary page containers even though their gauges are shared950.
for name,identity in [('unlit',10),('lit',20)]:
element(name,(0,990,770,0),element_id=identity,parent='.opsemi.window',layer=-1,
text=background)
element('warn_back',(0,990,770,0),parent='.opsemi.warning',layer=0,text=background)
element('warn_title',(40,950,650,470),parent='.opsemi.warning',layer=2,
text='<align hstyle=center><color value=ff8888ff><font face=/font/big.font xscale=3 yscale=3>WARNINGS &amp; FAULTS</font></align>')
element('warn_text',(40,950,450,260),parent='.opsemi.warning',layer=2,
text='<align hstyle=center><color value=ffececec><font face=/font/big.font xscale=3 yscale=3>Visit SERVICE!</font></align>')
def child_fields(children):
return f' my_children: {len(children)}\n'+''.join(f' my_children[{i}]: {child}\n' for i,child in enumerate(children))
def group(name,identity,children,layer=0):
return (f'ui::group : .opsemi.{name} {{\n fitting: false\n'+child_fields(children)+
f' coords_l: 0\n coords_r: 990\n coords_t: 770\n coords_b: 0\n area_l: 0\n area_r: 990\n area_t: 770\n area_b: 0\n id: {identity}\n layer: {layer}\n tab: -1\n pointer: -1\n my_parent: .opsemi.window\n}}\n')
page_names=['.opsemi.warning','.opsemi.shared','.opsemi.page300','.opsemi.page200','.opsemi.basic','.opsemi.page400']+background_names
text=('SiiNunit\n{\nui::window : .opsemi.window {\n window_handler: null\n clip_children: true\n keep_aspect: none\n fitting: false\n'+child_fields(page_names)+
' coords_l: 0\n coords_r: 990\n coords_t: 770\n coords_b: 0\n area_l: 0\n area_r: 990\n area_t: 770\n area_b: 0\n id: 0\n layer: 0\n tab: -1\n pointer: -1\n my_parent: null\n}\n'+
''.join(group(name,identity,[]) for name,identity in [('basic',100),('page200',200),('page300',300),('page400',400)])+
group('warning',900,warning_names,1)+group('shared',950,names)+'\n'.join(nodes)+'\n}\n')
validate_dashboard_hierarchy(text)
return text.encode('utf-8')
def build(source, output, *, patch_left_mesh=True):
source = Path(source)
interior = (source / INTERIOR_DEF).read_text(encoding='utf-8')
material = (source / RIGHT_MATERIAL).read_text(encoding='utf-8')
native_ui_tobj = source / NATIVE_UI_TOBJ
if native_ui_tobj.exists() and native_ui_tobj.read_bytes()[:40] != UI_TOBJ_PREFIX:
raise ValueError('Original dashboard UI texture contract differs from inspected mod')
if ('standard.tesla.2019.interior' not in interior
or '/ui/dashboard/peterbilt_579.sii' not in interior
or '/vehicle/truck/share/gps.tobj' not in material):
raise ValueError('Extracted Tesla interior/material do not match inspected mod')
interior = interior.replace('/ui/dashboard/peterbilt_579.sii', '/ui/dashboard/atsop_tesla_semi.sii')
if not re.search(r'\buse_mile_units\s*:', interior):
interior = interior.replace('backlight_with_lights:', 'use_mile_units: true\n\tbacklight_with_lights:', 1)
material = material.replace('/vehicle/truck/share/gps.tobj', '/' + RIGHT_TEXTURE)
assets = {
INTERIOR_DEF: interior.encode('utf-8'), RIGHT_MATERIAL: material.encode('utf-8'),
'ui/dashboard/atsop_tesla_semi.sii': dashboard_ui(),
RIGHT_TEXTURE: tobj(PLACEHOLDER), PLACEHOLDER: placeholder_dds(),
# Match native display.mat's UI shader, named binding, and relative TOBJ
# semantics exactly. Do not borrow the exterior/right-screen material.
LEFT_MATERIAL: b'material : "ui"\n{\n texture : "left_status.tobj"\n texture_name : "texture"\n}\n',
LEFT_TEXTURE: tobj(LEFT_PLACEHOLDER, ui_texture=True), LEFT_PLACEHOLDER: placeholder_dds('left'),
'manifest.sii': b'SiiNunit\n{\nmod_package : .opsemi.package {\n package_version: "0.2.2"\n display_name: "ATS OP Tesla screens"\n author: "Local ATS OP"\n category[]: "ui"\n description_file: "mod_description.txt"\n}\n}\n',
'mod_description.txt': b'Private companion for the installed Tesla Semi mod. Load above the original. Left: native imperial truck instruments plus optional live app status. Original signal/high-beam/parking/air/fuel symbols are hidden where the custom panel provides equivalents; native service, STOP, generic and differential-lock warnings remain. Right: live road and navigation panel. Removing this addon restores original screens and symbols.\n',
}
geometry_report=None
symbol_report=None
if patch_left_mesh:
# The original physical left display is three disjoint material/UV
# islands; changing dashboard_path alone cannot cover its baked art.
assets[MODEL],geometry_report=patch_left_screen((source/MODEL).read_bytes(),(source/DESCRIPTOR).read_bytes())
assets[ANIM_MODEL],symbol_report=patch_duplicate_symbols(
(source/ANIM_MODEL).read_bytes(),(source/ANIM_DESCRIPTOR).read_bytes())
asset_root = ROOT / 'mod_assets/tesla_semi_screens'
for path in asset_root.rglob('*'):
if path.is_file():
assets[path.relative_to(asset_root).as_posix()] = path.read_bytes()
for name,payload in assets.items():
if name.endswith('.sii'):
validate_unit_names(payload.decode('utf-8'),name)
output = Path(output)
output.parent.mkdir(parents=True, exist_ok=True)
pending = output.with_suffix('.scs.building')
with zipfile.ZipFile(pending, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
for name, payload in sorted(assets.items()):
archive.writestr(name, payload)
pending.replace(output)
report = dict(addon=str(output.resolve()), installed=False, original_modified=False,
right_screen_live=False, expected_original_mod_sha256=SOURCE_MOD_SHA256,
width=WIDTH, height=HEIGHT, format='BGRA8_UNORM', marker=MARKER.decode(),
screen_uv_orientation='vertical reflection; image rows reversed before upload',
marker_layout='first row, B=ASCII byte, G=0xA7, R=0x51, A=255',
shared_memory_name='Local\\ATSNativeDashboardV1',
left_screen_live=False,
left_shared_memory_name='Local\\ATSNativeDashboardLeftV1',
left_marker=LEFT_MARKER.decode(),
left_screen_uv_orientation='normal top-down UI image; no right-screen UV correction',
left_ui_tobj_prefix_hex=UI_TOBJ_PREFIX.hex(),
left_native_instruments_preserved=True,
left_geometry_patch=geometry_report,
left_duplicate_symbol_patch=symbol_report,
left_status_bounds=dict(left=20,right=970,top=495,bottom=20),
source_files={p: hashlib.sha256((source/p).read_bytes()).hexdigest()
for p in (INTERIOR_DEF, RIGHT_MATERIAL)},
sha256=hashlib.sha256(output.read_bytes()).hexdigest(),
entries={n: hashlib.sha256(p).hexdigest() for n,p in assets.items()})
output.with_suffix('.inspection.json').write_text(json.dumps(report, indent=2)+'\n', encoding='utf-8')
return report
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('extracted_mod', type=Path)
parser.add_argument('--output', type=Path, default=ROOT/'diagnostics/tesla-screen-addon/ATS_OP_Tesla_Screens.scs')
args = parser.parse_args()
print(json.dumps(build(args.extracted_mod, args.output), indent=2))