"""依頼 445: look_393/render_393.py を そのまま読み (書き換えない. render_393 → render_389 → render_368), look の look445 の 4 つを足して描く.
  metal   : 関節の銀色. サーボ (sts3215_03a_v1) のホーン (直径 20mm の円板) の面を 金属の材質にし, ホーンの 4 つの穴の上に ねじの頭 (平たい円柱) を置く.
            ねじは ホーンに付く部品 (子) の座標で持つ (prep_445.json. 関節が回ると 子と一緒に回る)
  cam_tex : 手首カメラの裏. 基板 (cam_board) の 裏と縁の面 と 裏の部品 (cam_back) に 基板の写真 (prep_445 の tex/board_back_445.png) を
            基板の面 (cable_366.cam_board_frame の e1・e2) に沿って貼る. 色 = 写真 (sRGB → 線形) × gain
  wires   : サーボの線を 3 本撚りに替える (cable_445.wire_lines. 色 = 赤・白・黒)
  cam     : 黒いケーブルの通り道を cable_445.cam_line に替える (腕に沿う留め位置を足し, 輪の留め具の所に小さな輪)
look445 に無いものは 元 (render_393) のまま. ラベルの絵 (--labels): ねじ = ラベル 2 (腕)・部品 14, 線 = ラベル 10・部品 12, 黒いケーブル = 部品 11.

使い方 (Blender の中. 引数は render_368 と同じ):
  blender -b --factory-startup --python so101/sim/look_445/render_445.py -- --look sim/look_445/look_445.json --src ... --out ... --tag v445 --cams desk,wrist
"""
import math
import sys
from pathlib import Path

import bmesh
import bpy
import numpy as np
from mathutils import Matrix

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent.parent
SRC = SO101 / "sim" / "look_393" / "render_393.py"
code = SRC.read_text()
tail = 'G["build"], G["label_mode"] = build, label_mode'
assert tail in code
H = {"__file__": str(SRC), "__name__": "render_393"}
exec(compile(code[:code.index(tail)], str(SRC), "exec"), H)
G = H["G"]
LOOK = G["LOOK"]
INFO = H["INFO"]
L5 = LOOK.get("look445", {})
sys.path.insert(0, str(HERE))
import cable_445 as C5  # noqa: E402
CB = C5.CB
PART_METAL = 14


def metal_material(name, m):
    mat = G["principled"](name, m["rgb"], m["rough"], m.get("spec", 0.5))
    mat.node_tree.nodes["Principled BSDF"].inputs["Metallic"].default_value = m["metallic"]
    return mat


def add_horn_metal(m):
    """sts3215_03a_v1 の形の ホーンの面に 2 つ目の材質 (金属) を当てる (形は 5 つのサーボで共有. 1 つ目の材質は object の側のまま)."""
    me = bpy.data.meshes.get("sts3215_03a_v1")
    if me is None:
        return 0
    me.materials.append(metal_material("horn445", m))
    v = np.array([vv.co[:] for vv in me.vertices])
    horn = (v[:, 1] > 0.0163) & (np.hypot(v[:, 0], v[:, 2] - 0.01174) < 0.0105)
    n = 0
    for p in me.polygons:
        if all(horn[i] for i in p.vertices):
            p.material_index = 1
            n += 1
    return n


def screw_mesh():
    bm = bmesh.new()
    bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=20, radius1=1.0, radius2=0.8, depth=1.0)
    bmesh.ops.translate(bm, vec=(0, 0, 0.5), verts=bm.verts)  # 底 z = 0・上 z = 1
    me = bpy.data.meshes.new("screw445")
    bm.to_mesh(me)
    bm.free()
    for p in me.polygons:
        p.use_smooth = True
    return me


def add_screws(sc, objs, m):
    me = screw_mesh()
    mat = metal_material("screw445", {**m, "rgb": m.get("screw_rgb", m["rgb"]), "rough": m.get("screw_rough", m["rough"])})
    me.materials.append(mat)
    r, h = m["screw_r_mm"] / 1000, m["screw_h_mm"] / 1000
    for j, s in enumerate(m["screws"]):
        z = np.asarray(s["axis"], float)
        x = np.cross(z, [1.0, 0, 0]) if abs(z[0]) < 0.9 else np.cross(z, [0, 1.0, 0])
        x /= np.linalg.norm(x)
        y = np.cross(z, x)
        p = np.asarray(s["pos_mm"], float) / 1000
        S = Matrix([[x[0] * r, y[0] * r, z[0] * h, p[0]], [x[1] * r, y[1] * r, z[1] * h, p[1]],
                    [x[2] * r, y[2] * r, z[2] * h, p[2]], [0, 0, 0, 1]])
        o = bpy.data.objects.new(f"screw445_{j}", me)
        o.color = (G["L_ARM"] / 10.0, 0.0, PART_METAL / 20.0, 1)
        sc.collection.objects.link(o)
        objs[f"screw445_{j}"] = (o, S, objs[s["geom"]][2], s["geom"])
    return len(m["screws"])


def tex_material(c, img):
    m = G["principled"]("board_tex445", (1, 1, 1), c["rough"], c["spec"])
    nt = m.node_tree
    b = nt.nodes["Principled BSDF"]
    tx = nt.nodes.new("ShaderNodeTexImage")
    tx.image = img
    tx.interpolation = "Linear"
    tx.extension = "EXTEND"
    mul = nt.nodes.new("ShaderNodeMix")
    mul.data_type = "RGBA"
    mul.blend_type = "MULTIPLY"
    mul.inputs["Factor"].default_value = 1.0
    mul.clamp_result = True
    nt.links.new(tx.outputs["Color"], mul.inputs[6])
    mul.inputs[7].default_value = (*([c["gain"]] * 3), 1)
    nt.links.new(mul.outputs[2], b.inputs["Base Color"])
    return m


def add_board_tex(objs, c):
    """基板の 裏と縁の面 (面の向き · n < 0.3) と 裏の部品 に 写真を貼る (UV = 基板の面の e1・e2 に沿って. 絵の右 = e1・絵の下 = e2)."""
    meshes = np.load(SO101 / LOOK["assets"]["meshes"]["path"])
    geoms = {r["name"]: r for r in __import__("json").loads((SO101 / LOOK["assets"]["geoms"]["path"]).read_text())}
    v = meshes[geoms["g32"]["mesh"] + "_v"].astype(float) * 1000
    c0, n, e1, e2 = CB.cam_board_frame(v)
    (a1, b1), (a2, b2) = c["uv_e1_mm"], c["uv_e2_mm"]
    img = bpy.data.images.load(str(SO101 / c["image"]))
    img.colorspace_settings.name = "sRGB"
    mat = tex_material(c, img)
    cnt = 0
    for nm in ("cam_board", "cam_back"):
        if nm not in objs:
            continue
        me = objs[nm][0].data
        me.materials.append(mat)
        k = len(me.materials) - 1
        uv = me.uv_layers.new(name="UVMap")
        for p in me.polygons:
            if nm == "cam_back" or np.dot(np.array(p.normal[:]), n) < 0.3:
                p.material_index = k
                cnt += 1
        for li, lp in enumerate(me.loops):
            q = np.array(me.vertices[lp.vertex_index].co[:]) * 1000 - c0
            uv.data[li].uv = ((q @ e1 - a1) / (b1 - a1), 1 - (q @ e2 - a2) / (b2 - a2))
    return cnt


# ---- ケーブル ---------------------------------------------------------------------
CURVES5 = []  # (curve の object, 線の名前)


def lines(geoms):
    cab = {k: v for k, v in L5.items() if k in ("cam", "wires")}
    out = C5.all_lines(geoms, cab, old_cam=CB.cam_cable if "cam" not in cab else None)
    if "wires" not in cab:  # 元の 平たい 3 本 (render_368 と同じ)
        for nm, P, r, kind in CB.all_lines(geoms):
            if kind == "servo":
                for j, k in enumerate((-1, 0, 1)):
                    out.append((f"{nm}_{j}", G["strand_offsets"](P, k, LOOK["cable"]["wire_gap_mm"]), r, "wire", j))
    return out


def add_cables(sc, geoms0):
    CURVES5.clear()
    c = G["MAT"]["cable"]
    cm = G["principled"]("cable", c["cable_rgb"], c["cable_rough"], c["cable_spec"])
    W = L5.get("wires", {})
    rgbs = W.get("wire_rgb", c["wire_rgb"])
    wm = [G["principled"](f"wire{j}", rgb, W.get("wire_rough", c["wire_rough"]), W.get("wire_spec", c["wire_spec"])) for j, rgb in enumerate(rgbs)]
    for nm, P, r, kind, j in lines(geoms0):
        if kind == "cam":
            o = G["make_curve"](sc, nm, len(P), r, cm, G["L_CABLE"], G["PART"]["cam_cable"])
        else:
            o = G["make_curve"](sc, nm, len(P), r, wm[j], G["L_CABLE"], G["PART"]["wire"])
        CURVES5.append((o, nm))


def update_curves(geoms):
    L = {nm: P for nm, P, *_ in lines(geoms)}
    for o, nm in CURVES5:
        for j, p in enumerate(L[nm]):
            o.data.splines[0].points[j].co = (float(p[0]), float(p[1]), float(p[2]), 1.0)


_build = H["build"]


def build(block_mm, geoms0):
    sc, objs, cams = _build(block_mm, geoms0)
    m = L5.get("metal")
    if m:
        INFO["horn_faces"] = add_horn_metal(m)
        INFO["screws"] = add_screws(sc, objs, m)
    c = L5.get("cam_tex")
    if c:
        INFO["board_tex_faces"] = add_board_tex(objs, c)
    INFO["look445"] = sorted(L5)
    return sc, objs, cams


G["add_cables"], G["update_curves"] = add_cables, update_curves
G["build"], G["label_mode"] = build, H["label_mode"]
G["main"]()
print("render_445", INFO, flush=True)
