"""Orient, scale and pivot generated GLB models to three.js conventions. Target frame: metres, +Y up, the asset's forward along -Z, pivot at its base, grip, centre or back face. Tripo returns Y-up models whose yaw depends on the image they were made from: its preview camera looks from +X, so the side shown in that image faces +X, and weapons are shown side-on with the barrel along Z. The yaw comes from bounding-box/PCA geometry, kind-specific cues (a character's toes, a weapon's grip) and the rendered preview's silhouette; doubtful choices are reported, not hidden. Every vertex is kept: the scene roots are wrapped in one node (yaw, uniform scale, translation), which is safe for skinned meshes and keeps separate animation clips bound by bone name. """ from __future__ import annotations import json import math from pathlib import Path import struct from typing import Any, Mapping import numpy as np NORMALIZER_VERSION = 1 WRAPPER_NAME = "gbb_normalized" DIRECTIONS = {"+X": (1.0, 0.0), "-X": (-1.0, 0.0), "+Z": (0.0, 1.0), "-Z": (0.0, -1.0)} SIZE_KEYS = ("width", "height", "depth") _JSON, _BIN = 0x4E4F534A, 0x004E4942 _COMPONENTS = {5120: " tuple[dict, bytes]: data = Path(path).read_bytes() if len(data) < 20 or data[:4] != b"glTF": raise GlbError("not a binary glTF (.glb) file") version, length = struct.unpack_from(" None: payload = json.dumps(gltf, separators=(",", ":"), ensure_ascii=False).encode("utf-8") payload += b" " * (-len(payload) % 4) chunks = struct.pack(" np.ndarray: accessor = gltf["accessors"][index] if "sparse" in accessor or "bufferView" not in accessor: raise GlbError("sparse or view-less accessors are not supported") dtype = np.dtype(_COMPONENTS[accessor["componentType"]]) width, count = _WIDTH[accessor["type"]], int(accessor["count"]) view = gltf["bufferViews"][accessor["bufferView"]] if view.get("buffer", 0) != 0 or "uri" in (gltf.get("buffers") or [{}])[0]: raise GlbError("external buffers are not supported") start = int(view.get("byteOffset", 0)) + int(accessor.get("byteOffset", 0)) stride = int(view.get("byteStride") or dtype.itemsize * width) if count and start + stride * (count - 1) + dtype.itemsize * width > len(binary): raise GlbError("an accessor reads past the binary chunk") values = np.ndarray((count, width), dtype, binary, start, (stride, dtype.itemsize)).astype(np.float64) if accessor.get("normalized") and dtype.kind in "iu": bits = dtype.itemsize * 8 values = (np.maximum(values / (2 ** (bits - 1) - 1), -1.0) if dtype.kind == "i" else values / (2 ** bits - 1)) return values # ---------------------------------------------------------------- scene geometry def _rotation(x: float, y: float, z: float, w: float) -> np.ndarray: return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]) def _local(node: Mapping[str, Any]) -> np.ndarray: if "matrix" in node: return np.array(node["matrix"], dtype=float).reshape(4, 4).T matrix = np.eye(4) matrix[:3, :3] = _rotation(*node.get("rotation", (0, 0, 0, 1))) * np.array(node.get("scale", (1, 1, 1)), float) matrix[:3, 3] = node.get("translation", (0, 0, 0)) return matrix def _worlds(gltf: Mapping[str, Any]) -> dict[int, np.ndarray]: nodes = gltf.get("nodes", []) parent: dict[int, int] = {} for index, node in enumerate(nodes): for child in node.get("children", []): if child in parent or not 0 <= child < len(nodes): raise GlbError("invalid node hierarchy") parent[child] = index worlds: dict[int, np.ndarray] = {} def world(index: int, depth: int = 0) -> np.ndarray: if index not in worlds: if depth > len(nodes): raise GlbError("the node hierarchy has a cycle") matrix = _local(nodes[index]) worlds[index] = (world(parent[index], depth + 1) @ matrix) if index in parent else matrix return worlds[index] for index in range(len(nodes)): world(index) return worlds def _scene_roots(gltf: Mapping[str, Any]) -> list[int]: scenes = gltf.get("scenes") or [] if scenes: return list(scenes[gltf.get("scene", 0)].get("nodes", [])) children = {child for node in gltf.get("nodes", []) for child in node.get("children", [])} return [index for index in range(len(gltf.get("nodes", []))) if index not in children] def _skin_matrix(gltf: Mapping[str, Any], binary: bytes, skin: Mapping[str, Any], worlds: Mapping[int, np.ndarray]) -> tuple[np.ndarray, bool]: """Bind-pose transform of a skinned mesh: joint world matrix x inverse bind matrix.""" joints = skin.get("joints") or [] if not joints: return np.eye(4), True if "inverseBindMatrices" in skin: inverse = _accessor(gltf, binary, skin["inverseBindMatrices"]).reshape(-1, 4, 4).transpose(0, 2, 1) else: inverse = np.repeat(np.eye(4)[None], len(joints), axis=0) products = np.stack([worlds[joint] @ inverse[k] for k, joint in enumerate(joints)]) spread = float(np.abs(products - products[0]).max()) return products[0], spread <= 1e-3 * max(1.0, float(np.abs(products[0]).max())) def scene_triangles(gltf: Mapping[str, Any], binary: bytes) -> tuple[np.ndarray, list[str]]: """World-space triangles (n, 3, 3) of the default scene, plus caveats.""" required = set(gltf.get("extensionsRequired", [])) if required & _COMPRESSED: raise GlbError("compressed geometry (" + ", ".join(sorted(required & _COMPRESSED)) + ")") nodes, worlds = gltf.get("nodes", []), _worlds(gltf) notes: set[str] = set() found: list[np.ndarray] = [] stack, seen = list(_scene_roots(gltf)), set() while stack: index = stack.pop() if index in seen: continue seen.add(index) node = nodes[index] stack.extend(node.get("children", [])) if "mesh" not in node: continue matrix = worlds[index] if "skin" in node: matrix, bind_pose = _skin_matrix(gltf, binary, gltf["skins"][node["skin"]], worlds) if not bind_pose: notes.add("skinned mesh is not stored in its bind pose; bounds are approximate") for primitive in gltf["meshes"][node["mesh"]].get("primitives", []): mode = primitive.get("mode", 4) if mode not in (4, 5, 6) or "POSITION" not in primitive.get("attributes", {}): continue positions = _accessor(gltf, binary, primitive["attributes"]["POSITION"])[:, :3] indices = (_accessor(gltf, binary, primitive["indices"])[:, 0].astype(np.int64) if "indices" in primitive else np.arange(len(positions))) if mode == 5: faces = np.stack([indices[:-2], indices[1:-1], indices[2:]], axis=1) elif mode == 6: faces = np.stack([np.full(max(len(indices) - 2, 0), indices[0] if len(indices) else 0), indices[1:-1], indices[2:]], axis=1) else: faces = indices[: len(indices) // 3 * 3].reshape(-1, 3) if faces.size and (faces.min() < 0 or faces.max() >= len(positions)): raise GlbError("a triangle index is out of range") found.append((positions @ matrix[:3, :3].T + matrix[:3, 3])[faces]) triangles = np.concatenate(found) if found else np.zeros((0, 3, 3)) if not len(triangles): raise GlbError("the scene has no triangles") return triangles, sorted(notes) def measure(path: Path) -> dict[str, list[float]]: """Axis-aligned bounds of a GLB's default scene, in its own frame.""" triangles, _ = scene_triangles(*read_glb(path)) points = triangles.reshape(-1, 3) low, high = points.min(axis=0), points.max(axis=0) return {"min": [round(float(v), 5) for v in low], "max": [round(float(v), 5) for v in high], "size": [round(float(v), 5) for v in high - low]} # ---------------------------------------------------------------- preview silhouettes def _fit(mask: np.ndarray, size: int = _SILHOUETTE) -> np.ndarray: from PIL import Image ys, xs = np.nonzero(mask) crop = mask[ys.min(): ys.max() + 1, xs.min(): xs.max() + 1] scale = (size - 4) / max(crop.shape) width, height = max(1, round(crop.shape[1] * scale)), max(1, round(crop.shape[0] * scale)) resized = Image.fromarray(crop.astype(np.uint8) * 255).resize((width, height), Image.Resampling.BILINEAR) canvas = np.zeros((size, size), dtype=bool) top, left = (size - height) // 2, (size - width) // 2 canvas[top: top + height, left: left + width] = np.asarray(resized) > 127 return canvas def _preview_mask(path: Path) -> np.ndarray | None: from PIL import Image with Image.open(path) as image: rgba = np.asarray(image.convert("RGBA")) if rgba[..., 3].min() < 250: mask = rgba[..., 3] > 127 else: # Opaque render: separate the object from the corner background colour. corners = rgba[[0, 0, -1, -1], [0, -1, 0, -1], :3].astype(float) mask = np.abs(rgba[..., :3].astype(float) - np.median(corners, axis=0)).max(axis=-1) > 24 return _fit(mask) if mask.sum() >= 50 else None def _render(triangles: np.ndarray, camera: str, elevation: float) -> np.ndarray: """Orthographic silhouette seen from ``camera`` (a DIRECTIONS key), +Y up.""" from PIL import Image, ImageDraw cx, cz = DIRECTIONS[camera] angle = math.radians(elevation) forward = -np.array([cx * math.cos(angle), math.sin(angle), cz * math.cos(angle)]) right = np.cross(forward, (0.0, 1.0, 0.0)) right /= np.linalg.norm(right) up = np.cross(right, forward) xs, ys = triangles @ right, triangles @ up span = max(float(xs.max() - xs.min()), float(ys.max() - ys.min()), 1e-9) scale = (_SILHOUETTE - 4) / span px = (xs - (xs.max() + xs.min()) / 2) * scale + _SILHOUETTE / 2 py = _SILHOUETTE / 2 - (ys - (ys.max() + ys.min()) / 2) * scale image = Image.new("L", (_SILHOUETTE, _SILHOUETTE)) draw = ImageDraw.Draw(image) for triangle in np.stack([px, py], axis=-1).tolist(): draw.polygon([tuple(point) for point in triangle], fill=255) mask = np.asarray(image) > 127 return _fit(mask) if mask.any() else mask def _iou(mask: np.ndarray, target: np.ndarray) -> float: union = int((mask | target).sum()) return int((mask & target).sum()) / union if union else 0.0 def preview_scores(triangles: np.ndarray, preview: Path) -> dict[str, dict[str, float]] | None: """Silhouette IoU of the preview against the model seen from each horizontal side. ``mirrored`` scores the left-right mirror of the same render: a view and its mirror match equally for a symmetric model, so only a real asymmetry (not the unknown camera elevation) can tell which of two opposite sides was shown. """ target = _preview_mask(preview) if target is None: return None if len(triangles) > _MAX_RENDER_TRIANGLES: areas = np.linalg.norm(np.cross(triangles[:, 1] - triangles[:, 0], triangles[:, 2] - triangles[:, 0]), axis=1) triangles = triangles[np.argsort(areas)[-_MAX_RENDER_TRIANGLES:]] scores: dict[str, dict[str, float]] = {"iou": {}, "mirrored": {}} for camera in DIRECTIONS: best = (-1.0, 0.0) for elevation in _PREVIEW_ELEVATIONS: mask = _render(triangles, camera, elevation) best = max(best, (_iou(mask, target), _iou(mask[:, ::-1], target))) scores["iou"][camera], scores["mirrored"][camera] = round(best[0], 4), round(best[1], 4) return scores # ---------------------------------------------------------------- decisions def _positive(value: object) -> bool: return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and value > 0 def _cues(triangles: np.ndarray) -> dict[str, Any]: centroids = triangles.mean(axis=1) areas = .5 * np.linalg.norm(np.cross(triangles[:, 1] - triangles[:, 0], triangles[:, 2] - triangles[:, 0]), axis=1) weights = areas / max(float(areas.sum()), 1e-12) points = triangles.reshape(-1, 3) low, high = points.min(axis=0), points.max(axis=0) extent, middle = high - low, (low + high) / 2 body = (centroids * weights[:, None]).sum(axis=0) cues: dict[str, Any] = {"toe": {}, "grip": {}} feet = centroids[:, 1] <= low[1] + .06 * extent[1] lower = centroids[:, 1] <= low[1] + .45 * extent[1] for axis, column in (("X", 0), ("Z", 2)): if feet.any(): # Toes reach further in front of the body than heels behind it. ahead, behind = centroids[feet, column].max() - body[column], body[column] - centroids[feet, column].min() cues["toe"][axis] = float((ahead - behind) / max(ahead + behind, 1e-9)) else: cues["toe"][axis] = 0.0 grip_weight = float(weights[lower].sum()) offset = (centroids[lower, column] * weights[lower]).sum() / grip_weight - middle[column] if grip_weight else 0.0 cues["grip"][axis] = float(offset / max(float(extent[column]), 1e-9)) planar = centroids[:, [0, 2]] - body[[0, 2]] covariance = (planar * weights[:, None]).T @ planar values, vectors = np.linalg.eigh(covariance) major = vectors[:, 1] yaw = math.degrees(math.atan2(major[1], major[0])) % 180 cues["pca"] = {"major_axis_degrees_from_x": round(yaw, 2), "off_axis_degrees": round(min(yaw % 90, 90 - yaw % 90), 2), "anisotropy": round(float(values[1] / max(values[0], 1e-12)), 3)} return cues def _decide(kind: str, forward: str, extent: np.ndarray, cues: Mapping[str, Any], scores: Mapping[str, Mapping[str, float]] | None, expected: Mapping[str, Any]) -> dict[str, Any]: """Choose the native horizontal direction that becomes -Z.""" if forward == "none": return {"direction": None, "confidence": "high", "sources": ["forward is not meaningful for this asset"], "uncertain": []} uncertain: list[str] = [] long_axis, short_axis = ("X", "Z") if extent[0] >= extent[2] else ("Z", "X") ratio = max(extent[0], extent[2]) / max(min(extent[0], extent[2]), 1e-9) votes: dict[str, list[tuple[float, str]]] = {"X": [], "Z": []} camera_axis = None iou = scores["iou"] if scores else {} if iou: best = {axis: max(iou[f"+{axis}"], iou[f"-{axis}"]) for axis in ("X", "Z")} camera_axis = "X" if best["X"] >= best["Z"] else "Z" margin = abs(best["X"] - best["Z"]) if margin >= .03: side = camera_axis if forward == "depicted_front" else ("Z" if camera_axis == "X" else "X") votes[side].append((min(3.0, margin * 10), f"preview camera looks along {camera_axis}")) elongated = 2.0 if ratio >= 1.3 else .5 if kind == "character" and forward == "depicted_front": votes[short_axis].append((elongated, "arms/shoulders span the wider horizontal axis")) if forward == "muzzle": votes[long_axis].append((elongated, "the barrel lies along the longer horizontal axis")) width, depth = expected.get("width"), expected.get("depth") if kind != "character" and _positive(width) and _positive(depth): weight = 1.5 if ratio >= 1.15 else .3 if depth >= 1.25 * width: votes[long_axis].append((weight, "expected depth exceeds width")) elif width >= 1.25 * depth: votes[short_axis].append((weight, "expected width exceeds depth")) # Tripo's convention: the depicted front faces +X; weapons are shown side-on. votes["X" if forward == "depicted_front" else "Z"].append((.5, "Tripo convention")) totals = {axis: sum(weight for weight, _ in items) for axis, items in votes.items()} axis = "X" if totals["X"] >= totals["Z"] else "Z" other = "Z" if axis == "X" else "X" if totals[other] >= 1: # Some real cue (not just the convention) points the other way. uncertain.append(f"forward axis {axis} ({'; '.join(r for _, r in votes[axis])}) conflicts with " f"{other} ({'; '.join(r for _, r in votes[other])})") sources = [f"axis {axis}: " + "; ".join(r for _, r in votes[axis])] sign, strong = 0, False if forward == "muzzle": offset = cues["grip"][axis] if abs(offset) >= .03: sign, strong = (-1 if offset > 0 else 1), abs(offset) >= .08 sources.append(f"grip sits toward {'+' if offset > 0 else '-'}{axis}, so the muzzle points the other way") else: uncertain.append("grip and muzzle ends are indistinct; front and back may be swapped") else: if iou and camera_axis == axis: mirrored = scores["mirrored"] asymmetry = ((iou[f"+{axis}"] - mirrored[f"+{axis}"]) - (iou[f"-{axis}"] - mirrored[f"-{axis}"])) / 2 if abs(asymmetry) >= .06: sign, strong = (1 if asymmetry > 0 else -1), True sources.append("preview silhouette is asymmetric and shows the front") if not sign and axis == "X": sign = 1 sources.append("Tripo preview camera sits on +X" + ("" if camera_axis == "X" else " (no preview check)")) if kind == "character" and abs(cues["toe"][axis]) >= .05: toes = 1 if cues["toe"][axis] > 0 else -1 if not sign: sign = toes sources.append("toes point forward") elif toes != sign: uncertain.append(f"toes point {'+' if toes > 0 else '-'}{axis}, against the {sources[-1]}") else: sources.append("toes agree") if not sign: sign = 1 uncertain.append(f"front and back along {axis} are ambiguous") confidence = "low" if uncertain else ("high" if strong and not totals[other] else "medium") return {"direction": f"{'+' if sign > 0 else '-'}{axis}", "confidence": confidence, "sources": sources, "uncertain": uncertain} def _scale(kind: str, expected: Mapping[str, Any], measured: Mapping[str, float]) -> tuple[float, str, list[str], list[str]]: given = {key: float(expected[key]) for key in SIZE_KEYS if _positive(expected.get(key))} if not given: return 1.0, "", ["no expected size; kept the generator's own size"], [] primary = expected.get("primary") if primary not in given: primary = _PRIMARY.get(kind) if _PRIMARY.get(kind) in given else max(given, key=given.__getitem__) if measured[primary] <= 1e-9: return 1.0, primary, [], [f"model has no {primary}; kept the generator's own size"] scale = given[primary] / measured[primary] notes, uncertain = [], [] for key, value in given.items(): if key == primary or (kind == "character" and key != "height") or measured[key] <= 1e-9: continue actual = measured[key] * scale ratio = value / actual message = f"{key} is {actual:.2f} m after scaling by {primary}, expected {value:.2f} m" if not .5 <= ratio <= 2: uncertain.append(message) elif not .67 <= ratio <= 1.5: notes.append(message) if not .01 <= scale <= 100: uncertain.append(f"scale factor {scale:.4g} is implausible for a generated model") return scale, primary, notes, uncertain def _pivot(pivot: str, triangles: np.ndarray) -> tuple[np.ndarray, list[str]]: points = triangles.reshape(-1, 3) low, high = points.min(axis=0), points.max(axis=0) middle = (low + high) / 2 if pivot == "base": return np.array([middle[0], low[1], middle[2]]), [] if pivot == "back": # Forward is -Z, so the wall-side face is at max Z. return np.array([middle[0], middle[1], high[2]]), [] if pivot == "grip": centroids = triangles.mean(axis=1) areas = np.linalg.norm(np.cross(triangles[:, 1] - triangles[:, 0], triangles[:, 2] - triangles[:, 0]), axis=1) grip = (centroids[:, 1] <= low[1] + .45 * (high[1] - low[1])) & (centroids[:, 2] >= middle[2]) if areas[grip].sum() >= .02 * areas.sum(): point = (centroids[grip] * areas[grip, None]).sum(axis=0) / areas[grip].sum() return np.array([middle[0], point[1], point[2]]), [] return middle, ["no grip-like lower rear part; pivot placed at the centre"] return middle, [] def analyze(path: Path, *, kind: str, forward: str, pivot: str, expected_size_m: Mapping[str, Any], preview: Path | None = None) -> dict[str, Any]: """Decide yaw, scale and pivot for one GLB without modifying it.""" triangles, caveats = scene_triangles(*read_glb(path)) points = triangles.reshape(-1, 3) extent = points.max(axis=0) - points.min(axis=0) if extent.max() <= 1e-9: raise GlbError("the model has no extent") cues = _cues(triangles) scores = preview_scores(triangles, Path(preview)) if preview and Path(preview).is_file() else None decision = _decide(kind, forward, extent, cues, scores, expected_size_m) uncertain = list(decision["uncertain"]) notes = list(caveats) if not scores and forward != "none": notes.append("no usable rendered preview; orientation uses geometry and Tripo's convention only") if cues["pca"]["anisotropy"] >= 1.5 and cues["pca"]["off_axis_degrees"] > 15: uncertain.append(f"major horizontal axis is {cues['pca']['off_axis_degrees']}° off the X/Z axes; " "yaw is limited to 90° steps") yaw = 0.0 if decision["direction"]: fx, fz = DIRECTIONS[decision["direction"]] yaw = math.atan2(fx, -fz) # Rotation about +Y that takes (fx, 0, fz) to (0, 0, -1). cos, sin = math.cos(yaw), math.sin(yaw) rotated = triangles @ np.array([[cos, 0, sin], [0, 1, 0], [-sin, 0, cos]]).T rotated_points = rotated.reshape(-1, 3) span = rotated_points.max(axis=0) - rotated_points.min(axis=0) measured = dict(zip(SIZE_KEYS, map(float, span))) scale, primary, scale_notes, scale_uncertain = _scale(kind, expected_size_m, measured) notes += scale_notes uncertain += scale_uncertain origin, pivot_notes = _pivot(pivot, rotated * scale) uncertain += pivot_notes translation = -origin final = rotated_points * scale + translation return { "version": NORMALIZER_VERSION, "forward_native": decision["direction"], "yaw_degrees": round(math.degrees(yaw), 4), "scale": round(scale, 6), "scale_from": primary, "translation": [round(float(v), 6) for v in translation], "pivot": pivot, "size_m": {key: round(float(value), 4) for key, value in zip(SIZE_KEYS, final.max(axis=0) - final.min(axis=0))}, "bounds": {"min": [round(float(v), 4) for v in final.min(axis=0)], "max": [round(float(v), 4) for v in final.max(axis=0)]}, "confidence": "low" if uncertain else decision["confidence"], "sources": decision["sources"], "uncertain": uncertain, "notes": notes, "evidence": {"source_size": [round(float(v), 4) for v in extent], "preview_iou": scores, "toe": {k: round(v, 4) for k, v in cues["toe"].items()}, "grip": {k: round(v, 4) for k, v in cues["grip"].items()}, "pca": cues["pca"]}, } def write_normalized(source: Path, target: Path, result: Mapping[str, Any]) -> None: """Copy ``source`` with its default scene wrapped in the normalizing node.""" gltf, binary = read_glb(source) nodes = gltf.setdefault("nodes", []) if not gltf.get("scenes"): gltf["scenes"] = [{"nodes": _scene_roots(gltf)}] scene = gltf["scenes"][gltf.get("scene", 0)] half = math.radians(float(result["yaw_degrees"])) / 2 nodes.append({ "name": WRAPPER_NAME, "children": list(scene.get("nodes", [])), "translation": [float(v) for v in result["translation"]], "rotation": [0.0, math.sin(half), 0.0, math.cos(half)], "scale": [float(result["scale"])] * 3, "extras": {"gbb_normalization": {"version": NORMALIZER_VERSION, "forward": "-Z", "up": "+Y", "units": "m", "pivot": result["pivot"]}}, }) scene["nodes"] = [len(nodes) - 1] write_glb(target, gltf, binary)