Implement Bubble controller, sprite and VR01 body behavior

This commit is contained in:
UnixNight committed 2026-11-02 16:57:54 -05:00
1 parent 9ea578492d
commit 1ae5f4251c
51 files changed
+2811 -54

No files matched your search

+224
View File
@@ -0,0 +1,224 @@
#!/usr/bin/env python3
"""Read-only Bubble body/VR01 coverage and bounded floor-policy projections.
Static evidence and source projections are distinct from the generated copied-code
probe. No original file is changed or executed in place.
"""
from __future__ import annotations
import argparse
from collections import Counter
from dataclasses import dataclass, replace
import hashlib
import json
import math
from pathlib import Path
import struct
import sys
from bubble import f32
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'extractors'))
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'levels'))
from omt import Database, read_material, read_shape
from gam import parse
BODIES = (
('vr01_ctor', 0x455ef0, 0x455fd8, '93c98d72b0c8f0da102068beff19f9b8ebb0da58fa6a4d524ae09415f814f088'),
('floor_game', 0x44e030, 0x44e444, '6ae67944afc53bd050279c1e2356c614e8cd534c7a94ef9628bf0bbfd028fe91'),
('base_floor', 0x462520, 0x462647, 'ba8f47f8b62db304821b751872db003d37605031c57423542f8040c9ef9d7e68'),
('lava_enter', 0x42ab00, 0x42ab2a, '06010f1d0ca453459062f8cb0f96caf3fd2c605cee88547315ddee43b051430a'),
('lava_damage', 0x42a8d0, 0x42a918, '88a303b3ae7cca7fc4c3935848077bbaf5393f83ed184b8e042e67803c3c4863'),
('lava_flash', 0x4257d6, 0x425864, '7f239b21895a710aa766c8d4b8213c70d931e785399c01f8ea1fbec66e19f65d'),
('polygon_setter', 0x472580, 0x47258d, 'e7fe0271b3f9cffbde6e23f64ff533a86042f4c063a804430921b7fe1e9e036b'),
('shape_setter', 0x4725c0, 0x4725cd, '4f7a906d71c1d56117bba8c9ccd2d757c1ed9ee09e40e2a3930388b650b4427d'),
)
SITES = (
('player_base_before_owner', 0x43796a, 'e8e166fdff'),
('animated_base_floor', 0x40e0eb, 'e830440500'),
('base_integrates', 0x46253d, 'ff9010020000'),
('base_polygon', 0x46254f, 'ff9238030000'),
('base_game130', 0x46258f, 'ff9530010000'),
('lava_low', 0x44e170, '83fd6e7c32'),
('lava_high', 0x44e175, '83fd777f2d'),
('lava_entry_callback', 0x44e18e, 'ff9098010000'),
('lava_latch_on', 0x44e194, 'c686021e000001'),
('lava_damage_callback', 0x44e19f, 'ff9264010000'),
('lava_leave_callback', 0x44e1bb, 'ff909c010000'),
('lava_latch_off', 0x44e1c1, '889e021e0000'),
('lava_sound35', 0x44e32c, 'c7824c05000023000000'),
('ordinary_sound5', 0x44e407, 'c7824c05000005000000'),
('floor_sound_changed', 0x44e426, 'ff92e4010000'),
('wrapper_flash_late', 0x424c88, 'ff92b4010000'),
('flash_duration4', 0x49d5e8, '00008040'),
('support_polygon_publish', 0x47bba1, 'ff923c030000'),
('support_shape_publish', 0x47bb91, 'ff904c030000'),
('landing_noop', 0x472970, 'c3'),
('grounded_radius160', 0x4246b4, '6800002043'),
('grounded_radius60', 0x4246dc, '6800007042'),
('factor_authored_live', 0x4711e0, '8b4424048b115089412cff9254020000'),
('game_filter_false', 0x475cd0, '32c0c21800'),
('nc_shape_skip', 0x44dd64, '83f86374078b178bcfff522c'),
('checkpoint_filter', 0x4791c7, '5355e8f202000083c40884'),
('game_filter', 0x4791d9, '5355e8c005000083c40884c0740c'),
)
TABLES = (
(0x4cd740, 0x134, 0x475cd0), (0x4cd740, 0x130, 0x44e030),
(0x4a373c, 0x338, 0x472570), (0x4a373c, 0x33c, 0x472580),
(0x4a373c, 0x34c, 0x4725c0), (0x4a373c, 0x37c, 0x472970),
(0x4a3bdc, 0x198, 0x42ab00), (0x4a3bdc, 0x19c, 0x472970),
(0x4a3bdc, 0x164, 0x42a8d0), (0x4a3bdc, 0x1e4, 0x42aec0),
)
def geometry(root, name):
db = Database(find_case(root, 'omt/' + name))
materials = {e.id: e.name for e in db.entries if e.type == '3DMa'}
textures = {e.id: read_material(db.payload(e))['texture'] for e in db.entries if e.type == '3DMa'}
shapes, records = [], []
for entry in sorted((e for e in db.entries if e.type == '3DSh'), key=lambda e: e.id):
shape = read_shape(db.payload(entry))
shapes.append(dict(id=entry.id, name=entry.name, payload_offset=entry.offset,
payload_sha256=hashlib.sha256(db.payload(entry)).hexdigest(),
vertices=len(shape['vertices']), polygons=len(shape['polygons'])))
for index, polygon in enumerate(shape['polygons']):
link = polygon['material']
identity = link['id'] if link and link['type'] == '3DMa' else None
material = materials.get(identity)
registered = not (entry.name or '').lower().startswith('nc') and not (
material and material.lower() in {'cstart', *(f'ccheck{i}' for i in range(1, 10))})
ny = polygon['normal'][1]
records.append(dict(shape=entry.id, polygon=index, corners=len(polygon['corners']),
material=identity, material_name=material, texture=textures.get(identity),
normal=polygon['normal'],
registered=registered, wall=registered and ny < f32(.7),
callback374=registered and f32(-.7) < ny < f32(.7)))
return dict(name=name, sha256=hashlib.sha256(db.data).hexdigest(), shapes=shapes,
polygon_count=len(records), registered=sum(p['registered'] for p in records),
walls=sum(p['wall'] for p in records), polygons=records)
def collect(root):
root = Path(root)
pe = PE(find_case(root, 'Neutron.exe'))
if hashlib.sha256(pe.data).hexdigest() != EXE_SHA256:
raise ValueError('Unsupported original executable')
bodies, sites, tables = [], [], []
for name, start, end, expected in BODIES:
if hashlib.sha256(read_va(pe, start, end-start)).hexdigest() != expected:
raise ValueError('Changed source body ' + name)
bodies.append(dict(name=name, va=hex(start), file_offset=hex(pe.offset(start-pe.base)),
length=end-start, sha256=expected))
for name, va, expected in SITES:
actual = read_va(pe, va, len(bytes.fromhex(expected))).hex()
if actual != expected:
raise ValueError(f'Changed {name} at {va:x}: {actual}')
sites.append(dict(name=name, va=hex(va), file_offset=hex(pe.offset(va-pe.base)), bytes=actual))
for table, slot, target in TABLES:
if struct.unpack('<I', read_va(pe, table+slot, 4))[0] != target:
raise ValueError('Changed virtual binding')
tables.append(dict(table=hex(table), slot=hex(slot), target=hex(target),
file_offset=hex(pe.offset(table+slot-pe.base))))
dll = PE(find_case(root, 'OMT2.dll'))
dll_hash = '3ec41ead011adf56387a6dbd4580e5b5a9721b5f8020c8a56420f42824354943'
if hashlib.sha256(dll.data).hexdigest() != dll_hash:
raise ValueError('Unsupported OMT DLL')
texture_set = '8b44240485c0898180000000'
if read_va(dll, 0x100013b5, len(bytes.fromhex(texture_set))).hex() != texture_set:
raise ValueError('Changed OMT material texture publication')
gam = find_case(root, 'gam/VR01.gam').read_bytes()
return dict(sha256=EXE_SHA256, bodies=bodies, sites=sites, tables=tables,
archives=[geometry(root, name) for name in ('VR01.omt', 'VR04.omt')],
vr01_gam_sha256=hashlib.sha256(gam).hexdigest(),
vr01_entities=dict(Counter(e.kind for e in parse(gam).entities)),
material_texture=dict(dll_sha256=dll_hash, exported_set_texture=hex(0x100013a0),
write_va=hex(0x100013b5), file_offset=hex(dll.offset(0x100013b5-dll.base)), bytes=texture_set),
scope='Static guarded source and bounded projections; isolated original probe is separate.')
@dataclass(frozen=True)
class LavaState:
entered: bool = False
flashing: bool = False
timer: float = 0
sound_selector: int = 5
def floor_phase(state, material, raw_mode, *, eligible=True, integration=True,
polygon_present=True, material_present=True, texture_present=True):
"""462520→44E030 restricted to actualVR01 IDs; excludes other damage flags.
This phase consumes retained338 even if current218=false. Caller preserves
that polygon until next successful support. Energy/score helpers own clamps
and tutorial exemption. Audio requests are distinct from playback evidence.
"""
if material not in (None, 0, 1, 2, 3, 4, 111):
raise ValueError('Outside VR01 floor-policy projection')
if not (eligible and integration and polygon_present and material_present and texture_present):
return state, ()
actions = []
lava = material == 111
if lava:
if not state.entered:
actions += ['sound39']
if raw_mode != 0:
actions += ['sound190']
state = replace(state, entered=True)
if not state.flashing and raw_mode != 0:
state = replace(state, flashing=True, timer=0)
actions += ['energy_minus5_common_helper', 'score_minus5_common_helper', 'cancel_mode1']
elif state.entered:
state = replace(state, entered=False)
selector = 35 if lava else 5
if selector != state.sound_selector:
actions += [f'retarget_existing_floor_loop_{selector}']
return replace(state, sound_selector=selector), tuple(actions)
def lava_flash(state, seconds):
"""4257D6 finite projection, assuming1DED/1E03 false; no x87/fsin parity."""
if not math.isfinite(seconds) or not 0 <= seconds < 1:
raise ValueError('Bounded finite timestep required')
if not state.flashing:
return state, None
#4257E8 compares the unrounded x87 sum before4257EE storesfloat; FSIN
#also consumes that retained sum. Python double models this bounded sum.
total = f32(state.timer) + f32(seconds)
timer = f32(total)
if total > 4:
return replace(state, flashing=False, timer=timer), (1., 1., 1., 1.)
pulse = f32((math.sin(total * 20) + 1) * .5)
return replace(state, timer=timer), (pulse, 1., pulse, 1.)
def generate_probe(output):
"""Reuse the isolated body's synthetic virtuals; no game actor/input/audio."""
source = Path(__file__).with_name('body_step_probe.c').read_text()
marker = ' puts("BODY_COMPONENT_COMPLETE:'
if source.count(marker) != 1:
raise ValueError('Unexpected body fixture source')
extra = ''' b=initial();b.radius=160;b.factor=.415f;b.position.y=66.4f;b.previous=b.position;run("bubble_floor",b,1);
b=initial();b.radius=160;b.factor=.415f;b.position.y=26;b.previous=b.position;run("bubble_spawn",b,1);
b=initial();b.radius=160;b.factor=.415f;run("bubble_equip_no_forced_lowering",b,1);
b=initial();b.position.y=66.4f;b.previous=b.position;run("bubble_cleanup_raise",b,1);
b=initial();b.radius=160;b.factor=.415f;b.position.y=66.4f;b.previous=b.position;b.supported=1;b.velocity.y=300;run("bubble_small_bounce",b,1);
b=initial();b.radius=160;b.factor=.415f;b.position.y=66.4f;b.previous=b.position;b.supported=1;b.velocity.y=900;run("bubble_held_bounce",b,1);
'''
output = Path(output).resolve()
project = Path(__file__).resolve().parents[2]
if output.is_relative_to(project.parent / 'Original'):
raise ValueError('Generated source must be outside originals')
output.write_text(source.replace(marker, extra + marker))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original', type=Path)
parser.add_argument('--probe-source', type=Path)
args = parser.parse_args()
report = collect(args.original)
if args.probe_source:
generate_probe(args.probe_source)
print(json.dumps(report, indent=2))
+229
View File
@@ -0,0 +1,229 @@
#!/usr/bin/env python3
"""Read-only Bubble movement source guards and bounded arithmetic projections.
Static source projections do not execute original gameplay or emulate x87/trig
table precision. REA Evidence/provider limitations are in bubble-motion.md.
"""
from __future__ import annotations
import argparse
from dataclasses import dataclass
import hashlib
import json
import math
from pathlib import Path
import struct
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
BODIES = (
('frame', 0x437940, 0x437c3a, '9579bfb1c4d9ae6abf2a1c78d6f99544871a63216fb80b9a906e3a76ebe27983'),
('apply', 0x4387e0, 0x438a58, 'c4de9afecf895c0ae30d5e939716e66abe33e7306506ddf0da981ede5061371c'),
('input', 0x439900, 0x43a111, '895f27be2ad03f49230fe34e98753095285a61f52b4adbbb15f1dd7c868b2901'),
('dispatch', 0x438a60, 0x438bb4, '99717e7fbac658abcb4b825047d2c35714b8b9e1361534374a109e8556641fc9'),
('jump_predicate', 0x4378d0, 0x43793a, 'f723e460743e29309cdb0efdb8b25df2513490bd84e9d175e6493f963614ab01'),
('landing_hook', 0x42a720, 0x42a72b, '157917f7713b11d5959c99602ce485abe99a268e396dc380d329bc52acd7e93a'),
('empty_hook', 0x472970, 0x472971, 'ae3f4619b0413d70d3004b9131c3752153074e45725be13b9a148978895e359e'),
('fire_predicate', 0x42a7a0, 0x42a7d6, 'c8fa10f42eefe68a195d9980f1a57558a240cd7877bfeab567e7868c0ddf419f'),
('support_pose', 0x42469b, 0x4246e9, '40e025e4bdc8bcdbcb24651e3d81908a5b7a9e2cc8de81d733da7490ea76c1d4'),
('wrapper_input', 0x426030, 0x4263f0, '365773538a65d99bd9e5d04c790eee7758ee528bdc385dba309f49d49ea9e5bb'),
('vector_transform', 0x472b10, 0x472c10, 'ee9516aef07738fcf7da370af74185f7522686759218ad1bf4d93be46f0c28b2'),
)
VTABLES = (
(0x4a3bdc, 0x128, 0x439900), (0x4a3bdc, 0x13c, 0x4387e0),
(0x4a3bdc, 0x154, 0x42a720), (0x4a3bdc, 0x158, 0x4378d0),
(0x4a3bdc, 0x15c, 0x42a7a0), (0x4a373c, 0x2bc, 0x471f10),
(0x4a373c, 0x2c4, 0x471f40), (0x4a373c, 0x38c, 0x472b10),
)
CONSTANTS = ((0x48d948, 'f', .5), (0x48d96c, 'f', 100.),
(0x4a3e78, 'f', -50.), (0x48d400, 'f', 50.),
(0x49d5b8, 'f', 0.0181818176060915),
(0x4afd2c, 'f', -.25), (0x49d5dc, 'f', 0.9090909361839294),
(0x494cb8, 'd', 1.8), (0x4a6850, 'd', .8),
(0x4a2ad0, 'd', .2), (0x48e598, 'd', 1.5))
SITES = (
('mode2_apply_dispatch', 0x437a5d, 33), ('publish_speed', 0x437c22, 17),
('nonzero_velocity_gate', 0x43884e, 17), ('yaw_add', 0x43885f, 34),
('velocity_store', 0x438950, 44), ('support_gate', 0x43899a, 18),
('held_jump_bounce900', 0x4389d8, 45), ('released_bounce300', 0x438a0c, 68),
('fire_forward_mode2', 0x439abb, 43), ('support_input_decay', 0x439ba2, 75),
('turn50', 0x439cb2, 73), ('mode2_lean', 0x439cfb, 55),
('mode2_camera', 0x439f4d, 239), ('base_input_first', 0x426081, 8),
('gadget_input_consumes', 0x426095, 17), ('drain_after_input', 0x426264, 65),
('supported_stop', 0x4246a9, 51),
)
HANDOFF_BODIES = (
('cleanupA20', 0x428037, 0x4280cc, 'b8891ee4fb67c566785ed329194717c3e30a895bd15bda91eedd81d76d026a55'),
('normal_destinations', 0x43951e, 0x4395cf, 'b3c30081c2f5dad2b51b240d1b91eb345700bcf9f3ff356793724890340a40ce'),
('normal_direction_flags', 0x438f66, 0x4393fb, '5e8af054cbf28fb5f676f6f05a0efea4c8e2ebc1ae69cce09abbca57f60a68e2'),
('rotation', 0x43a420, 0x43a5cf, 'e052ee855e625d03a3317dcc7d507081c7519576381afa5741572157e5ffb988'),
('constructorA20', 0x4226c9, 0x4226d5, '41cfd341bf4e4602eb69c04e4837e05de62746a3117335b651e4ab29ddac9c8d'),
('normal_air_pose', 0x439d81, 0x439e33, '38d71efb31ca7ee03e248658bf469e0141a1cbf47f177b63d10cea9c7b5469da'),
)
def collect_handoff(pe: PE):
"""Bounded direct-displacement search; does not rule out derived aliases."""
bodies = []
for name, start, end, expected in HANDOFF_BODIES:
actual = hashlib.sha256(read_va(pe, start, end-start)).hexdigest()
if actual != expected:
raise ValueError(f'Changed handoff span {name}')
bodies.append(dict(name=name, va=hex(start), file_offset=hex(pe.offset(start-pe.base)),
length=end-start, sha256=actual))
text = next(s for s in pe.sections if s['name'] == '.text')
start, size = text['file_offset'], text['raw_size']
raw = pe.data[start:start+size]
matches = []
offset = 0
while (offset := raw.find(struct.pack('<I', 0xa20), offset)) >= 0:
matches.append(pe.va(start+offset))
offset += 1
expected = [0x4226d1,0x428047,0x42821c,0x45cfe3,0x45d024,0x45d035]
if matches != expected:
raise ValueError('Changed A20 literal/displacement search boundary')
# First3 are MOV disp32 writes; remaining3 are unrelated PUSH immediates.
for va, prefix in [(0x4226cf,b'\x89\x9d'), (0x428045,b'\xc7\x86'), (0x42821a,b'\xc7\x86')]:
if read_va(pe, va, 2) != prefix:
raise ValueError('Changed direct A20 write')
return dict(bodies=bodies, text_va=hex(pe.base+text['rva']), text_size=size,
a20_raw_dword_occurrences=[hex(a) for a in matches],
a20_direct_writes=['0x4226cf','0x428045','0x42821a'],
a20_consumer=None, derived_aliases_excluded=False,
cleanup_resets_euler=False, ground_no_input_resets_euler=False,
accepted_ground_destination_pitch=0, accepted_ground_destination_roll=0,
ordinary_air_destination_pitch=0, ordinary_air_roll_multiplier=-1)
def collect(original: Path | str):
pe = PE(find_case(Path(original), 'Neutron.exe'))
digest = hashlib.sha256(pe.data).hexdigest()
if digest != EXE_SHA256:
raise ValueError('Unexpected original EXE identity')
bodies = []
for name, start, end, expected in BODIES:
actual = hashlib.sha256(read_va(pe, start, end-start)).hexdigest()
if actual != expected:
raise ValueError(f'Changed source span {name}')
bodies.append(dict(name=name, va=hex(start), file_offset=hex(pe.offset(start-pe.base)),
length=end-start, sha256=actual))
for base, slot, expected in VTABLES:
if struct.unpack('<I', read_va(pe, base+slot, 4))[0] != expected:
raise ValueError(f'Changed virtual {base:x}+{slot:x}')
for va, kind, expected in CONSTANTS:
if struct.unpack('<'+kind, read_va(pe, va, struct.calcsize(kind)))[0] != expected:
raise ValueError(f'Changed constant {va:x}')
return dict(sha256=digest, bodies=bodies,
sites=[dict(name=n, va=hex(v), file_offset=hex(pe.offset(v-pe.base)),
bytes=read_va(pe, v, z).hex()) for n,v,z in SITES],
vtables=[dict(table=hex(b), slot=hex(s), target=hex(t)) for b,s,t in VTABLES],
constants=[dict(va=hex(a), value=v) for a,k,v in CONSTANTS],
movement_mode=2, max_speed=1350, bounce_released=300, bounce_held=900,
bounce_sound=106, landing_mode_reset=False, handoff=collect_handoff(pe))
def finite(*values):
if not all(math.isfinite(v) for v in values):
raise ValueError('Finite bounded inputs required')
@dataclass(frozen=True)
class InputResult:
speed: float
turn: float
target_pitch: float
target_roll: float
def keyboard_step(speed: float, turn: float, seconds: float, *, forward=False,
backward=False, left=False, right=False, fire=False, supported=False,
maximum=1350.) -> InputResult:
"""439900 keyboard subset; effective fire predicate supplied by caller.
Includes supported slowdown before Down and separate later apply slowdown.
Mouse/analog and camera are documented but deliberately not approximated here.
"""
finite(speed, turn, seconds, maximum)
if not 0 <= seconds < 1 or maximum <= 0:
raise ValueError('Bounded timestep and positive maximum required')
amount = 100*seconds
if left:
turn += amount
elif right:
turn -= amount
elif turn < 0:
turn = min(0, turn+amount)
elif turn > 0:
turn = max(0, turn-amount)
throttle = forward or fire
if throttle and speed < maximum:
speed = min(maximum, speed+30)
if not throttle and speed > maximum*0.9090909361839294:
speed -= 17.5
if supported:
speed = speed-17.5 if speed > 0 else 0.
if backward:
if speed > 0:
speed = max(0., speed-(35. if supported else 17.5))
elif speed < 0:
speed = min(0., speed+35.)
turn = max(-50., min(50., turn))
return InputResult(speed, turn, -10. if throttle else 10. if backward else 0., -.25*turn)
@dataclass(frozen=True)
class ApplyResult:
velocity: tuple[float, float, float]
yaw: float
published_speed: float
sound: int | None
movement_mode: int = 2
def apply_step(speed: float, turn: float, yaw: float, pitch: float,
velocity: tuple[float, float, float], seconds: float, *,
supported=False, jump=False, friction=.8) -> ApplyResult:
"""4387E0 algebra with host trig; original table quantization is not emulated.
XZ is composed using pre-bounce speed, while the published scalar can halve.
Original acceleration and impulse are untouched by this routine.
"""
finite(speed, turn, yaw, pitch, seconds, friction, *velocity)
if not 0 <= seconds < 1:
raise ValueError('Bounded timestep required')
side = 0.
if any(v != 0 for v in velocity):
yaw += turn*seconds
side = turn*(1-friction)*speed*0.0181818176060915
sine, cosine = math.sin(math.radians(yaw)), math.cos(math.radians(yaw))
forward = speed*math.cos(math.radians(pitch))
vx, vy, vz = -sine*forward+cosine*side, velocity[1], cosine*forward+sine*side
sound = None
if supported:
if jump:
vy, sound = 900., 106
else:
speed *= .5
vy = 300.
return ApplyResult((vx,vy,vz), yaw, speed, sound)
def ordinary_destination(previous: tuple[float,float,float], yaw: float, turn: float,
*, airborne=False, accepted_ground_direction=False):
"""Bounded destination handoff, not rotation/interpolation scheduling.
Ordinary ground no-input preserves the prior Bubble target. Accepted ground
steering replaces pitch/roll with0; normal airborne input supplies roll-turn.
"""
finite(*previous, yaw, turn)
if airborne:
return (0., yaw, -turn)
if accepted_ground_direction:
return (0., yaw, 0.)
return previous
if __name__ == '__main__':
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument('original', type=Path)
print(json.dumps(collect(cli.parse_args().original), indent=2))
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Export the original C3DBubble Canv1 unchanged into a generated directory.
Archive/id binding is recovered in docs/gameplay/bubble.md. This utility reads
assets only; it neither executes original code nor bakes pulse, tint or scaling.
"""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
from entities import resolve_asset
from omt import Database, FormatError, read_canvas, write_png
ARCHIVE_SHA256 = 'b584ffa4a38f4bc809b3ea8f4321e0c08f2719e22df41a3fb4cd143ed89b3bef'
PAYLOAD_SHA256 = '9b6cdce95bd408fa1dc806d30520df65971f25d1663ab8da4ca6bf41380805ec'
RGBA_SHA256 = 'a3a678c47c1ce94946b1136560a84f3ef86c6884b981256a9fbff62fe8a988e4'
def digest(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def export_bubble(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')
# Guard output aliases before any write, including existing child symlinks.
files = {name: output/name for name in ('canvas_1.rgba', 'canvas_1.png', 'bubble.json')}
if any(path.resolve() != path for path in files.values()):
raise ValueError('Generated Bubble files must not be symlinks')
database = Database(resolve_asset(original, 'omt/RetainedSprites.omt'))
if digest(database.data) != ARCHIVE_SHA256:
raise FormatError('Unexpected original Bubble archive identity')
matches = [e for e in database.entries if e.type == 'Canv' and e.id == 1]
if len(matches) != 1:
raise FormatError('Expected one original Bubble Canv1')
entry = matches[0]
if (entry.name, entry.offset, entry.size) != ('orangebubble', 0x17FCE, 66322):
raise FormatError('Unexpected original Bubble canvas metadata')
payload = database.payload(entry)
if digest(payload) != PAYLOAD_SHA256:
raise FormatError('Unexpected original Bubble payload identity')
canvas = read_canvas(payload)
rgba = canvas['rgba']
if (canvas['width'], canvas['height'], len(rgba)) != (146, 146, 146*146*4):
raise FormatError('Unexpected original Bubble canvas dimensions')
if digest(rgba) != RGBA_SHA256:
raise FormatError('Unexpected original Bubble decoded pixels')
manifest = dict(schema=1, source=database.path.name, sourceSha256=ARCHIVE_SHA256,
textures=[dict(id=1, name=entry.name, width=146, height=146,
path='canvas_1.rgba', png='canvas_1.png', sourceOffset=entry.offset,
sourceBytes=entry.size, sourceSha256=PAYLOAD_SHA256, rgbaSha256=RGBA_SHA256)])
output.mkdir(parents=True, exist_ok=True)
files['canvas_1.rgba'].write_bytes(rgba)
write_png(files['canvas_1.png'], 146, 146, rgba)
files['bubble.json'].write_text(json.dumps(manifest, indent=2)+'\n', encoding='utf-8')
return manifest
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original', type=Path)
parser.add_argument('--output', type=Path, required=True, help='Generated texture directory')
args = parser.parse_args()
export_bubble(args.original, args.output)
print(f'Original Bubble Canv1 exported: {args.output}/bubble.json')
if __name__ == '__main__':
main()
+2
View File
@@ -12,6 +12,7 @@ from models import prepare_models
from ui import export_ui
from gadget_resources import export_gadget_resources
from gadget_followup_assets import export_meter
from bubble_resources import export_bubble
from sound_bank import export_sound_bank
@@ -82,6 +83,7 @@ def main():
export_ui(Database(find_archive(args.original, 'screens')), args.output / 'ui', Database(args.original / 'alpha.omt'))
export_gadget_resources(Database(find_archive(args.original, 'screens')), args.output / 'gadgets')
export_meter(args.original, args.output / 'invisible-meter')
export_bubble(args.original,args.output/'bubble')
effects = export_sound_bank(args.original, args.output / 'effects')
print(f"SoundEffects.omt: {len(effects['resources'])} original sound identities")
for name in args.audio: