"""MITRA の3D（glb）を mitra_dims.json から作る。
座標：原点＝前後の車軸の中間の真下の地面。+X 前、+Y 上、+Z 右。単位 m（glTF）。
動く部品（親子のつながり。視点ページはこの名前の節を回す・動かす）:
  body                      車体（ばね上）。上下・前後の傾き・左右の傾き
  susp_F{L,R}               前のアームの付け根。X 軸まわりに回る（左右に振れる）
    steer_F{L,R}            前輪の向きを変える軸（Y 軸まわり）
      wheel_F{L,R}          前輪（Z 軸まわりに回る）
  susp_R{L,R}               後ろのアームの付け根。Z 軸まわりに回る（前後に振れる）
    wheel_R{L,R}            後輪（Z 軸まわりに回る）
  option_deck               オプションのアルミフレーム一式（出し入れできる）
  印（形なし）: mark_deck_front_edge・mark_option_top_front・spring_top_*・spring_bot_*（ばねを伸び縮みさせる両端）
"""
import json, math, sys
import numpy as np
import trimesh
from trimesh.visual.material import PBRMaterial

D = json.load(open(sys.argv[1] if len(sys.argv) > 1 else "mitra_dims.json"))
v = lambda sec, k: D[sec][k]["v"]
M = 0.001  # mm -> m

COL = {
    "alu": [0.84, 0.85, 0.86, 1], "plate": [0.40, 0.40, 0.39, 1], "black": [0.06, 0.06, 0.07, 1],
    "tire": [0.09, 0.09, 0.09, 1], "hub": [0.45, 0.46, 0.47, 1], "motor": [0.55, 0.56, 0.57, 1],
    "battery": [0.22, 0.23, 0.25, 1], "spring": [0.80, 0.80, 0.78, 1], "damper": [0.12, 0.12, 0.13, 1], "wheel": [0.62, 0.63, 0.65, 1], "slot": [0.38, 0.39, 0.41, 1], "bolt": [0.72, 0.73, 0.74, 1],
}
def mat(name):
    rough = 0.35 if name in ("alu", "spring", "motor") else 0.7
    metal = 0.8 if name in ("alu", "spring", "motor", "hub") else 0.05
    if name in ("bolt", "slot"): metal, rough = 0.3, 0.5
    if name == "tire": rough = 0.92
    if name == "alu": metal, rough = 0.25, 0.45   # 環境の映り込みがない画面でも銀色に見えるように
    return PBRMaterial(name=name, baseColorFactor=COL[name], metallicFactor=metal, roughnessFactor=rough, doubleSided=(name in ("tire", "wheel")))

def paint(m, name):
    m.visual = trimesh.visual.TextureVisuals(material=mat(name))
    return m

def T(x=0, y=0, z=0):
    t = np.eye(4); t[:3, 3] = [x * M, y * M, z * M]; return t

def box(sx, sy, sz, cx, cy, cz, c):
    b = trimesh.creation.box(extents=[sx * M, sy * M, sz * M]); b.apply_translation([cx * M, cy * M, cz * M]); return paint(b, c)

def tube(p0, p1, d, c, sections=20):
    p0 = np.array(p0, float) * M; p1 = np.array(p1, float) * M
    t = trimesh.creation.cylinder(radius=d / 2 * M, segment=[p0, p1], sections=sections); return paint(t, c)

def ring_z(outer_d, inner_d, width, c, sections=48):
    """Z 軸（車軸）まわりの輪。中心は原点。"""
    o = trimesh.creation.cylinder(radius=outer_d / 2 * M, height=width * M, sections=sections)
    if inner_d > 0:
        i = trimesh.creation.cylinder(radius=inner_d / 2 * M, height=width * 1.2 * M, sections=sections)
        o = o.difference(i) if o.is_volume and i.is_volume else o
    return paint(o, c)

def bent_u(tip_x, h, width, depth, d, c, back_dir):
    """U の字の棒（前の棒・後ろの取っ手）。tip_x が一番外、back_dir=-1 で後ろへ戻る。"""
    hw = width / 2; xb = tip_x + back_dir * depth
    parts = [tube([tip_x, h, -hw], [tip_x, h, hw], d, c), tube([tip_x, h, -hw], [xb, h, -hw], d, c), tube([tip_x, h, hw], [xb, h, hw], d, c)]
    return trimesh.util.concatenate(parts)

# ---------------- タイヤ（3.00-4・外径260×幅85） ----------------
# 断面は寸法図の正面の外形、トレッドは広報資料の写真（後ろ・斜め後ろ）から読んだ。
TIRE_N = 54            # 1周のブロックの数（後ろからの写真：真ん中で約14.5mm おき）
GROOVE = 4.0           # 溝の深さ
BUTT = 2.5             # 肩から横の面へ続く細いひだの高さ

def _tire_outline():
    """正面図で測った［下がり, 半分の幅］をなめらかにつなぐ。頂上は丸い"""
    from scipy.interpolate import CubicSpline
    tab = np.array(D["wheel"]["tire_profile"]["v"], float); kz = 42.5 / tab[-1, 1]
    pts = np.array([(130.0 - d, z * kz) for d, z in tab])
    full = np.vstack([pts[:0:-1] * [1, -1], pts])                    # 左右を対称にして頂上をなめらかに
    t = np.concatenate([[0], np.cumsum(np.hypot(*np.diff(full, axis=0).T))])
    cs = CubicSpline(t, full); tm = t[len(pts) - 1]
    out = [tuple(cs(u)) for u in np.linspace(tm, t[-1], 70)]
    out[0] = (130.0, 0.0); r0 = out[-1][0]
    for q in np.linspace(0, 1, 22)[1:]:                               # いちばん広い所からリムへ
        out.append((r0 - (r0 - 60) * q, 42.5 * (1 - q) + 27.5 * q + 4.8 * math.sin(math.pi * q)))
    return np.array(out)
_TO = _tire_outline()
_seg = np.diff(_TO, axis=0); _len = np.hypot(_seg[:, 0], _seg[:, 1])
_S = np.concatenate([[0], np.cumsum(_len)])
_tan = np.vstack([_seg[0], (_seg[:-1] + _seg[1:]) / 2, _seg[-1]]); _tan /= np.linalg.norm(_tan, axis=1)[:, None]
_NR, _NZ = _tan[:, 1], -_tan[:, 0]          # 外向き
def TP(s_):
    return (np.interp(s_, _S, _TO[:, 0]), np.interp(s_, _S, _TO[:, 1]), np.interp(s_, _S, _NR), np.interp(s_, _S, _NZ))
def s_at_z(z_):   # 肩まで（z が増える範囲）
    i = int(np.argmax(_TO[:, 1])); return float(np.interp(z_, _TO[:i + 1, 1], _S[:i + 1]))
def s_at_r(r_):
    return float(np.interp(-r_, -_TO[:, 0], _S))
S_EDGE = s_at_z(33.0)      # トレッドの端（寸法図の縦の線 ±33mm）
S_B1 = s_at_r(96.0)        # ひだの終わり（いちばん幅の広い所）
def TD(s_):
    return float(np.interp(s_, [0, S_EDGE, S_EDGE + 3, S_B1, S_B1 + 6], [GROOVE, GROOVE, BUTT, BUTT, 0.0]))

def _patch(u_lo, u_hi, ss, k):
    """(u, s) の四角い面を、外形の上から胴まで押し出したブロック。u はブロックの間隔を1とした周の位置"""
    pitch = 2 * math.pi / TIRE_N
    top, bot = [], []
    for s_ in ss:
        r, z, nr, nz = TP(s_); dd = TD(s_) + 0.8
        for j in range(k + 1):
            th = (u_lo(s_) + (u_hi(s_) - u_lo(s_)) * j / k) * pitch
            top.append((r * math.cos(th), r * math.sin(th), z))
            rb, zb = r - dd * nr, z - dd * nz
            bot.append((rb * math.cos(th), rb * math.sin(th), zb))
    m = len(ss) - 1; n = (m + 1) * (k + 1)
    idx = lambda i, j: i * (k + 1) + j
    F = []
    for i in range(m):
        for j in range(k):
            a_, b_, c_, d_ = idx(i, j), idx(i + 1, j), idx(i + 1, j + 1), idx(i, j + 1)
            F += [(a_, b_, c_), (a_, c_, d_)]
    loop = [idx(i, 0) for i in range(m + 1)] + [idx(m, j) for j in range(1, k + 1)] + [idx(i, k) for i in range(m - 1, -1, -1)] + [idx(0, j) for j in range(k - 1, 0, -1)]
    for e in range(len(loop)):
        p_, q_ = loop[e], loop[(e + 1) % len(loop)]
        F += [(q_, p_, p_ + n), (q_, p_ + n, q_ + n)]
    V = np.array(top + bot) * M; F = np.array(F)
    c = V[F[0]].mean(axis=0); nrm = np.cross(V[F[0][1]] - V[F[0][0]], V[F[0][2]] - V[F[0][0]])
    radial = np.array([c[0], c[1], 0.0])
    if np.dot(nrm, radial) < 0 and abs(np.dot(nrm, radial)) > 1e-12: F = F[:, ::-1]
    elif abs(np.dot(nrm, radial)) <= 1e-12 and nrm[2] < 0: F = F[:, ::-1]
    return V, F

def tire_parts(sec="wheel"):
    # 胴（溝の底の面）
    ss = np.linspace(0, _S[-1], 90)
    half = []
    for s_ in ss:
        r, z, nr, nz = TP(s_); d_ = TD(s_); half.append((r - d_ * nr, z - d_ * nz))
    prof = [(r, -z) for r, z in reversed(half)] + half[1:]
    carc = trimesh.creation.revolve(np.array(prof) * M, sections=96)
    c0 = carc.triangles_center[0]; n0 = carc.face_normals[0]
    probe = int(np.argmax(np.hypot(carc.triangles_center[:, 0], carc.triangles_center[:, 1])))
    cc = carc.triangles_center[probe]
    if np.dot(carc.face_normals[probe], [cc[0], cc[1], 0]) < 0: carc.invert()
    carc.vertex_normals  # なめらかな面として書き出す
    paint(carc, "tire")
    # ブロック。片側を作り、反対側は半径の軸で180°回した形（向きの決まっていないトレッド）
    Vs, Fs, off = [], [], 0
    def put(V, F):
        nonlocal off
        Vs.append(V); Fs.append(F + off); off += len(V)
    SM = 8.5
    chev_ss = np.concatenate([np.linspace(1.5, SM, 4), np.linspace(SM, 15.5, 4)[1:]])   # s は断面に沿った長さ
    s_e = s_at_z(37.0)
    out_ss = np.linspace(18.5, s_e, 7)
    but_ss = np.linspace(s_e + 1.5, S_B1 + 5.5, 6)
    RX = trimesh.transformations.rotation_matrix(math.pi, [1, 0, 0])[:3, :3]
    for kk in range(TIRE_N):
        blocks = [
            _patch(lambda s_: kk + 0.32 * abs(s_ - SM) / 7.0, lambda s_: kk + 0.32 * abs(s_ - SM) / 7.0 + 0.74, chev_ss, 2),          # 真ん中寄りの列：く の字
            _patch(lambda s_: kk + 0.5 + 0.40 * (s_ - 18.5) / (s_e - 18.5), lambda s_: kk + 0.5 + 0.40 * (s_ - 18.5) / (s_e - 18.5) + 0.72, out_ss, 2),  # 外の列：斜めのブロック。肩まで回り込む
            _patch(lambda s_: kk + 0.5 + 0.40 + 0.16, lambda s_: kk + 0.5 + 0.40 + 0.16 + 0.40, but_ss, 1),                              # 肩から横の面へのひだ
        ]
        for V, F in blocks:
            put(V, F); put(V @ RX.T, F)
    tread = paint(trimesh.Trimesh(np.vstack(Vs), np.vstack(Fs), process=False), "tire")
    # ホイール（灰色の樹脂の皿・丸い穴4つ・放射のひだ・真ん中のふた）
    rim_r = v(sec, "rim_flange_d") / 2
    disc = trimesh.creation.revolve(np.array([(0.5, -24), (17, -24), (17, -21), (50, -17), (56, -20), (rim_r, -25), (rim_r, 25), (56, 20), (50, 17), (17, 21), (17, 24), (0.5, 24)]) * M, sections=64)
    cc = disc.triangles_center; pr = int(np.argmax(cc[:, 2]))
    if disc.face_normals[pr][2] < 0: disc.invert()
    fins = []
    from shapely.geometry import Polygon
    for g0 in (0, 90, 180, 270):
        for dg in (-21, 0, 21):
            a_ = math.radians(g0 + dg)
            for side in (-1, 1):
                f = trimesh.creation.extrude_polygon(Polygon([(24, 0), (56, -4.5), (56, 4.5)]), 3.0)
                f.apply_scale(M); f.apply_translation([0, 0, (side * 19.0 - 1.5) * M])
                f.apply_transform(trimesh.transformations.rotation_matrix(a_, [0, 0, 1])); fins.append(f)
    wheel = paint(trimesh.util.concatenate([disc] + fins), "wheel")
    holes = []
    for kq in range(4):
        a_ = math.pi / 4 + kq * math.pi / 2
        for side in (-1, 1):
            h = trimesh.creation.cylinder(radius=11 * M, height=1.0 * M, sections=28)
            h.apply_translation([33 * math.cos(a_) * M, 33 * math.sin(a_) * M, side * 19.3 * M]); holes.append(h)
    holes = paint(trimesh.util.concatenate(holes), "black")
    return [("tire_carcass", carc), ("tire_tread", tread), ("wheel_disc", wheel), ("wheel_holes", holes)]

scene = trimesh.Scene()
def add(geom, name, parent, tf=None):
    scene.add_geometry(geom, node_name=name, geom_name=name, parent_node_name=parent, transform=tf if tf is not None else np.eye(4))

def node(name, parent, tf):
    scene.graph.update(frame_from=parent, frame_to=name, matrix=tf)


_WHEEL_GEO = None
def add_wheel(wn):
    """車輪の形は1つだけ持ち、4輪はそれを指す"""
    global _WHEEL_GEO
    if _WHEEL_GEO is None:
        _WHEEL_GEO = tire_parts()
        for gname, g in _WHEEL_GEO:
            scene.add_geometry(g, node_name=f"{wn}_{gname}", geom_name=gname, parent_node_name=wn)
    else:
        for gname, g in _WHEEL_GEO:
            scene.graph.update(frame_from=wn, frame_to=f"{wn}_{gname}", matrix=np.eye(4), geometry=gname)
ROOT = scene.graph.base_frame
node("mitra", ROOT, np.eye(4))
node("body", "mitra", np.eye(4))

# ---------------- 車体（ばね上） ----------------
fx, rx = v("derived", "deck_front_x"), v("derived", "deck_rear_x")
L, W, Htop = v("spec", "deck_length"), v("spec", "deck_width"), v("spec", "deck_top_height")
PD = v("deck", "pipe_d"); PH = v("deck", "pipe_center_h"); CR = v("deck", "corner_r")
def polytube(pts, d, c, closed=False):
    pts = [np.array(q, float) for q in pts]
    if closed: pts = pts + [pts[0]]
    segs = [tube(pts[i], pts[i + 1], d, c) for i in range(len(pts) - 1) if np.linalg.norm(pts[i + 1] - pts[i]) > 1e-6]
    balls = []
    for q in pts:
        sp = trimesh.creation.icosphere(subdivisions=1, radius=d / 2 * M); sp.apply_translation(q * M); balls.append(paint(sp, c))
    return trimesh.util.concatenate(segs + balls)
def arc(c0, r, a0, a1, y, n=7):
    return [(c0[0] + r * math.cos(t), y, c0[1] + r * math.sin(t)) for t in np.linspace(a0, a1, n)]
# 上の枠：丸パイプの輪（外の大きさ 887×401、上の面が荷台上面高 355）
xf, xr, zs = fx - PD / 2, rx + PD / 2, W / 2 - PD / 2
hoop = (arc((xf - CR, zs - CR), CR, math.pi / 2, 0, PH) + arc((xf - CR, -zs + CR), CR, 0, -math.pi / 2, PH)
        + arc((xr + CR, -zs + CR), CR, -math.pi / 2, -math.pi, PH) + arc((xr + CR, zs - CR), CR, math.pi, math.pi / 2, PH))
cf = [polytube(hoop, PD, "black", closed=True)]
CX = v("deck", "cross_x")
for xx in CX:
    cf.append(tube([xx, PH, -zs], [xx, PH, zs], 25, "black"))
cf.append(tube([CX[0], PH, 0], [CX[1], PH, 0], 25, "black"))
# 前の縦のパイプ2本 → 下で後ろへ曲がり、斜め外へ広がって側面へ → 車軸のあいだを後ろへ（下のパイプ）
FPX, FPZ, LH = xf, 60, 125
for s_ in (-1, 1):
    path = [(FPX, PH, s_ * FPZ), (FPX, LH + 30, s_ * FPZ), (FPX - 9, LH + 9, s_ * FPZ), (FPX - 30, LH, s_ * FPZ),
            (330, LH, s_ * FPZ), (CX[0] + 25, LH, s_ * (zs - 12)), (CX[0], LH, s_ * zs), (CX[1], LH, s_ * zs)]
    cf.append(polytube(path, 25, "black"))
    for xx in CX:                                                                # 側面の柱
        cf.append(tube([xx, LH, s_ * zs], [xx, PH, s_ * zs], 25, "black"))
    cf.append(box(30, 40, 16, FPX - 5, v("front_bar", "center_h") + 18, s_ * (v("front_bar", "width") / 2), "black"))  # U の字の棒の受け
cf.append(box(40, 22, 2 * FPZ + 60, FPX - 5, 154, 0, "black"))                    # 前のパイプ2本をつなぐ横の部材
cf.append(box(60, 40, 2 * v("front_suspension", "arm_pivot_z") + 40, v("derived", "front_axle_x"), v("front_suspension", "arm_pivot_h") + 6, 0, "black"))  # 前のアームの付け根を受ける梁
cf.append(tube([v("derived", "front_axle_x"), LH, -zs + 60], [v("derived", "front_axle_x"), LH, zs - 60], 22, "black"))
# 後ろ：輪から下りる柱と、ばねの上の受け
for s_ in (-1, 1):
    cf.append(tube([xr + 20, PH, s_ * zs], [xr + 20, 250, s_ * zs], 25, "black"))
    cf.append(box(40, 30, 30, v("rear_suspension", "damper_x"), v("rear_suspension", "damper_top_h") - 5, s_ * (zs - 5), "black"))
add(trimesh.util.concatenate(cf), "chassis", "body")

# 前の棒・後ろの取っ手
ftip = v("front_bar", "tip_x") - v("front_bar", "tube_d") / 2
rtip = v("rear_handle", "tip_x") + v("rear_handle", "tube_d") / 2
add(bent_u(ftip, v("front_bar", "center_h"), v("front_bar", "width"), ftip - (FPX - 5), v("front_bar", "tube_d"), "black", -1), "front_bar", "body")
add(bent_u(rtip, v("rear_handle", "center_h"), v("rear_handle", "width"), (rx + 40) - rtip, v("rear_handle", "tube_d"), "black", 1), "rear_handle", "body")

# 電池2個・制御の箱・前輪の向きを変えるモーターの箱
BB = D["battery_box"]
for nm, key in (("battery_mid", "mid_x"), ("battery_rear", "rear_x")):
    x0_, x1_ = BB[key]["v"]
    bt = [box(x0_ - x1_, BB["top_h"]["v"] - BB["bottom_h"]["v"] - 14, BB["width"]["v"], (x0_ + x1_) / 2, (BB["top_h"]["v"] + BB["bottom_h"]["v"]) / 2 - 7, 0, "battery"),
          box(x0_ - x1_ - 8, 14, BB["width"]["v"] - 8, (x0_ + x1_) / 2, BB["top_h"]["v"] - 7, 0, "black")]
    add(trimesh.util.concatenate(bt), nm, "body")
add(box(134, 172, 40, 93, 236, -(zs + 2), "black"), "controller_box", "body")
add(box(43, 81, 90, FPX + 14.5, 201.5, 0, "black"), "steering_servo", "body")

# オプション：アルミフレーム（カバープレート付き）セット。別の節にして、出し入れできるようにする
# 40mm 角のアルミの角フレーム。4つの面の真ん中に溝（へこみ）が1本ずつ入っている
node("option_deck", "body", np.eye(4))
from shapely.geometry import Polygon as _Poly
OW, OH = v("deck", "option_profile"); SW, SD = v("deck", "option_slot"); OL, OWD = v("deck", "option_outer")
OB, OT = v("deck", "option_bottom_h"), v("deck", "option_top_h")
def _profile_poly():
    h, w2 = OW / 2, SW / 2
    pts = []
    for q in range(4):                          # 4つの面を回しながら、真ん中に溝を切る
        ca, sa = math.cos(q * math.pi / 2), math.sin(q * math.pi / 2)
        for (px, py) in ((h - 1.5, -h), (h, -h + 1.5), (h, -w2), (h - SD, -w2), (h - SD, w2), (h, w2), (h, h - 1.5), (h - 1.5, h)):
            pts.append((px * ca - py * sa, px * sa + py * ca))
    return _Poly(pts)
def alu_bar(length, along):
    """角フレーム1本。along='x' か 'z'。溝の底は少し暗い色にして、へこみが見えるようにする"""
    m = trimesh.creation.extrude_polygon(_profile_poly(), length); m.apply_translation([0, 0, -length / 2])   # Z に伸びる
    floor = []
    for q in range(4):
        f = trimesh.creation.box(extents=[0.4, SW - 0.6, length - 1]); f.apply_translation([OW / 2 - SD + 0.25, 0, 0])
        f.apply_transform(trimesh.transformations.rotation_matrix(q * math.pi / 2, [0, 0, 1])); floor.append(f)
    floor = trimesh.util.concatenate(floor)
    for g in (m, floor):
        g.apply_scale(M)
        if along == "x": g.apply_transform(trimesh.transformations.rotation_matrix(math.pi / 2, [0, 1, 0]))
    return paint(m, "alu"), paint(floor, "slot")
ocx = (fx + rx) / 2; ox0, ox1 = ocx + OL / 2, ocx - OL / 2; oy = (OB + OT) / 2
CAP = 4
bars, floors = [], []
def put_bar(length, along, x, z):
    m, f = alu_bar(length, along)
    for g in (m, f): g.apply_translation([x * M, oy * M, z * M])
    bars.append(m); floors.append(f)
for s_ in (-1, 1):
    put_bar(OL - 2 * CAP, "x", ocx, s_ * (OWD / 2 - OW / 2))                 # 左右の長いフレーム
cross_x = (ox0 - OW / 2, ocx, ox1 + OW / 2)
for xx in cross_x:
    put_bar(OWD - 2 * OW, "z", xx, 0)                                         # 前・真ん中・後ろの横のフレーム
add(trimesh.util.concatenate(bars), "option_frame", "option_deck")
add(trimesh.util.concatenate(floors), "option_frame_slots", "option_deck")
# 板2枚（フレームの内側に落とし込み。上の面はフレームより 2mm 低い）と、四隅のねじ
pl, screws = [], []
zin = OWD / 2 - OW - 1
for i in range(2):
    xa, xb = cross_x[i] - OW / 2 - 1, cross_x[i + 1] + OW / 2 + 1
    pl.append(box(xa - xb, 3, 2 * zin, (xa + xb) / 2, OT - 3.5, 0, "plate"))
    for xs in (xa - 14, xb + 14):
        for zs_ in (-zin + 14, zin - 14):
            c_ = trimesh.creation.cylinder(radius=5 * M, height=2.4 * M, sections=16)
            c_.apply_transform(trimesh.transformations.rotation_matrix(math.pi / 2, [1, 0, 0])); c_.apply_translation([xs * M, (OT - 1.2) * M, zs_ * M]); screws.append(c_)
add(trimesh.util.concatenate(pl), "option_plates", "option_deck")
bk, bolts = [], []
def hexbolt(x, y, z, axis):
    c_ = trimesh.creation.cylinder(radius=8.5 * M, height=1.6 * M, sections=20)      # つば
    h_ = trimesh.creation.cylinder(radius=6.2 * M, height=6.5 * M, sections=6); h_.apply_translation([0, 0, 3.2 * M])
    g = trimesh.util.concatenate([c_, h_])
    if axis == "z-": g.apply_transform(trimesh.transformations.rotation_matrix(math.pi, [1, 0, 0]))
    if axis == "x+": g.apply_transform(trimesh.transformations.rotation_matrix(math.pi / 2, [0, 1, 0]))
    if axis == "x-": g.apply_transform(trimesh.transformations.rotation_matrix(-math.pi / 2, [0, 1, 0]))
    g.apply_translation([x * M, y * M, z * M]); bolts.append(g)
def bracket(x, z, side_face):
    y0, y1 = PH - 17, oy + 17                    # 下のボルトはパイプの中心、上のボルトはアルミの溝の中心
    if side_face:
        sg = 1 if z > 0 else -1
        bk.append(box(30, y1 - y0, 4, x, (y0 + y1) / 2, z + sg * 2, "black"))
        for yy in (PH, oy): hexbolt(x, yy, z + sg * 4.8, "z+" if sg > 0 else "z-")
    else:
        sg = 1 if x > ocx else -1
        bk.append(box(4, y1 - y0, 30, x + sg * 2, (y0 + y1) / 2, z, "black"))
        for yy in (PH, oy): hexbolt(x + sg * 4.8, yy, z, "x+" if sg > 0 else "x-")
for s_ in (-1, 1):
    for xx in (252, -32, -315): bracket(xx, s_ * OWD / 2, True)
    for zz in (-95, 95): bracket(ox0 if s_ > 0 else ox1, zz, False)
    for xx in (ox0 - CAP / 2, ox1 + CAP / 2):
        bk.append(box(CAP, OH + 1, OW + 1, xx, oy, s_ * (OWD / 2 - OW / 2), "black"))   # 長いフレームの端の黒いふた
add(trimesh.util.concatenate(bk), "option_brackets", "option_deck")
add(paint(trimesh.util.concatenate(bolts + screws), "bolt"), "option_bolts", "option_deck")

# ---------------- 前の足（左右に振れるアーム＋向きを変える軸＋車輪） ----------------
FS = D["front_suspension"]
fax = v("derived", "front_axle_x"); wch = v("derived", "wheel_center_height"); half = v("derived", "track_tire_center") / 2
pz, ph_ = FS["arm_pivot_z"]["v"], FS["arm_pivot_h"]["v"]
kz = FS["kingpin_z"]["v"]
for side, sgn in (("L", -1), ("R", 1)):
    sn = f"susp_F{side}"
    node(sn, "body", T(fax, ph_, sgn * pz))
    # アーム（付け根からナックルまで）。ニュートラルで車輪の中心が高さ130 になる向き
    dz = (kz - pz); dy = wch - ph_
    arm = trimesh.util.concatenate([tube([-25, 0, 0], [-25, dy, sgn * dz], 22, "black"), tube([25, 0, 0], [25, dy, sgn * dz], 22, "black"),
                                    tube([-25, dy, sgn * dz], [25, dy, sgn * dz], 26, "black")])
    add(arm, f"arm_F{side}", sn)
    stn = f"steer_F{side}"
    node(stn, sn, T(0, dy, sgn * dz))
    add(trimesh.util.concatenate([tube([0, -55, 0], [0, 60, 0], 24, "black"), tube([0, 0, 0], [0, 0, sgn * (half - kz - 30)], 30, "black"),
                                  tube([0, 20, 0], [-60, 20, 0], 10, "black")]), f"knuckle_F{side}", stn)
    wn = f"wheel_F{side}"
    node(wn, stn, T(0, 0, sgn * (half - kz)))
    add_wheel(wn)
    # ばねの両端の印
    st = FS["spring_top"]["v"]
    node(f"spring_top_F{side}", "body", T(st[0], st[1], sgn * st[2]))
    node(f"spring_bot_F{side}", sn, T(0, 25, sgn * (FS["spring_bottom_on_arm_z"]["v"] - pz)))

# ---------------- 後ろの足（前後に振れるアーム＋ハブのモーター＋車輪） ----------------
RS = D["rear_suspension"]
rax = v("derived", "rear_axle_x")
for side, sgn in (("L", -1), ("R", 1)):
    sn = f"susp_R{side}"
    az = RS["arm_z"]["v"]
    node(sn, "body", T(RS["arm_pivot_x"]["v"], RS["arm_pivot_h"]["v"], sgn * az))
    ax, ay = rax - RS["arm_pivot_x"]["v"], wch - RS["arm_pivot_h"]["v"]
    ex = RS["damper_x"]["v"] - RS["arm_pivot_x"]["v"]
    plate = trimesh.util.concatenate([tube([0, 0, 0], [ax, ay, 0], 34, "black"), tube([ax, ay, 0], [ex, ay - 5, 0], 26, "black"),
                                      tube([0, 0, -20], [0, 0, 20], 40, "black")])
    add(plate, f"arm_R{side}", sn)
    mot = paint(trimesh.creation.cylinder(radius=v("wheel", "rear_hub_motor_d") / 2 * M, height=v("wheel", "rear_hub_motor_len") * M, sections=40), "motor")
    mot.apply_translation([0, 0, sgn * (half - 42.5 - v("wheel", "rear_hub_motor_len") / 2 - az) * M])
    zc = sgn * (half - 42.5 - v("wheel", "rear_hub_motor_len") / 2 - az)
    gb = box(120, 110, 60, 55, 50, zc, "motor")                                   # ギヤ箱の鋳物（車軸から前上へ）
    gb.apply_transform(trimesh.transformations.rotation_matrix(math.radians(25), [0, 0, 1], [0, 0, 0]))
    m2 = tube([95, 30, zc], [215, 30, zc], 72, "bolt")                             # 銀色の筒のモーター（前へ寝ている）
    mot = trimesh.util.concatenate([mot, gb]); MOT2 = m2
    mn = f"motor_R{side}"
    node(mn, sn, T(ax, ay, 0))
    add(mot, f"{mn}_case", mn)
    add(MOT2, f"{mn}_motor", mn)
    wn = f"wheel_R{side}"
    node(wn, mn, T(0, 0, sgn * (half - az)))
    add_wheel(wn)
    node(f"spring_top_R{side}", "body", T(RS["damper_x"]["v"], RS["damper_top_h"]["v"], sgn * az))
    node(f"spring_bot_R{side}", sn, T(ex, ay - 5, 0))

# ばね（長さ1m の単位の形。視点ページで両端の印に合わせて伸び縮みさせる）
def unit_spring(col):
    pts = []
    for t in np.linspace(0, 1, 200):
        a = t * 2 * math.pi * 8
        pts.append([0.018 * math.cos(a), t, 0.018 * math.sin(a)])
    segs = [tube(np.array(pts[i]) / M, np.array(pts[i + 1]) / M, 5, col, sections=6) for i in range(0, 199, 1)]
    body = tube([0, 0.0 / M, 0], [0, 0.55 / M, 0], 26, "damper")
    rod = tube([0, 0.5 / M, 0], [0, 1.0 / M, 0], 12, "spring")
    return trimesh.util.concatenate(segs + [body, rod])
for k in ("FL", "FR", "RL", "RR"):
    node(f"spring_{k}", "body", np.eye(4))
    add(unit_spring("spring" if k[0] == "F" else "damper"), f"spring_{k}_mesh", f"spring_{k}")

node("mark_deck_front_edge", "mitra", T(fx, Htop, 0))          # パイプの枠の上・前の端
node("mark_option_top_front", "mitra", T(ox0, OT, 0))       # オプションのアルミフレームの上・前の端

# ばねをニュートラルの位置に合わせる（下の印→上の印へ、Y 軸を向けて長さを合わせる）
def world(n):
    return scene.graph.get(n)[0][:3, 3]
for k in ("FL", "FR", "RL", "RR"):
    a, b2 = world(f"spring_bot_{k}"), world(f"spring_top_{k}")
    d = b2 - a; l = np.linalg.norm(d); y = d / l
    x = np.cross(y, [0, 0, 1.0]); x = x / np.linalg.norm(x) if np.linalg.norm(x) > 1e-6 else np.array([1.0, 0, 0])
    z = np.cross(x, y)
    tf = np.eye(4); tf[:3, 0] = x; tf[:3, 1] = y * l; tf[:3, 2] = z; tf[:3, 3] = a
    scene.graph.update(frame_from="body", frame_to=f"spring_{k}", matrix=tf)
    print(f"spring {k}: length {l / M:.0f}mm")

out = sys.argv[2] if len(sys.argv) > 2 else "mitra_v1.glb"
scene.export(out)
print("wrote", out)
# 確かめ：外形
b = scene.bounds / M
print("bounds mm  x %.1f..%.1f  y %.1f..%.1f  z %.1f..%.1f" % (b[0][0], b[1][0], b[0][1], b[1][1], b[0][2], b[1][2]))
