Files
Neutron/tools/binary/rocketship_body.py
T

168 lines
8.6 KiB
Python

#!/usr/bin/env python3
"""Guarded Rocketship body callbacks and isolated probe evidence.
Pure projections omit actual rider/audio/scene execution. The optional C probe
executes copied370/374 instructions with synthetic body/rider/audio dependencies.
"""
from __future__ import annotations
import argparse
from dataclasses import dataclass
import hashlib
import json
import math
from pathlib import Path
import re
import struct
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
from rocketship import collect as rocket_collect
BODIES = (
('ceiling', 0x43eb70, 0x43ebaf, '501a86c0a0263c4087932081a1516579f3a1fdb985d244682997e012a242ad3f'),
('wall', 0x43e8d0, 0x43ea49, '5a3c59889ae6ee9c4d599c1116782c7a2e8213c1b2cad9c22f7b8b55c1ee32a2'),
('physics', 0x479d20, 0x47a32a, '5f4b05518bef5e5f0ecc3909ff0de0b43d2c7350c6beae0c4f797d3238a77fa1'),
('prevent_setter', 0x470f70, 0x470f83, 'b4963d8c48531af2870e39531aadfa8c1178542943ba51d8e3b57184256ee81a'),
('pair_getter', 0x471930, 0x471937, '72ca47ad0ea64edf6110c3a080c805774593958fb2d34dce19f63261a8242327'),
('pair_setter', 0x471940, 0x47194d, 'fa5b69a6074a26a0b8dd535d288645d2875039673639282571e029a60479cd37'),
('pair_notify_gate', 0x470bf0, 0x470c44, '5211f48735716c7a7426486f0b44ae9e93388546d825437edc6ef3f787e2aa8d'),
('dynamic_push_gate', 0x47b2eb, 0x47b3a5, '75e20325939a77354add4decb44bba860003d56914426dc1b98f6d52c08056cb'),
)
TABLES = ((0x370, 0x43eb70), (0x374, 0x43e8d0), (0x378, 0x472750),
(0x37c, 0x472970), (0x1e0, 0x471930), (0x1e4, 0x471940),
(0x208, 0x4719d0), (0x20c, 0x4719e0), (0x210, 0x4719f0))
def collect(original: Path | str):
report = rocket_collect(Path(original))
pe = PE(find_case(Path(original), 'Neutron.exe'))
records = []
for name, start, end, expected in BODIES:
digest = hashlib.sha256(read_va(pe, start, end-start)).hexdigest()
if digest != expected:
raise ValueError(f'Changed Rocketship body span {name}')
records.append(dict(name=name, va=hex(start), file_offset=hex(pe.offset(start-pe.base)),
length=end-start, sha256=digest))
for slot, target in TABLES:
if struct.unpack('<I', read_va(pe, 0x4b25ac+slot, 4))[0] != target:
raise ValueError(f'Changed Rocketship body virtual {slot:x}')
# Rocket construction specifically enables prevent-lowering, unlike a
# generic CGameObject; radius/factor alone do not establish this flag.
if read_va(pe, 0x43d90d, 9) != bytes.fromhex('6a018bcee85a360300'):
raise ValueError('Changed Rocketship prevent-lowering initialization')
if read_va(pe, 0x472970, 1) != b'\xc3':
raise ValueError('Changed no-op landing callback')
report.update(body_callbacks=records,
body_vtables=[dict(slot=hex(s), target=hex(t)) for s,t in TABLES],
prevent_lowering=True, support_clearance_f32=struct.unpack('<f',struct.pack('<f',50*struct.unpack('<f',struct.pack('<f',.6))[0]))[0],
ceiling_velocity_y=-120., ceiling_preserves_acceleration=True,
wall_uses_reflection=False, flag137_is_integration_gate=False,
scope='Guarded body state/callbacks; optional isolated-original probes are separate from whole-game fidelity')
return report
@dataclass(frozen=True)
class WallEffect:
energy_delta: float
score_delta: int
duration: float
clear_rider_latch: bool
secondary_rider_callback: bool = False
sound: int = 197
def wall_effect(material_id=0, *, rider=True, polygon=True, material=True,
definition=True, active=False, rider_latch=False):
"""43E8D0 decision only. Actual rider callback executes synchronously."""
if not rider or not polygon or not material:
return None
if definition:
if 130 <= material_id <= 139:
return None if active else WallEffect(-10., -10, 5., True)
if 185 <= material_id <= 189:
return None if rider_latch else WallEffect(-5., -5, 5., False, True)
if material_id in (-1,170):
return None
return None if active else WallEffect(-1., -1, 1., True)
def ceiling_velocity(velocity):
if len(velocity) != 3 or not all(math.isfinite(v) for v in velocity):
raise ValueError('Finite three-component velocity required')
return (velocity[0], -120., velocity[2])
def callback_probe_results(log: Path, executable: Path):
source = Path(__file__).with_name('rocketship_body_probe.c')
content = log.read_text()
if 'ROCKET_BODY_CALLBACK_COMPLETE:' not in content:
raise ValueError('Incomplete Rocketship callback probe')
names = ('id','rider','polygon','material','definition','active','rider_latch')
inputs = {name:dict(zip(names,map(int,values.split(',')),strict=True))
for name,values in re.findall(r'wall\("(\w+)",([^;]+)\);',source.read_text())}
for name,value in re.findall(r'ceiling\("(\w+)",([^;]+)\);',source.read_text()):
inputs[name] = dict(ceiling_velocity=float(value))
cases = []
for name,values in re.findall(r'^CASE (\w+) (.+)$',content,re.M):
if name not in inputs or any(c['name']==name for c in cases):
raise ValueError('Unexpected or duplicate Rocketship callback case')
fields = {}
for key,value in re.findall(r'(\w+)=([^\s]+)',values):
fields[key] = [float(v) for v in value.split(',')] if ',' in value else float(value)
if not {'velocity','acceleration','root','active','timer','duration','impulse','riderflag','calls','damage','points','seconds','secondary','sounds','soundid'} <= fields.keys():
raise ValueError('Missing Rocketship callback output field')
cases.append(dict(name=name,input=inputs[name],observed=fields))
if len(cases) != len(inputs):
raise ValueError('Missing Rocketship callback cases')
return dict(source_sha256=EXE_SHA256, scope='Copied370/374; body accessors, rider and audio synthetic',
generator_sha256=hashlib.sha256(source.read_bytes()).hexdigest(),
executable_sha256=hashlib.sha256(executable.read_bytes()).hexdigest(),
log_sha256=hashlib.sha256(log.read_bytes()).hexdigest(),cases=cases)
def body_support_probe(output: Path):
"""Generate six50/.6/prevent-lowering body cases from existing harness."""
source = Path(__file__).with_name('body_step_probe.c').read_text()
marker = ' puts("BODY_COMPONENT_COMPLETE:'
if source.count(marker) != 1:
raise ValueError('Unexpected original body harness')
extra = ''' b=initial();b.radius=50;b.factor=.6f;b.position.y=30;b.previous=b.position;run("rocket_floor",b,1);
b=initial();b.radius=50;b.factor=.6f;b.position.y=10;b.previous=b.position;run("rocket_spawn_low",b,1);
b=initial();b.radius=50;b.factor=.6f;run("rocket_no_forced_lowering",b,1);
b=initial();b.radius=50;b.factor=.6f;b.position.y=30;b.previous=b.position;b.velocity.y=300;run("rocket_rise",b,1);
b=initial();b.radius=50;b.factor=.6f;b.position.y=30;b.previous=b.position;b.supported=1;b.velocity=(Vec){120,0,-60,0};b.acceleration.y=800;run("rocket_friction",b,1);
b=initial();b.radius=50;b.factor=.6f;b.position.y=30;b.previous=b.position;b.supported=1;b.velocity=(Vec){120,0,-60,0};b.acceleration.y=800;b.speed=160;run("rocket_published_nonzero",b,1);
'''
output = output.resolve()
originals = Path(__file__).resolve().parents[3]/'Original'
if output.is_relative_to(originals) or originals.is_relative_to(output):
raise ValueError('Generated output must be separate from originals')
output.write_text(source.replace(marker,extra+marker))
def main():
cli=argparse.ArgumentParser(description=__doc__)
cli.add_argument('original',type=Path)
cli.add_argument('--output',type=Path)
cli.add_argument('--callback-log',type=Path)
cli.add_argument('--callback-executable',type=Path)
cli.add_argument('--body-probe-source',type=Path)
args=cli.parse_args();report=collect(args.original)
if bool(args.callback_log) != bool(args.callback_executable):
cli.error('Use callback log/executable together')
if args.callback_log:
report['original_callback_probe']=callback_probe_results(args.callback_log,args.callback_executable)
if args.body_probe_source:
body_support_probe(args.body_probe_source)
text=json.dumps(report,indent=2,allow_nan=False)+'\n'
if args.output:
target=args.output.resolve();original=args.original.resolve()
if target.is_relative_to(original) or original.is_relative_to(target):
cli.error('Output must be separate from originals')
target.write_text(text)
else: print(text,end='')
if __name__=='__main__':main()