diff --git a/tools/vehicles/build_ferret.py b/tools/vehicles/build_ferret.py new file mode 100644 index 0000000..83046f3 --- /dev/null +++ b/tools/vehicles/build_ferret.py @@ -0,0 +1,341 @@ +"""Build the Ferret (Light Tracked Scout Tankette) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _build_track_pod(name: str, side: float, parent) -> None: + """Build one wide articulated steel track pod with roadwheels, drive sprockets, and track shoes.""" + pod_x = side * 0.86 + pod = vc.make_empty(name, parent=parent, location=(pod_x, 0.0, 0.0)) + + # Track loop keypoints in (y, z): front idler -> bottom roadwheels -> rear sprocket -> top return + # Ground at z = 0.0 (track shoe thickness ~0.04 -> wheel bottom at z = 0.04) + rw_r = 0.25 + rw_z = rw_r + 0.04 + rw_ys = (-0.90, -0.30, 0.30, 0.90) + idler_y, idler_z, idler_r = -1.48, 0.46, 0.22 + sproc_y, sproc_z, sproc_r = 1.46, 0.48, 0.23 + track_w = 0.40 + + # Roadwheels (4) + Front Idler + Rear Drive Sprocket + for i, ry in enumerate(rw_ys): + vc.make_tube_part( + f"{name}_rw_tire_{i}", rw_r, rw_r, track_w * 0.82, segments=16, + mat_name="rubber_dark", parent=pod, location=(-track_w * 0.41, ry, rw_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_rw_hub_{i}", rw_r * 0.66, rw_r * 0.66, track_w * 0.88, segments=12, + mat_name="olive_armor", parent=pod, location=(-track_w * 0.44, ry, rw_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_idler", idler_r, idler_r, track_w * 0.78, segments=14, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.39, idler_y, idler_z), rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_tube_part( + f"{name}_sprocket", sproc_r, sproc_r, track_w * 0.82, segments=14, + mat_name="gunmetal", parent=pod, location=(-track_w * 0.41, sproc_y, sproc_z), rotation_deg=(0.0, 90.0, 0.0), + ) + + # Track belt loop + articulated grouser shoes sampled evenly around closed perimeter + # Build loop path points in (y, z) + loop_yz: list[tuple[float, float]] = [] + # Front idler arc (from top-front down to bottom-front) + for k in range(7): + ang = math.radians(95.0 + 145.0 * (k / 6.0)) + loop_yz.append((idler_y + math.cos(ang) * (idler_r + 0.025), idler_z + math.sin(ang) * (idler_r + 0.025))) + # Bottom run across roadwheels + loop_yz.append((-0.90, 0.02)) + loop_yz.append((0.90, 0.02)) + # Rear sprocket arc (from bottom-rear up to top-rear) + for k in range(7): + ang = math.radians(-65.0 + 145.0 * (k / 6.0)) + loop_yz.append((sproc_y + math.cos(ang) * (sproc_r + 0.025), sproc_z + math.sin(ang) * (sproc_r + 0.025))) + # Top return run + loop_yz.append((0.40, 0.73)) + loop_yz.append((-0.40, 0.73)) + + # Continuous inner track band via core.sweep (with up=+X, outline's h spans X and w spans thickness) + path_3d = [[0.0, y, z] for (y, z) in loop_yz] + vc.make_swept_profile( + f"{name}_track_band", + "box", + 0.030, + track_w * 0.92, + 0.030, + path_3d, + up=[1.0, 0.0, 0.0], + mat_name="rubber_dark", + parent=pod, + closed=True, + ) + + # Articulated steel grouser shoes along loop + # Compute cumulative arc length + pts = loop_yz + [loop_yz[0]] + segs = [math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]) for i in range(len(loop_yz))] + total_len = sum(segs) + n_shoes = 38 + + def build_shoes(bm: bmesh.types.BMesh) -> None: + for s_idx in range(n_shoes): + target_d = total_d = (s_idx / n_shoes) * total_len + acc = 0.0 + for i, sl in enumerate(segs): + if acc + sl >= target_d or i == len(segs) - 1: + t = (target_d - acc) / max(sl, 1e-6) + y0, z0 = pts[i] + y1, z1 = pts[i + 1] + py = y0 + (y1 - y0) * t + pz = z0 + (z1 - z0) * t + ang = math.atan2(z1 - z0, y1 - y0) + # Normal pointing outward from loop (y, z) + m = ( + Matrix.Translation((0.0, py, pz)) + @ Matrix.Rotation(ang, 4, "X") + @ Matrix.Diagonal((track_w, 0.085, 0.026, 1.0)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + break + acc += sl + + vc.make_bmesh_object(f"{name}_shoes", build_shoes, "gunmetal", parent=pod) + + # Armored track fender & upper side skirt (Brokkr plate.v0 slab) + vc.make_box(f"{name}_fender_top", (track_w + 0.06, 3.24, 0.055), "olive_armor", parent=pod, location=(0.0, -0.02, 0.79), bevel=0.008) + vc.make_box(f"{name}_fender_front", (track_w + 0.06, 0.34, 0.055), "olive_armor", parent=pod, location=(0.0, -1.72, 0.68), rotation_deg=(36.0, 0.0, 0.0), bevel=0.008) + vc.make_box(f"{name}_fender_rear", (track_w + 0.06, 0.32, 0.055), "olive_armor", parent=pod, location=(0.0, 1.66, 0.68), rotation_deg=(-36.0, 0.0, 0.0), bevel=0.008) + + # Outer bolted track skirt covering upper roadwheels + skirt_pts = [ + [side * 0.22, -1.36, 0.78], + [side * 0.22, 1.36, 0.78], + [side * 0.22, 1.18, 0.36], + [side * 0.22, -1.16, 0.36], + ] + vc.make_box( + f"{name}_skirt", + (0.045, 2.52, 0.40), + "olive_armor", + parent=pod, + location=(side * (track_w * 0.5 + 0.025), 0.0, 0.58), + bevel=0.008, + ) + + +def build_ferret() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("FerretRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # --- 1. Lower Tub & Wedge Glacis Hull (Brokkr plate.v0 convex hull) --- + vc.make_box("lower_tub", (1.28, 3.06, 0.44), "gunmetal", parent=chassis, location=(0.0, -0.04, 0.46), bevel=0.012) + + hull_pts = [ + [-0.64, -1.68, 0.46], [0.64, -1.68, 0.46], + [0.68, -1.68, 0.64], [-0.68, -1.68, 0.64], + [-0.68, -0.78, 1.04], [0.68, -0.78, 1.04], + [-0.68, 0.66, 1.04], [0.68, 0.66, 1.04], + [-0.64, 1.66, 0.80], [0.64, 1.66, 0.80], + [-0.64, 1.66, 0.50], [0.64, 1.66, 0.50], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "ferret_hull", + "mat": "olive_armor", + "bevel": 0.014, + "sides": "one", + "mirror": False, + "points": hull_pts, + "clad": { + "mat": "olive_armor", + "facets": [{"n": [0.0, -0.45, 0.89], "cos": 0.90}], + "min_area": 0.12, + "lifts": [0.008, 0.014], + "inset": 0.05, + "gap": 0.016, + "split": 0.90, + "seed": 601, + "bolt_r": 0.012, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + }, + # Sloped upper hull sponson cheek plates + { + "name": "ferret_sponson", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.76, 0.14, 0.90], + "normal": [0.85, 0.0, 0.52], + "up": [0.0, 0.0, 1.0], + "right": [0.0, -1.0, 0.0], + "outline": [[-0.94, -0.14], [0.94, -0.14], [0.76, 0.14], [-0.78, 0.14]], + "thick": 0.05, + "taper": 0.014, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.30, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Headlights, tow shackles, and flank cylindrical mufflers + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"headlight_{tag}", (0.12, 0.12, 0.10), "gunmetal", parent=chassis, location=(side * 0.82, -1.52, 0.88), bevel=0.008) + vc.make_box(f"tow_shackle_{tag}", (0.06, 0.10, 0.10), "signal_orange", parent=chassis, location=(side * 0.42, -1.72, 0.56), bevel=0.005) + # Side exhaust muffler + copper pipes + vc.make_tube_part( + f"muffler_{tag}", 0.085, 0.085, 0.62, segments=12, + mat_name="gunmetal", parent=chassis, location=(side * 0.80, 0.72, 0.92), rotation_deg=(-90.0, 0.0, 0.0), + ) + vc.make_swept_tube( + f"muffler_pipe_{tag}", + [[side * 0.62, 0.64, 0.92], [side * 0.80, 0.72, 0.92], [side * 0.80, 1.44, 0.90]], + 0.032, segments=8, mat_name="copper_rad", parent=chassis, fillet_r=0.03, + ) + + # --- 2. Wide Articulated Track Pods --- + _build_track_pod("track_pod_L", 1.0, chassis) + _build_track_pod("track_pod_R", -1.0, chassis) + + # --- 3. Low Octagonal Turret (joint.turret_yaw) --- + turret_pivot = vc.make_empty("joint.turret_yaw", parent=chassis, location=(0.0, -0.18, 1.04)) + vc.tag_joint(turret_pivot, "joint.turret_yaw", [0.0, 1.0, 0.0], -180.0, 180.0) + joints_manifest = [{"id": "joint.turret_yaw", "axis": [0.0, 1.0, 0.0], "min": -180.0, "max": 180.0}] + + # Turret ring race + vc.make_tube_part("turret_race", 0.54, 0.58, 0.07, segments=20, mat_name="gunmetal", parent=turret_pivot, location=(0.0, 0.0, 0.0)) + + turret_pts = [ + [-0.46, -0.52, 0.06], [0.46, -0.52, 0.06], + [0.54, -0.10, 0.06], [0.48, 0.56, 0.06], + [-0.48, 0.56, 0.06], [-0.54, -0.10, 0.06], + [-0.36, -0.40, 0.42], [0.36, -0.40, 0.42], + [0.42, -0.06, 0.42], [0.38, 0.46, 0.42], + [-0.38, 0.46, 0.42], [-0.42, -0.06, 0.42], + ] + turret_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "ferret_turret_shell", + "mat": "olive_armor", + "bevel": 0.012, + "sides": "one", + "mirror": False, + "points": turret_pts, + }, + ], + } + vc.make_plates(turret_doc, parent=turret_pivot) + + # Commander hatch & front optic prism + cheek pylon shelf + vc.make_tube_part("commander_cupola", 0.17, 0.18, 0.08, segments=12, mat_name="olive_armor", parent=turret_pivot, location=(-0.16, 0.14, 0.42)) + vc.make_box("turret_optic", (0.14, 0.16, 0.10), "smoked_glass", parent=turret_pivot, location=(0.18, -0.26, 0.45), bevel=0.006) + vc.make_box("turret_mantlet_collar", (0.28, 0.16, 0.22), "gunmetal", parent=turret_pivot, location=(0.0, -0.50, 0.24), bevel=0.008) + vc.make_box("cheek_pylon_shelf", (0.24, 0.34, 0.08), "gunmetal", parent=turret_pivot, location=(0.56, 0.02, 0.22), bevel=0.006) + + # --- 4. Visible Exterior Hardpoints (3x4 Dorsal Grid) --- + # 1) Front wedge glacis armor stud rail + vc.add_hardpoint_slot( + "hp.armor.glacis", + "armor", + parent=chassis, + location=(0.0, -1.24, 0.85), + rotation_deg=(-66.0, 0.0, 0.0), + size=(1.12, 0.34, 0.08), + ) + # 2) Main turret weapon collar + vc.add_hardpoint_slot( + "hp.weapon.turret", + "weapon", + parent=turret_pivot, + location=(0.0, -0.02, 0.43), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.62, 0.62, 0.10), + ) + # 3) Turret cheek pod weapon collar (on left +X cheek pylon shelf) + vc.add_hardpoint_slot( + "hp.weapon.pod", + "weapon", + parent=turret_pivot, + location=(0.58, 0.02, 0.27), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.34, 0.34, 0.07), + ) + # 4) Rear engine bay frame + vc.add_hardpoint_slot( + "hp.engine.rear", + "engine", + parent=chassis, + location=(0.0, 0.82, 0.94), + rotation_deg=(-12.0, 0.0, 0.0), + size=(0.86, 0.66, 0.13), + ) + # 5) Rear deck copper radiator louver bay + vc.add_hardpoint_slot( + "hp.radiator.deck", + "radiator", + parent=chassis, + location=(0.0, 1.42, 0.81), + rotation_deg=(-14.0, 0.0, 0.0), + size=(0.88, 0.44, 0.09), + ) + + # --- 5. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "ferret" / "ferret.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "ferret" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "ferret_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="ferret", + name="Ferret", + vehicle_class="Light Tracked Scout Tankette", + grid_width=3, + grid_height=4, + mask=[ + "###", + "###", + "###", + "###", + ], + hardpoints=[ + {"id": "hp.armor.glacis", "kind": "armor", "x": 0, "y": 0, "w": 3, "h": 1, "modelNodeId": "hp.armor.glacis"}, + {"id": "hp.weapon.pod", "kind": "weapon", "x": 0, "y": 1, "w": 1, "h": 1, "modelNodeId": "hp.weapon.pod"}, + {"id": "hp.weapon.turret", "kind": "weapon", "x": 1, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.weapon.turret"}, + {"id": "hp.engine.rear", "kind": "engine", "x": 2, "y": 2, "w": 1, "h": 2, "modelNodeId": "hp.engine.rear"}, + {"id": "hp.radiator.deck", "kind": "radiator", "x": 1, "y": 3, "w": 1, "h": 1, "modelNodeId": "hp.radiator.deck"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[ferret] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "ferret", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_ferret() diff --git a/tools/vehicles/build_gear.py b/tools/vehicles/build_gear.py new file mode 100644 index 0000000..60b095d --- /dev/null +++ b/tools/vehicles/build_gear.py @@ -0,0 +1,144 @@ +"""Build the 6 modular starter gear GLBs into assets/gear/.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _export_gear(name: str, root) -> tuple[int, dict]: + glb_path = vc.ASSETS_GEAR_DIR / f"{name}.glb" + tris, bounds = vc.export_vehicle_glb(glb_path, root=root) + print(f"[gear:{name}] tris={tris} bounds={bounds} glb={glb_path}") + return tris, bounds + + +def build_mg_762() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Pintle base + yoke + receiver + perforated barrel shroud + side ammo box + spade grips + vc.make_tube_part("pintle_base", 0.14, 0.12, 0.06, segments=12, mat_name="gunmetal", parent=root) + vc.make_box("cradle_yoke", (0.14, 0.18, 0.18), "gunmetal", parent=root, location=(0.0, 0.0, 0.15), bevel=0.006) + vc.make_box("receiver", (0.12, 0.44, 0.14), "olive_armor", parent=root, location=(0.0, -0.04, 0.28), bevel=0.006) + vc.make_tube_part("barrel_shroud", 0.032, 0.028, 0.48, segments=10, mat_name="gunmetal", parent=root, location=(0.0, -0.24, 0.29), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_tube_part("barrel_inner", 0.014, 0.014, 0.68, segments=8, mat_name="gunmetal", parent=root, location=(0.0, -0.24, 0.29), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_box("ammo_box", (0.14, 0.22, 0.16), "olive_armor", parent=root, location=(0.14, -0.02, 0.25), bevel=0.006) + vc.make_box("ammo_latch", (0.04, 0.10, 0.04), "signal_orange", parent=root, location=(0.14, -0.02, 0.34), bevel=0.003) + for side in (-1.0, 1.0): + vc.make_tube_part(f"grip_{'L' if side > 0 else 'R'}", 0.012, 0.012, 0.10, segments=6, mat_name="rubber_dark", parent=root, location=(side * 0.06, 0.22, 0.23)) + _export_gear("mg_762", root) + + +def build_autocannon() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Turret base ring + twin armored trunnion cheeks + dual 20mm barrels + twin ammo drums + vc.make_tube_part("turret_collar", 0.26, 0.24, 0.08, segments=16, mat_name="gunmetal", parent=root) + vc.make_box("gun_housing", (0.30, 0.46, 0.24), "olive_armor", parent=root, location=(0.0, 0.04, 0.20), bevel=0.010) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_tube_part(f"barrel_jacket_{tag}", 0.036, 0.030, 0.42, segments=10, mat_name="gunmetal", parent=root, location=(side * 0.085, -0.18, 0.22), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_tube_part(f"barrel_tube_{tag}", 0.018, 0.018, 0.88, segments=8, mat_name="gunmetal", parent=root, location=(side * 0.085, -0.18, 0.22), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_tube_part(f"muzzle_brake_{tag}", 0.028, 0.028, 0.09, segments=8, mat_name="copper_rad", parent=root, location=(side * 0.085, -1.00, 0.22), rotation_deg=(90.0, 0.0, 0.0)) + vc.make_tube_part(f"ammo_drum_{tag}", 0.13, 0.13, 0.16, segments=14, mat_name="olive_armor", parent=root, location=(side * 0.22, 0.14, 0.24), rotation_deg=(0.0, 90.0 * side, 0.0)) + vc.make_box("optic_pod", (0.10, 0.14, 0.09), "smoked_glass", parent=root, location=(0.0, -0.08, 0.36), bevel=0.005) + _export_gear("autocannon", root) + + +def build_recoilless() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Pedestal + heavy long recoilless tube + flared rear venturi + top optic rail + vc.make_tube_part("base_flange", 0.20, 0.18, 0.07, segments=14, mat_name="gunmetal", parent=root) + vc.make_box("trunnion_post", (0.14, 0.20, 0.20), "gunmetal", parent=root, location=(0.0, 0.02, 0.16), bevel=0.008) + tube_prof = [ + [0.055, -0.58], + [0.085, -0.58], + [0.095, -0.35], + [0.095, 0.42], + [0.072, 0.46], + [0.072, 0.78], + [0.088, 0.82], + [0.062, 0.82], + [0.055, 0.44], + ] + vc.make_lathe_part("launcher_tube", tube_prof, segments=16, loop=True, smooth=True, mat_name="olive_armor", parent=root, location=(0.0, 0.0, 0.32), rotation_deg=(-90.0, 0.0, 0.0)) + vc.make_box("breech_band", (0.20, 0.12, 0.20), "signal_orange", parent=root, location=(0.0, 0.26, 0.32), bevel=0.006) + vc.make_tube_part("sight_tube", 0.028, 0.032, 0.22, segments=10, mat_name="gunmetal", parent=root, location=(0.11, -0.02, 0.36), rotation_deg=(90.0, 0.0, 0.0)) + _export_gear("recoilless", root) + + +def build_copper_rad() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Industrial copper finned radiator bank + armored end tanks + coolant pipes + base flange + vc.make_box("base_flange", (0.48, 0.42, 0.045), "gunmetal", parent=root, location=(0.0, 0.0, 0.0225), bevel=0.006) + vc.make_kit_part( + "copper_fins", + "mechanical", + "radiator_stack", + {"fins": 10, "fin_w": 0.36, "fin_h": 0.24, "fin_t": 0.008, "pitch": 0.032, "segments": 10}, + mat_name="copper_rad", + parent=root, + location=(0.0, -0.145, 0.18), + rotation_deg=(-90.0, 0.0, 0.0), + ) + for side in (-1.0, 1.0): + vc.make_box(f"end_tank_{'L' if side > 0 else 'R'}", (0.06, 0.38, 0.26), "gunmetal", parent=root, location=(side * 0.21, 0.0, 0.18), bevel=0.008) + vc.make_swept_tube(f"coolant_pipe_{'L' if side > 0 else 'R'}", [[side * 0.21, 0.14, 0.26], [side * 0.21, 0.24, 0.18], [side * 0.16, 0.24, 0.06]], 0.018, segments=8, mat_name="copper_rad", parent=root, fillet_r=0.02) + vc.make_box("top_cap_bar", (0.44, 0.06, 0.04), "signal_orange", parent=root, location=(0.0, -0.15, 0.31), bevel=0.004) + _export_gear("copper_rad", root) + + +def build_gilded_lance() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Imperial Tourist ornate gilded thermal lance with ivory cowl, gold flutes, and cyan condenser rings + vc.make_tube_part("imperial_base", 0.24, 0.21, 0.08, segments=18, mat_name="imperial_gold", parent=root) + vc.make_box("ivory_cowl", (0.28, 0.52, 0.22), "imperial_ivory", parent=root, location=(0.0, 0.02, 0.20), bevel=0.014) + vc.make_box("gold_crest", (0.10, 0.44, 0.08), "imperial_gold", parent=root, location=(0.0, 0.02, 0.32), bevel=0.008) + vc.make_tube_part("lance_core", 0.042, 0.026, 0.96, segments=14, mat_name="imperial_gold", parent=root, location=(0.0, -0.20, 0.22), rotation_deg=(90.0, 0.0, 0.0)) + for i, dy in enumerate((-0.42, -0.64, -0.86)): + vc.make_tube_part(f"condenser_ring_{i}", 0.062 - i * 0.006, 0.062 - i * 0.006, 0.04, segments=14, mat_name="cyan_coil", parent=root, location=(0.0, dy, 0.22), rotation_deg=(90.0, 0.0, 0.0)) + _export_gear("gilded_lance", root) + + +def build_gold_radiator() -> None: + vc.reset_scene() + vc.ensure_materials() + root = vc.make_empty("GearRoot") + # Imperial Tourist ornate gilded louver array with ivory housing & cyan thermal core + vc.make_box("imperial_flange", (0.48, 0.42, 0.045), "imperial_gold", parent=root, location=(0.0, 0.0, 0.0225), bevel=0.006) + vc.make_box("ivory_shroud", (0.44, 0.38, 0.22), "imperial_ivory", parent=root, location=(0.0, 0.0, 0.155), bevel=0.012) + vc.make_box("cyan_core", (0.34, 0.28, 0.16), "cyan_coil", parent=root, location=(0.0, 0.0, 0.16), bevel=0.004) + def build_gold_vanes(bm: bmesh.types.BMesh) -> None: + for i in range(7): + y = -0.14 + 0.28 * (i / 6.0) + m = Matrix.Translation((0.0, y, 0.265)) @ Matrix.Rotation(math.radians(20.0), 4, "X") @ Matrix.Diagonal((0.38, 0.022, 0.055, 1.0)) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + vc.make_bmesh_object("gold_vanes", build_gold_vanes, "imperial_gold", parent=root) + _export_gear("gold_radiator", root) + + +def build_all_gear() -> None: + build_mg_762() + build_autocannon() + build_recoilless() + build_copper_rad() + build_gilded_lance() + build_gold_radiator() + + +if __name__ == "__main__": + build_all_gear() diff --git a/tools/vehicles/build_hornet.py b/tools/vehicles/build_hornet.py new file mode 100644 index 0000000..281cc7e --- /dev/null +++ b/tools/vehicles/build_hornet.py @@ -0,0 +1,397 @@ +"""Build the Hornet (Light Ducted-Fan VTOL Gunship) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +from mathutils import Matrix + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _build_ducted_nacelle(name: str, side: float, parent, joints_manifest: list[dict]) -> None: + """Build a pivoting armored ducted-fan nacelle with inner copper thrust collar and spinning rotor.""" + nacelle_id = f"joint.nacelle_{'l' if side > 0 else 'r'}" + nacelle_pivot = vc.make_empty( + nacelle_id, + parent=parent, + location=(side * 1.18, 0.10, 1.32), + rotation_deg=(-18.0, 0.0, 0.0), + ) + vc.tag_joint(nacelle_pivot, nacelle_id, [1.0, 0.0, 0.0], -45.0, 75.0) + joints_manifest.append({"id": nacelle_id, "axis": [1.0, 0.0, 0.0], "min": -45.0, "max": 75.0}) + + # Upper olive-drab armored duct shroud (CCW in (r, z) for core.lathe) + shroud_prof = [ + [0.34, -0.06], + [0.44, -0.06], + [0.47, 0.02], + [0.47, 0.22], + [0.43, 0.28], + [0.35, 0.28], + [0.33, 0.20], + [0.34, -0.06], + ] + vc.make_lathe_part( + f"{name}_shroud", + shroud_prof[:-1], + segments=22, + loop=True, + smooth=True, + mat_name="olive_armor", + parent=nacelle_pivot, + ) + # Lower copper thermal exhaust skirt + skirt_prof = [ + [0.33, -0.20], + [0.41, -0.20], + [0.44, -0.06], + [0.34, -0.06], + ] + vc.make_lathe_part( + f"{name}_skirt", + skirt_prof, + segments=22, + loop=True, + smooth=True, + mat_name="copper_rad", + parent=nacelle_pivot, + ) + # Stator cross vanes + hinge yoke collar + for ang_deg in (0.0, 90.0): + vc.make_box( + f"{name}_stator_{int(ang_deg)}", + (0.68, 0.04, 0.06), + "gunmetal", + parent=nacelle_pivot, + location=(0.0, 0.0, -0.08), + rotation_deg=(0.0, 0.0, ang_deg), + bevel=0.004, + ) + vc.make_box( + f"{name}_hinge_lug", + (0.16, 0.22, 0.16), + "gunmetal", + parent=nacelle_pivot, + location=(-side * 0.44, 0.0, 0.08), + bevel=0.008, + ) + + # Spinning rotor hub + 4 pitched fan blades (about glTF +Y = Blender +Z) + rotor_id = f"joint.rotor_{'l' if side > 0 else 'r'}" + rotor_pivot = vc.make_empty(rotor_id, parent=nacelle_pivot, location=(0.0, 0.0, 0.04)) + vc.tag_joint(rotor_pivot, rotor_id, [0.0, 1.0, 0.0], -360.0, 360.0) + joints_manifest.append({"id": rotor_id, "axis": [0.0, 1.0, 0.0], "min": -360.0, "max": 360.0}) + + spinner_prof = [ + [0.0, -0.04], + [0.10, -0.04], + [0.10, 0.06], + [0.06, 0.16], + [0.0, 0.22], + ] + vc.make_lathe_part(f"{name}_spinner", spinner_prof, segments=14, loop=False, smooth=True, mat_name="gunmetal", parent=rotor_pivot) + + def build_blades(bm: bmesh.types.BMesh) -> None: + for i in range(4): + a = i * math.pi * 0.5 + m = ( + Matrix.Rotation(a, 4, "Z") + @ Matrix.Translation((0.20, 0.0, 0.02)) + @ Matrix.Rotation(math.radians(22.0), 4, "X") + @ Matrix.Diagonal((0.24, 0.085, 0.014, 1.0)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + + vc.make_bmesh_object(f"{name}_blades", build_blades, "gunmetal", parent=rotor_pivot) + + +def build_hornet() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("HornetRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # --- 1. Rugged Steel Landing Skids (grounded at Z = 0) --- + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_swept_tube( + f"skid_runner_{tag}", + [ + [side * 0.72, -1.56, 0.16], + [side * 0.72, -1.24, 0.032], + [side * 0.72, 1.06, 0.032], + ], + 0.032, + segments=8, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.08, + ) + # Front & rear diagonal skid struts up to fuselage belly + for s_tag, sy_lo, sy_hi in (("f", -0.82, -0.68), ("r", 0.52, 0.44)): + vc.make_swept_tube( + f"skid_strut_{tag}_{s_tag}", + [[side * 0.72, sy_lo, 0.04], [side * 0.40, sy_hi, 0.54]], + 0.026, + segments=8, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.0, + ) + + # --- 2. Faceted Armored Cockpit & Fuselage Hull (Brokkr plate.v0) --- + hull_pts = [ + [-0.28, -1.86, 0.56], [0.28, -1.86, 0.56], + [-0.36, -1.78, 0.78], [0.36, -1.78, 0.78], + [-0.58, -0.86, 0.46], [0.58, -0.86, 0.46], + [-0.64, -0.64, 1.02], [0.64, -0.64, 1.02], + [-0.64, 0.76, 1.02], [0.64, 0.76, 1.02], + [-0.56, 0.88, 0.54], [0.56, 0.88, 0.54], + [-0.44, 0.64, 1.44], [0.44, 0.64, 1.44], + [-0.44, -0.26, 1.44], [0.44, -0.26, 1.44], + ] + canopy_pts = [ + [-0.34, -1.66, 0.78], [0.34, -1.66, 0.78], + [-0.52, -0.88, 1.02], [0.52, -0.88, 1.02], + [-0.42, -0.28, 1.40], [0.42, -0.28, 1.40], + [-0.36, -0.88, 1.38], [0.36, -0.88, 1.38], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "hornet_fuselage", + "mat": "olive_armor", + "bevel": 0.014, + "sides": "one", + "mirror": False, + "points": hull_pts, + }, + { + "name": "hornet_canopy", + "mat": "smoked_glass", + "bevel": 0.008, + "sides": "one", + "mirror": False, + "points": canopy_pts, + }, + # Cheek armor skirts with bolts + { + "name": "hornet_cheek", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.58, -0.62, 0.76], + "normal": [0.92, -0.28, 0.26], + "up": [0.0, 0.0, 1.0], + "right": [-0.28, -0.96, 0.0], + "outline": [[-0.56, -0.14], [0.52, -0.18], [0.48, 0.16], [-0.46, 0.14]], + "thick": 0.04, + "taper": 0.012, + "back": 0.90, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.24, "mat": "gunmetal", "params": "r=0.011"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Canopy structural armor ribs + nose EO/IR optics pod + vc.make_swept_tube( + "canopy_spine", + [[0.0, -1.68, 0.78], [0.0, -0.90, 1.40], [0.0, -0.26, 1.44]], + 0.024, segments=6, mat_name="olive_armor", parent=chassis, fillet_r=0.04, + ) + for side in (-1.0, 1.0): + vc.make_swept_tube( + f"canopy_rib_{'L' if side > 0 else 'R'}", + [[side * 0.33, -1.65, 0.78], [side * 0.37, -0.89, 1.38], [side * 0.43, -0.28, 1.42]], + 0.020, segments=6, mat_name="olive_armor", parent=chassis, fillet_r=0.04, + ) + vc.make_box("nose_optics_housing", (0.24, 0.20, 0.18), "gunmetal", parent=chassis, location=(0.0, -1.86, 0.66), bevel=0.01) + vc.make_tube_part("nose_optics_lens", 0.065, 0.065, 0.06, segments=12, mat_name="smoked_glass", parent=chassis, location=(0.0, -1.94, 0.66), rotation_deg=(90.0, 0.0, 0.0)) + + # Stub wings + nacelle outrigger arms + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box( + f"stub_wing_{tag}", + (0.68, 0.56, 0.09), + "olive_armor", + parent=chassis, + location=(side * 0.74, 0.14, 0.74), + rotation_deg=(0.0, side * 8.0, side * -10.0), + bevel=0.01, + ) + vc.make_box( + f"nacelle_arm_{tag}", + (0.46, 0.30, 0.18), + "gunmetal", + parent=chassis, + location=(side * 0.62, 0.10, 1.32), + bevel=0.01, + ) + + # --- 3. Pivoting Ducted-Fan Nacelles + Hydraulic Tilt Actuators --- + joints_manifest: list[dict] = [] + for side in (1.0, -1.0): + tag = "L" if side > 0 else "R" + _build_ducted_nacelle(f"nacelle_{tag}", side, chassis, joints_manifest) + # Dual hydraulic tilt actuator from dorsal shoulder clevis out to nacelle hinge lug + vc.make_box(f"tilt_clevis_{tag}", (0.10, 0.14, 0.10), "gunmetal", parent=chassis, location=(side * 0.44, -0.10, 1.38), bevel=0.005) + vc.make_ram_span( + f"tilt_actuator_{tag}", + [side * 0.44, -0.10, 1.38], + [side * 0.78, 0.08, 1.38], + body_r=0.028, + rod_r=0.015, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="copper_rad", + ) + + # --- 4. Skeletal Truss Tail Boom & V/T Tailfins --- + # Rear boom mounting bulkhead + 3-chord space-frame tail boom anchored inside fuselage + vc.make_box("tail_boom_collar", (0.44, 0.28, 0.42), "gunmetal", parent=chassis, location=(0.0, 0.74, 1.10), bevel=0.01) + boom_top_l = [0.16, 0.62, 1.24] + boom_top_r = [-0.16, 0.62, 1.24] + boom_bot = [0.0, 0.62, 0.94] + tail_top_l = [0.07, 2.38, 1.34] + tail_top_r = [-0.07, 2.38, 1.34] + tail_bot = [0.0, 2.38, 1.16] + for cname, p0, p1 in [ + ("boom_tl", boom_top_l, tail_top_l), + ("boom_tr", boom_top_r, tail_top_r), + ("boom_bt", boom_bot, tail_bot), + ]: + vc.make_swept_tube(cname, [p0, p1], 0.020, segments=6, mat_name="gunmetal", parent=chassis, fillet_r=0.0) + + # Truss bay diagonals along the tail boom + n_bays = 5 + def lerp3(a, b, t): + return [a[k] + (b[k] - a[k]) * t for k in range(3)] + + for i in range(n_bays): + t0 = i / n_bays + t1 = (i + 1) / n_bays + p_tl0, p_tr0, p_b0 = lerp3(boom_top_l, tail_top_l, t0), lerp3(boom_top_r, tail_top_r, t0), lerp3(boom_bot, tail_bot, t0) + p_tl1, p_tr1, p_b1 = lerp3(boom_top_l, tail_top_l, t1), lerp3(boom_top_r, tail_top_r, t1), lerp3(boom_bot, tail_bot, t1) + vc.make_swept_tube(f"boom_cross_{i}", [p_tl1, p_tr1, p_b1, p_tl1], 0.012, segments=6, mat_name="gunmetal", parent=chassis, fillet_r=0.0) + vc.make_swept_tube(f"boom_diag_l_{i}", [p_tl0, p_b1], 0.011, segments=6, mat_name="gunmetal", parent=chassis, fillet_r=0.0) + vc.make_swept_tube(f"boom_diag_r_{i}", [p_tr0, p_b1], 0.011, segments=6, mat_name="gunmetal", parent=chassis, fillet_r=0.0) + + # Swept-back V-tail stabilizers + ventral fin + tail hub + vc.make_box("tail_fin_hub", (0.16, 0.24, 0.20), "gunmetal", parent=chassis, location=(0.0, 2.36, 1.26), bevel=0.008) + for side in (-1.0, 1.0): + vc.make_box( + f"vtail_{'L' if side > 0 else 'R'}", + (0.04, 0.34, 0.62), + "olive_armor", + parent=chassis, + location=(side * 0.24, 2.40, 1.54), + rotation_deg=(22.0, side * -38.0, 0.0), + bevel=0.006, + ) + vc.make_box("ventral_fin", (0.035, 0.26, 0.24), "olive_armor", parent=chassis, location=(0.0, 2.36, 1.04), rotation_deg=(22.0, 0.0, 0.0), bevel=0.006) + + # --- 5. Visible Exterior Hardpoints (4x4 Dorsal Grid) --- + # 1) Chin gimbal collar (under nose, pointing +Z forward and -Y downward) + vc.add_hardpoint_slot( + "hp.weapon.chin", + "weapon", + parent=chassis, + location=(0.0, -1.46, 0.48), + rotation_deg=(0.0, 180.0, 0.0), + size=(0.42, 0.42, 0.08), + ) + # 2 & 3) Stub-wing weapon pylons (under left/right wings) + vc.add_hardpoint_slot( + "hp.weapon.wing_l", + "weapon", + parent=chassis, + location=(0.88, 0.14, 0.69), + rotation_deg=(0.0, 180.0, 0.0), + size=(0.34, 0.34, 0.07), + ) + vc.add_hardpoint_slot( + "hp.weapon.wing_r", + "weapon", + parent=chassis, + location=(-0.88, 0.14, 0.69), + rotation_deg=(0.0, 180.0, 0.0), + size=(0.34, 0.34, 0.07), + ) + # 4) Dorsal turbine core engine bay + vc.add_hardpoint_slot( + "hp.engine.core", + "engine", + parent=chassis, + location=(0.0, 0.26, 1.44), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.74, 0.80, 0.13), + ) + # 5 & 6) Twin copper-louvered nacelle root exhaust radiator bays + vc.add_hardpoint_slot( + "hp.radiator.nacelle_l", + "radiator", + parent=chassis, + location=(0.58, -0.32, 1.24), + rotation_deg=(72.0, 0.0, 34.0), + size=(0.36, 0.32, 0.09), + ) + vc.add_hardpoint_slot( + "hp.radiator.nacelle_r", + "radiator", + parent=chassis, + location=(-0.58, -0.32, 1.24), + rotation_deg=(72.0, 0.0, -34.0), + size=(0.36, 0.32, 0.09), + ) + + # --- 6. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "hornet" / "hornet.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "hornet" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "hornet_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="hornet", + name="Hornet", + vehicle_class="Light Ducted-Fan VTOL Gunship", + grid_width=4, + grid_height=4, + mask=[ + ".##.", + "####", + "####", + ".##.", + ], + hardpoints=[ + {"id": "hp.weapon.chin", "kind": "weapon", "x": 1, "y": 0, "w": 1, "h": 2, "modelNodeId": "hp.weapon.chin"}, + {"id": "hp.radiator.nacelle_l", "kind": "radiator", "x": 0, "y": 1, "w": 1, "h": 1, "modelNodeId": "hp.radiator.nacelle_l"}, + {"id": "hp.radiator.nacelle_r", "kind": "radiator", "x": 3, "y": 1, "w": 1, "h": 1, "modelNodeId": "hp.radiator.nacelle_r"}, + {"id": "hp.weapon.wing_l", "kind": "weapon", "x": 0, "y": 2, "w": 1, "h": 1, "modelNodeId": "hp.weapon.wing_l"}, + {"id": "hp.engine.core", "kind": "engine", "x": 1, "y": 2, "w": 2, "h": 2, "modelNodeId": "hp.engine.core"}, + {"id": "hp.weapon.wing_r", "kind": "weapon", "x": 3, "y": 2, "w": 1, "h": 1, "modelNodeId": "hp.weapon.wing_r"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[hornet] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "hornet", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_hornet() diff --git a/tools/vehicles/build_jackal.py b/tools/vehicles/build_jackal.py new file mode 100644 index 0000000..2e18b67 --- /dev/null +++ b/tools/vehicles/build_jackal.py @@ -0,0 +1,403 @@ +"""Build the Jackal (Light Wheeled Dune Buggy) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def build_jackal() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("JackalRoot") + chassis = vc.make_empty("Chassis", parent=root) + + # Dimensions & key coordinates (Blender: -Y forward, +Z up, +X left) + front_y = -1.12 + rear_y = 1.08 + track_x = 0.84 + wheel_r = 0.41 + wheel_w = 0.29 + axle_z = wheel_r + + # --- 1. Belly pan & central backbone --- + vc.make_box("belly_pan", (0.76, 2.24, 0.08), "gunmetal", parent=chassis, location=(0.0, 0.0, 0.34), bevel=0.01) + vc.make_box("front_diff", (0.28, 0.28, 0.20), "gunmetal", parent=chassis, location=(0.0, front_y, 0.42), bevel=0.01) + vc.make_box("rear_transaxle", (0.34, 0.36, 0.24), "gunmetal", parent=chassis, location=(0.0, rear_y, 0.44), bevel=0.01) + + # --- 2. Tubular Chromoly Rollcage & Bullbar (Brokkr core.sweep) --- + r_main = 0.025 + r_brace = 0.020 + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + # Lower sill rail + vc.make_swept_tube( + f"cage_sill_{tag}", + [ + [side * 0.30, -1.42, 0.48], + [side * 0.48, -0.78, 0.36], + [side * 0.48, 0.56, 0.36], + [side * 0.42, 1.38, 0.56], + ], + r_main, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + # Main A-pillar -> roof rail -> fastback B/C-pillar + vc.make_swept_tube( + f"cage_arch_{tag}", + [ + [side * 0.34, -1.24, 0.62], + [side * 0.44, -0.70, 0.82], + [side * 0.39, -0.14, 1.44], + [side * 0.39, 0.44, 1.44], + [side * 0.42, 1.38, 0.82], + [side * 0.42, 1.38, 0.56], + ], + r_main, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + # Mid beltline side bar + diagonal door brace + vc.make_swept_tube( + f"cage_belt_{tag}", + [ + [side * 0.45, -0.70, 0.78], + [side * 0.48, 0.52, 0.78], + [side * 0.42, 1.36, 0.80], + ], + r_brace, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + vc.make_swept_tube( + f"cage_diag_{tag}", + [[side * 0.46, -0.45, 0.42], [side * 0.41, 0.42, 1.42]], + r_brace, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + # Shock tower hoop + vc.make_swept_tube( + f"shock_hoop_{tag}", + [ + [side * 0.32, -1.28, 0.54], + [side * 0.38, -1.04, 0.80], + [side * 0.38, -0.78, 0.74], + ], + r_brace, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + + # Transverse rollcage crossbars & front tubular bullbar + for idx, (y_pos, z_pos, half_w) in enumerate([ + (-0.70, 0.82, 0.44), + (-0.14, 1.44, 0.39), + (0.44, 1.44, 0.39), + (0.54, 0.78, 0.46), + (1.38, 0.82, 0.42), + (1.38, 0.56, 0.42), + ]): + vc.make_swept_tube( + f"cage_cross_{idx}", + [[-half_w, y_pos, z_pos], [half_w, y_pos, z_pos]], + r_brace, + segments=8, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.0, + ) + + # Front stinger bullbar + twin headlights + vc.make_swept_tube( + "front_bullbar", + [ + [-0.32, -1.40, 0.48], + [-0.24, -1.64, 0.56], + [-0.16, -1.68, 0.68], + [0.16, -1.68, 0.68], + [0.24, -1.64, 0.56], + [0.32, -1.40, 0.48], + ], + r_main, + segments=8, + mat_name="gunmetal", + parent=chassis, + ) + for side in (-1.0, 1.0): + vc.make_tube_part( + f"headlight_{'L' if side > 0 else 'R'}", + r0=0.045, + r1=0.055, + length=0.08, + segments=12, + mat_name="gunmetal", + parent=chassis, + location=(side * 0.28, -1.46, 0.66), + rotation_deg=(90.0, 0.0, 0.0), + ) + + # --- 3. Hard Armour Plates (Brokkr plate.v0) --- + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "jackal_side", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.47, -0.05, 0.58], + "normal": [1.0, 0.0, 0.14], + "up": [0.0, 0.0, 1.0], + "right": [0.0, -1.0, 0.0], + "outline": [[-0.58, -0.16], [0.58, -0.14], [0.68, 0.16], [-0.42, 0.22]], + "thick": 0.04, + "taper": 0.015, + "back": 0.92, + }, + "clad": { + "mat": "olive_armor", + "facets": "outer", + "min_area": 0.04, + "lifts": [0.008, 0.012], + "inset": 0.04, + "gap": 0.015, + "split": 0.55, + "seed": 401, + "bolt_r": 0.012, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.26, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + { + "name": "jackal_hood", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "one", + "mirror": False, + "slab": { + "at": [0.0, -0.98, 0.73], + "normal": [0.0, -0.32, 0.95], + "up": [0.0, -0.95, -0.32], + "right": [1.0, 0.0, 0.0], + "outline": [[-0.28, 0.30], [0.28, 0.30], [0.38, -0.28], [-0.38, -0.28]], + "thick": 0.045, + "taper": 0.018, + "back": 0.90, + }, + "clad": { + "mat": "olive_armor", + "facets": "outer", + "min_area": 0.05, + "lifts": [0.008, 0.014], + "inset": 0.04, + "gap": 0.014, + "split": 0.60, + "seed": 402, + "bolt_r": 0.012, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.24, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + { + "name": "jackal_roof", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "one", + "mirror": False, + "slab": { + "at": [0.0, 0.14, 1.455], + "normal": [0.0, 0.0, 1.0], + "up": [0.0, -1.0, 0.0], + "right": [1.0, 0.0, 0.0], + "outline": {"w": 0.74, "h": 0.62, "clip": 0.08}, + "thick": 0.036, + "taper": 0.012, + "back": 0.94, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.22, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # --- 4. Cockpit Seats & Firewall --- + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"seat_base_{tag}", (0.32, 0.34, 0.08), "rubber_dark", parent=chassis, location=(side * 0.20, 0.08, 0.42), bevel=0.01) + vc.make_box(f"seat_back_{tag}", (0.30, 0.08, 0.48), "rubber_dark", parent=chassis, location=(side * 0.20, 0.24, 0.68), rotation_deg=(14.0, 0.0, 0.0), bevel=0.01) + vc.make_box("rear_firewall", (0.76, 0.04, 0.42), "gunmetal", parent=chassis, location=(0.0, 0.46, 0.60), bevel=0.005) + vc.make_swept_tube("steer_col", [[0.18, -0.58, 0.80], [0.18, -0.34, 0.92]], 0.018, segments=8, mat_name="gunmetal", parent=chassis, fillet_r=0.0) + + # --- 5. Double-Wishbone Suspension, Coilovers & 4 Knobby Wheels --- + joints_manifest: list[dict] = [] + + for is_front, y_ax, prefix in [(True, front_y, "f"), (False, rear_y, "r")]: + for side, s_tag in [(1.0, "l"), (-1.0, "r")]: + j_suffix = f"{prefix}{s_tag}" + in_x = side * 0.24 + out_x = side * 0.68 + # Upper & lower A-arms (two separate wishbone legs meeting at the ball joint) + for leg_tag, dy in (("a", -0.16), ("b", 0.16)): + vc.make_swept_tube( + f"wishbone_lo_{j_suffix}_{leg_tag}", + [[in_x, y_ax + dy, 0.36], [out_x, y_ax, axle_z - 0.06]], + 0.018, + segments=6, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.0, + ) + for leg_tag, dy in (("a", -0.14), ("b", 0.14)): + vc.make_swept_tube( + f"wishbone_hi_{j_suffix}_{leg_tag}", + [[in_x, y_ax + dy, 0.52], [out_x, y_ax, axle_z + 0.08]], + 0.016, + segments=6, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.0, + ) + # Coilover shock strut from knuckle up to shock tower + tower_z = 0.80 if is_front else 0.86 + tower_y = y_ax + (0.04 if is_front else -0.06) + vc.make_ram_span( + f"coilover_{j_suffix}", + [side * 0.40, tower_y, tower_z], + [side * 0.62, y_ax, axle_z - 0.02], + body_r=0.028, + rod_r=0.016, + parent=chassis, + mat_barrel="gunmetal", + mat_rod="gunmetal", + coil_rings=6, + ) + + # Steering knuckle (front only) + wheel hub spin joint + knuckle_loc = (side * track_x, y_ax, axle_z) + if is_front: + steer_id = f"joint.steer_{j_suffix}" + steer_node = vc.make_empty(steer_id, parent=chassis, location=(side * 0.68, y_ax, axle_z)) + vc.tag_joint(steer_node, steer_id, [0.0, 1.0, 0.0], -32.0, 32.0) + joints_manifest.append({"id": steer_id, "axis": [0.0, 1.0, 0.0], "min": -32.0, "max": 32.0}) + vc.make_box(f"knuckle_{j_suffix}", (0.08, 0.11, 0.18), "gunmetal", parent=steer_node, bevel=0.005) + wheel_parent = steer_node + wheel_loc = (side * (track_x - 0.68), 0.0, 0.0) + else: + vc.make_box(f"hub_carrier_{j_suffix}", (0.10, 0.12, 0.18), "gunmetal", parent=chassis, location=(side * 0.68, y_ax, axle_z), bevel=0.005) + wheel_parent = chassis + wheel_loc = knuckle_loc + + wheel_id = f"joint.wheel_{j_suffix}" + wheel_pivot = vc.make_knobby_wheel( + wheel_id, + radius=wheel_r, + width=wheel_w, + parent=wheel_parent, + location=wheel_loc, + tread_lugs=16, + rim_segments=18, + side_sign=int(side), + ) + wheel_pivot.name = wheel_id + vc.tag_joint(wheel_pivot, wheel_id, [1.0, 0.0, 0.0], -360.0, 360.0) + joints_manifest.append({"id": wheel_id, "axis": [1.0, 0.0, 0.0], "min": -360.0, "max": 360.0}) + + # --- 6. Visible Exterior Hardpoint Slots --- + # 1) Roof weapon collar ring + vc.add_hardpoint_slot( + "hp.weapon.roof", + "weapon", + parent=chassis, + location=(0.0, 0.14, 1.47), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.62, 0.62, 0.10), + ) + # 2) Open rear engine bay frame + twin exhaust sweeps + vc.add_hardpoint_slot( + "hp.engine.rear", + "engine", + parent=chassis, + location=(0.0, 0.90, 0.62), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.62, 0.72, 0.16), + ) + for side in (-1.0, 1.0): + vc.make_swept_tube( + f"exhaust_{'L' if side > 0 else 'R'}", + [ + [side * 0.24, 0.78, 0.68], + [side * 0.36, 1.12, 0.66], + [side * 0.38, 1.48, 0.74], + ], + 0.028, + segments=8, + mat_name="copper_rad", + parent=chassis, + ) + # 3) Upright rear copper radiator louver bay (tilted -58 deg so fins & copper header read in hero + dorsal) + vc.add_hardpoint_slot( + "hp.radiator.rear", + "radiator", + parent=chassis, + location=(0.0, 1.38, 0.96), + rotation_deg=(-58.0, 0.0, 0.0), + size=(0.58, 0.44, 0.11), + ) + vc.make_box("rad_header_tank", (0.58, 0.09, 0.08), "copper_rad", parent=chassis, location=(0.0, 1.46, 1.15), bevel=0.008) + + # --- 7. Export GLB, Manifest & 4-Panel Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "jackal" / "jackal.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "jackal" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "jackal_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="jackal", + name="Jackal", + vehicle_class="Light Wheeled Dune Buggy", + grid_width=3, + grid_height=4, + mask=[ + "###", + "###", + "###", + "###", + ], + hardpoints=[ + {"id": "hp.weapon.roof", "kind": "weapon", "x": 1, "y": 0, "w": 1, "h": 2, "modelNodeId": "hp.weapon.roof"}, + {"id": "hp.engine.rear", "kind": "engine", "x": 1, "y": 2, "w": 1, "h": 2, "modelNodeId": "hp.engine.rear"}, + {"id": "hp.radiator.rear", "kind": "radiator", "x": 2, "y": 3, "w": 1, "h": 1, "modelNodeId": "hp.radiator.rear"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[jackal] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "jackal", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_jackal() diff --git a/tools/vehicles/build_mule.py b/tools/vehicles/build_mule.py new file mode 100644 index 0000000..59d532f --- /dev/null +++ b/tools/vehicles/build_mule.py @@ -0,0 +1,298 @@ +"""Build the Mule (Medium 6x6 Armored Gun Truck) chassis GLB, manifest.json, and preview.""" +from __future__ import annotations + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def build_mule() -> dict: + vc.reset_scene() + vc.ensure_materials() + + root = vc.make_empty("MuleRoot") + chassis = vc.make_empty("Chassis", parent=root) + + front_y = -1.52 + mid_y = 0.88 + rear_y = 1.92 + track_x = 0.98 + wheel_r = 0.49 + wheel_w = 0.34 + axle_z = wheel_r + + # --- 1. Ladder Frame Rails, Axles, Bumper & Fuel Tanks --- + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"frame_rail_{tag}", (0.12, 4.54, 0.18), "gunmetal", parent=chassis, location=(side * 0.46, 0.0, 0.62), bevel=0.008) + # Side cylindrical fuel tanks (Brokkr mechanical kit tank) + vc.make_kit_part( + f"fuel_tank_{tag}", + "mechanical", + "tank", + {"radius": 0.19, "length": 0.86, "segments": 14}, + mat_name="gunmetal", + parent=chassis, + location=(side * 0.78, -0.35, 0.56), + rotation_deg=(90.0, 0.0, 0.0), + ) + + for idx, y_ax in enumerate((front_y, mid_y, rear_y)): + vc.make_tube_part( + f"axle_tube_{idx}", + 0.065, + 0.065, + track_x * 1.66, + segments=10, + mat_name="gunmetal", + parent=chassis, + location=(-track_x * 0.83, y_ax, axle_z), + rotation_deg=(0.0, 90.0, 0.0), + ) + vc.make_box(f"diff_{idx}", (0.28, 0.28, 0.24), "gunmetal", parent=chassis, location=(0.0, y_ax, axle_z), bevel=0.01) + + # Heavy front steel bumper + tow shackles + vc.make_box("front_bumper", (2.16, 0.24, 0.24), "gunmetal", parent=chassis, location=(0.0, -2.26, 0.66), bevel=0.014) + for side in (-1.0, 1.0): + vc.make_box(f"bumper_shackle_{'L' if side > 0 else 'R'}", (0.07, 0.12, 0.14), "signal_orange", parent=chassis, location=(side * 0.52, -2.40, 0.62), bevel=0.006) + vc.make_box(f"headlight_box_{'L' if side > 0 else 'R'}", (0.16, 0.12, 0.14), "gunmetal", parent=chassis, location=(side * 0.78, -2.18, 0.92), bevel=0.008) + + # --- 2. Armored Hood & Sloped Armored Cab (Brokkr plate.v0 + faceted cab) --- + # Hood core + front grille frame + vc.make_box("hood_core", (1.36, 1.06, 0.60), "olive_armor", parent=chassis, location=(0.0, -1.66, 1.04), bevel=0.015) + vc.make_box("cab_lower", (1.84, 1.18, 0.68), "olive_armor", parent=chassis, location=(0.0, -0.54, 1.06), bevel=0.015) + + # Sloped upper armored cab via plate.v0 convex hull ("faces" / "points") + cab_pts = [ + [-0.90, -1.12, 1.34], [0.90, -1.12, 1.34], + [0.90, 0.04, 1.34], [-0.90, 0.04, 1.34], + [-0.78, -0.82, 2.02], [0.78, -0.82, 2.02], + [0.80, 0.02, 2.02], [-0.80, 0.02, 2.02], + ] + plates_doc = { + "schema": "brokkr.plates.v0", + "plates": [ + { + "name": "mule_cab_upper", + "mat": "olive_armor", + "bevel": 0.016, + "sides": "one", + "mirror": False, + "points": cab_pts, + }, + # Flared front wheel fenders + { + "name": "mule_fender_front", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.92, -1.52, 1.08], + "normal": [0.18, 0.0, 0.98], + "up": [0.0, -1.0, 0.0], + "right": [0.98, 0.0, -0.18], + "outline": [[-0.24, 0.54], [0.24, 0.54], [0.24, -0.54], [-0.24, -0.54]], + "thick": 0.06, + "taper": 0.015, + "back": 0.92, + }, + "fits": [ + {"kind": "bolts", "inset": 0.02, "spacing": 0.28, "mat": "gunmetal", "params": "r=0.012"}, + ], + }, + # Armored cab doors with stepped clad panels + { + "name": "mule_door", + "mat": "olive_armor", + "bevel": 0.008, + "sides": "both", + "mirror": False, + "slab": { + "at": [0.93, -0.54, 1.18], + "normal": [1.0, 0.0, 0.0], + "up": [0.0, 0.0, 1.0], + "right": [0.0, -1.0, 0.0], + "outline": [[-0.44, -0.34], [0.44, -0.34], [0.40, 0.36], [-0.44, 0.36]], + "thick": 0.04, + "taper": 0.012, + "back": 0.94, + }, + "clad": { + "mat": "olive_armor", + "facets": "outer", + "min_area": 0.06, + "lifts": [0.008, 0.012], + "inset": 0.04, + "gap": 0.014, + "split": 0.65, + "seed": 501, + "bolt_r": 0.012, + "bolt_mat": "gunmetal", + "bevel": 0.004, + }, + "fits": [ + {"kind": "part", "part": "handle", "at": [0.24, -0.04], "roll": 0.0, "mat": "gunmetal", "params": "length=0.20;lift=0.045;r=0.012"}, + ], + }, + ], + } + vc.make_plates(plates_doc, parent=chassis) + + # Armored smoked glass windshield slit & side viewports + vc.make_box("windshield_slit", (1.28, 0.08, 0.16), "smoked_glass", parent=chassis, location=(0.0, -0.98, 1.68), rotation_deg=(-22.0, 0.0, 0.0), bevel=0.004) + for side in (-1.0, 1.0): + vc.make_box(f"side_glass_{'L' if side > 0 else 'R'}", (0.06, 0.46, 0.22), "smoked_glass", parent=chassis, location=(side * 0.86, -0.46, 1.66), rotation_deg=(0.0, side * -12.0, 0.0), bevel=0.004) + + # --- 3. Open Armored Cargo Bed + Rear Mudguards --- + vc.make_box("bed_floor", (2.06, 2.26, 0.12), "gunmetal", parent=chassis, location=(0.0, 1.24, 0.92), bevel=0.01) + # Bed side walls (stepped armor with ribs & tubular top grab rail) + for side in (-1.0, 1.0): + tag = "L" if side > 0 else "R" + vc.make_box(f"bed_wall_{tag}", (0.10, 2.22, 0.68), "olive_armor", parent=chassis, location=(side * 0.98, 1.24, 1.32), bevel=0.01) + for ry in (0.35, 0.95, 1.55, 2.15): + vc.make_box(f"bed_rib_{tag}_{ry:.2f}", (0.05, 0.08, 0.64), "olive_armor", parent=chassis, location=(side * 1.04, ry, 1.32), bevel=0.004) + vc.make_swept_tube( + f"bed_rail_{tag}", + [[side * 0.98, 0.16, 1.68], [side * 0.98, 0.16, 1.82], [side * 0.98, 2.32, 1.82], [side * 0.98, 2.32, 1.68]], + 0.022, + segments=8, + mat_name="gunmetal", + parent=chassis, + fillet_r=0.03, + ) + # Rear tandem fender flare + vc.make_box(f"rear_fender_{tag}", (0.38, 1.98, 0.08), "olive_armor", parent=chassis, location=(side * 0.94, 1.40, 1.06), bevel=0.008) + + # Tailgate + vc.make_box("bed_tailgate", (1.92, 0.10, 0.62), "olive_armor", parent=chassis, location=(0.0, 2.32, 1.29), bevel=0.01) + # Central turret pedestal drum in cargo bed + vc.make_tube_part("bed_pedestal", 0.44, 0.48, 0.58, segments=16, mat_name="gunmetal", parent=chassis, location=(0.0, 1.36, 0.98)) + + # --- 4. 6x6 Off-Road Wheels & Front Steering Knuckles --- + joints_manifest: list[dict] = [] + for axle_tag, y_ax, steerable in (("f", front_y, True), ("m", mid_y, False), ("r", rear_y, False)): + for side, s_tag in ((1.0, "l"), (-1.0, "r")): + j_suffix = f"{axle_tag}{s_tag}" + if steerable: + steer_id = f"joint.steer_{j_suffix}" + steer_node = vc.make_empty(steer_id, parent=chassis, location=(side * 0.80, y_ax, axle_z)) + vc.tag_joint(steer_node, steer_id, [0.0, 1.0, 0.0], -30.0, 30.0) + joints_manifest.append({"id": steer_id, "axis": [0.0, 1.0, 0.0], "min": -30.0, "max": 30.0}) + wheel_parent = steer_node + wheel_loc = (side * (track_x - 0.80), 0.0, 0.0) + else: + wheel_parent = chassis + wheel_loc = (side * track_x, y_ax, axle_z) + + wheel_id = f"joint.wheel_{j_suffix}" + wheel_pivot = vc.make_knobby_wheel( + wheel_id, + radius=wheel_r, + width=wheel_w, + parent=wheel_parent, + location=wheel_loc, + tread_lugs=16, + rim_segments=18, + side_sign=int(side), + ) + wheel_pivot.name = wheel_id + vc.tag_joint(wheel_pivot, wheel_id, [1.0, 0.0, 0.0], -360.0, 360.0) + joints_manifest.append({"id": wheel_id, "axis": [1.0, 0.0, 0.0], "min": -360.0, "max": 360.0}) + + # --- 5. Visible Exterior Hardpoints (3x5 Dorsal Grid) --- + # Front bumper/grille armor rail + vc.add_hardpoint_slot( + "hp.armor.front", + "armor", + parent=chassis, + location=(0.0, -2.28, 1.00), + rotation_deg=(-90.0, 0.0, 0.0), + size=(1.32, 0.36, 0.09), + ) + # Hood engine bay frame + vc.add_hardpoint_slot( + "hp.engine.front", + "engine", + parent=chassis, + location=(0.0, -1.66, 1.32), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.88, 0.86, 0.14), + ) + # Cab roof weapon pintle ring + vc.add_hardpoint_slot( + "hp.weapon.cab", + "weapon", + parent=chassis, + location=(0.0, -0.44, 2.02), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.56, 0.56, 0.09), + ) + # Main cargo-bed turret ring + vc.add_hardpoint_slot( + "hp.weapon.bed_main", + "weapon", + parent=chassis, + location=(0.0, 1.36, 1.56), + rotation_deg=(0.0, 0.0, 0.0), + size=(0.98, 0.98, 0.12), + ) + # Twin flank radiator louver pods behind cab (horizontal louvers: local +Y = +Z up) + vc.add_hardpoint_slot( + "hp.radiator.left", + "radiator", + parent=chassis, + location=(1.04, 0.56, 1.40), + rotation_deg=(90.0, 0.0, 90.0), + size=(0.78, 0.72, 0.14), + ) + vc.add_hardpoint_slot( + "hp.radiator.right", + "radiator", + parent=chassis, + location=(-1.04, 0.56, 1.40), + rotation_deg=(90.0, 0.0, -90.0), + size=(0.78, 0.72, 0.14), + ) + + # --- 6. Export GLB, Manifest & Preview --- + glb_path = vc.ASSETS_VEHICLES_DIR / "mule" / "mule.glb" + manifest_path = vc.ASSETS_VEHICLES_DIR / "mule" / "manifest.json" + preview_path = vc.PREVIEWS_DIR / "mule_preview.png" + + tri_count, bounds = vc.export_vehicle_glb(glb_path, root=root) + vc.write_manifest( + manifest_path, + vehicle_id="mule", + name="Mule", + vehicle_class="Medium 6x6 Armored Gun Truck", + grid_width=3, + grid_height=5, + mask=[ + "###", + "###", + "###", + "###", + "###", + ], + hardpoints=[ + {"id": "hp.armor.front", "kind": "armor", "x": 0, "y": 0, "w": 3, "h": 1, "modelNodeId": "hp.armor.front"}, + {"id": "hp.radiator.left", "kind": "radiator", "x": 0, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.radiator.left"}, + {"id": "hp.engine.front", "kind": "engine", "x": 1, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.engine.front"}, + {"id": "hp.radiator.right", "kind": "radiator", "x": 2, "y": 1, "w": 1, "h": 2, "modelNodeId": "hp.radiator.right"}, + {"id": "hp.weapon.cab", "kind": "weapon", "x": 0, "y": 3, "w": 1, "h": 1, "modelNodeId": "hp.weapon.cab"}, + {"id": "hp.weapon.bed_main", "kind": "weapon", "x": 1, "y": 3, "w": 2, "h": 2, "modelNodeId": "hp.weapon.bed_main"}, + ], + joints=joints_manifest, + bounds=bounds, + tri_count=tri_count, + ) + vc.render_four_panel_preview(preview_path) + print(f"[mule] tris={tri_count} bounds={bounds} glb={glb_path}") + return {"id": "mule", "tris": tri_count, "bounds": bounds} + + +if __name__ == "__main__": + build_mule() diff --git a/tools/vehicles/vehicle_common.py b/tools/vehicles/vehicle_common.py new file mode 100644 index 0000000..99aa3cc --- /dev/null +++ b/tools/vehicles/vehicle_common.py @@ -0,0 +1,1114 @@ +"""Shared Brokkr-powered vehicle construction, hardpoint sockets, joint tagging, +GLB export, manifest emission, and 4-panel preview rendering for Rust to Dust. + +All Blender geometry is authored in Blender right-handed Z-up coordinates with: + -Y = vehicle forward (+Z in exported glTF) + +Y = vehicle rear (-Z in exported glTF) + +Z = vehicle up (+Y in exported glTF, grounded at Z = 0) + +X = vehicle left (+X in exported glTF) + -X = vehicle right (-X in exported glTF) + +Export uses bpy.ops.export_scene.gltf(..., export_yup=True, export_extras=True) +so Godot receives +Z forward, +Y up, minY ~ 0.0, and rtd.* custom properties. +""" +from __future__ import annotations + +import json +import math +import sys +from pathlib import Path +from typing import Any, Callable, Sequence + +import bmesh +import bpy +import numpy as np +from mathutils import Euler, Matrix, Vector + +BROKKR_BLENDER_DIR = Path(r"F:\Projects\Brokkr\surfaces\blender") +if str(BROKKR_BLENDER_DIR) not in sys.path: + sys.path.insert(0, str(BROKKR_BLENDER_DIR)) + +import brokkr_mesh_polish # noqa: E402, F401 +import brokkr_kitbash # noqa: E402 +from brokkr_kitbash import core, plate, ram # noqa: E402, F401 + +REPO_ROOT = Path(__file__).resolve().parents[2] +ASSETS_VEHICLES_DIR = REPO_ROOT / "assets" / "vehicles" +ASSETS_GEAR_DIR = REPO_ROOT / "assets" / "gear" +PREVIEWS_DIR = Path(__file__).resolve().parent / "previews" + +# Shared industrial PBR palette (sRGB hex -> linear PBR base color) +PALETTE: dict[str, dict[str, Any]] = { + "olive_armor": {"hex": "#4e5740", "metallic": 0.28, "roughness": 0.58}, + "gunmetal": {"hex": "#2c302e", "metallic": 0.78, "roughness": 0.40}, + "rubber_dark": {"hex": "#191a19", "metallic": 0.04, "roughness": 0.86}, + "copper_rad": {"hex": "#9c5a34", "metallic": 0.86, "roughness": 0.34}, + "socket_bay": {"hex": "#151816", "metallic": 0.55, "roughness": 0.72}, + "signal_orange": {"hex": "#d96c27", "metallic": 0.18, "roughness": 0.44}, + "smoked_glass": {"hex": "#1e2a2d", "metallic": 0.12, "roughness": 0.10, "alpha": 0.82}, + # Imperial Tourist & salvage gear accents + "imperial_gold": {"hex": "#d4a634", "metallic": 0.90, "roughness": 0.26}, + "imperial_ivory": {"hex": "#ebe4d1", "metallic": 0.16, "roughness": 0.38}, + "cyan_coil": {"hex": "#38c9d8", "metallic": 0.20, "roughness": 0.25, "emission": "#38c9d8", "emission_strength": 1.8}, +} + +_KITS_CACHE: dict[str, dict] = {} + + +def srgb_hex_to_linear(hex_str: str) -> tuple[float, float, float, float]: + h = hex_str.lstrip("#") + vals = [int(h[i : i + 2], 16) / 255.0 for i in (0, 2, 4)] + + def to_lin(c: float) -> float: + return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 + + return (to_lin(vals[0]), to_lin(vals[1]), to_lin(vals[2]), 1.0) + + +def reset_scene() -> bpy.types.Scene: + """Clear all objects, meshes, materials, cameras, lights, and orphan data.""" + bpy.ops.wm.read_factory_settings(use_empty=True) + scene = bpy.context.scene + scene.unit_settings.system = "METRIC" + scene.unit_settings.scale_length = 1.0 + return scene + + +def ensure_materials() -> dict[str, bpy.types.Material]: + """Create shared industrial PBR materials cleanly on Principled BSDF.""" + mats: dict[str, bpy.types.Material] = {} + for name, spec in PALETTE.items(): + mat = bpy.data.materials.get(name) + if mat is None: + mat = bpy.data.materials.new(name=name) + mat.use_nodes = True + nt = mat.node_tree + nt.nodes.clear() + out = nt.nodes.new("ShaderNodeOutputMaterial") + bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled") + nt.links.new(bsdf.outputs["BSDF"], out.inputs["Surface"]) + bsdf.inputs["Base Color"].default_value = srgb_hex_to_linear(spec["hex"]) + bsdf.inputs["Metallic"].default_value = float(spec["metallic"]) + bsdf.inputs["Roughness"].default_value = float(spec["roughness"]) + if "alpha" in spec: + bsdf.inputs["Alpha"].default_value = float(spec["alpha"]) + mat.blend_method = "BLEND" if hasattr(mat, "blend_method") else "HASHED" + if "emission" in spec: + bsdf.inputs["Emission Color"].default_value = srgb_hex_to_linear(spec["emission"]) + bsdf.inputs["Emission Strength"].default_value = float(spec.get("emission_strength", 1.0)) + mats[name] = mat + return mats + + +def load_kit(name: str) -> dict: + if name not in _KITS_CACHE: + _KITS_CACHE[name] = core.load_kit(name) + return _KITS_CACHE[name] + + +def _assign_material(obj: bpy.types.Object, mat_name: str) -> None: + mat = bpy.data.materials.get(mat_name) + if mat is None: + ensure_materials() + mat = bpy.data.materials[mat_name] + if len(obj.data.materials): + obj.data.materials[0] = mat + else: + obj.data.materials.append(mat) + + +def _link_object( + obj: bpy.types.Object, + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), +) -> bpy.types.Object: + scene = bpy.context.scene + if obj.name not in scene.collection.objects: + scene.collection.objects.link(obj) + if parent is not None: + obj.parent = parent + obj.matrix_parent_inverse = Matrix.Identity(4) + obj.location = Vector(location) + obj.rotation_mode = "XYZ" + obj.rotation_euler = Euler([math.radians(a) for a in rotation_deg], "XYZ") + return obj + + +def _add_bevel(obj: bpy.types.Object, width: float, segments: int = 1, angle_deg: float = 30.0) -> None: + if width <= 0.0: + return + mod = obj.modifiers.new("Bevel", "BEVEL") + mod.width = width + mod.segments = segments + mod.limit_method = "ANGLE" + mod.angle_limit = math.radians(angle_deg) + mod.harden_normals = False + + +def make_empty( + name: str, + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + display_type: str = "PLAIN_AXES", + display_size: float = 0.12, +) -> bpy.types.Object: + obj = bpy.data.objects.new(name, None) + obj.empty_display_type = display_type + obj.empty_display_size = display_size + return _link_object(obj, parent=parent, location=location, rotation_deg=rotation_deg) + + +def make_mesh_from_swept( + name: str, + swept: Any, + mat_name: str, + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.0, +) -> bpy.types.Object: + mesh = bpy.data.meshes.new(name) + brokkr_kitbash.write_mesh(mesh, swept) + obj = bpy.data.objects.new(name, mesh) + _assign_material(obj, mat_name) + _link_object(obj, parent=parent, location=location, rotation_deg=rotation_deg) + if bevel > 0.0: + _add_bevel(obj, bevel, segments=1) + return obj + + +def _build_inline_shape(name: str, shape_dict: dict[str, Any]) -> core.Built: + doc = { + "schema": core.SCHEMA, + "kit": "inline", + "doc": "inline part", + "socketTypes": {}, + "parts": [{ + "name": "p", + "doc": name, + "params": [], + "shapes": [shape_dict], + "sockets": [], + }], + } + checked = core.check_kit(doc) + return core.build(checked["parts"]["p"], {}) + + +def make_tube_part( + name: str, + r0: float, + r1: float, + length: float, + segments: int = 12, + inner0: float = 0.0, + inner1: float = 0.0, + smooth: bool = True, + mat_name: str = "gunmetal", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.0, +) -> bpy.types.Object: + shape_dict: dict[str, Any] = { + "shape": "tube", + "r0": float(r0), + "r1": float(r1), + "length": float(length), + "segments": int(segments), + "smooth": bool(smooth), + } + if inner0 > 0.0 or inner1 > 0.0: + shape_dict["inner0"] = float(inner0) + shape_dict["inner1"] = float(inner1) + return make_mesh_from_swept( + name, + _build_inline_shape(name, shape_dict), + mat_name, + parent=parent, + location=location, + rotation_deg=rotation_deg, + bevel=bevel, + ) + + +def make_lathe_part( + name: str, + profile: Sequence[Sequence[float]], + segments: int = 16, + loop: bool = False, + smooth: bool = True, + mat_name: str = "gunmetal", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.0, +) -> bpy.types.Object: + shape_dict = { + "shape": "lathe", + "segments": int(segments), + "loop": bool(loop), + "smooth": bool(smooth), + "profile": [[float(p[0]), float(p[1])] for p in profile], + } + return make_mesh_from_swept( + name, + _build_inline_shape(name, shape_dict), + mat_name, + parent=parent, + location=location, + rotation_deg=rotation_deg, + bevel=bevel, + ) + + +def make_kit_part( + name: str, + kit_name: str, + part_name: str, + params: dict[str, Any] | None = None, + mat_name: str = "gunmetal", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.0, +) -> bpy.types.Object: + kit = load_kit(kit_name) + part_def = core.part(kit, part_name) + built = core.build(part_def, params or {}) + return make_mesh_from_swept( + name=name, + swept=built, + mat_name=mat_name, + parent=parent, + location=location, + rotation_deg=rotation_deg, + bevel=bevel, + ) + + +def _auto_ups(path: np.ndarray, closed: bool = False) -> np.ndarray: + """Compute smooth non-collinear up vectors along any 3D polyline for core.sweep.""" + n = len(path) + steps = (np.roll(path, -1, axis=0) - path)[: n if closed else n - 1] + lengths = np.linalg.norm(steps, axis=1, keepdims=True) + tangents = steps / np.maximum(lengths, 1e-9) + if closed: + vert_tan = tangents + np.roll(tangents, 1, axis=0) + else: + vert_tan = np.vstack([tangents[:1], tangents[:-1] + tangents[1:], tangents[-1:]]) + vert_tan /= np.maximum(np.linalg.norm(vert_tan, axis=1, keepdims=True), 1e-9) + ups = np.zeros_like(vert_tan) + ref = np.array([0.0, 0.0, 1.0]) if abs(vert_tan[0, 2]) < 0.85 else np.array([1.0, 0.0, 0.0]) + u0 = ref - vert_tan[0] * float(ref @ vert_tan[0]) + ups[0] = u0 / np.linalg.norm(u0) + for i in range(1, n): + u = ups[i - 1] - vert_tan[i] * float(ups[i - 1] @ vert_tan[i]) + norm = float(np.linalg.norm(u)) + if norm < 1e-5: + alt = np.array([1.0, 0.0, 0.0]) if abs(vert_tan[i, 0]) < 0.85 else np.array([0.0, 1.0, 0.0]) + u = alt - vert_tan[i] * float(alt @ vert_tan[i]) + norm = float(np.linalg.norm(u)) + ups[i] = u / norm + return ups + + +def fillet_polyline(points: Sequence[Sequence[float]], radius: float = 0.05, subdivs: int = 2, closed: bool = False) -> np.ndarray: + """Round interior corners of a 3D polyline so core.sweep stays well below TURN_LIMIT.""" + pts = np.asarray(points, dtype=np.float64) + if len(pts) < 3 or radius <= 0.0: + return pts + out: list[np.ndarray] = [] + n = len(pts) + indices = range(n) if closed else range(1, n - 1) + if not closed: + out.append(pts[0]) + for i in indices: + p_prev = pts[(i - 1) % n] + p_curr = pts[i] + p_next = pts[(i + 1) % n] + v_in = p_curr - p_prev + v_out = p_next - p_curr + l_in = float(np.linalg.norm(v_in)) + l_out = float(np.linalg.norm(v_out)) + if l_in < 1e-6 or l_out < 1e-6: + out.append(p_curr) + continue + d_in = v_in / l_in + d_out = v_out / l_out + if float(d_in @ d_out) > 0.995: + out.append(p_curr) + continue + trim = min(radius, 0.35 * l_in, 0.35 * l_out) + a = p_curr - d_in * trim + b = p_curr + d_out * trim + for k in range(subdivs + 1): + t = k / subdivs + # Quadratic Bezier corner blend + pt = (1 - t) ** 2 * a + 2 * (1 - t) * t * p_curr + t ** 2 * b + out.append(pt) + if not closed: + out.append(pts[-1]) + return np.array(out, dtype=np.float64) + + +def make_swept_tube( + name: str, + points: Sequence[Sequence[float]], + radius: float, + segments: int = 8, + mat_name: str = "gunmetal", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + closed: bool = False, + fillet_r: float = 0.04, +) -> bpy.types.Object: + path = fillet_polyline(points, radius=fillet_r, subdivs=2, closed=closed) if fillet_r > 0 else np.asarray(points, dtype=np.float64) + ups = _auto_ups(path, closed=closed) + swept = core.sweep(path, core.circle(radius, segments), ups, closed=closed) + return make_mesh_from_swept(name, swept, mat_name, parent=parent, location=location, rotation_deg=rotation_deg) + + +def make_swept_profile( + name: str, + section: str, + w: float, + h: float, + t: float, + points: Sequence[Sequence[float]], + up: Sequence[float] | None = None, + mat_name: str = "gunmetal", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + closed: bool = False, +) -> bpy.types.Object: + path = np.asarray(points, dtype=np.float64) + ups = np.asarray(up, dtype=np.float64) if up is not None else _auto_ups(path, closed=closed) + swept = core.sweep(path, core.profile(section, w, h, t), ups, closed=closed) + return make_mesh_from_swept(name, swept, mat_name, parent=parent, location=location, rotation_deg=rotation_deg) + + +def make_box( + name: str, + size: Sequence[float], + mat_name: str = "olive_armor", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.008, +) -> bpy.types.Object: + sx, sy, sz = (float(v) for v in size) + V = core.BOX_SIGNS * np.array([sx, sy, sz], dtype=np.float64) + swept = core.Swept( + V=V, + faces=core.BOX_FACES.ravel().astype(np.int32), + counts=np.full(6, 4, dtype=np.int32), + smooth=np.zeros(6, dtype=bool), + sharp=core.NO_SHARP.astype(np.int32), + ) + return make_mesh_from_swept(name, swept, mat_name, parent=parent, location=location, rotation_deg=rotation_deg, bevel=bevel) + + +def make_bmesh_object( + name: str, + builder: Callable[[bmesh.types.BMesh], None], + mat_name: str = "olive_armor", + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + bevel: float = 0.0, + smooth: bool = False, +) -> bpy.types.Object: + bm = bmesh.new() + builder(bm) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces) + mesh = bpy.data.meshes.new(name) + bm.to_mesh(mesh) + bm.free() + if smooth: + for poly in mesh.polygons: + poly.use_smooth = True + obj = bpy.data.objects.new(name, mesh) + _assign_material(obj, mat_name) + _link_object(obj, parent=parent, location=location, rotation_deg=rotation_deg) + if bevel > 0.0: + _add_bevel(obj, bevel, segments=1) + return obj + + +def _write_vf_mesh(name: str, V: np.ndarray, faces: list[list[int]], mat_name: str, parent: bpy.types.Object | None = None, bevel: float = 0.0) -> bpy.types.Object: + mesh = bpy.data.meshes.new(name) + mesh.from_pydata(np.asarray(V, dtype=np.float64).tolist(), [], [[int(k) for k in f] for f in faces]) + sharp = mesh.attributes.get("sharp_face") or mesh.attributes.new("sharp_face", "BOOLEAN", "FACE") + sharp.data.foreach_set("value", np.ones(len(mesh.polygons), dtype=bool)) + mesh.update() + obj = bpy.data.objects.new(name, mesh) + _assign_material(obj, mat_name) + _link_object(obj, parent=parent) + if bevel > 0.0: + _add_bevel(obj, bevel, segments=1, angle_deg=15.0) + return obj + + +def make_plates( + table_doc: dict[str, Any], + parent: bpy.types.Object | None = None, + prefix: str = "", + side: int = 1, +) -> list[bpy.types.Object]: + """Build Brokkr hard armour plates (brokkr.plates.v0) directly into Blender objects.""" + checked = plate.check(table_doc) + entries = plate.build(checked, side=side) + created: list[bpy.types.Object] = [] + for entry in entries: + row = checked["plates"][entry["row"]] + pname = f"{prefix}{entry['name']}" + solid_obj = _write_vf_mesh(pname, entry["solid"][0], entry["solid"][1], row["mat"], parent=parent, bevel=row["bevel"]) + created.append(solid_obj) + clad = row["clad"] + if clad: + if len(entry["panels"][1]): + p_obj = _write_vf_mesh(f"{pname}.panels", entry["panels"][0], entry["panels"][1], clad["mat"], parent=solid_obj, bevel=clad["bevel"]) + created.append(p_obj) + if len(entry["bolts"][1]): + b_obj = _write_vf_mesh(f"{pname}.bolts", entry["bolts"][0], entry["bolts"][1], clad["bolt_mat"], parent=solid_obj, bevel=0.0) + created.append(b_obj) + for fit_mat, fit_mesh in entry["fits"].items(): + if len(fit_mesh[1]): + f_obj = _write_vf_mesh(f"{pname}.fit.{fit_mat}", fit_mesh[0], fit_mesh[1], fit_mat, parent=solid_obj, bevel=0.0) + created.append(f_obj) + return created + + +def make_knobby_wheel( + name: str, + radius: float, + width: float, + parent: bpy.types.Object | None = None, + location: Sequence[float] = (0.0, 0.0, 0.0), + tread_lugs: int = 18, + rim_segments: int = 20, + side_sign: int = 1, +) -> bpy.types.Object: + """Build a crisp game-ready off-road wheel centered at (0,0,0) spinning about local X. + + side_sign = +1 for left (+X) wheel (hub faces +X), -1 for right (-X) wheel (hub faces -X). + """ + hub_pivot = make_empty(f"{name}_hub", parent=parent, location=location) + # Tire carcass via lathe rotated onto X axis (tube/lathe builds along +Z, so rot_y = 90) + r_rim = radius * 0.56 + r_side = radius * 0.92 + hw = width * 0.5 + tire_profile = [ + [r_rim * 0.96, -hw * 0.85], + [r_side, -hw * 0.95], + [radius * 0.96, -hw * 0.72], + [radius * 0.96, hw * 0.72], + [r_side, hw * 0.95], + [r_rim * 0.96, hw * 0.85], + ] + make_lathe_part( + f"{name}_tire", + tire_profile, + segments=rim_segments, + loop=True, + smooth=True, + mat_name="rubber_dark", + parent=hub_pivot, + rotation_deg=(0.0, 90.0, 0.0), + ) + + # Staggered knobby tread lugs around circumference (compact, low poly, high visual read) + def build_tread(bm: bmesh.types.BMesh) -> None: + lug_w = width * 0.38 + lug_h = radius * 0.055 + lug_len = (2.0 * math.pi * radius / tread_lugs) * 0.52 + for i in range(tread_lugs): + ang = 2.0 * math.pi * i / tread_lugs + for row_s in (-1.0, 1.0): + a = ang + (0.5 if row_s > 0 else 0.0) * (2.0 * math.pi / tread_lugs) + cy = math.cos(a) * (radius * 0.965) + cz = math.sin(a) * (radius * 0.965) + cx = row_s * hw * 0.42 + mat = ( + Matrix.Translation((cx, cy, cz)) + @ Matrix.Rotation(a, 4, "X") + @ Matrix.Scale(lug_w, 4, (1, 0, 0)) + @ Matrix.Scale(lug_h, 4, (0, 1, 0)) + @ Matrix.Scale(lug_len, 4, (0, 0, 1)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=mat) + + make_bmesh_object(f"{name}_treads", build_tread, "rubber_dark", parent=hub_pivot) + + # Steel wheel dish rim + hub cap (CCW in (r, z); +Z points outward via rot_y = 90 * side_sign) + rim_profile = [ + [0.0, -hw * 0.45], + [r_rim * 0.98, -hw * 0.45], + [r_rim * 0.98, hw * 0.86], + [r_rim * 0.82, hw * 0.86], + [r_rim * 0.72, hw * 0.48], + [r_rim * 0.30, hw * 0.48], + [r_rim * 0.25, hw * 0.82], + [0.0, hw * 0.82], + ] + make_lathe_part( + f"{name}_rim", + rim_profile, + segments=16, + loop=False, + smooth=True, + mat_name="gunmetal", + parent=hub_pivot, + rotation_deg=(0.0, 90.0 * side_sign, 0.0), + ) + + # Hub lug ring + def build_lugs(bm: bmesh.types.BMesh) -> None: + hx = side_sign * hw * 0.62 + for i in range(6): + a = 2.0 * math.pi * i / 6.0 + r_b = r_rim * 0.50 + m = Matrix.Translation((hx, math.cos(a) * r_b, math.sin(a) * r_b)) @ Matrix.Rotation(math.pi * 0.5, 4, "Y") + bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=6, radius1=radius * 0.042, radius2=radius * 0.042, depth=width * 0.14, matrix=m) + + make_bmesh_object(f"{name}_hubbolts", build_lugs, "signal_orange", parent=hub_pivot) + return hub_pivot + + +def make_ram_span( + name: str, + p_base: Sequence[float], + p_tip: Sequence[float], + body_r: float = 0.036, + rod_r: float = 0.020, + parent: bpy.types.Object | None = None, + mat_barrel: str = "gunmetal", + mat_rod: str = "copper_rad", + coil_rings: int = 0, +) -> bpy.types.Object: + """Create a realistic hydraulic actuator or coilover strut spanning p_base -> p_tip.""" + a = np.asarray(p_base, dtype=np.float64) + b = np.asarray(p_tip, dtype=np.float64) + vec = b - a + total = float(np.linalg.norm(vec)) + if total < 1e-4: + raise ValueError(f"Ram {name} has zero span") + z_dir = Vector((vec / total).tolist()) + quat = Vector((0.0, 0.0, 1.0)).rotation_difference(z_dir) + rot_deg = tuple(math.degrees(v) for v in quat.to_euler("XYZ")) + root = make_empty(name, parent=parent, location=a.tolist(), rotation_deg=rot_deg) + + body_len = max(0.05, total * 0.54) + rod_len = max(0.05, total * 0.56) + if 0.05 <= body_r <= 0.12 and 0.2 <= body_len <= 1.0 and 0.2 <= rod_len <= 2.0 and 0.01 <= rod_r <= 0.02: + make_kit_part( + f"{name}_barrel", + "mechanical", + "ram_barrel", + {"body_r": body_r, "body_len": body_len, "rod_r": rod_r, "segments": 10}, + mat_name=mat_barrel, + parent=root, + ) + make_kit_part( + f"{name}_rod", + "mechanical", + "ram_rod", + {"body_r": body_r, "rod_r": rod_r, "length": rod_len, "segments": 10}, + mat_name=mat_rod, + parent=root, + location=(0.0, 0.0, total), + rotation_deg=(180.0, 0.0, 0.0), + ) + else: + make_tube_part(f"{name}_barrel", body_r, body_r, body_len, segments=10, mat_name=mat_barrel, parent=root) + make_tube_part( + f"{name}_rod", + rod_r, + rod_r, + rod_len, + segments=8, + mat_name=mat_rod, + parent=root, + location=(0.0, 0.0, total - rod_len), + ) + if coil_rings > 0: + def build_coils(bm: bmesh.types.BMesh) -> None: + z0 = total * 0.16 + z1 = total * 0.78 + for k in range(coil_rings): + z = z0 + (z1 - z0) * (k / max(1, coil_rings - 1)) + # Octagonal spring ring + pts = [] + rc = body_r * 1.48 + for s in range(10): + ang = 2.0 * math.pi * s / 10.0 + pts.append((rc * math.cos(ang), rc * math.sin(ang), z)) + # Build small torus-like faceted collar ring + for s in range(10): + p0 = Vector(pts[s]) + p1 = Vector(pts[(s + 1) % 10]) + mid = (p0 + p1) * 0.5 + seg_dir = (p1 - p0).normalized() + q_seg = Vector((0, 0, 1)).rotation_difference(seg_dir) + m = Matrix.Translation(mid) @ q_seg.to_matrix().to_4x4() + bmesh.ops.create_cone( + bm, cap_ends=True, cap_tris=False, segments=6, + radius1=body_r * 0.24, radius2=body_r * 0.24, + depth=(p1 - p0).length * 1.08, matrix=m, + ) + + make_bmesh_object(f"{name}_coil", build_coils, "signal_orange", parent=root) + return root + + +def add_hardpoint_slot( + hp_id: str, + kind: str, + parent: bpy.types.Object, + location: Sequence[float], + rotation_deg: Sequence[float] = (0.0, 0.0, 0.0), + size: Sequence[float] = (0.55, 0.55, 0.12), +) -> bpy.types.Object: + """Create standardized VISIBLE exterior hardpoint socket geometry + tagged rtd.id anchor Empty. + + The anchor Empty is named `hp_id`, carries custom properties `rtd.id` and `rtd.kind`, + and sits at the mounting plane origin with local +Z normal (+Y in glTF) pointing outward. + """ + if kind not in ("weapon", "radiator", "engine", "armor"): + raise ValueError(f"Unsupported hardpoint kind {kind!r}") + + sx, sy, sz = (float(v) for v in size) + # Visual frame parented alongside the anchor + bay_root = make_empty(f"slot_frame.{hp_id}", parent=parent, location=location, rotation_deg=rotation_deg) + + if kind == "weapon": + r_outer = min(sx, sy) * 0.48 + r_inner = r_outer * 0.72 + collar_h = max(0.055, sz * 0.65) + # Octagonal bolted collar ring via Brokkr lathe + collar_prof = [ + [r_inner, 0.0], + [r_outer, 0.0], + [r_outer, collar_h * 0.65], + [r_outer * 0.92, collar_h], + [r_inner * 1.04, collar_h], + [r_inner, collar_h * 0.35], + ] + make_lathe_part( + f"{hp_id}.collar", + collar_prof, + segments=12, + loop=True, + smooth=False, + mat_name="gunmetal", + parent=bay_root, + ) + # Recessed dark weapon socket floor + make_box(f"{hp_id}.well", (r_inner * 1.65, r_inner * 1.65, 0.024), "socket_bay", parent=bay_root, location=(0.0, 0.0, 0.012), bevel=0.0) + # Twin mounting rails + 4 signal-orange lock lugs + 8 perimeter bolts + rail_sep = r_inner * 0.52 + for side in (-1.0, 1.0): + make_box( + f"{hp_id}.rail_{'l' if side > 0 else 'r'}", + (0.04, r_inner * 1.45, collar_h * 0.72), + "gunmetal", + parent=bay_root, + location=(side * rail_sep, 0.0, collar_h * 0.38), + bevel=0.004, + ) + def build_lugs_and_bolts(bm: bmesh.types.BMesh) -> None: + for ang_deg in (45.0, 135.0, 225.0, 315.0): + a = math.radians(ang_deg) + rl = r_outer * 0.88 + m = Matrix.Translation((rl * math.cos(a), rl * math.sin(a), collar_h * 0.96)) @ Matrix.Rotation(a, 4, "Z") + bmesh.ops.create_cube(bm, size=1.0, matrix=m @ Matrix.Diagonal((0.065, 0.042, 0.032, 1.0))) + + make_bmesh_object(f"{hp_id}.lugs", build_lugs_and_bolts, "signal_orange", parent=bay_root) + + def build_bolts(bm: bmesh.types.BMesh) -> None: + for k in range(8): + a = 2.0 * math.pi * k / 8.0 + rb = r_outer * 0.84 + m = Matrix.Translation((rb * math.cos(a), rb * math.sin(a), collar_h * 0.85)) + bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=6, radius1=0.016, radius2=0.014, depth=0.02, matrix=m) + + make_bmesh_object(f"{hp_id}.bolts", build_bolts, "gunmetal", parent=bay_root) + anchor_z = collar_h * 0.82 + + elif kind == "radiator": + frame_t = max(0.035, min(sx, sy) * 0.09) + depth = max(0.07, sz) + # Recessed dark bay floor + make_box(f"{hp_id}.well", (sx * 0.92, sy * 0.92, depth * 0.4), "socket_bay", parent=bay_root, location=(0.0, 0.0, depth * 0.2), bevel=0.0) + # Outer armored louver frame (4 bars) + make_box(f"{hp_id}.frame_top", (sx, frame_t, depth), "gunmetal", parent=bay_root, location=(0.0, sy * 0.5 - frame_t * 0.5, depth * 0.5), bevel=0.005) + make_box(f"{hp_id}.frame_bot", (sx, frame_t, depth), "gunmetal", parent=bay_root, location=(0.0, -sy * 0.5 + frame_t * 0.5, depth * 0.5), bevel=0.005) + make_box(f"{hp_id}.frame_l", (frame_t, sy - frame_t * 2, depth), "gunmetal", parent=bay_root, location=(sx * 0.5 - frame_t * 0.5, 0.0, depth * 0.5), bevel=0.005) + make_box(f"{hp_id}.frame_r", (frame_t, sy - frame_t * 2, depth), "gunmetal", parent=bay_root, location=(-sx * 0.5 + frame_t * 0.5, 0.0, depth * 0.5), bevel=0.005) + # Copper radiator core louvers inside the bay + n_fins = max(5, min(11, int(sy / 0.065))) + def build_louvers(bm: bmesh.types.BMesh) -> None: + inner_w = sx - frame_t * 2.2 + inner_h = sy - frame_t * 2.2 + for i in range(n_fins): + y = -inner_h * 0.44 + inner_h * 0.88 * (i / max(1, n_fins - 1)) + m = ( + Matrix.Translation((0.0, y, depth * 0.58)) + @ Matrix.Rotation(math.radians(24.0), 4, "X") + @ Matrix.Diagonal((inner_w, 0.018, depth * 0.42, 1.0)) + ) + bmesh.ops.create_cube(bm, size=1.0, matrix=m) + + make_bmesh_object(f"{hp_id}.louvers", build_louvers, "copper_rad", parent=bay_root) + # Corner flange bolts + signal-orange lock tabs + def build_tabs(bm: bmesh.types.BMesh) -> None: + for xs in (-1.0, 1.0): + for ys in (-1.0, 1.0): + m = Matrix.Translation((xs * (sx * 0.42), ys * (sy * 0.42), depth * 1.02)) + bmesh.ops.create_cube(bm, size=1.0, matrix=m @ Matrix.Diagonal((0.045, 0.045, 0.022, 1.0))) + + make_bmesh_object(f"{hp_id}.locktabs", build_tabs, "signal_orange", parent=bay_root) + anchor_z = depth * 0.55 + + elif kind == "engine": + wall_t = max(0.045, min(sx, sy) * 0.10) + depth = max(0.11, sz) + # Deep dark engine bay recess + make_box(f"{hp_id}.well", (sx * 0.90, sy * 0.90, depth * 0.35), "socket_bay", parent=bay_root, location=(0.0, 0.0, depth * 0.18), bevel=0.0) + # Armored coaming rails + for xs in (-1.0, 1.0): + make_box(f"{hp_id}.coam_{'l' if xs > 0 else 'r'}", (wall_t, sy, depth), "gunmetal", parent=bay_root, location=(xs * (sx * 0.5 - wall_t * 0.5), 0.0, depth * 0.5), bevel=0.006) + for ys in (-1.0, 1.0): + make_box(f"{hp_id}.coam_{'b' if ys > 0 else 'f'}", (sx - wall_t * 2, wall_t, depth * 0.85), "gunmetal", parent=bay_root, location=(0.0, ys * (sy * 0.5 - wall_t * 0.5), depth * 0.42), bevel=0.006) + # Twin internal engine mount cradle rails + exhaust manifold stubs + for xs in (-1.0, 1.0): + make_box(f"{hp_id}.cradle_{'l' if xs > 0 else 'r'}", (0.05, sy * 0.72, depth * 0.45), "gunmetal", parent=bay_root, location=(xs * sx * 0.22, 0.0, depth * 0.45), bevel=0.004) + make_swept_tube( + f"{hp_id}.manifold_{'l' if xs > 0 else 'r'}", + [ + [xs * sx * 0.16, -sy * 0.26, depth * 0.55], + [xs * sx * 0.30, -sy * 0.12, depth * 0.74], + [xs * sx * 0.30, sy * 0.20, depth * 0.74], + ], + 0.022, + segments=8, + mat_name="copper_rad", + parent=bay_root, + fillet_r=0.03, + ) + # Signal-orange lock pins at corners + def build_pins(bm: bmesh.types.BMesh) -> None: + for xs in (-1.0, 1.0): + for ys in (-1.0, 1.0): + m = Matrix.Translation((xs * (sx * 0.40), ys * (sy * 0.40), depth * 1.02)) + bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=8, radius1=0.022, radius2=0.018, depth=0.036, matrix=m) + + make_bmesh_object(f"{hp_id}.lockpins", build_pins, "signal_orange", parent=bay_root) + anchor_z = depth * 0.45 + + else: # "armor" + rail_h = max(0.05, sz) + # Backing plate & stud rails across the glacis / flank + make_box(f"{hp_id}.rail", (sx * 0.92, sy * 0.32, rail_h * 0.55), "gunmetal", parent=bay_root, location=(0.0, 0.0, rail_h * 0.28), bevel=0.006) + n_boss = max(3, min(5, int(sx / 0.32) + 1)) + def build_bosses(bm: bmesh.types.BMesh) -> None: + for i in range(n_boss): + x = -sx * 0.38 + sx * 0.76 * (i / max(1, n_boss - 1)) + m = Matrix.Translation((x, 0.0, rail_h * 0.65)) + bmesh.ops.create_cube(bm, size=1.0, matrix=m @ Matrix.Diagonal((0.09, sy * 0.48, rail_h * 0.45, 1.0))) + + make_bmesh_object(f"{hp_id}.bosses", build_bosses, "gunmetal", parent=bay_root) + + def build_studs(bm: bmesh.types.BMesh) -> None: + for i in range(n_boss): + x = -sx * 0.38 + sx * 0.76 * (i / max(1, n_boss - 1)) + m = Matrix.Translation((x, 0.0, rail_h * 0.98)) + bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=8, radius1=0.024, radius2=0.018, depth=0.038, matrix=m) + + make_bmesh_object(f"{hp_id}.studs", build_studs, "signal_orange", parent=bay_root) + anchor_z = rail_h * 0.75 + + # Authoritative glTF Empty anchor + anchor = make_empty( + hp_id, + parent=bay_root, + location=(0.0, 0.0, anchor_z), + rotation_deg=(0.0, 0.0, 0.0), + display_type="ARROWS", + display_size=0.18, + ) + anchor["rtd.id"] = hp_id + anchor["rtd.kind"] = kind + anchor["rtd.size"] = [float(sx), float(sy), float(sz)] + return anchor + + +def tag_joint( + node: bpy.types.Object, + joint_id: str, + axis_gltf: Sequence[float], + min_val: float, + max_val: float, +) -> bpy.types.Object: + """Tag a pivot/mechanism node with rtd.joint metadata exported in glTF extras.""" + node["rtd.joint"] = joint_id + node["rtd.axis"] = [float(axis_gltf[0]), float(axis_gltf[1]), float(axis_gltf[2])] + node["rtd.min"] = float(min_val) + node["rtd.max"] = float(max_val) + return node + + +def scene_triangle_count(context: bpy.types.Context | None = None) -> int: + ctx = context or bpy.context + depsgraph = ctx.evaluated_depsgraph_get() + total = 0 + for obj in ctx.scene.objects: + if obj.type != "MESH" or obj.name.startswith("_preview_"): + continue + ev = obj.evaluated_get(depsgraph) + me = ev.to_mesh() + me.calc_loop_triangles() + total += len(me.loop_triangles) + ev.to_mesh_clear() + return total + + +def scene_bounds_blender(context: bpy.types.Context | None = None) -> tuple[Vector, Vector]: + ctx = context or bpy.context + depsgraph = ctx.evaluated_depsgraph_get() + mins = [math.inf, math.inf, math.inf] + maxs = [-math.inf, -math.inf, -math.inf] + for obj in ctx.scene.objects: + if obj.type != "MESH" or obj.name.startswith("_preview_"): + continue + ev = obj.evaluated_get(depsgraph) + me = ev.to_mesh() + mw = obj.matrix_world + for v in me.vertices: + w = mw @ v.co + for i in range(3): + mins[i] = min(mins[i], w[i]) + maxs[i] = max(maxs[i], w[i]) + ev.to_mesh_clear() + return Vector(mins), Vector(maxs) + + +def ground_root_to_z0(root: bpy.types.Object) -> float: + """Shift root along Z so the lowest evaluated mesh vertex sits at Z = 0.""" + bpy.context.view_layer.update() + b_min, _ = scene_bounds_blender() + if math.isfinite(b_min.z) and abs(b_min.z) > 1e-5: + root.location.z -= b_min.z + bpy.context.view_layer.update() + return -b_min.z + return 0.0 + + +def bounds_gltf_from_blender(b_min: Vector, b_max: Vector) -> dict[str, list[float]]: + """Convert Blender Z-up bounds to glTF Y-up bounds: (x, y, z)_gltf = (x, z, -y)_blender.""" + g_min = [round(b_min.x, 4), round(b_min.z, 4), round(-b_max.y, 4)] + g_max = [round(b_max.x, 4), round(b_max.z, 4), round(-b_min.y, 4)] + size = [round(g_max[i] - g_min[i], 4) for i in range(3)] + return {"min": g_min, "max": g_max, "size": size} + + +def export_vehicle_glb(glb_path: Path, root: bpy.types.Object | None = None) -> tuple[int, dict[str, list[float]]]: + """Ground scene (if root given), measure evaluated tris & glTF bounds, and export .glb.""" + if root is not None: + ground_root_to_z0(root) + bpy.context.view_layer.update() + tri_count = scene_triangle_count() + b_min, b_max = scene_bounds_blender() + bounds_gltf = bounds_gltf_from_blender(b_min, b_max) + + glb_path.parent.mkdir(parents=True, exist_ok=True) + # Hide any preview helper objects if present + bpy.ops.export_scene.gltf( + filepath=str(glb_path), + export_format="GLB", + export_yup=True, + export_extras=True, + export_apply=True, + export_materials="EXPORT", + export_normals=True, + export_texcoords=True, + use_visible=True, + ) + return tri_count, bounds_gltf + + +def write_manifest( + manifest_path: Path, + *, + vehicle_id: str, + name: str, + vehicle_class: str, + grid_width: int, + grid_height: int, + mask: Sequence[str] | Sequence[bool], + hardpoints: list[dict[str, Any]], + joints: list[dict[str, Any]], + bounds: dict[str, list[float]], + tri_count: int, + plane: str = "Dorsal", +) -> None: + if len(mask) == grid_height and isinstance(mask[0], str): + mask_bools = [ch == "#" for row in mask for ch in row] + else: + mask_bools = [bool(v) for v in mask] + doc = { + "schema": "rtd.vehicle.manifest.v1", + "id": vehicle_id, + "name": name, + "class": vehicle_class, + "plane": plane, + "gridWidth": grid_width, + "gridHeight": grid_height, + "mask": mask_bools, + "hardpoints": hardpoints, + "joints": joints, + "bounds": bounds, + "triCount": int(tri_count), + } + manifest_path.parent.mkdir(parents=True, exist_ok=True) + manifest_path.write_text(json.dumps(doc, indent=2) + "\n", encoding="utf-8") + + +def _aim_camera_at(cam_obj: bpy.types.Object, eye: Vector, target: Vector) -> None: + cam_obj.location = eye + direction = (target - eye).normalized() + cam_obj.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler() + + +def render_four_panel_preview(preview_path: Path, panel_w: int = 640, panel_h: int = 480) -> Path: + """Render 3/4 Hero, Front (-Y), Side (+X), and Top Dorsal (+Z) views via EEVEE into one 2x2 PNG.""" + scene = bpy.context.scene + bpy.context.view_layer.update() + b_min, b_max = scene_bounds_blender() + center = (b_min + b_max) * 0.5 + extent = max((b_max - b_min).length, 1.5) + + # Setup world + studio lighting + ground plinth + world = bpy.data.worlds.new("_preview_world") + scene.world = world + world.use_nodes = True + bg = world.node_tree.nodes.get("Background") + if bg: + bg.inputs["Color"].default_value = (0.045, 0.050, 0.048, 1.0) + bg.inputs["Strength"].default_value = 1.1 + + # Ground disc (dark slate) + floor_mat = bpy.data.materials.new("_preview_floor_mat") + floor_mat.use_nodes = True + f_bsdf = floor_mat.node_tree.nodes.get("Principled BSDF") + if f_bsdf: + f_bsdf.inputs["Base Color"].default_value = (0.08, 0.085, 0.082, 1.0) + f_bsdf.inputs["Roughness"].default_value = 0.88 + bpy.ops.mesh.primitive_cylinder_add(vertices=48, radius=extent * 1.4, depth=0.04, location=(center.x, center.y, b_min.z - 0.021)) + floor_obj = bpy.context.active_object + floor_obj.name = "_preview_floor" + floor_obj.data.materials.append(floor_mat) + + def add_sun(name: str, rot_deg: Sequence[float], energy: float, color: Sequence[float]) -> bpy.types.Object: + ldata = bpy.data.lights.new(name, type="SUN") + ldata.energy = energy + ldata.color = color + lobj = bpy.data.objects.new(name, ldata) + scene.collection.objects.link(lobj) + lobj.rotation_euler = Euler([math.radians(a) for a in rot_deg], "XYZ") + return lobj + + lights = [ + add_sun("_preview_key", (48.0, 12.0, -35.0), 3.4, (1.0, 0.96, 0.90)), + add_sun("_preview_fill", (55.0, -15.0, 135.0), 1.4, (0.78, 0.86, 0.98)), + add_sun("_preview_rim", (25.0, 0.0, 175.0), 1.6, (1.0, 0.90, 0.78)), + ] + + cam_data = bpy.data.cameras.new("_preview_cam") + cam_data.lens = 42.0 + cam_obj = bpy.data.objects.new("_preview_cam", cam_data) + scene.collection.objects.link(cam_obj) + scene.camera = cam_obj + + scene.render.engine = "BLENDER_EEVEE" + scene.render.resolution_x = panel_w + scene.render.resolution_y = panel_h + scene.render.resolution_percentage = 100 + scene.render.image_settings.file_format = "PNG" + scene.render.image_settings.color_mode = "RGBA" + if hasattr(scene, "eevee"): + scene.eevee.taa_render_samples = 16 + + size_vec = b_max - b_min + d_hero = extent * 1.18 + d_ortho = max(size_vec.x, size_vec.y, size_vec.z) * 1.25 + + views = [ + ("hero", "PERSP", center + Vector((d_hero * 0.72, -d_hero * 0.85, d_hero * 0.46)), center), + ("front", "ORTHO", center + Vector((0.0, -d_ortho * 2.0, size_vec.z * 0.04)), center), + ("side", "ORTHO", center + Vector((d_ortho * 2.0, 0.0, size_vec.z * 0.04)), center), + ("top", "ORTHO", center + Vector((0.0, 0.0, d_ortho * 2.0)), center), + ] + + preview_path.parent.mkdir(parents=True, exist_ok=True) + tmp_files: list[Path] = [] + panels: list[np.ndarray] = [] + + for idx, (tag, proj, eye, tgt) in enumerate(views): + cam_data.type = proj + if proj == "ORTHO": + aspect = panel_w / max(1, panel_h) + if tag == "front": + cam_data.ortho_scale = max(size_vec.x * 1.32, size_vec.z * aspect * 1.38) + elif tag == "side": + cam_data.ortho_scale = max(size_vec.y * 1.24, size_vec.z * aspect * 1.35) + else: + cam_data.ortho_scale = max(size_vec.x * 1.30, size_vec.y * aspect * 1.22) + _aim_camera_at(cam_obj, eye, tgt) + # Keep top view upright with nose (-Y) pointing up in image + if tag == "top": + cam_obj.rotation_euler = Euler((0.0, 0.0, math.radians(180.0)), "XYZ") + + tmp_png = preview_path.with_name(f".tmp_{preview_path.stem}_{tag}.png") + tmp_files.append(tmp_png) + scene.render.filepath = str(tmp_png) + bpy.ops.render.render(write_still=True) + + img = bpy.data.images.load(str(tmp_png), check_existing=False) + arr = np.empty(panel_w * panel_h * 4, dtype=np.float32) + img.pixels.foreach_get(arr) + bpy.data.images.remove(img) + panels.append(arr.reshape((panel_h, panel_w, 4))) + + # Stitch 2x2 grid (note Blender image pixel row 0 is bottom): + # Top row in final PNG = [hero (TL), front (TR)] -> higher Y in Blender image space + # Bottom row in final PNG = [side (BL), top (BR)] -> lower Y in Blender image space + top_row = np.concatenate([panels[0], panels[1]], axis=1) + bot_row = np.concatenate([panels[2], panels[3]], axis=1) + # 4px dark divider lines + grid = np.concatenate([bot_row, top_row], axis=0) + grid[:, panel_w - 2 : panel_w + 2, :3] = 0.25 + grid[panel_h - 2 : panel_h + 2, :, :3] = 0.25 + + out_img = bpy.data.images.new("_preview_composite", width=panel_w * 2, height=panel_h * 2, alpha=True) + out_img.pixels.foreach_set(grid.ravel().tolist()) + out_img.filepath_raw = str(preview_path) + out_img.file_format = "PNG" + out_img.save() + bpy.data.images.remove(out_img) + + # Cleanup temp renders and preview objects + for tmp in tmp_files: + if tmp.exists(): + tmp.unlink() + for obj in [floor_obj, cam_obj, *lights]: + bpy.data.objects.remove(obj, do_unlink=True) + bpy.data.materials.remove(floor_mat) + bpy.data.worlds.remove(world) + + return preview_path diff --git a/tools/vehicles/verify_glbs.py b/tools/vehicles/verify_glbs.py new file mode 100644 index 0000000..84d1dc2 --- /dev/null +++ b/tools/vehicles/verify_glbs.py @@ -0,0 +1,228 @@ +"""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") +EXPECTED_GEAR = ("mg_762", "autocannon", "recoilless", "copper_rad", "gilded_lance", "gold_radiator") + + +def parse_glb_json(glb_path: Path) -> dict[str, Any]: + 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(" 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]) -> tuple[int, np.ndarray, np.ndarray]: + nodes = gltf.get("nodes", []) + meshes = gltf.get("meshes", []) + accessors = gltf.get("accessors", []) + 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] + 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 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 = parse_glb_json(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") + + # 4. Check GLB triangle count & grounded +Y-up / +Z-forward bounds + tri_total, g_min, g_max = compute_glb_stats(gltf) + if not (1500 <= tri_total <= 35000): + raise AssertionError(f"{vid}: tri count {tri_total} outside [1500, 35000]") + 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 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()}") + + return { + "id": vid, + "tris": tri_total, + "bytes": glb_path.stat().st_size, + "hardpoints": len(manifest["hardpoints"]), + "joints": len(manifest["joints"]), + "minY": round(float(g_min[1]), 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 = parse_glb_json(glb_path) + tri_total, g_min, g_max = compute_glb_stats(gltf) + 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: + print(f" {r['id']:8s} | tris={r['tris']:5d} | size={r['size']} | minY={r['minY']} | hps={r['hardpoints']} | joints={r['joints']} | {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())