Implement verified Grappler body camera and helpers in VR08

This commit is contained in:
UnixNight committed 2026-11-04 11:27:03 -05:00
1 parent ffea678e90
commit 43806fe862
39 files changed
+2429 -40

No files matched your search

+198
View File
@@ -0,0 +1,198 @@
#!/usr/bin/env python3
"""Guard the Grappler/body handoff and generate its isolated copied-code probe.
Original files are read only. The generated probe uses synthetic actors and a
two-triangle grid; it does not start the original game or run its entry point.
"""
import argparse
import hashlib
import json
from pathlib import Path
import struct
from body_step_evidence import collect as body_collect
from checkpoint_script_state import find_case, read_va
from collision_response import header
from pe_inspect import PE
RANGES = (
('physics_scheduler', 0x479BC0, 0x479D1B, '857abe5d3602741415f84c7a735cd867a86126eb0ed8049ecebf962025d45e64'),
('attached', 0x429D00, 0x42A660, '9f4f17bafbca614ee64094df4d951c53cb122f8e15adb9fd7f8a58be589cc2f3'),
('jimmy_wall', 0x42A660, 0x42A714, 'd52831057c35afbdb73babff81857a6a3cfb2466f639b8be0a80e6300d386b0c'),
('player_wall_full', 0x43AA40, 0x43AFE3, '2acd114eb62fe67490d9301bc8e68f196830be74eb9076f52f79111467344a78'),
('ceiling_stop', 0x472690, 0x47274A, 'febfe9381b19074c41b229b314307c85f95710a35c7907935f76519052d4b50c'),
)
SPHERE = (0x695D4C, 0x695D5C, 0x5CFBE0, 0x5CFBE8)
def collect(original):
report = body_collect(original)
pe = PE(find_case(Path(original), 'Neutron.exe'))
report['handoff_ranges'] = []
for name, start, end, digest in RANGES:
data = read_va(pe, start, end-start)
if hashlib.sha256(data).hexdigest() != digest:
raise ValueError(f'Changed {name}')
report['handoff_ranges'].append(dict(name=name, va=hex(start),
file_offset=hex(pe.offset(start-pe.base)), length=end-start, sha256=digest))
if name in ('jimmy_wall', 'player_wall_full', 'ceiling_stop'):
for target in (0x4F0588, 0x4F8210, 0x4F82BC, 0x4F82C0,
0x49D5B4, 0x48E5A0, 0x48D914):
value = struct.pack('<I', target)
for index in range(len(data)-3):
if data[index:index+4] == value:
report['probe_operands'].append(dict(va=start+index, target=target))
report['probe_operands'].sort(key=lambda value: value['va'])
# Neither support routine even addresses these sphere-context variables.
report['support_sphere_references'] = {}
for name, start, end in (('support', 0x47B890, 0x47BBB0),
('nearest_support_query', 0x47C6E0, 0x47CA8B)):
data = read_va(pe, start, end-start)
found = [hex(va) for va in SPHERE if struct.pack('<I', va) in data]
if found:
raise ValueError(f'Unexpected sphere-context operand in {name}: {found}')
report['support_sphere_references'][name] = found
report['scope'] = ('Source identity and bounded body/support/attached handoff. '
'Support/ray metadata is separate; this is not whole-scene scheduler verification.')
return report
PROBE = r'''
typedef void (__cdecl *Dispatch)(void*,Vec*,Vec,int);
typedef int (__cdecl *Ray)(Vec,Vec,int);
typedef void (__cdecl *Support)(Body*);
typedef void (TC *Contact)(void*,Vec,void*);
static unsigned contact370,contact374;
static Vec observedNormal;
static unsigned detached;
static void TC detach(void*b) {(void)b;detached++;}
static void TC callback370(Body*b,Vec normal,void*p) {
(void)b;(void)p;contact370++;observedNormal=normal;
}
static void TC callback374(Body*b,Vec normal,void*p) {
(void)b;(void)p;contact374++;observedNormal=normal;
}
static unsigned char wallPolygon[0x30],wallShape[0x90],wallCorners[60];
static Vec wallPoints[3]={{-1000,-1000,0,1},{-1000,1000,0,1},{1000,1000,0,1}};
typedef struct {void *last;float face,edge;Vec hit;} Context;
static Context context(void) {
return (Context){*(void**)AT(0x695d4c),*(float*)AT(0x695d5c),
*(float*)AT(0x5cfbe0),*(Vec*)AT(0x5cfbe8)};
}
static int same(Context a,Context b) {
return a.last==b.last&&!memcmp(&a.face,&b.face,4)&&!memcmp(&a.edge,&b.edge,4)
&&!memcmp(&a.hit,&b.hit,sizeof(Vec));
}
static void wall(void) {
*(Vec*)(wallPolygon+8)=(Vec){0,0,1,0};
*(void**)(wallPolygon+0x24)=wallCorners;*(void**)(wallShape+0x68)=wallPoints;
for(unsigned i=0;i<3;i++)*(unsigned*)(wallCorners+i*20)=i;
for(int x=127;x<=132;x++)for(int z=129;z<=130;z++)for(int g=0;g<2;g++) {
Node*s=&sentinels[g][260*x+z],*n=calloc(1,sizeof(Node));void**r=calloc(1,0x1c);
require(n&&r,"wall fixture allocation");r[0]=wallPolygon;r[1]=wallShape;n->value=r;
n->next=s;n->previous=s->previous;s->previous->next=n;s->previous=n;
}
}
static void snapshot(const char*name,Body*b,unsigned a,unsigned c,int unchanged) {
Context s=context();
printf("CASE %s root=%.9g,%.9g,%.9g lastWall=%d face=%.9g edge=%.9g "
"hit=%.9g,%.9g,%.9g callback370=%u callback374=%u unchanged=%d support=%d\n",
name,b->position.x,b->position.y,b->position.z,s.last==wallPolygon,s.face,s.edge,
s.hit.x,s.hit.y,s.hit.z,contact370-a,contact374-c,unchanged,b->supported);
}
static void full_callbacks(void) {
// Direct offsets belong to the original player interface, not our Body stub.
unsigned char jimmy[0x2100],before[0x2100],material[0x20],definition[0x20];
uintptr_t completeTable[0x500/4];
for(unsigned i=0;i<sizeof(completeTable)/sizeof(*completeTable);i++)completeTable[i]=(uintptr_t)missing;
completeTable[0x204/4]=(uintptr_t)detach;
const unsigned ids[]={0,2,3,4};
for(unsigned i=0;i<4;i++)for(unsigned grounded=0;grounded<2;grounded++)
for(unsigned mature=0;mature<2;mature++)for(unsigned fast=0;fast<2;fast++) {
memset(jimmy,0,sizeof(jimmy));memset(material,0,sizeof(material));memset(definition,0,sizeof(definition));
*(uintptr_t*)jimmy=(uintptr_t)completeTable;
*(uintptr_t*)(jimmy+0xc0)=(uintptr_t)table;
*(float*)(jimmy+0xc0+0x774)=mature?4.0f:0.0f;
*(unsigned short*)(jimmy+0xc0+0x704)=grounded;
*(void**)(wallPolygon+4)=material;*(void**)(material+0xc)=definition;*(unsigned*)(definition+8)=ids[i];
memcpy(before,jimmy,sizeof(jimmy));
((Contact)AT(0x43aa40))(jimmy+0xc0,(Vec){0,0,1,0},wallPolygon);
require(!memcmp(before,jimmy,sizeof(jimmy)),"ordinary full Player callback is a no-op");
*(unsigned short*)AT(0x4f0588)=7;*(unsigned char*)AT(0x4f8210)=1;
*(float*)AT(0x4f82bc)=fast?61:60;*(float*)AT(0x4f82c0)=0;detached=0;
((Contact)AT(0x42a660))(jimmy+0xc0,(Vec){0,0,1,0},wallPolygon);
require(detached==fast&&jimmy[0xc0+0x1d65]==fast,"full wall wrapper detach and latch");
require(*(float*)AT(0x4f82bc)==0&&*(float*)AT(0x4f82c0)==0,"wall wrapper clears swing");
printf("MATERIAL id=%u grounded=%u mature=%u fast=%u baseUnchanged=1 detached=%u latch=%u\n",
ids[i],grounded,mature,fast,detached,jimmy[0xc0+0x1d65]);
}
Body b=initial();b.velocity=(Vec){3,5,7,0};b.acceleration=(Vec){11,13,17,0};
((Contact)AT(0x472690))(&b,(Vec){0,-1,0,0},wallPolygon);
require(b.velocity.x==3&&b.velocity.y==0&&b.velocity.z==7&&b.acceleration.x==11
&&b.acceleration.y==0&&b.acceleration.z==17,"source ceiling positive Y only");
b.velocity.y=-5;b.acceleration.y=13;
((Contact)AT(0x472690))(&b,(Vec){0,-1,0,0},wallPolygon);
require(b.velocity.y==-5&&b.acceleration.y==0,"ceiling components independent");
puts("CEILING independentPositiveYOnly=1");
}
int main(void) {
setbuf(stdout,NULL);map_copy();setup();wall();
table[0x370/4]=(uintptr_t)callback370;table[0x374/4]=(uintptr_t)callback374;
*(unsigned char*)AT(0x4f69e5)=1;*(unsigned char*)AT(0x695d46)=0;
Body b=initial();b.position.z=70;b.previous=b.position;b.velocity.z=-1000;
((BodyStep)AT(0x479d20))(&b,1.0f/60);
snapshot("body_wall_and_floor",&b,0,0,0);
require(context().last==wallPolygon&&contact374==1&&b.supported,"body contact plus support");
Context retained=context();unsigned a=contact370,c=contact374;
((Support)AT(0x47b890))(&b);
snapshot("support_preserves_sphere",&b,a,c,same(retained,context()));
require(same(retained,context()),"support must preserve sphere state");
a=contact370;c=contact374;
int hit=((Ray)AT(0x47c6e0))((Vec){0,100,100,1},(Vec){0,-100,100,1},0)&0xff;
snapshot("ray_preserves_sphere",&b,a,c,same(retained,context()));
require(hit&&same(retained,context())&&*(void**)AT(0x695d54)==polygon,"ray separate polygon");
a=contact370;c=contact374;
Vec p=b.position;((Dispatch)AT(0x47b4b0))(&b,&p,(Vec){0,0,10,0},1);b.position=p;
snapshot("attached_depart_replays_wall",&b,a,c,same(retained,context()));
require(same(retained,context())&&contact374-c==1,"stale terminal callback replay");
a=contact370;c=contact374;
p=b.position;((Dispatch)AT(0x47b4b0))(&b,&p,(Vec){0,0,0,0},1);
snapshot("zero_delta_skips_replay",&b,a,c,same(retained,context()));
require(contact370==a&&contact374==c,"tiny delta returns before terminal callback");
float normals[]={-.70000005f,-.7f,-.69999993f};
const char*names[]={"below_threshold_370","equal_threshold_370","above_threshold_374"};
for(unsigned i=0;i<3;i++) {
*(Vec*)(wallPolygon+8)=(Vec){0,normals[i],1,0};
a=contact370;c=contact374;p=b.position;
((Dispatch)AT(0x47b4b0))(&b,&p,(Vec){0,0,10,0},1);
snapshot(names[i],&b,a,c,same(retained,context()));
require((i<2?contact370-a:contact374-c)==1,"strict callback threshold");
}
full_callbacks();
puts("GRAPPLER_BODY_COMPONENT_COMPLETE: copied body/support/ray/dispatcher, synthetic grid");
return 0;
}
'''
def generate(original, output):
output = Path(output).resolve()
if output.is_relative_to(Path(original).resolve()):
raise ValueError('Generated files must be outside originals')
output.mkdir(parents=True, exist_ok=True)
report = collect(original)
(output/'collision_response_relocations.h').write_text(header(report))
base = (Path(__file__).parent/'body_step_probe.c').read_text()
base = base.replace('int main(void) {', 'static int prior_body_main(void) {')
(output/'grappler_body_probe.c').write_text(base+PROBE)
(output/'source.json').write_text(json.dumps(report, indent=2)+'\n')
return report
if __name__ == '__main__':
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument('original', type=Path)
cli.add_argument('--generate-probe', type=Path)
args = cli.parse_args()
result = generate(args.original, args.generate_probe) if args.generate_probe else collect(args.original)
print(json.dumps(result, indent=2))
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env python3
"""Guarded Grappler follow-camera/lifetime projection; never executes originals.
Only the ordinary walking/air follow branches are modeled. Camera flags828/851,
Bubble movement2, scene-entry snap and whole frame scheduling remain separate.
"""
from __future__ import annotations
import argparse
from dataclasses import dataclass, replace
import hashlib
import json
from pathlib import Path
import struct
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
from rocketship_motion_camera import add_axis, f32, rotate
SPANS = (
('equip',0x4297dd,0x429857,'8d8c915150a29692734293b0048429f77f8467e50ab4e5449e7110f9d3a060eb'),
('attach-camera',0x426d53,0x426da0,'8858a5eec86ee75575aafdfc6eadabc707432821a0db34cd3e6c663d21c423bf'),
('detach',0x429c10,0x429cf7,'aad9706ec19de0d162827fe957e91fb4a513423d6e6901de9a29e4c780f7df97'),
('cleanup',0x4287ac,0x42883b,'7f1a0574e1a04b1893e2599749616af049854408e1296a2f50e0510b6847d1e5'),
('ground-follow',0x439625,0x4398f2,'43ae070dd7f5b3de39cef33e9af25c2847a5e35bfa172dc479292e896ef14a88'),
('air-follow',0x439900,0x43a111,'895f27be2ad03f49230fe34e98753095285a61f52b4adbbb15f1dd7c868b2901'),
('air-eye-transform',0x43a5d0,0x43a750,'d903035a775b5f2436ea203bfa40a812335c7c75d038592ec766a374d78e47a0'),
('camera-ray',0x43b820,0x43b90f,'da79aee91ec334b7cba52edb6b3e0a016e6c553cace3a77a908f13c55af949ad'),
('camera-defaults',0x437740,0x43778e,'8a03dc8f9289f76b96be53a678e54729e345624fe98b6045e93236a303d3cb12'),
('action-guard',0x43aff0,0x43b0b6,'f439e7317ada3ffb0bc2a9dbfad19539e0faf6e97de463ebaa5b9825d27f7d82'),
('constructor-globals',0x422761,0x4227d9,'76d9d28d1a7d655cc48a435af2c77017e86c610a586356859a13e53ea33235df'),
)
VTABLES = ((0x120, 0x43a5d0), (0x124, 0x438bc0), (0x128, 0x439900),
(0x16c, 0x43b820), (0x170, 0x437740), (0x150, 0x43aff0),
(0x204, 0x429c10))
CONSTANTS = ((0x4afce8, 'd', 1.9), (0x4a2ad0, 'd', .2),
(0x4a0ce0, 'd', 1.2), (0x49d5ac, 'f', .75),
(0x4a3138, 'f', 1.5), (0x48e5e8, 'f', 45.511112213134766))
def collect(original):
pe = PE(find_case(Path(original), 'Neutron.exe'))
if hashlib.sha256(pe.data).hexdigest() != EXE_SHA256:
raise ValueError('Unexpected original EXE identity')
spans = []
for name, start, end, expected in SPANS:
digest = hashlib.sha256(read_va(pe, start, end-start)).hexdigest()
if digest != expected:
raise ValueError('Changed source span '+name)
spans.append(dict(name=name, va=hex(start), end=hex(end),
file_offset=hex(pe.offset(start-pe.base)), sha256=digest))
for slot, expected in VTABLES:
if struct.unpack('<I', read_va(pe, 0x4a3bdc+slot, 4))[0] != expected:
raise ValueError('Changed Jimmy virtual '+hex(slot))
for va, fmt, expected in CONSTANTS:
if struct.unpack('<'+fmt, read_va(pe, va, struct.calcsize(fmt)))[0] != expected:
raise ValueError('Changed camera constant '+hex(va))
if read_va(pe, 0x4ef6d8, 6) != b'SWING\0':
raise ValueError('Changed protected action literal')
return dict(source_sha256=EXE_SHA256, spans=spans,
vtables=[dict(slot=hex(s), target=hex(t)) for s,t in VTABLES],
constants=[dict(va=hex(v),type=f,value=x) for v,f,x in CONSTANTS],
scope='Static guards and bounded Python projection; no original execution')
@dataclass(frozen=True)
class CameraLocals:
eye: tuple = (0., 200., -350.)
look: tuple = (0., 80., 0.)
gains: tuple = (1.6, 1., 1.6)
def equip(camera):
"""4297DD writes six locals, leaves gains untouched."""
return replace(camera, eye=(0.,50.,-350.), look=(0.,150.,80.))
def attach(camera):
"""426D writes eye Y/Z and gains; retains eye X and all look coordinates."""
return replace(camera, eye=(camera.eye[0],400.,-650.), gains=(.8,1.,.8))
def detach(camera, attached=True):
"""429C10 is a strict no-op when its attached global is already false."""
if not attached:
return camera
return CameraLocals((0.,50.,-350.),(0.,130.,100.),(1.6,1.,1.6))
def cleanup(camera, attached=True):
"""4287FC detaches then invokes complete170 normal camera defaults."""
return CameraLocals()
def desired(camera, root=(0.,0.,0.), euler=(0.,0.,0.), turn_rate=0.,
movement_mode=0, adjustment=10.):
"""Return desired world eye/look and effective gains for ordinary branches.
Air eye helper43A5D0 flattens pitch and adds turn_rate to logical yaw.
Ground game384 uses complete logical Euler for both points. Values are
projections of guarded instructions, not original x87-bit identity.
"""
if movement_mode == 2:
raise ValueError('Bubble mode2 uses separate air smoothing branches')
if movement_mode == 0:
eye_local=(camera.eye[0],f32(camera.eye[1]-2*adjustment),camera.eye[2])
look_local=(camera.look[0],f32(camera.look[1]+1.9*adjustment),camera.look[2])
eye_rotation=euler
gains=(camera.gains[0],camera.gains[1]+.2,camera.gains[2])
else:
eye_local,look_local=camera.eye,camera.look
eye_rotation=(0.,add_axis(euler[1],turn_rate),euler[2])
gains=(1.2,2.,1.2)
eye=tuple(f32(a+b) for a,b in zip(root,rotate(eye_local,eye_rotation)))
look=tuple(f32(a+b) for a,b in zip(root,rotate(look_local,euler)))
return eye,look,gains
def follow(camera, old_eye, dt, hit=None, **kwargs):
"""One ordinary follow pass. Aim vector intentionally uses PRE-update eye."""
eye,look,gains=desired(camera,**kwargs)
ray_gain=1.
if hit is not None:
eye=tuple(f32(a-(a-b)*.75) for a,b in zip(look,hit))
ray_gain=1.5
updated=tuple(f32(old+(new-old)*gain*ray_gain*dt)
for old,new,gain in zip(old_eye,eye,gains))
return dict(eye=updated,look=look,desired_eye=eye,ray_gain=ray_gain,
aim_vector=tuple(f32(a-b) for a,b in zip(look,old_eye)))
def main():
cli=argparse.ArgumentParser(description=__doc__)
cli.add_argument('original',type=Path)
cli.add_argument('--output',type=Path)
args=cli.parse_args()
result=json.dumps(collect(args.original),indent=2)+'\n'
if args.output: args.output.write_text(result)
else: print(result,end='')
if __name__=='__main__': main()