Files
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

205 lines
8.8 KiB
Python

"""Native 70334 ModelBlob rows for generated MD20/MD21 collision models.
ModelBlob.cpp loads FDID 764428 and hashes MBBB's 28-byte rows by FileDataID.
Each row is uint32 FDID followed by the collision-vertex min/max XYZ. Native
rows remain authoritative; conflicting identities or existing bounds fail.
This module builds decoded bytes only and does not register or install assets.
"""
import math
import struct
from m2_format_compare import _extent
_ROW = struct.Struct('<I6f')
_MAX_BYTES = 67108864
_MAX_ROWS = 1048576
def _fdid(value):
# Zero and UINT32_MAX are the native hash's empty/deleted key sentinels.
if type(value) is not int or not 0 < value < 0xffffffff:
raise ValueError('ModelBlob FileDataID outside native key range')
return value
def _native_body(raw):
if type(raw) is not bytes or not 304 <= len(raw) <= _MAX_BYTES:
raise ValueError('Bounded native M2 bytes required')
body = raw
if raw[:4] == b'MD21':
size = struct.unpack_from('<I', raw, 4)[0]
if not 304 <= size <= len(raw) - 8:
raise ValueError('MD21 body extent')
body = raw[8:8 + size]
if body[:4] != b'MD20' or struct.unpack_from('<I', body, 4)[0] not in (272, 274):
raise ValueError('Native MD20 version required')
return body
def collision_vertex_aabb(raw):
"""Return six collision-vertex extrema, or None when index count is zero.
The MD20 header box is deliberately not used: generated models can carry
reversed corners while their actual collision vertices remain valid.
Array offsets are relative to the MD20 body, including inside MD21.
"""
body = _native_body(raw)
index_count, index_offset = struct.unpack_from('<II', body, 0xd8)
vertex_count, vertex_offset = struct.unpack_from('<II', body, 0xe0)
normal_count, normal_offset = struct.unpack_from('<II', body, 0xe8)
indices = _extent(body, index_offset, index_count, 2, 304)
vertices = _extent(body, vertex_offset, vertex_count, 12, 304)
_extent(body, normal_offset, normal_count, 12, 304)
if index_count % 3:
raise ValueError('Collision indices must form triangles')
if not index_count:
return None
if not vertex_count:
raise ValueError('Collision indices without vertices')
if any(index >= vertex_count for (index,) in struct.iter_unpack('<H', indices)):
raise ValueError('Collision index outside vertex array')
lower = [math.inf] * 3
upper = [-math.inf] * 3
for vertex in struct.iter_unpack('<3f', vertices):
if not all(math.isfinite(value) for value in vertex):
raise ValueError('Nonfinite collision vertex')
for axis, value in enumerate(vertex):
lower[axis] = min(lower[axis], value)
upper[axis] = max(upper[axis], value)
return tuple(lower + upper)
def normalize_reversed_collision_bounds(raw):
"""Opt in to correcting an exact geometry-reversed header corner pair.
Ordered native boxes remain untouched, even when they differ from their
vertex AABB. Empty collision sentinels remain untouched. A reversed pair
must equal the actual vertex maxima/minima in the opposite order; an
unrelated or partially reversed box is refused. Only its 24 bytes change.
"""
body = _native_body(raw)
base = 8 if raw[:4] == b'MD21' else 0
lower = struct.unpack_from('<3f', body, 0xbc)
upper = struct.unpack_from('<3f', body, 0xc8)
audit = dict(kind='geometry-derived-reversed-collision-corners-v1',
changed=False, body_offset=base, bounds_offset=base + 0xbc,
old_bounds_hex=body[0xbc:0xd4].hex(),
all_non_collision_bounds_bytes_preserved=True,
collision_geometry_unchanged=True, native_acceptance=False)
if not all(math.isfinite(value) for value in lower + upper):
raise ValueError('Nonfinite collision bounds')
index_count = struct.unpack_from('<I', body, 0xd8)[0]
vertex_count = struct.unpack_from('<I', body, 0xe0)[0]
if all(a <= b for a, b in zip(lower, upper)) or not index_count or not vertex_count:
return raw, audit
actual = collision_vertex_aabb(raw)
if (struct.pack('<3f', *actual[:3]) != body[0xc8:0xd4] or
struct.pack('<3f', *actual[3:]) != body[0xbc:0xc8]):
raise ValueError('Reversed collision bounds not exact vertex extrema')
output = bytearray(raw)
output[base + 0xbc:base + 0xd4] = struct.pack('<6f', *actual)
audit.update(changed=True, collision_vertices=vertex_count,
geometry_min=list(actual[:3]), geometry_max=list(actual[3:]),
new_bounds_hex=bytes(output[base + 0xbc:base + 0xd4]).hex())
return bytes(output), audit
def _blob_rows(raw):
if type(raw) is not bytes or not 20 <= len(raw) <= _MAX_BYTES:
raise ValueError('Bounded native ModelBlob bytes required')
at = 0
version = None
table = None
while at < len(raw):
if at + 8 > len(raw):
raise ValueError('Short ModelBlob chunk header')
tag, size = struct.unpack_from('<4sI', raw, at)
end = at + 8 + size
if end > len(raw):
raise ValueError('ModelBlob chunk overruns file')
if tag == b'RVBM':
if version is not None or size != 4:
raise ValueError('One four-byte MBVR required')
version = struct.unpack_from('<I', raw, at + 8)[0]
elif tag == b'BBBM':
if table is not None or size % _ROW.size or size // _ROW.size > _MAX_ROWS:
raise ValueError('One bounded 28-byte MBBB table required')
table = (at, end)
at = end
if version != 0 or table is None:
raise ValueError('Pinned native MBVR0/MBBB required')
start, end = table
rows = {}
previous = 0
for offset in range(start + 8, end, _ROW.size):
ident, *bounds = _ROW.unpack_from(raw, offset)
_fdid(ident)
if ident <= previous:
raise ValueError('ModelBlob rows must have sorted unique IDs')
if (not all(math.isfinite(value) for value in bounds) or
any(bounds[axis] > bounds[axis + 3] for axis in range(3))):
raise ValueError('ModelBlob bounds must be finite and ordered')
rows[ident] = raw[offset:offset + _ROW.size]
previous = ident
return rows, table
def extend_model_blob(raw, models):
"""Preserve native chunks/rows and add collision rows for generated models.
On every build, pass the pinned original native ModelBlob and all current
converted model payloads. Do not use an enriched previous build as the
baseline when models change: existing rows are intentionally authoritative.
``models`` is a mapping or iterable of ``(FileDataID, bytes)`` pairs. Repeated
IDs must carry byte-identical payloads, even when two payloads would produce
equal boxes. Existing rows must equal their geometry-derived candidate;
they are never replaced. A second pass with the same inputs is unchanged.
"""
rows, (start, end) = _blob_rows(raw)
original_count = len(rows)
seen = {}
added = []
omitted = []
duplicates = 0
present = 0
pairs = models.items() if hasattr(models, 'items') else models
for ident, payload in pairs:
_fdid(ident)
if type(payload) is not bytes:
raise ValueError('M2 payload must be immutable bytes')
if ident in seen:
if seen[ident] != payload:
raise ValueError('Conflicting payloads share a ModelBlob FileDataID')
duplicates += 1
continue
seen[ident] = payload
bounds = collision_vertex_aabb(payload)
if bounds is None:
if ident in rows:
raise ValueError('Existing ModelBlob row has no model collision indices')
omitted.append(ident)
continue
candidate = _ROW.pack(ident, *bounds)
if ident in rows:
if rows[ident] != candidate:
raise ValueError('Existing ModelBlob row conflicts with model geometry')
present += 1
else:
rows[ident] = candidate
added.append(ident)
if len(rows) > _MAX_ROWS:
raise ValueError('ModelBlob row limit exceeded')
output = raw
if added:
body = b''.join(rows[ident] for ident in sorted(rows))
output = raw[:start + 4] + struct.pack('<I', len(body)) + body + raw[end:]
if len(output) > _MAX_BYTES:
raise ValueError('ModelBlob byte limit exceeded')
return output, dict(original_rows=original_count, final_rows=len(rows),
model_inputs=len(seen), added_ids=sorted(added),
no_collision_ids=sorted(omitted), existing_equal_rows=present,
identical_duplicate_inputs=duplicates, changed=output != raw,
native_rows_and_other_chunks_preserved=True)