RustToDust/tools/vehicles/verify_glbs.py

463 lines
19 KiB
Python

"""Validate all exported vehicle GLBs, manifests, hardpoint anchors, joints, bounds, and gear GLBs."""
from __future__ import annotations
import json
import math
import struct
import sys
from pathlib import Path
from typing import Any
import numpy as np
REPO_ROOT = Path(__file__).resolve().parents[2]
VEHICLES_DIR = REPO_ROOT / "assets" / "vehicles"
GEAR_DIR = REPO_ROOT / "assets" / "gear"
EXPECTED_VEHICLES = (
"jackal", "mule", "ferret", "hornet", "mammoth", "ironclad", "anvil", "condor",
"breaker", "paladin", "raptor", "manticore", "bastion", "spectre", "kestrel",
)
RETROFIT_MECHS = frozenset({"breaker", "paladin", "raptor", "manticore", "bastion", "spectre", "kestrel"})
EXPECTED_GEAR = ("mg_762", "autocannon", "recoilless", "copper_rad", "gilded_lance", "gold_radiator")
def parse_glb(glb_path: Path) -> tuple[dict[str, Any], bytes]:
data = glb_path.read_bytes()
if len(data) < 20:
raise AssertionError(f"{glb_path}: file too small ({len(data)} bytes)")
magic, version, total_len = struct.unpack_from("<III", data, 0)
if magic != 0x46546C67 or version != 2:
raise AssertionError(f"{glb_path}: invalid GLB header magic={hex(magic)} version={version}")
if total_len != len(data):
raise AssertionError(f"{glb_path}: header length {total_len} != file size {len(data)}")
chunk_len, chunk_type = struct.unpack_from("<II", data, 12)
if chunk_type != 0x4E4F534A:
raise AssertionError(f"{glb_path}: first chunk is not JSON ({hex(chunk_type)})")
gltf = json.loads(data[20 : 20 + chunk_len].decode("utf-8"))
bin_off = 20 + chunk_len
bin_blob = b""
if bin_off + 8 <= len(data):
b_len, b_type = struct.unpack_from("<II", data, bin_off)
if b_type == 0x004E4942:
bin_blob = data[bin_off + 8 : bin_off + 8 + b_len]
return gltf, bin_blob
def parse_glb_json(glb_path: Path) -> dict[str, Any]:
return parse_glb(glb_path)[0]
def _node_local_matrix(node: dict[str, Any]) -> np.ndarray:
if "matrix" in node:
return np.array(node["matrix"], dtype=np.float64).reshape(4, 4).T
m = np.eye(4, dtype=np.float64)
if "scale" in node:
sx, sy, sz = node["scale"]
m = m @ np.diag([sx, sy, sz, 1.0])
if "rotation" in node:
qx, qy, qz, qw = node["rotation"]
xx, yy, zz = qx * qx, qy * qy, qz * qz
xy, xz, yz = qx * qy, qx * qz, qy * qz
wx, wy, wz = qw * qx, qw * qy, qw * qz
r = np.array([
[1 - 2 * (yy + zz), 2 * (xy - wz), 2 * (xz + wy), 0.0],
[2 * (xy + wz), 1 - 2 * (xx + zz), 2 * (yz - wx), 0.0],
[2 * (xz - wy), 2 * (yz + wx), 1 - 2 * (xx + yy), 0.0],
[0.0, 0.0, 0.0, 1.0],
], dtype=np.float64)
m = r @ m
if "translation" in node:
tx, ty, tz = node["translation"]
m[:3, 3] = [tx, ty, tz]
return m
def compute_glb_stats(gltf: dict[str, Any], bin_blob: bytes = b"") -> tuple[int, np.ndarray, np.ndarray]:
nodes = gltf.get("nodes", [])
meshes = gltf.get("meshes", [])
accessors = gltf.get("accessors", [])
buffer_views = gltf.get("bufferViews", [])
scenes = gltf.get("scenes", [])
root_indices = scenes[gltf.get("scene", 0)]["nodes"] if scenes else list(range(len(nodes)))
tri_total = 0
g_min = np.array([math.inf, math.inf, math.inf], dtype=np.float64)
g_max = np.array([-math.inf, -math.inf, -math.inf], dtype=np.float64)
def walk(node_idx: int, parent_mat: np.ndarray) -> None:
nonlocal tri_total, g_min, g_max
node = nodes[node_idx]
world = parent_mat @ _node_local_matrix(node)
if "mesh" in node:
mesh = meshes[node["mesh"]]
for prim in mesh.get("primitives", []):
mode = prim.get("mode", 4)
if mode == 4:
if "indices" in prim:
tri_total += accessors[prim["indices"]]["count"] // 3
elif "POSITION" in prim.get("attributes", {}):
tri_total += accessors[prim["attributes"]["POSITION"]]["count"] // 3
pos_acc_idx = prim.get("attributes", {}).get("POSITION")
if pos_acc_idx is not None:
acc = accessors[pos_acc_idx]
if bin_blob and "bufferView" in acc and acc.get("componentType") == 5126 and acc.get("type") == "VEC3":
bv = buffer_views[acc["bufferView"]]
off = bv.get("byteOffset", 0) + acc.get("byteOffset", 0)
stride = bv.get("byteStride", 12)
count = acc["count"]
if stride == 12:
pts = np.frombuffer(bin_blob, dtype="<f4", count=count * 3, offset=off).reshape(count, 3)
else:
raw = np.frombuffer(bin_blob, dtype=np.uint8, count=count * stride, offset=off).reshape(count, stride)
pts = raw[:, :12].view("<f4").reshape(count, 3)
wc = pts @ world[:3, :3].T + world[:3, 3]
else:
pmin = np.array(acc["min"], dtype=np.float64)
pmax = np.array(acc["max"], dtype=np.float64)
corners = np.array([
[x, y, z, 1.0]
for x in (pmin[0], pmax[0])
for y in (pmin[1], pmax[1])
for z in (pmin[2], pmax[2])
], dtype=np.float64)
wc = (world @ corners.T).T[:, :3]
g_min = np.minimum(g_min, wc.min(axis=0))
g_max = np.maximum(g_max, wc.max(axis=0))
for child_idx in node.get("children", []):
walk(child_idx, world)
ident = np.eye(4, dtype=np.float64)
for r_idx in root_indices:
walk(r_idx, ident)
return tri_total, g_min, g_max
def _read_accessor(
accessors: list[dict[str, Any]],
buffer_views: list[dict[str, Any]],
bin_blob: bytes,
acc_idx: int,
) -> np.ndarray:
acc = accessors[acc_idx]
bv = buffer_views[acc["bufferView"]]
off = bv.get("byteOffset", 0) + acc.get("byteOffset", 0)
count = acc["count"]
ct = acc["componentType"]
typ = acc["type"]
if typ == "VEC3" and ct == 5126:
stride = bv.get("byteStride", 12)
if stride == 12:
return np.frombuffer(bin_blob, dtype="<f4", count=count * 3, offset=off).reshape(count, 3).astype(np.float64)
raw = np.frombuffer(bin_blob, dtype=np.uint8, count=count * stride, offset=off).reshape(count, stride)
return raw[:, :12].view("<f4").reshape(count, 3).astype(np.float64)
if typ == "SCALAR":
dtype = {5121: np.uint8, 5123: "<u2", 5125: "<u4"}[ct]
return np.frombuffer(bin_blob, dtype=dtype, count=count, offset=off).astype(np.int64)
raise ValueError(f"Unsupported accessor type={typ} componentType={ct}")
def _pt_tri_dist2(p: np.ndarray, a: np.ndarray, b: np.ndarray, c: np.ndarray) -> float:
ab = b - a
ac = c - a
ap = p - a
d1 = float(np.dot(ab, ap))
d2 = float(np.dot(ac, ap))
if d1 <= 0.0 and d2 <= 0.0:
return float(np.dot(ap, ap))
bp = p - b
d3 = float(np.dot(ab, bp))
d4 = float(np.dot(ac, bp))
if d3 >= 0.0 and d4 <= d3:
return float(np.dot(bp, bp))
vc = d1 * d4 - d3 * d2
if vc <= 0.0 and d1 >= 0.0 and d3 <= 0.0:
denom = d1 - d3
v = d1 / denom if denom > 1e-18 else 0.0
q = a + v * ab
return float(np.dot(p - q, p - q))
cp = p - c
d5 = float(np.dot(ab, cp))
d6 = float(np.dot(ac, cp))
if d6 >= 0.0 and d5 <= d6:
return float(np.dot(cp, cp))
vb = d5 * d2 - d1 * d6
if vb <= 0.0 and d2 >= 0.0 and d6 <= 0.0:
denom = d2 - d6
w = d2 / denom if denom > 1e-18 else 0.0
q = a + w * ac
return float(np.dot(p - q, p - q))
va = d3 * d6 - d5 * d4
if va <= 0.0 and (d4 - d3) >= 0.0 and (d5 - d6) >= 0.0:
denom = (d4 - d3) + (d5 - d6)
w = (d4 - d3) / denom if denom > 1e-18 else 0.0
q = b + w * (c - b)
return float(np.dot(p - q, p - q))
s = va + vb + vc
if s <= 1e-18:
return min(float(np.dot(ap, ap)), float(np.dot(bp, bp)), float(np.dot(cp, cp)))
denom = 1.0 / s
q = a + ab * (vb * denom) + ac * (vc * denom)
return float(np.dot(p - q, p - q))
def _min_dist_to_tris(
pt: np.ndarray,
tris: np.ndarray,
tri_mins: np.ndarray,
tri_maxs: np.ndarray,
) -> float:
d_box = np.maximum(0.0, np.maximum(tri_mins - pt, pt - tri_maxs))
d2_box = np.sum(d_box * d_box, axis=1)
order = np.argsort(d2_box)
min_d2 = math.inf
for idx in order:
if d2_box[idx] > min_d2:
break
t = tris[idx]
d2 = _pt_tri_dist2(pt, t[0], t[1], t[2])
if d2 < min_d2:
min_d2 = d2
return math.sqrt(min_d2)
def measure_hardpoint_gaps(gltf: dict[str, Any], bin_blob: bytes) -> dict[str, tuple[float, float]]:
"""Return {hp_id: (center_to_hull_m, min_slot_vert_to_hull_m)} for all hardpoints in GLB."""
nodes = gltf.get("nodes", [])
meshes = gltf.get("meshes", [])
accessors = gltf.get("accessors", [])
buffer_views = gltf.get("bufferViews", [])
scenes = gltf.get("scenes", [])
root_indices = scenes[gltf.get("scene", 0)]["nodes"] if scenes else list(range(len(nodes)))
parent_of: dict[int, int] = {}
for idx, n in enumerate(nodes):
for c in n.get("children", []):
parent_of[c] = idx
hp_roots: dict[int, str] = {}
hp_anchors: dict[str, int] = {}
for idx, n in enumerate(nodes):
extras = n.get("extras") or {}
if "rtd.id" in extras:
hp_id = str(extras["rtd.id"])
hp_anchors[hp_id] = idx
p = parent_of.get(idx)
if p is not None and str(nodes[p].get("name", "")).startswith("slot_frame."):
hp_roots[p] = hp_id
hp_node_set: dict[int, str] = {}
def mark_hp(idx: int, hp_id: str) -> None:
hp_node_set[idx] = hp_id
for c in nodes[idx].get("children", []):
mark_hp(c, hp_id)
for r_idx, hp_id in hp_roots.items():
mark_hp(r_idx, hp_id)
hull_tris: list[np.ndarray] = []
hp_pts: dict[str, list[np.ndarray]] = {}
node_world: dict[int, np.ndarray] = {}
def walk(idx: int, pmat: np.ndarray) -> None:
n = nodes[idx]
w = pmat @ _node_local_matrix(n)
node_world[idx] = w
if "mesh" in n:
for prim in meshes[n["mesh"]].get("primitives", []):
if prim.get("mode", 4) != 4:
continue
pos = _read_accessor(accessors, buffer_views, bin_blob, prim["attributes"]["POSITION"])
wpos = pos @ w[:3, :3].T + w[:3, 3]
if idx in hp_node_set:
hp_pts.setdefault(hp_node_set[idx], []).append(wpos)
else:
if "indices" in prim:
ind = _read_accessor(accessors, buffer_views, bin_blob, prim["indices"]).reshape(-1, 3)
else:
ind = np.arange(len(pos), dtype=np.int64).reshape(-1, 3)
hull_tris.append(wpos[ind])
for c in n.get("children", []):
walk(c, w)
ident = np.eye(4, dtype=np.float64)
for r_idx in root_indices:
walk(r_idx, ident)
if not hull_tris:
return {}
tris = np.concatenate(hull_tris, axis=0)
tri_mins = tris.min(axis=1)
tri_maxs = tris.max(axis=1)
gaps: dict[str, tuple[float, float]] = {}
for r_idx, hp_id in hp_roots.items():
p_slot = node_world[r_idx][:3, 3]
p_anchor = node_world[hp_anchors[hp_id]][:3, 3]
out_vec = p_anchor - p_slot
out_len = float(np.linalg.norm(out_vec))
n_out = out_vec / out_len if out_len > 1e-6 else np.array([0.0, 1.0, 0.0])
d_center = _min_dist_to_tris(p_slot, tris, tri_mins, tri_maxs)
pts = np.concatenate(hp_pts.get(hp_id, []), axis=0) if hp_id in hp_pts else np.empty((0, 3))
if len(pts) > 0:
proj = (pts - p_slot) @ n_out
base_pts = pts[proj <= 0.03]
if len(base_pts) == 0:
base_pts = pts
if len(base_pts) > 256:
base_pts = base_pts[np.linspace(0, len(base_pts) - 1, 256, dtype=int)]
d_vert = min(_min_dist_to_tris(p, tris, tri_mins, tri_maxs) for p in base_pts)
else:
d_vert = d_center
gaps[hp_id] = (d_center, d_vert)
return gaps
def validate_vehicle(vid: str) -> dict[str, Any]:
vdir = VEHICLES_DIR / vid
glb_path = vdir / f"{vid}.glb"
manifest_path = vdir / "manifest.json"
if not glb_path.is_file():
raise AssertionError(f"Missing GLB: {glb_path}")
if not manifest_path.is_file():
raise AssertionError(f"Missing manifest: {manifest_path}")
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
gltf, bin_blob = parse_glb(glb_path)
nodes = gltf.get("nodes", [])
# 1. Check hardpoint grid bounds, mask activity, and zero overlaps
gw, gh = int(manifest["gridWidth"]), int(manifest["gridHeight"])
mask = manifest["mask"]
if len(mask) != gw * gh:
raise AssertionError(f"{vid}: mask length {len(mask)} != {gw * gh}")
occupied: dict[tuple[int, int], str] = {}
for hp in manifest["hardpoints"]:
hx, hy, hw, hh = hp["x"], hp["y"], hp["w"], hp["h"]
if not (0 <= hx and hx + hw <= gw and 0 <= hy and hy + hh <= gh):
raise AssertionError(f"{vid}: hardpoint {hp['id']} out of grid bounds ({hx},{hy} {hw}x{hh} on {gw}x{gh})")
for cy in range(hy, hy + hh):
for cx in range(hx, hx + hw):
if not mask[cy * gw + cx]:
raise AssertionError(f"{vid}: hardpoint {hp['id']} covers inactive cell ({cx},{cy})")
if (cx, cy) in occupied:
raise AssertionError(f"{vid}: cell ({cx},{cy}) overlaps between {occupied[(cx, cy)]} and {hp['id']}")
occupied[(cx, cy)] = hp["id"]
# 2. Check every manifest hardpoint modelNodeId exists as a unique node with extras["rtd.id"] and extras["rtd.kind"]
by_rtd_id: dict[str, list[dict]] = {}
by_rtd_joint: dict[str, list[dict]] = {}
for node in nodes:
extras = node.get("extras") or {}
if "rtd.id" in extras:
by_rtd_id.setdefault(str(extras["rtd.id"]), []).append(node)
if "rtd.joint" in extras:
by_rtd_joint.setdefault(str(extras["rtd.joint"]), []).append(node)
for hp in manifest["hardpoints"]:
target_id = hp["modelNodeId"]
matches = by_rtd_id.get(target_id, [])
if len(matches) != 1:
raise AssertionError(f"{vid}: hardpoint {target_id!r} matched {len(matches)} GLB nodes (expected 1)")
node = matches[0]
extras = node.get("extras", {})
if extras.get("rtd.kind") != hp["kind"]:
raise AssertionError(f"{vid}: node {target_id} rtd.kind={extras.get('rtd.kind')!r} != manifest {hp['kind']!r}")
if node.get("name") != target_id:
raise AssertionError(f"{vid}: node name {node.get('name')!r} != {target_id!r}")
# 3. Check every manifest joint exists with rtd.joint, rtd.axis, rtd.min, rtd.max
for j in manifest["joints"]:
jid = j["id"]
matches = by_rtd_joint.get(jid, [])
if len(matches) != 1:
raise AssertionError(f"{vid}: joint {jid!r} matched {len(matches)} GLB nodes (expected 1)")
extras = matches[0].get("extras", {})
for key in ("rtd.axis", "rtd.min", "rtd.max"):
if key not in extras:
raise AssertionError(f"{vid}: joint {jid!r} missing {key} in GLB extras")
plane = manifest.get("plane")
if plane not in ("Dorsal", "Coronal"):
raise AssertionError(f"{vid}: invalid plane {plane!r}")
# 4. Check GLB triangle count & grounded +Y-up / +Z-forward bounds
tri_total, g_min, g_max = compute_glb_stats(gltf, bin_blob)
max_tris = 50000 if vid in RETROFIT_MECHS else 35000
min_tris = 15000 if vid in RETROFIT_MECHS else 1500
if not (min_tris <= tri_total <= max_tris):
raise AssertionError(f"{vid}: tri count {tri_total} outside [{min_tris}, {max_tris}]")
if abs(tri_total - manifest["triCount"]) > 0:
raise AssertionError(f"{vid}: GLB tri count {tri_total} != manifest triCount {manifest['triCount']}")
if abs(float(g_min[1])) > 0.02:
raise AssertionError(f"{vid}: GLB not grounded at minY=0 (got minY={g_min[1]:.4f})")
size = g_max - g_min
if vid in RETROFIT_MECHS:
if not (2.5 <= size[0] <= 14.0 and 5.0 <= size[1] <= 12.5 and 2.5 <= size[2] <= 16.0):
raise AssertionError(f"{vid}: implausible mech bounds size {size.tolist()}")
elif not (1.2 <= size[0] <= 5.0 and 1.0 <= size[1] <= 3.5 and 2.5 <= size[2] <= 6.5):
raise AssertionError(f"{vid}: implausible bounds size {size.tolist()}")
# 5. Flush-seating check: every hardpoint slot center and base vertices must sit <= 0.025m from hull geometry
hp_gaps = measure_hardpoint_gaps(gltf, bin_blob)
if len(hp_gaps) != len(manifest["hardpoints"]):
raise AssertionError(f"{vid}: measured {len(hp_gaps)} hardpoint slots != manifest {len(manifest['hardpoints'])}")
max_gap = 0.0
for hp in manifest["hardpoints"]:
hid = hp["modelNodeId"]
d_center, d_vert = hp_gaps[hid]
if d_center > 0.025 or d_vert > 0.025:
raise AssertionError(
f"{vid}: floating/buried hardpoint {hid!r} (center_to_hull={d_center:.4f}m, base_to_hull={d_vert:.4f}m > 0.025m)"
)
max_gap = max(max_gap, d_center, d_vert)
return {
"id": vid,
"plane": plane,
"tris": tri_total,
"bytes": glb_path.stat().st_size,
"hardpoints": len(manifest["hardpoints"]),
"joints": len(manifest["joints"]),
"mechanisms": len((manifest.get("mechanisms") or {}).get("dofs", [])),
"minY": round(float(g_min[1]), 4),
"maxHpGap": round(max_gap, 4),
"size": [round(float(v), 3) for v in size],
}
def validate_gear(gid: str) -> dict[str, Any]:
glb_path = GEAR_DIR / f"{gid}.glb"
if not glb_path.is_file():
raise AssertionError(f"Missing gear GLB: {glb_path}")
gltf, bin_blob = parse_glb(glb_path)
tri_total, g_min, g_max = compute_glb_stats(gltf, bin_blob)
if tri_total <= 0 or tri_total > 10000:
raise AssertionError(f"gear/{gid}: unexpected tri count {tri_total}")
if abs(float(g_min[1])) > 0.02:
raise AssertionError(f"gear/{gid}: not grounded at minY=0 (got {g_min[1]:.4f})")
return {
"id": gid,
"tris": tri_total,
"bytes": glb_path.stat().st_size,
"size": [round(float(v), 3) for v in (g_max - g_min)],
}
def main() -> int:
v_reports = [validate_vehicle(v) for v in EXPECTED_VEHICLES]
g_reports = [validate_gear(g) for g in EXPECTED_GEAR]
print("=== VEHICLE GLB VALIDATION PASSED ===")
for r in v_reports:
mech_tag = f" | dofs={r['mechanisms']}" if r["mechanisms"] else ""
print(f" {r['id']:10s} | {r['plane']:7s} | tris={r['tris']:5d} | size={r['size']} | minY={r['minY']} | hpGap={r['maxHpGap']:.4f}m | hps={r['hardpoints']} | joints={r['joints']}{mech_tag} | {r['bytes']/1024:.1f} KiB")
print("=== GEAR GLB VALIDATION PASSED ===")
for r in g_reports:
print(f" {r['id']:14s} | tris={r['tris']:4d} | size={r['size']} | {r['bytes']/1024:.1f} KiB")
return 0
if __name__ == "__main__":
sys.exit(main())