Files
Neutron/tools/binary/checkpoint_camera_ray.py
T

157 lines
7.2 KiB
Python

#!/usr/bin/env python3
"""Read-only C5 ray evidence and bounded grid-order reference (not runtime code)."""
import argparse
from collections import Counter
import hashlib
import json
import math
from pathlib import Path
import struct
import sys
from pe_inspect import PE
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'extractors'))
from omt import Database, read_shape
EXE_HASH = 'f5281076e1a2492f2d61f87aae3f4544b6d0f535ebe33f9fbb6f78710fe1aea8'
CELL_SCALE = struct.unpack('<f', bytes.fromhex('6f12033b'))[0]
CELL_ORIGIN = 130.0
GRID_SIZE = 260
ANCHORS = (
('enabled_gate', 0x47C210, 'a0e5694f005684c0745c'),
('wall_query_return_on_hit', 0x47C23D, 'e83e00000083c42484c07404b0015ec3'),
('all_query_fallback', 0x47C26C, 'e83f020000'),
('wall_cell_list', 0x47C3DF, '8b04ad249b5000'),
('wall_triangle_return_first', 0x47C442, 'e8c9d5feff83c42484c0753d'),
('wall_next_fifo_node', 0x47C44E, '8b368b04ad249b50003bf07591'),
('inclusive_z_then_x_loop', 0x47C463, '43663bda0f8e37ffffff8b5c241041663b4c2414894c24180f8e1affffff'),
('first_hit_identity', 0x47C48B, '8b4704a3585d69008b0f5f5e5d890d545d6900b0015b'),
('all_cell_list', 0x47C60F, '8b04ad7cfc5c00'),
('all_triangle_return_first', 0x47C672, 'e899d3feff83c42484c0753d'),
('fifo_append_tail', 0x4798A2, '8947048b4804890183c00885c0'),
('wall_normal_filter', 0x4798B3, 'd94424148b8680fc5c00d81d74d9480040898680fc5c00dfe0f6c401743d'),
('caller_actor_getter_first', 0x43B83F, 'ff9010030000'),
('caller_actor_getter_second', 0x43B84E, 'ff9210030000'),
('caller_end_and_false_sidedness', 0x43B854, '8b74242c6a0083ec108bcc56e8fbe6fcff'),
('caller_incoming_look_vector', 0x43B865, '83ec108d5424408bcc52e8ece6fcffe897090400'),
('getter_reads_interface_position', 0x472304, '8b91140200008910'),
('jimmy_getter_slot', 0x4A3A4C, '00234700'),
('default_camera_adjustment10', 0x438CC6, 'c7854c08000000002041'),
('mouse_relative_camera_adjustment', 0x438C78, 'd8854c080000d99d4c080000'),
('one_sided_triangle_gate', 0x469C7E, '8a84248000000084c00f8491010000'),
('negative_t_reject', 0x469DDD, '753f'),
('strict_endpoint_reject', 0x469DEE, '752e'),
('nc_shape_skip', 0x44DD64, '83f86374078b178bcfff522c'),
('terrain_register_call', 0x464B18, 'e823460100'),
('checkpoint_filter', 0x4791C7, '5355e8f202000083c40884'),
('game_filter', 0x4791D9, '5355e8c005000083c40884c0740c'),
('polygon_array_step48', 0x479473, '8b838c00000083c5303be889'),
('shape_id_increment', 0x44DEAF, '46'),
('lab_game_polygon_filter_slot', 0x4C3E04, 'd05c4700'),
('vr04_game_polygon_filter_slot', 0x4CEA44, 'd05c4700'),
('outside_game_polygon_filter_slot', 0x4C5BB4, 'd05c4700'),
('route_game_filter_false', 0x475CD0, '32c0c21800'),
)
def cell_coordinate(value):
"""Stored float scale, x87 truncation, then signed16 comparison domain.
Python double arithmetic is a bounded order oracle, not an x87 boundary oracle.
"""
if not math.isfinite(value):
raise ValueError('Finite grid coordinate required')
number = math.trunc(value * CELL_SCALE + CELL_ORIGIN)
return (number + 32768) % 65536 - 32768
def cells_between(a, b):
"""Inclusive endpoint XZ rectangle, increasing X then increasing Z."""
xmin, xmax = sorted((cell_coordinate(a[0]), cell_coordinate(b[0])))
zmin, zmax = sorted((cell_coordinate(a[2]), cell_coordinate(b[2])))
# Skipping out-of-grid indices is equivalent to the source's loop rejection.
for x in range(max(0, xmin), min(GRID_SIZE - 1, xmax) + 1):
for z in range(max(0, zmin), min(GRID_SIZE - 1, zmax) + 1):
yield x, z
def first_hit(start, end, walls, all_polygons, accept, enabled=True, two_sided=False):
"""Order contract only; accept owns the separately recovered triangle kernel.
Grid values are FIFO polygon identities. Repeated polygons in multiple cells
are intentionally not deduplicated. Return first hit, not nearest distance.
"""
if not enabled:
return None
cells = tuple(cells_between(start, end))
for grid in (walls, all_polygons):
for cell in cells:
for polygon in grid.get(cell, ()):
hit = accept(polygon, start, end, two_sided)
if hit is not None:
return polygon, hit
return None
def route_geometry(original):
result = {}
checkpoint_names = {'cstart', *(f'ccheck{i}' for i in range(1, 10))}
for name in ('level1b.omt', 'VR04.omt', 'level1.omt'):
path = Path(original) / 'omt' / name
database = Database(path)
materials = {e.id: e.name for e in database.entries if e.type == '3DMa'}
corners = Counter()
ids, walls, checkpoint, excluded = [], 0, 0, 0
for entry in database.entries:
if entry.type != '3DSh':
continue
shape = read_shape(database.payload(entry))
if (entry.name or '').lower().startswith('nc'):
excluded += len(shape['polygons'])
continue
ids.append(entry.id)
for polygon in shape['polygons']:
material = polygon['material']
if material and materials.get(material['id']) in checkpoint_names:
checkpoint += 1
continue
corners[len(polygon['corners'])] += 1
walls += polygon['normal'][1] < struct.unpack('<f', bytes.fromhex('3333333f'))[0]
result[name] = {'sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
'registered_polygon_corner_counts': dict(corners),
'wall_grid_polygons': walls, 'nc_polygons_excluded': excluded,
'checkpoint_polygons_excluded': checkpoint,
'shape_ids_ascending': ids == sorted(ids)}
return result
def recover(original):
pe = PE(Path(original) / 'Neutron.exe')
if hashlib.sha256(pe.data).hexdigest() != EXE_HASH:
raise ValueError('Unrecognized executable hash')
anchors = []
for name, va, expected in ANCHORS:
offset = pe.offset(va - pe.base)
actual = pe.data[offset:offset + len(expected) // 2].hex()
if actual != expected:
raise ValueError(f'Instruction mismatch: {name} at {va:#x}')
anchors.append({'name': name, 'va': hex(va), 'file_offset': hex(offset), 'bytes': actual})
constants = []
for name, va, fmt in (('cell_scale', 0x4D6A04, 'f'), ('cell_origin', 0x49B1FC, 'f'),
('wall_normal_threshold', 0x48D974, 'f'),
('enabled_default', 0x4F69E5, 'B')):
offset = pe.offset(va - pe.base)
constants.append({'name': name, 'va': hex(va), 'file_offset': hex(offset),
'value': struct.unpack_from('<' + fmt, pe.data, offset)[0]})
return {'exe_sha256': EXE_HASH, 'anchors': anchors, 'constants': constants,
'route_geometry': route_geometry(original),
'limits': 'Static source/order evidence; no original execution, x87 boundary or GPU comparison'}
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('original', type=Path)
args = parser.parse_args()
print(json.dumps(recover(args.original), indent=2))