"""依頼 368: SO-101 の Blender の見た目の決まり so101/blender/look_blender_v1.json を作る (1 回だけ使う).

値は 依頼 366 の S123 (光 FA) が描いたときのものを そのまま集める (当てはめ直さない):
- 光 FA・机の絵のむらの直し (table_fit_FAf.png)・明るさの倍率 (gain_FA.json): 依頼 364
- 箱の置き方: 依頼 365 の so101/sim/box_365.json (読むだけ)
- 箱・ブロックの材質: 依頼 363 (V363) と 依頼 364 (BLOCK364)
- サーボ (servo_366.json)・ケーブル (cable_fit_366.json・cable_366 の太さ)・手首カメラ (render_366 の CAM366)・線の色 (CABLE366): 依頼 366
- 腕・爪・机の色と 光の元の値 (向き・色): 依頼 361 の check_361/scene/look.json
光の強さは render_366.lights と同じ式で 先に計算して入れる (パネル = π max(rgb) panel_k × π d², 後ろの光 = π max(rgb) back_k).

使い方: python3 so101/blender/make_look_368.py   # → so101/blender/look_blender_v1.json
"""

import hashlib
import json
import math
from pathlib import Path

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
OUT = HERE / "look_blender_v1.json"

# render_366.py の値 (依頼 361・363・364・366. ここに写した. render_366 は変えていない)
ROUGH = {"table": 0.8, "printed": 0.55, "servo": 0.45, "jaw": 0.7}
SPEC = {"table": 0.1, "printed": 0.3, "servo": 0.4, "jaw": 0.2}
SSS = {"jaw": [0.6, 0.003], "printed": [0.15, 0.002]}
LIGHT_FA = {"panel_az_deg": 10, "panel_el_deg": 40, "panel_dist_m": 1.4, "panel_k": 2.0, "panel_size_m": [0.25, 0.20],
            "panel_target": [0.22, -0.10, 0.0], "back_k": 0.5, "back_angle_deg": 40.0, "back_shadow": True, "amb_k": 0.8}
CAM366 = {"board_rgb": [0.20, 0.225, 0.20], "board_rough": 0.45, "board_spec": 0.5, "board_dots_rgb": [0.80, 0.78, 0.70], "board_dots_frac": 0.18,
          "board_noise_scale": 900.0, "lens_rgb": [0.04, 0.04, 0.04], "lens_rough": 0.2, "lens_spec": 0.8,
          "back_rgb": [0.10, 0.10, 0.10], "back_rough": 0.5, "back_spec": 0.5,
          "plug_rgb": [0.80, 0.79, 0.76], "plug_rough": 0.5, "plug_spec": 0.3, "plug_mm": [8.0, 4.0, 3.5]}
CABLE366 = {"cable_rgb": [0.045, 0.045, 0.045], "cable_rough": 0.45, "cable_spec": 0.5,
            "wire_rgb": [[0.55, 0.03, 0.03], [0.02, 0.02, 0.02], [0.75, 0.74, 0.72]], "wire_rough": 0.4, "wire_spec": 0.5}


def rd(p):
    return json.loads((SO101 / p).read_text())


def sha(p):
    return hashlib.sha256((SO101 / p).read_bytes()).hexdigest()


def toward(az, el):
    a, e = math.radians(az), math.radians(el)
    return [math.cos(e) * math.cos(a), math.cos(e) * math.sin(a), math.sin(e)]


def main():
    look = rd("check_361/scene/look.json")
    C = look["colors"]
    servo = rd("check_366/servo_366.json")
    fit = rd("check_366/cable_fit_366.json")
    box = rd("sim/box_365.json")["for_sim"]
    gain = rd("check_364/gain_FA.json")
    tex = "check_364/_tex/table_fit_FAf.png"

    # 光 (render_366.lights と同じ計算)
    L = look["lights"]
    mx = max(L[0]["rgb"])
    d = LIGHT_FA["panel_dist_m"]
    u = toward(LIGHT_FA["panel_az_deg"], LIGHT_FA["panel_el_deg"])
    panel = {"type": "AREA", "shape": "RECTANGLE", "size_m": LIGHT_FA["panel_size_m"], "dist_m": d, "target_m": LIGHT_FA["panel_target"],
             "az_deg": LIGHT_FA["panel_az_deg"], "el_deg": LIGHT_FA["panel_el_deg"], "toward": u,
             "pos_m": [LIGHT_FA["panel_target"][i] + d * u[i] for i in range(3)],
             "energy_W": math.pi * mx * LIGHT_FA["panel_k"] * math.pi * d * d, "color": [c / mx for c in L[0]["rgb"]], "shadow": bool(L[0]["shadow"]),
             "from": "依頼 364 FA: 25×20cm の面の光. 方位 10°・高さ 40°・机の (0.22, −0.10) から 1.4m. 強さ = 依頼 361 のパネル × 2.0 (平行光の強さ S を π d² S に直した)"}
    backs = []
    for Lj in L[1:]:
        m = max(Lj["rgb"])
        backs.append({"type": "SUN", "toward": Lj["u"], "energy": math.pi * m * LIGHT_FA["back_k"], "color": [c / m for c in Lj["rgb"]],
                      "angle_deg": LIGHT_FA["back_angle_deg"], "shadow": bool(Lj["shadow"]) and LIGHT_FA["back_shadow"]})
    amb = [c * LIGHT_FA["amb_k"] for c in look["ambient_rgb"]]

    wall = C["box_wall_353"]
    sv = {}
    for g, v in servo["servos"].items():
        sv[g] = {"rgb": v["rgb"], "rough": v["rough"], "spec": v["spec"], "coat": v.get("coat", 0.0), "coat_rough": v.get("coat_rough", 0.2), "from": v["from"]}

    out = {
        "name": "look_blender_v1",
        "robot": "SO-101 (LeRobot)",
        "made": "2026-11-30 依頼 368 (so101/blender/make_look_368.py. 値は 依頼 366 の S123・光 FA で描いたときのまま. 当てはめ直していない)",
        "use": "これからの Blender の依頼は このファイルを読む. 描く: so101/blender/render_368.py --look so101/blender/look_blender_v1.json. "
               "値を変えるときは このファイルを書き換えず look_blender_v2.json を作る",
        "decided": {
            "by": "エイイチ", "when": "2026-11-30 7:28",
            "what": ["光は FA (依頼 364)",
                     "依頼 364 の机の絵のむらの直しと, 依頼 366 のサーボ・ケーブル・基板の値 (servo_366.json・cable_fit_366.json・render_366 の CAM366・CABLE366) を Blender の決まりにする",
                     "箱は 依頼 365 の so101/sim/box_365.json",
                     "箱の内側に写る半円は 実物に切り欠きはない. 形には足さない"],
        },
        "paths_base": "so101/ (下の path は so101/ からの相対)",
        "assets": {
            "geoms": {"path": "check_361/scene/geoms.json", "from": "依頼 361 (MuJoCo lv8 の geom の並び・ラベル・群)"},
            "meshes": {"path": "check_361/scene/meshes.npz", "from": "依頼 361 (腕の形)"},
            "table_texture": {"path": tex, "sha256": sha(tex), "colorspace": "Non-Color", "interpolation": "Linear",
                              "from": "依頼 364: 机の絵を平らにして FA で描き (table_flat_s40.png), 当てはめの本 tune01 の実機のむらを掛け直したもの (post_364 --make-tex-fit tune01:FAf)"},
        },
        "render": {"engine": "CYCLES", "device": "GPU (Metal. Mac)", "samples": 32, "adaptive_sampling": False, "denoise": "OPENIMAGEDENOISE (GPU)",
                   "max_bounces": 8, "diffuse_bounces": 3, "glossy_bounces": 2, "transmission_bounces": 4, "caustics": False,
                   "view_transform": "Raw", "png": "RGB 16bit", "persistent_data": True,
                   "from": "依頼 361・364 (サンプル 32 は 依頼 361 から)"},
        "cameras": {**look["cams"], "from": "依頼 361 (sensor_fit VERTICAL・sensor_height 24mm・lens = 12 / tan(fovy/2)・clip 0.001〜10m. 位置はコマごとの 4×4 = poses.json)"},
        "light": {"name": "FA", "panel": panel, "back": backs, "ambient_rgb": amb, "ambient_camera_ray_black": True,
                  "from": "依頼 364 の FA (エイイチ 2026-11-30 7:28 に決定). 後ろの柔らかい光 = 依頼 361 の lights[1:] × 0.5・広がり 40°・影あり. 部屋全体 = 依頼 361 の ambient × 0.8 (カメラから直に見える所は黒)"},
        "materials": {
            "table_outside": {"rgb": C["table_outside"], "rough": ROUGH["table"], "spec": SPEC["table"], "from": "依頼 361"},
            "table_tex": {"rgb": "table_texture の絵", "rough": ROUGH["table"], "spec": SPEC["table"], "from": "依頼 361 (絵は 依頼 364)"},
            "printed": {"rgb": C["printed"], "rough": ROUGH["printed"], "spec": SPEC["printed"], "sss": SSS["printed"], "from": "依頼 361 (腕の白い部品・手首カメラの台 g30)"},
            "jaw": {"rgb": C["jaw_353"], "rough": ROUGH["jaw"], "spec": SPEC["jaw"], "sss": SSS["jaw"], "from": "依頼 361 (爪 g28・g34)"},
            "servo_base": {"rgb": C["servo"], "rough": ROUGH["servo"], "spec": SPEC["servo"], "from": "依頼 361 (下の servos に無いサーボだけ. 今は使っていない)"},
            "servos": {**sv, "from": "依頼 366 servo_366.json (当てはめの本 check_363/tune01 の実機 ÷ 364 FA の Y の比. 3 回直した). 材質は object の側に持つ"},
            "block": {"rgb": C["block"], "rough": 0.25, "spec": 0.8, "coat": 0.5, "coat_rough": 0.15, "bevel_mm": 1.0, "bevel_samples": 8, "bounce_k": 0.6,
                      "from": "依頼 363 (角の丸み 1mm) と 依頼 364 (上塗り 0.5・粗さ 0.25・照り返し ×0.6 = 拡散の光線には 色 × 0.6 の拡散だけを返す)"},
            "box": {"out": {"rgb": [c * 0.75 for c in wall], "rough": 0.5, "spec": 0.3},
                    "rim": {"rgb": [c * 0.6 for c in wall], "rough": 0.5, "spec": 0.3},
                    "in": {"rgb": wall, "rough": 0.5, "spec": 0.3},
                    "floor": {"rgb": wall, "rough": 0.5, "spec": 0.3},
                    "from": "依頼 363 (透けなし・底は壁と同じ色・上の切り口 ×0.6・外の壁 ×0.75. 色の元 = 依頼 361 の box_wall_353)"},
            "cam": {**CAM366, "from": "依頼 366 render_366.CAM366 (手首カメラの形を 基板・レンズ・裏の部品に分け 白い差し口を足す. 基板の地は 3 回直した)"},
            "cable": {**CABLE366, "from": "依頼 366 render_366.CABLE366 (手首カメラの黒いケーブル・手首のサーボのまわりの 赤・黒・白 の 3 本)"},
        },
        "box": {"xy_mm": box["xy"], "yaw_deg": box["yaw"], "outer_mm": box["size_xy"], "height_mm": box["height"], "wall_mm": box["wall"], "floor_mm": 3.0,
                "units": "アームの座標 mm (原点 = 台座の回る軸の机の面, +x 前, +y 左). 向き = +x から +y へ回る度",
                "shape": "上が開いた 1 つの閉じた形 (外の壁・上の切り口・内の壁・底の内側). 切り欠きは無い",
                "from": "依頼 365 so101/sim/box_365.json の for_sim (読んで写した). 底の厚さ 3mm は 依頼 363"},
        "cable": {"cam_radius_mm": 1.5, "wire_radius_mm": 0.55, "wire_strands": 3, "wire_gap_mm": 1.1,
                  "cam_cable": fit["cam_cable"], "cam_rest_mm": fit["cam_rest_mm"], "cam_out": fit["cam_out"], "sag_gravity": fit["sag_gravity"],
                  "servo_wires": [{k: w[k] for k in ("name", "a", "b", "rest_mm", "out")} for w in fit["servo_wires"]],
                  "shape": "cable_366.py (留め位置を geom の 4×4 で動かし, 区間ごとに rest のたるみ (放物線) + Catmull-Rom)",
                  "from": "依頼 366 cable_fit_366.json (当てはめの本 check_363/tune01 の 12 コマで 16.3px) と cable_366.py の太さ"},
        "post": {"gain_bgr": gain["gain_bgr"], "how": "post_361.Post (歪み・くせを足して 640×480) の明るさの倍率",
                 "from": "依頼 364 gain_FA.json (当てはめの本 tune01・51 コマ)"},
        "not_in_shape": {"box_semicircle": "箱の内側に写る半円: 実物に切り欠きはない (エイイチ 2026-11-30). 形には足さない. 見込みは check_368/REPORT.md"},
        "labels": {"L_TABLE": 1, "L_ARM": 2, "L_SERVO": 3, "L_BLOCK": 4, "L_BOXF": 5, "L_BOXW": 6, "L_JAW": 7, "L_BOXO": 8, "L_BOXR": 9, "L_CABLE": 10,
                   "part": {"g4": 1, "g6": 2, "g12": 3, "g20": 4, "g22": 5, "g26": 6, "cam_board": 7, "cam_lens": 8, "cam_back": 9, "cam_plug": 10,
                            "cam_cable": 11, "wire": 12, "cam_mount": 13},
                   "how": "ラベルの絵 (--labels): 赤 = ラベル ÷ 10, 緑 = 0.5 + 法線の z / 2, 青 = 部品の番号 ÷ 20 (依頼 366 と同じ)"},
    }
    OUT.write_text(json.dumps(out, ensure_ascii=False, indent=1))
    print(OUT)


if __name__ == "__main__":
    main()
