"""依頼 390: so101/sim/look_389/render_389.py (板の縁・部屋) を そのまま読み (書き換えない), look の detail_390 にある 腕の細部だけを足して描く.
  board_rim : 手首カメラの基板の ふちの明るい帯 (実機: 黒い基板のまわりに 明るい灰色の枠). 基板の材質に 帯 (ふちから rim_mm) を混ぜる.
              基板の地・点の色と量は look の materials.cam (board_rgb・board_dots_rgb・board_dots_frac) をそのまま使う
  ring      : 黒いケーブルの留め具の 輪 (g18 に付く. 中心・軸・半径は fit/ring_390.json)
  cable2    : 2 本目の黒い線 (サーボ g20 の差し口 → 留め具 g18 → 台座 g3. fit/cable2_390.json). 毎コマ cable_366.chain で形を作る
  wires     : サーボの赤白黒の線 (3 本並び). replace = true なら look の cable.servo_wires (依頼 366 の wire_wrist) の代わりに描く (fit/loop_right_390.json)
look に detail_390 が無ければ render_389 と同じ. サーボのつやは look の materials.servos をそのまま (render_368 の決まり) 使う.

使い方 (Blender の中. 引数は render_368 と同じ):
  blender -b --factory-startup --python so101/sim/look_390/render_390.py -- --look sim/look_390/look_390_<組>.json --src ... --out ... --tag v3 --labels
"""
import math
from pathlib import Path

import bpy
import numpy as np

SO101 = Path(__file__).resolve().parent.parent.parent
SRC = SO101 / "sim" / "look_389" / "render_389.py"
code = SRC.read_text().rstrip()
tail = 'G["build"], G["world"], G["label_mode"] = build, world, label_mode\nG["main"]()\nprint("render_389", INFO, flush=True)'
assert code.endswith(tail)
H = {"__file__": str(SRC), "__name__": "render_389"}
exec(compile(code[:-len(tail)], str(SRC), "exec"), H)
G = H["G"]
G["build"], G["world"], G["label_mode"] = H["build"], H["world"], H["label_mode"]
LOOK = G["LOOK"]
D = LOOK.get("detail_390", {})
CB = G["CB"]
INFO = {}
EXTRA = []  # (curve の object, 種類, 3 本のうち何本目)


def V(nt, op, a, b=None):
    n = nt.nodes.new("ShaderNodeVectorMath")
    n.operation = op
    for k, v in enumerate((a, b)):
        if v is None:
            continue
        if isinstance(v, (tuple, list)):
            n.inputs[k].default_value = v
        else:
            nt.links.new(v, n.inputs[k])
    return n.outputs["Value"] if op in ("DOT_PRODUCT", "LENGTH", "DISTANCE") else n.outputs["Vector"]


def M(nt, op, a, b=None):
    n = nt.nodes.new("ShaderNodeMath")
    n.operation = op
    for k, v in enumerate((a, b)):
        if v is None:
            continue
        if isinstance(v, (int, float)):
            n.inputs[k].default_value = v
        else:
            nt.links.new(v, n.inputs[k])
    return n.outputs[0]


_board_material = G["board_material"]


def board_material():
    """元の基板の材質 (地 + 点) に ふちの帯を混ぜる. 帯 = 基板の四角 (形の座標) の ふちから rim_mm の内側."""
    m = _board_material()
    r = D.get("board_rim")
    if not r:
        return m
    nt = m.node_tree
    b = nt.nodes["Principled BSDF"]
    src = b.inputs["Base Color"].links[0].from_socket
    c0 = np.asarray(r["center_mm"], float) / 1000  # 形の座標は m
    e1, e2 = np.asarray(r["e1"], float), np.asarray(r["e2"], float)  # 単位ベクトル
    tc = nt.nodes.new("ShaderNodeTexCoord")
    p = V(nt, "SUBTRACT", tc.outputs["Object"], tuple(c0))
    u = M(nt, "ABSOLUTE", V(nt, "DOT_PRODUCT", p, tuple(e1)))
    w = M(nt, "ABSOLUTE", V(nt, "DOT_PRODUCT", p, tuple(e2)))
    du = M(nt, "SUBTRACT", u, (r["half_mm"][0] - r["rim_mm"]) / 1000)
    dw = M(nt, "SUBTRACT", w, (r["half_mm"][1] - r["rim_mm"]) / 1000)
    fac = M(nt, "GREATER_THAN", M(nt, "MAXIMUM", du, dw), 0.0)
    mix = nt.nodes.new("ShaderNodeMix")
    mix.data_type = "RGBA"
    nt.links.new(fac, mix.inputs["Factor"])
    nt.links.new(src, mix.inputs[6])
    mix.inputs[7].default_value = (*r["rgb"], 1)
    nt.links.new(mix.outputs[2], b.inputs["Base Color"])
    rr = nt.nodes.new("ShaderNodeMix")
    rr.data_type = "FLOAT"
    nt.links.new(fac, rr.inputs["Factor"])
    rr.inputs[2].default_value = LOOK["materials"]["cam"]["board_rough"]
    rr.inputs[3].default_value = r["rough"]
    nt.links.new(rr.outputs[0], b.inputs["Roughness"])
    INFO["board_rim"] = r["rim_mm"]
    return m


def ring_curve(sc, rg):
    c = np.asarray(rg["center_mm"], float) / 1000
    ax = np.asarray(rg["axis_g18"], float)
    a = np.cross(ax, [0, 0, 1.0]) if abs(ax[2]) < 0.9 else np.cross(ax, [1.0, 0, 0])
    a /= np.linalg.norm(a)
    b = np.cross(ax, a)
    t = np.linspace(0, 2 * np.pi, 48, endpoint=False)
    P = [c + rg["R_mm"] / 1000 * (np.cos(tt) * a + np.sin(tt) * b) for tt in t]
    cu = bpy.data.curves.new("ring390", "CURVE")
    cu.dimensions = "3D"
    cu.bevel_depth = rg["r_mm"] / 1000
    cu.bevel_resolution = 3
    sp = cu.splines.new("POLY")
    sp.points.add(len(P) - 1)
    for j, p in enumerate(P):
        sp.points[j].co = (*[float(x) for x in p], 1.0)
    sp.use_cyclic_u = True
    o = bpy.data.objects.new("ring390", cu)
    return o


def chain_pts(geoms, ch):
    old = CB.SAG_GRAVITY
    CB.SAG_GRAVITY = ch["sag_gravity"]
    try:
        return CB.chain(geoms, [(g, tuple(p)) for g, p in ch["anchors"]], ch["rest_mm"], [(g, tuple(o)) for g, o in ch["out"]], n_sag=8, n_per=3)
    finally:
        CB.SAG_GRAVITY = old


_build = G["build"]


def build(block_mm, geoms0):
    sc, objs, cams = _build(block_mm, geoms0)
    EXTRA.clear()
    MAT = LOOK["materials"]
    LB = LOOK["labels"]
    c = MAT["cable"]
    rg = D.get("ring")
    if rg:
        o = ring_curve(sc, rg)
        o.data.materials.append(G["principled"]("ring390", rg["rgb"], rg["rough"], rg["spec"]))
        o.color = (LB["L_CABLE"] / 10.0, 0.0, LB["part"]["cam_cable"] / 20.0, 1)
        sc.collection.objects.link(o)
        from mathutils import Matrix
        objs["ring390"] = (o, Matrix.Identity(4), 2, rg["geom"])
        INFO["ring"] = rg["R_mm"]
    c2 = D.get("cable2")
    if c2:
        P = chain_pts(geoms0, c2)
        cm = G["principled"]("cable2_390", c2["rgb"], c["cable_rough"], c["cable_spec"])
        EXTRA.append((G["make_curve"](sc, "cable2_390", len(P), c2["radius_mm"], cm, LB["L_CABLE"], LB["part"]["cam_cable"]), c2, -9))
        INFO["cable2"] = c2["radius_mm"]
    wr = D.get("wires")
    if wr:
        if wr.get("replace"):
            for co, i, k in list(G["CURVES"]):
                if i > 0:  # 0 = 手首カメラの線. 1 から = look の servo_wires
                    G["CURVES"].remove((co, i, k))
                    bpy.data.objects.remove(co)
        wm = [G["principled"](f"wire390_{j}", rgb, c["wire_rough"], c["wire_spec"]) for j, rgb in enumerate(c["wire_rgb"])]
        for w in wr["list"]:
            P = chain_pts(geoms0, w)
            for j, k in enumerate((-1, 0, 1)):
                EXTRA.append((G["make_curve"](sc, f"{w['name']}_{j}", len(P), LOOK["cable"]["wire_radius_mm"], wm[j], LB["L_CABLE"], LB["part"]["wire"]), w, k))
        INFO["wires"] = [w["name"] for w in wr["list"]]
    return sc, objs, cams


_update = G["update_curves"]


def update_curves(geoms):
    _update(geoms)
    for o, ch, k in EXTRA:
        P = chain_pts(geoms, ch)
        if k not in (-9, -1):
            P = G["strand_offsets"](P, k, LOOK["cable"]["wire_gap_mm"])
        for j, p in enumerate(P):
            o.data.splines[0].points[j].co = (float(p[0]), float(p[1]), float(p[2]), 1.0)


G["board_material"], G["build"], G["update_curves"] = board_material, build, update_curves
G["main"]()
print("render_390", INFO, flush=True)
