Implement source-backed Scooter vehicle in tutorial and outside
This commit is contained in:
1 parent
8df5e81070
commit
62c07a3d59
44 files changed
+3135
-174
No files matched your search
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Guarded Scooter drive/input source and copied-code probe preparation."""
|
||||
import argparse,hashlib,json,re,struct,subprocess
|
||||
from pathlib import Path
|
||||
from scooter import collect as scooter_collect
|
||||
from checkpoint_script_state import find_case,read_va
|
||||
from pe_inspect import PE
|
||||
|
||||
RANGES=((0x421910,0x421ba4),(0x467000,0x467045),(0x4669f0,0x466aea),(0x458890,0x458a00),(0x473320,0x47353a),(0x465220,0x46582d),(0x465830,0x465dfe),(0x421c10,0x421cf7),
|
||||
(0x476ff0,0x477490),(0x4723f0,0x472420),(0x472480,0x472570),(0x472b10,0x472c10))
|
||||
EVIDENCE_RANGES=RANGES+((0x467080,0x4679c0),(0x468020,0x468300),
|
||||
(0x412f90,0x413030),(0x466af0,0x466b30),(0x425120,0x425170),
|
||||
(0x41e0f9,0x41e1f8),(0x41e2f0,0x41e3a0),(0x408e40,0x409010))
|
||||
def collect(original):
|
||||
report=scooter_collect(original);pe=PE(find_case(Path(original),'Neutron.exe'))
|
||||
# Only absolute data/IAT references found in decoded disassembly are eligible.
|
||||
targets=set()
|
||||
for start,end in RANGES:
|
||||
result=subprocess.run(['objdump','-d','-Mintel',f'--start-address={start}',f'--stop-address={end}',str(pe.path)],capture_output=True,text=True,check=True)
|
||||
targets.update(int(v,16) for v in re.findall(r'ds:0x([0-9a-f]+)',result.stdout))
|
||||
targets.update((0x48d104,0x48d10c))
|
||||
report['motion_ranges']=[dict(va=hex(start),file_offset=hex(pe.offset(start-pe.base)),length=end-start,
|
||||
sha256=hashlib.sha256(read_va(pe,start,end-start)).hexdigest()) for start,end in EVIDENCE_RANGES]
|
||||
report['motion_relocations']=[]
|
||||
for start,end in RANGES:
|
||||
data=read_va(pe,start,end-start)
|
||||
for target in sorted(targets):
|
||||
for match in re.finditer(re.escape(struct.pack('<I',target)),data):
|
||||
report['motion_relocations'].append(dict(va=start+match.start(),target=target))
|
||||
report['motion_constants']={hex(va):struct.unpack('<d' if wide else '<f',read_va(pe,va,8 if wide else 4))[0]
|
||||
for va,wide in [(0x4d5888,False),(0x48d948,False),(0x49b1f8,False),(0x49fac0,False),(0x4d5880,True),
|
||||
(0x4d5878,False),(0x4d5870,True),(0x4a3144,False)]}
|
||||
return report
|
||||
|
||||
def generate(original,output):
|
||||
output=Path(output).resolve();original=Path(original).resolve()
|
||||
if output.is_relative_to(original) or original.is_relative_to(output):raise ValueError('Separate output required')
|
||||
output.mkdir(parents=True,exist_ok=True);report=collect(original)
|
||||
body=(Path(__file__).with_name('scooter_motion_probe.c')).read_text()
|
||||
body=body.replace('/* RELOCATIONS */',','.join('{0x%x,0x%x}'%(r['va'],r['target']) for r in report['motion_relocations']))
|
||||
(output/'scooter_motion_probe.c').write_text(body)
|
||||
(output/'source.json').write_text(json.dumps(report,indent=2)+'\n');return report
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('original',type=Path);p.add_argument('--generate-probe',type=Path);a=p.parse_args()
|
||||
r=generate(a.original,a.generate_probe) if a.generate_probe else collect(a.original)
|
||||
print(json.dumps(r,indent=2))
|
||||
@@ -0,0 +1,143 @@
|
||||
/* Copied465220 full arithmetic and465830 keyboard input. Synthetic base actor,
|
||||
body properties, wheel support, camera/audio/input; original OMT vector/trig. */
|
||||
#define main unused_grappler_main
|
||||
#include "grappler_scalar_probe.c"
|
||||
#undef main
|
||||
typedef struct{float x,y,z,w;}Vec;
|
||||
static uintptr_t game_table[0x440/4],outer_table[0x180/4],wheel_table[0x220/4];
|
||||
static unsigned char wheels[4][0x200];
|
||||
static Vec velocity,acceleration,angular;static float scalar,friction;static int supported,missing_slot;
|
||||
#define GF(g,o) (*(float*)((g)+(o)))
|
||||
static void TC missing(void*self){fprintf(stderr,"MISSING caller=%x self=%x\n",(unsigned)((unsigned char*)__builtin_return_address(0)-mapped+0x400000),(unsigned)self);require(0,"unexpected virtual call");}
|
||||
static int TC zero(void*self){(void)self;return 0;}
|
||||
static int TC enabled(void*self){(void)self;return 1;}
|
||||
static int TC support(void*self){(void)self;return supported;}
|
||||
static int TC wheel_support(void*self){return ((unsigned char*)self)[4];}
|
||||
static float TC speed(void*self){(void)self;return scalar;}
|
||||
static float TC get_friction(void*self){(void)self;return friction;}
|
||||
static void TC set_speed(void*self,float v){(void)self;scalar=v;}
|
||||
static Vec*TC get_velocity(void*self,Vec*out){(void)self;*out=velocity;return out;}
|
||||
static void TC set_velocity(void*self,float x,float y,float z){(void)self;velocity=(Vec){x,y,z,0};}
|
||||
static void TC set_accel(void*self,float x,float y,float z){(void)self;acceleration=(Vec){x,y,z,0};}
|
||||
static Vec*TC get_angular(void*self,Vec*out){(void)self;*out=angular;return out;}
|
||||
static void TC set_angular(void*self,float x,float y,float z){(void)self;angular=(Vec){x,y,z,0};}
|
||||
static void TC add_angular(void*self,float x,float y,float z){(void)self;angular.x+=x;angular.y+=y;angular.z+=z;}
|
||||
static void TC add_velocity(void*self,float x,float y,float z){(void)self;velocity.x+=x;velocity.y+=y;velocity.z+=z;}
|
||||
static void TC noop_dt(void*self,float dt){(void)self;(void)dt;}
|
||||
static void TC noop(void*self){(void)self;}
|
||||
static void TC mouse(void*self,short*x,short*y){(void)self;*x=*y=0;}
|
||||
static void setup(void){
|
||||
map_source();
|
||||
const struct{uint32_t va,target;} reloc[]={/* RELOCATIONS */};
|
||||
for(unsigned i=0;i<sizeof(reloc)/sizeof(reloc[0]);i++){
|
||||
uint32_t value;memcpy(&value,AT(reloc[i].va),4);require(value==reloc[i].target,"absolute operand");
|
||||
value=(uintptr_t)AT(value);memcpy(AT(reloc[i].va),&value,4);
|
||||
}
|
||||
HMODULE dll=LoadLibraryA("Z:\\work\\game\\OMT2.dll");require(dll!=NULL,"copied OMT2");
|
||||
*(void**)AT(0x48d104)=GetProcAddress(dll,"?quick_magnitude@OMedia3DVector@@QBEMXZ");
|
||||
*(void**)AT(0x48d10c)=GetProcAddress(dll,"?global@OMediaCosSinTable@@2V1@A");
|
||||
require(*(void**)AT(0x48d104)&&*(void**)AT(0x48d10c),"OMT vector exports");
|
||||
float*trig=*(void**)AT(0x48d10c);printf("TABLE quarter sin=%.9g cos=%.9g\n",trig[4096],trig[16385+4096]);
|
||||
const unsigned char ready[]={0xb0,1,0xc3},base[]={0xc2,4,0};
|
||||
memcpy(AT(0x475ca0),ready,3);memcpy(AT(0x462520),base,3);
|
||||
for(unsigned i=0;i<sizeof(game_table)/4;i++)game_table[i]=(uintptr_t)missing;
|
||||
for(unsigned i=0;i<sizeof(outer_table)/4;i++)outer_table[i]=(uintptr_t)missing;
|
||||
outer_table[0x140/4]=(uintptr_t)AT(0x467000);game_table[0x278/4]=(uintptr_t)set_accel;
|
||||
game_table[0x2ac/4]=(uintptr_t)get_angular;game_table[0x2b4/4]=(uintptr_t)set_angular;game_table[0x2b8/4]=(uintptr_t)add_angular;
|
||||
game_table[0x220/4]=(uintptr_t)enabled;
|
||||
game_table[0x210/4]=(uintptr_t)enabled;game_table[0x218/4]=(uintptr_t)support;
|
||||
game_table[0x248/4]=(uintptr_t)get_friction;game_table[0x268/4]=(uintptr_t)speed;game_table[0x26c/4]=(uintptr_t)set_speed;
|
||||
game_table[0x2bc/4]=(uintptr_t)get_velocity;game_table[0x2c4/4]=(uintptr_t)set_velocity;game_table[0x2cc/4]=(uintptr_t)add_velocity;
|
||||
game_table[0x328/4]=(uintptr_t)AT(0x4723f0);game_table[0x334/4]=(uintptr_t)AT(0x472480);game_table[0x38c/4]=(uintptr_t)AT(0x472b10);
|
||||
outer_table[0x160/4]=(uintptr_t)noop;
|
||||
outer_table[0xf8/4]=(uintptr_t)mouse;outer_table[0xec/4]=(uintptr_t)noop_dt;outer_table[0x164/4]=(uintptr_t)noop;
|
||||
outer_table[0x120/4]=(uintptr_t)AT(0x421c10);outer_table[0x124/4]=(uintptr_t)AT(0x421c40);
|
||||
outer_table[0x128/4]=(uintptr_t)AT(0x421c70);outer_table[0x12c/4]=(uintptr_t)AT(0x421cb0);outer_table[0x130/4]=(uintptr_t)AT(0x413a60);
|
||||
for(int offset=0xfc;offset<=0x11c;offset+=4)outer_table[offset/4]=(uintptr_t)zero;
|
||||
for(int offset=0x134;offset<=0x150;offset+=4)outer_table[offset/4]=(uintptr_t)zero;
|
||||
outer_table[0x140/4]=(uintptr_t)AT(0x467000);game_table[0x1d8/4]=(uintptr_t)zero;
|
||||
wheel_table[0x218/4]=(uintptr_t)wheel_support;
|
||||
}
|
||||
static unsigned char*reset(float speed_in,float vx,float vy,float vz,float pitch,float yaw,float turn,int front,int rear,int ground){
|
||||
memset(object,0,sizeof(object));unsigned char*g=object+0xc0;*(void**)object=outer_table;*(void**)g=game_table;
|
||||
memset(AT(0x509830),0,0x1d0);acceleration=(Vec){3,4,5,0};angular=(Vec){10,20,30,0};scalar=speed_in;velocity=(Vec){vx,vy,vz,0};friction=.8f;supported=ground;
|
||||
GF(g,0x224)=pitch;GF(g,0x228)=yaw;GF(g,0x22c)=0;GF(g,0x57c)=turn;GF(g,0x560)=2250;
|
||||
*(int*)(g+0x590)=*(int*)(g+0x594)=1;GF(g,0x550)=700;GF(g,0x558)=1200;GF(g,0x568)=1485;*(short*)(g+0x540)=front;*(short*)(g+0x542)=rear;
|
||||
for(int i=0;i<4;i++){
|
||||
memset(wheels[i],0,sizeof(wheels[i]));*(void**)(wheels[i]+0xc0)=wheel_table;
|
||||
wheels[i][0xc4]=i<2?i<front:i-2<rear;*(void**)(g+0x4b8+i*4)=wheels[i];
|
||||
}
|
||||
return g;
|
||||
}
|
||||
static void drive(const char*name,float s,float vx,float vy,float vz,float p,float y,float t,int front,int rear,int ground,int throttle,int brake,int reverse,float timer,float dt){
|
||||
unsigned char*g=reset(s,vx,vy,vz,p,y,t,front,rear,ground);g[0x598]=throttle;g[0x599]=brake;g[0x59f]=reverse;GF(g,0x588)=timer;
|
||||
((void(TC*)(void*,float))AT(0x465220))(g,dt);
|
||||
printf("DRIVE %s in=%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%d,%d,%d,%d,%d,%d,%.9g,%.9g out=%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%.9g\n",name,s,vx,vy,vz,p,y,t,front,rear,ground,throttle,brake,reverse,timer,dt,scalar,velocity.x,velocity.y,velocity.z,GF(g,0x228),GF(g,0x580),GF(g,0x578),GF(g,0x588));
|
||||
}
|
||||
static void wall_case(const char*name,float s,Vec v,Vec n,int active,int up,float dt){
|
||||
unsigned char*g=reset(s,v.x,v.y,v.z,0,0,0,2,2,1);g[0x59b]=1;g[0x59c]=active;*AT(0x50985e)=up;F(0x696030)=dt;
|
||||
((void(TC*)(void*,Vec,void*))AT(0x421910))(g,n,NULL);
|
||||
printf("WALL %s in=%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%d,%d,%.9g out=%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%u\n",name,s,v.x,v.y,v.z,n.x,n.y,n.z,active,up,dt,scalar,velocity.x,velocity.y,velocity.z,acceleration.x,acceleration.y,acceleration.z,g[0x59c]);
|
||||
}
|
||||
static void crash_case(const char*name,float timer,float dt){
|
||||
unsigned char*g=reset(0,120,100,-60,0,0,0,2,2,1);g[0x59c]=1;GF(g,0x58c)=timer;
|
||||
((void(TC*)(void*,float))AT(0x4669f0))(object,dt);
|
||||
printf("CRASH %s in=%.9g,%.9g out=%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%u\n",name,timer,dt,velocity.x,velocity.y,velocity.z,angular.x,angular.y,angular.z,GF(g,0x58c),g[0x59c]);
|
||||
}
|
||||
static void face_case(const char*name,float p,float y,float r,float dp,float dy,float dr,float rate,float dt){
|
||||
unsigned char*g=reset(0,0,0,0,p,y,0,2,2,1);GF(g,0x22c)=r;GF(g,0x274)=dp;GF(g,0x278)=dy;GF(g,0x27c)=dr;GF(g,0x29c)=rate;g[5]=g[10]=1;
|
||||
((void(TC*)(void*,float))AT(0x473320))(g,dt);
|
||||
printf("FACE %s in=%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%.9g,%.9g out=%.9g,%.9g,%.9g\n",name,p,y,r,dp,dy,dr,rate,dt,GF(g,0x224),GF(g,0x228),GF(g,0x22c));
|
||||
}
|
||||
static void normal(const char*name,Vec n,float y){float initial=y,p=0,r=0;((void(*)(Vec*,float*,float*,float*))AT(0x476ff0))(&n,&p,&y,&r);printf("NORMAL %s in=%.9g,%.9g,%.9g,%.9g out=%.9g,%.9g,%.9g\n",name,n.x,n.y,n.z,initial,p,y,r);}
|
||||
static void input(const char*name,float s,float t,int keyturn,int rev,int brake,int up,int down,int left,int right,int rear,float dt){
|
||||
unsigned char*g=reset(s,0,0,0,0,0,t,2,rear,1);g[0x59d]=keyturn;g[0x59f]=rev;g[0x599]=brake;
|
||||
*AT(0x50985e)=up;*AT(0x509860)=down;*AT(0x50985d)=left;*AT(0x50985f)=right;
|
||||
((void(TC*)(void*,float))AT(0x465830))(g,dt);
|
||||
printf("INPUT %s in=%.9g,%.9g,%d,%d,%d,%d,%d,%d,%d,%d,%.9g out=%.9g,%.9g,%u,%u,%u,%u\n",name,s,t,keyturn,rev,brake,up,down,left,right,rear,dt,scalar,GF(g,0x57c),g[0x59d],g[0x59f],g[0x599],g[0x598]);
|
||||
}
|
||||
int main(void){
|
||||
setbuf(stdout,NULL);setup();
|
||||
drive("rest",0,0,0,0,0,0,0,2,2,1,0,0,0,0,.1f);
|
||||
drive("launch",100,0,0,0,0,0,0,2,2,1,1,0,0,0,.1f);
|
||||
drive("forward",300,0,0,300,0,0,0,2,2,1,1,0,0,0,.1f);
|
||||
drive("coast",300,0,0,300,0,0,0,2,2,1,0,0,0,0,.1f);
|
||||
drive("turn",300,0,0,300,0,0,30,2,2,1,1,0,0,0,.1f);
|
||||
drive("slowturn",80,0,0,80,0,0,-30,1,2,1,1,0,0,0,.1f);
|
||||
drive("drift",400,150,10,300,0,35,25,2,2,1,1,0,0,0,.1f);
|
||||
drive("falling",300,0,-100,300,0,0,0,2,2,1,1,0,0,0,.1f);
|
||||
drive("rising",300,0,100,300,0,0,0,2,2,1,1,0,0,0,.1f);
|
||||
drive("uphill",300,0,0,300,20,0,0,2,2,1,1,0,0,0,.1f);
|
||||
drive("downhill",300,0,0,300,-20,0,0,2,2,1,1,0,0,0,.1f);
|
||||
drive("reverse",-300,0,0,-300,0,0,30,2,2,1,0,1,1,0,.1f);
|
||||
drive("reverse_allowed",-300,0,0,-300,0,0,30,2,2,1,0,1,1,1.1f,.1f);
|
||||
drive("unsupported",300,0,0,300,0,0,30,2,2,0,1,0,0,0,.1f);
|
||||
drive("frontnone",300,0,0,300,0,0,30,0,2,1,1,0,0,0,.1f);
|
||||
drive("onewheel",300,0,0,300,0,0,30,1,0,1,1,0,0,0,.1f);
|
||||
drive("nowheels",300,0,0,300,0,0,30,0,0,1,1,0,0,0,.1f);
|
||||
drive("brakestill",0,0,0,0,0,0,0,2,2,1,0,1,1,0,.1f);
|
||||
drive("braketimer",0,0,0,0,0,0,0,2,2,1,0,1,1,1,.1f);
|
||||
drive("negativecoast",-30,0,0,-30,0,0,0,2,2,1,0,0,0,0,.1f);
|
||||
drive("tinycoast",.1f,0,0,.1f,0,0,0,2,2,1,0,0,0,0,.1f);
|
||||
drive("tick",1400,120,-13,1200,5,179,40,2,2,1,1,0,0,0,1.f/60);
|
||||
normal("flat",(Vec){0,1,0,0},0);normal("slopeZ",(Vec){0,.9396926f,.3420201f,0},0);normal("slopeX",(Vec){.3420201f,.9396926f,0,0},90);normal("slopeXZ",(Vec){.2f,.95f,.2f,0},45);
|
||||
for(int i=0;i<4;i++){
|
||||
char name[32];sprintf(name,"input%d",i);input(name,300,10,1,0,0,i==0,i==1,i==2,i==3,2,.1f);
|
||||
}
|
||||
input("nosupport",300,10,1,0,0,1,0,1,0,0,.1f);
|
||||
input("reverseheld",0,0,0,1,1,0,1,0,0,2,.1f);
|
||||
input("brakenegative",-300,0,0,0,0,0,1,0,0,2,.1f);
|
||||
input("both",300,44,0,1,1,1,1,1,1,2,.1f);
|
||||
input("cap",1490,-44,0,0,0,1,0,0,1,2,.1f);
|
||||
wall_case("head_on",600,(Vec){0,13,600,0},(Vec){0,0,-1,0},0,1,.1f);
|
||||
wall_case("side",600,(Vec){600,13,0,0},(Vec){-1,0,0,0},0,1,.1f);
|
||||
wall_case("side_no_throttle",600,(Vec){600,13,0,0},(Vec){-1,0,0,0},0,0,.1f);
|
||||
wall_case("glance",600,(Vec){400,-20,300,0},(Vec){-.8f,0,-.6f,0},0,1,.1f);
|
||||
wall_case("slow20",10,(Vec){0,13,20,0},(Vec){0,0,-1,0},0,1,.1f);
|
||||
wall_case("reverse",-300,(Vec){0,-13,-300,0},(Vec){0,0,1,0},0,0,.1f);
|
||||
wall_case("already_crash",0,(Vec){0,100,300,0},(Vec){0,0,-1,0},1,1,.1f);
|
||||
crash_case("begin",0,.1f);crash_case("before_end",3.8f,.1f);crash_case("equal_end",3.9f,.1f);crash_case("after_end",4,.1f);
|
||||
face_case("ordinary",10,20,30,0,30,0,5,.1f);face_case("seam",359,359,359,1,1,1,2,.1f);face_case("small",.1f,.1f,.1f,0,0,0,2,.1f);
|
||||
for(int i=0;i<4;i++){char name[32];sprintf(name,"slopeYaw%d",i);normal(name,(Vec){.2f,.95f,.2f,0},i*90);}
|
||||
puts("SCOOTER_MOTION_COMPLETE: copied465220/465830, synthetic dependencies");return 0;
|
||||
}
|
||||
@@ -16,6 +16,7 @@ from bubble_resources import export_bubble
|
||||
from baseball_resources import export_baseball
|
||||
from rocketship_resources import export_rocketship
|
||||
from grappler_resources import export_grappler
|
||||
from scooter_resources import export_scooter
|
||||
from sound_bank import export_sound_bank
|
||||
|
||||
|
||||
@@ -90,6 +91,7 @@ def main():
|
||||
export_baseball(args.original,args.output/'baseball')
|
||||
export_rocketship(args.original,args.output/'rocketship')
|
||||
export_grappler(args.original,args.output/'grappler')
|
||||
export_scooter(args.original,args.output/'scooter')
|
||||
effects = export_sound_bank(args.original, args.output / 'effects')
|
||||
print(f"SoundEffects.omt: {len(effects['resources'])} original sound identities")
|
||||
for name in args.audio:
|
||||
|
||||
@@ -1,100 +1,203 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Export original Scooter resource data; do not assign attachments or playback.
|
||||
"""Export exact Scooter OMT body/wheel and Jimmy rider resources.
|
||||
|
||||
The two Scooter ASE morphs have 195 indexed positions, whereas scooter.omt's
|
||||
body has 98. Keep these samples unbound rather than inventing UVs or a base.
|
||||
Mesh pivots, vertices, UVs, materials, texture pixels and morph samples are
|
||||
unchanged. Runtime owns source vehicle/wheel transforms and action selection.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from collections import Counter
|
||||
from dataclasses import asdict
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from ase import export_ase, read_ase
|
||||
from entities import resolve_asset
|
||||
from models import export_omt_model
|
||||
from omt import Database, FormatError, read_shape
|
||||
from gam import parse
|
||||
from omt import Database, FormatError, read_canvas, read_material, read_shape, write_png
|
||||
from png import read_png
|
||||
|
||||
SOURCES = {
|
||||
'Neutron.exe': 'f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8',
|
||||
'omt/scooter.omt': '8d4ffdafee5fd819c5220ee4f608c901a5988fe6b8b13316e15618f5eec75e81',
|
||||
'ASE/jimstop.ASE': 'b294d090ac5c4ec449d845db6d837f2cbedf5f7b812f5b6ed2bb70f85246f1d0',
|
||||
'ASE/jimscooter.ASE': 'b27c8cb80811eb70e391fc061dab99c7d5f0b4d884c109b34c673a1815508299',
|
||||
'ASE/jimscooterstop.ASE': 'edcdcc879a28757994525f815c88cd6dd46dc788b69ba2f902323d6de48cb873',
|
||||
'ASE/jimstop.ASE': 'b294d090ac5c4ec449d845db6d837f2cbedf5f7b812f5b6ed2bb70f85246f1d0',
|
||||
'ASE/godscooter.ASE': 'c18f1414ec2b397e0c8f8320f63830ab88630ea05a354bb99af34ce7fea79bd1',
|
||||
'ASE/godscooter2.ASE': 'fcf9ca5e8298efa7b4d551d9d09878c04f1f2647b6a30edfa2297617a7d63189',
|
||||
'png/jimycarl.png': '55ed165aaffe177cb62558a08d13fc3b2210da6e353065b108849d46df9dacb6',
|
||||
'gam/VR05.gam': 'f8a14585116bbf0f339b22f634a3fa66b5e7c967bdd19a21e98a18aea2c73a02',
|
||||
'gam/level1.gam': '40b809d007671e082c07c2766e487f30115a85ef3a067d5c15ff374b32cdb3f2',
|
||||
}
|
||||
CLIPS = ('jimscooter', 'jimscooterstop')
|
||||
JIMMY_RGBA_SHA256 = '5e54ccb99e9e060843cd7f80fd93ff8bf47f8779666e41d4240398354a278a3f'
|
||||
CANVASES = ((0, 'scooterwheel2', 22568, 3966, 32, 32,
|
||||
'92dfef71def8079db70ba4eaa47e973d45a0b3987418e87dbf65cc3cf0bf823b'),
|
||||
(1, 'goddard128', 26534, 65770, 128, 128,
|
||||
'b22651171a7b9f2c99831a1ff4fd8d01d11ccabfc276d71dd91bacd710cd1cba'))
|
||||
SHAPES = ((0, 'goddard01', 'body', 104, 19342, 98, 176),
|
||||
(1, 'wheel', 'wheel', 92304, 5814, 32, 56))
|
||||
# Mapped source spans: Init binds database0, Jimmy aliases, Goddard alias,
|
||||
# wheel's inherited visual binder. Values are guarded below before output.
|
||||
BINDINGS = (
|
||||
(0x4214f0, 0x421515, 'body database entry0'),
|
||||
(0x422c58, 0x422c80, 'Jimmy HISCOOT/HISCOOTSTOP'),
|
||||
(0x41cdf0, 0x41ce04, 'Goddard HISCOOT'),
|
||||
(0x468270, 0x46829a, 'wheel database visual binder'),
|
||||
(0x477550, 0x4775e2, 'MakeShapeUnLit material consumer'),
|
||||
)
|
||||
|
||||
|
||||
def digest(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def _json(path: Path, value):
|
||||
path.write_text(json.dumps(value, separators=(',', ':'), allow_nan=False)+'\n', encoding='utf-8')
|
||||
|
||||
|
||||
def _shape_scene(shape: dict, entry, materials: list, textures: list) -> dict:
|
||||
"""Same source corner/triangle-fan expansion as omt.export_scene, one shape."""
|
||||
scene = dict(source='scooter.omt', sha256=SOURCES['omt/scooter.omt'],
|
||||
coordinates='Original OMT coordinates and pivot, unchanged', vertices=[], uvs=[], normals=[],
|
||||
indices=[], meshes=[], materials=materials, textures=textures, collisionPolygons=[], warnings=[])
|
||||
names = {m['id']: m['name'] for m in materials}
|
||||
for polygon_index, poly in enumerate(shape['polygons']):
|
||||
first = len(scene['vertices']); first_index = len(scene['indices'])
|
||||
link = poly['material']; material = link['id'] if link else -1
|
||||
for corner in poly['corners']:
|
||||
scene['vertices'].append(shape['vertices'][corner['vertex']])
|
||||
scene['uvs'].append(corner['uv'])
|
||||
normal = corner['normal']
|
||||
scene['normals'].append(shape['normals'][normal] if normal < len(shape['normals']) else poly['normal'])
|
||||
for i in range(1, len(poly['corners'])-1):
|
||||
scene['indices'].extend((first, first+i, first+i+1))
|
||||
scene['collisionPolygons'].append(dict(shapeId=entry.id, polygonIndex=polygon_index,
|
||||
normal=poly['normal'], materialName=names.get(material), materialId=material if link else None))
|
||||
if scene['meshes'] and scene['meshes'][-1]['material'] == material:
|
||||
scene['meshes'][-1]['indexCount'] += len(scene['indices'])-first_index
|
||||
else:
|
||||
scene['meshes'].append(dict(name=entry.name, shapeId=entry.id,
|
||||
firstIndex=first_index, indexCount=len(scene['indices'])-first_index, material=material))
|
||||
if len(poly['corners']) != 3:
|
||||
raise FormatError('Scooter source topology unexpectedly needs fan triangulation')
|
||||
return scene
|
||||
|
||||
|
||||
def export_scooter(original: Path, output: Path) -> dict:
|
||||
original, output = original.resolve(), output.resolve()
|
||||
if output.is_relative_to(original) or original.is_relative_to(output):
|
||||
raise ValueError('Output must be separate from the original installation')
|
||||
# Existing descendants are checked before any helper writes into them.
|
||||
if output.exists() and any(p.is_symlink() for p in output.rglob('*')):
|
||||
raise ValueError('Generated Scooter paths must not contain symlinks')
|
||||
paths = {name: resolve_asset(original, name) for name in SOURCES}
|
||||
for name, path in paths.items():
|
||||
if hashlib.sha256(path.read_bytes()).hexdigest() != SOURCES[name]:
|
||||
if digest(path.read_bytes()) != SOURCES[name]:
|
||||
raise FormatError(f'Unexpected original Scooter source identity: {name}')
|
||||
clips = {name: read_ase(paths[f'ASE/{name}.ASE']) for name in (*CLIPS, 'jimstop')}
|
||||
base = clips['jimstop']['objects'][0]['samples'][0]
|
||||
if len(base['vertices']) != 426 or len(base['faces']) != 814 or not base['textureFaces']:
|
||||
raise FormatError('Jimmy source base lacks exact compatible textured topology')
|
||||
for stem in CLIPS:
|
||||
clip = clips[stem]
|
||||
if len(clip['objects']) != 1:
|
||||
raise FormatError('Unexpected Scooter rider object count')
|
||||
samples = clip['objects'][0]['samples']
|
||||
if tuple(s['time'] for s in samples) != (0, 480) or any(
|
||||
(len(s['vertices']), len(s['faces']), len(s['uvs']), len(s['textureFaces'])) != (426, 814, 0, 0) for s in samples):
|
||||
raise FormatError('Unexpected Scooter rider source samples/topology')
|
||||
jimmy = read_png(paths['png/jimycarl.png'])
|
||||
if (jimmy['width'], jimmy['height'], digest(jimmy['rgba'])) != (256, 256, JIMMY_RGBA_SHA256):
|
||||
raise FormatError('Unexpected Jimmy atlas pixels')
|
||||
database = Database(paths['omt/scooter.omt'])
|
||||
shapes = {}
|
||||
for identity, expected in ((0, ('goddard01', 98, 176)), (1, ('wheel', 32, 56))):
|
||||
entry = next(e for e in database.entries if e.type == '3DSh' and e.id == identity)
|
||||
shape = read_shape(database.payload(entry))
|
||||
if (entry.name, len(shape['vertices']), len(shape['polygons'])) != expected:
|
||||
raise FormatError('Unexpected original Scooter shape metadata')
|
||||
shapes[identity] = shape
|
||||
animations = {name: read_ase(path) for name, path in paths.items() if name.startswith('ASE/')}
|
||||
for name, animation in animations.items():
|
||||
expected_count = 195 if 'godscooter' in name else 426
|
||||
if len(animation['objects']) != 1 or len(animation['objects'][0]['samples']) != 2:
|
||||
raise FormatError('Unexpected original Scooter animation objects/samples')
|
||||
if any(len(s['vertices']) != expected_count for s in animation['objects'][0]['samples']):
|
||||
raise FormatError('Unexpected original Scooter morph vertex count')
|
||||
texture_path = resolve_asset(original, 'png/jimycarl.png')
|
||||
texture = read_png(texture_path)
|
||||
rgba = texture.pop('rgba')
|
||||
texture.update(source=texture_path.name, sourceSha256=hashlib.sha256(texture_path.read_bytes()).hexdigest(),
|
||||
rgbaSha256=hashlib.sha256(rgba).hexdigest(), path='../jimycarl.rgba')
|
||||
manifest = dict(schema=1, sources=SOURCES.copy(), shapes=[], animations=[], unboundMorphs=[],
|
||||
bindingPolicy='Resource-only export; caller owns original attachment, transforms and timing')
|
||||
shapes, textures, materials, pixels = {}, [], [], {}
|
||||
for entry in database.entries:
|
||||
payload = database.payload(entry)
|
||||
if entry.type == '3DSh':
|
||||
shapes[entry.id] = (entry, read_shape(payload))
|
||||
elif entry.type == '3DMa':
|
||||
materials.append(dict(id=entry.id, name=entry.name, **read_material(payload)))
|
||||
if set(shapes) != {0, 1} or len(materials) != 2:
|
||||
raise FormatError('Unexpected Scooter shape/material count')
|
||||
for id_, name, source_offset, source_bytes, width, height, rgba_sha in CANVASES:
|
||||
entries = [e for e in database.entries if e.type == 'Canv' and e.id == id_]
|
||||
if len(entries) != 1:
|
||||
raise FormatError('Unexpected Scooter texture identity')
|
||||
entry = entries[0]; canvas = read_canvas(database.payload(entry))
|
||||
if (entry.name, entry.offset, entry.size, canvas['width'], canvas['height'], digest(canvas['rgba'])) != (
|
||||
name, source_offset, source_bytes, width, height, rgba_sha):
|
||||
raise FormatError('Unexpected Scooter canvas metadata/pixels')
|
||||
pixels[id_] = canvas['rgba']
|
||||
textures.append(dict(id=id_, name=name, path=f'../canvas_{id_}.rgba', png=f'../canvas_{id_}.png',
|
||||
width=width, height=height, sourceOffset=source_offset, sourceBytes=source_bytes,
|
||||
sourceSha256=digest(database.payload(entry)), rgbaSha256=rgba_sha))
|
||||
if {m['id']: m['texture']['id'] for m in materials} != {0: 1, 1: 0}:
|
||||
raise FormatError('Scooter material-to-canvas links changed')
|
||||
scenes, shape_meta = {}, []
|
||||
for id_, name, folder, offset, size, vertices, polygons in SHAPES:
|
||||
entry, shape = shapes[id_]
|
||||
if (entry.name, entry.offset, entry.size, len(shape['vertices']), len(shape['polygons'])) != (
|
||||
name, offset, size, vertices, polygons):
|
||||
raise FormatError('Unexpected Scooter source shape metadata')
|
||||
counts = Counter(str(p['material']['id']) if p['material'] else 'null' for p in shape['polygons'])
|
||||
if counts != ({'0': 176} if id_ == 0 else {'1': 28, 'null': 28}):
|
||||
raise FormatError('Scooter source material assignment changed')
|
||||
scenes[folder] = _shape_scene(shape, entry, materials, textures)
|
||||
shape_meta.append(dict(shapeId=id_, name=name, path=f'{folder}/scene.json', sourceOffset=offset,
|
||||
sourceBytes=size, sourceSha256=digest(database.payload(entry)), indexedVertices=vertices,
|
||||
polygons=polygons, materialPolygons=dict(sorted(counts.items())),
|
||||
storedSphere=dict(center=list(shape['bounds'][:3]), radius=shape['bounds'][3],
|
||||
sourceCenterOffset=offset+8, sourceRadiusOffset=offset+20),
|
||||
bounds=[[min(v[i] for v in shape['vertices']) for i in range(3)],
|
||||
[max(v[i] for v in shape['vertices']) for i in range(3)]]))
|
||||
levels = []
|
||||
for name in ('gam/VR05.gam', 'gam/level1.gam'):
|
||||
level = parse(paths[name].read_bytes())
|
||||
levels.append(dict(source=paths[name].name, sha256=SOURCES[name],
|
||||
entities=[dict(ordinal=i, **asdict(e)) for i, e in enumerate(level.entities)]))
|
||||
# Import the established PE reader only after resource validation; no target execution.
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]/'binary'))
|
||||
from pe_inspect import PE
|
||||
from checkpoint_script_state import read_va
|
||||
pe = PE(paths['Neutron.exe'])
|
||||
spans = [dict(va=hex(start), fileOffset=hex(pe.offset(start-pe.base)), length=end-start,
|
||||
purpose=purpose, sha256=digest(read_va(pe, start, end-start))) for start, end, purpose in BINDINGS]
|
||||
manifest = dict(schema=1, sources=SOURCES.copy(), bodyMesh='body/scene.json', wheelMesh='wheel/scene.json',
|
||||
scootAnimation='jimscooter/animation.json', stopAnimation='jimscooterstop/animation.json',
|
||||
shapes=shape_meta, textures=textures, animations=[], levels=levels,
|
||||
bindings=dict(bodyDatabaseShape=0, wheelDatabaseShape=1, scootAlias='HISCOOT', stopAlias='HISCOOTSTOP',
|
||||
scootAction='SCOOT', stopAction='SCOOTSTOP', bodyUnlit=True, sourceSpans=spans),
|
||||
goddardTransformation=dict(source='godscooter.ASE', alias='HISCOOT', indexedVertices=195, polygons=370,
|
||||
sourceTimes=[0, 161], alternateSource='godscooter2.ASE',
|
||||
status='Source binding/inventory only; no compatible textured195-vertex base supplied; not active vehicle body'),
|
||||
bindingPolicy='Exact resources/source pivots. Runtime owns parent/child transforms, wheel spin/support, mounted root, action timing and lifecycle.')
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
for identity in shapes:
|
||||
folder = f'shape_{identity}'
|
||||
details = export_omt_model(database, identity, output/folder)
|
||||
manifest['shapes'].append(dict(id=identity, path=folder+'/scene.json', **details))
|
||||
(output/'jimycarl.rgba').write_bytes(rgba)
|
||||
for stem in ('jimscooter', 'jimscooterstop'):
|
||||
(output/'jimycarl.rgba').write_bytes(jimmy['rgba'])
|
||||
for id_, rgba in pixels.items():
|
||||
(output/f'canvas_{id_}.rgba').write_bytes(rgba)
|
||||
entry = next(e for e in textures if e['id'] == id_)
|
||||
write_png(output/f'canvas_{id_}.png', entry['width'], entry['height'], rgba)
|
||||
for folder, scene in scenes.items():
|
||||
(output/folder).mkdir(parents=True, exist_ok=True)
|
||||
_json(output/folder/'scene.json', scene)
|
||||
for stem in CLIPS:
|
||||
animation = export_ase(paths[f'ASE/{stem}.ASE'], output/stem, paths['ASE/jimstop.ASE'])
|
||||
animation['texture'] = texture
|
||||
animation['texture'] = dict(path='../jimycarl.rgba', width=256, height=256,
|
||||
source=paths['png/jimycarl.png'].name, sourceSha256=SOURCES['png/jimycarl.png'], rgbaSha256=JIMMY_RGBA_SHA256)
|
||||
_json(output/stem/'animation.json', animation)
|
||||
manifest['animations'].append(dict(source=stem+'.ASE', path=stem+'/animation.json'))
|
||||
for stem in ('godscooter', 'godscooter2'):
|
||||
animation = animations[f'ASE/{stem}.ASE']
|
||||
filename = stem+'-unbound.json'
|
||||
_json(output/filename, animation)
|
||||
manifest['unboundMorphs'].append(dict(source=stem+'.ASE', path=filename,
|
||||
vertices=195, sourceTimes=[s['time'] for s in animation['objects'][0]['samples']],
|
||||
reason='No matching textured base recovered; OMT body 98 and existing Goddard base 222 differ'))
|
||||
manifest['animations'].append(dict(source=paths[f'ASE/{stem}.ASE'].name, path=f'{stem}/animation.json',
|
||||
indexedVertices=426, polygons=814, sourceTimes=[0, 480]))
|
||||
_json(output/'scooter.json', manifest)
|
||||
return manifest
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('original', type=Path)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
if __name__ == '__main__':
|
||||
cli = argparse.ArgumentParser(description=__doc__)
|
||||
cli.add_argument('original', type=Path)
|
||||
cli.add_argument('--output', type=Path, required=True)
|
||||
args = cli.parse_args()
|
||||
export_scooter(args.original, args.output)
|
||||
print(f'Original Scooter resources exported: {args.output}/scooter.json')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in new issue
Block a user