"""依頼 363: render_361.py と同じ描き方 (MuJoCo が出した geom・カメラの 4×4 を当てるだけ) で, 白い箱とブロックの見た目を変えて描く.

依頼 361 から変えたところ:
- 箱: MuJoCo の箱 (底 1 つ・壁 4 つの直方体. 外寸は box_336 の 95.7×89.4mm) を使わず, 外寸 80×80mm・高さ 45mm・壁と底の厚さ 3mm の
  1 つの閉じた形 (上が開いた箱) を描く. 中心と向きは MuJoCo の箱 (box_floor の位置と向き) のまま. 壁どうしが重なる角の黒い点が出なくなる.
  面ごとに 材質を分ける (外の壁・内の壁・上の切り口・底の内側). ラベルの絵でも分ける (L_BOXF 底の内側・L_BOXW 内の壁・L_BOXO 外の壁と裏・L_BOXR 切り口)
- ブロック: 大きさは 本ごとの poses.json の block_size_mm (依頼 361 は geoms.json の ep00 の 23.7mm をどの本にも使っていた).
  材質 (色の倍率・粗さ・つや・角の丸み) を変えられる
- 光: パネル・後ろの柔らかい光・部屋全体 の強さの倍率と, 部屋全体の光を上から来る向きに寄せる割合を変えられる
- ラベルの絵の緑に 面の向き (法線の z. 0.5 + z/2) を入れる (ブロックの上の面・横の面を分けるため). 赤は依頼 361 と同じ (ラベル ÷ 10)

値の組は VARIANTS (下). 使い方 (Blender の中):
  blender -b --factory-startup --python so101/blender/render_363.py -- --src check_361/ep00 --out check_363/ep00 --var v1 --samples 32 [--labels] [--frames 0,5]
書き出す: <out>/bl_<var>_s<N>/<コマ>_<desk|wrist>.png・<out>/bl363_lab/ (ラベル + 法線 z)・<out>/times_<var>.json
"""
import json
import math
import sys
import time
from pathlib import Path

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

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
SCN = SO101 / "check_361" / "scene"  # 形・光・色 (依頼 361 の書き出し. 読むだけ)

# ラベル (appearance_337 と同じ番号. 8・9 は依頼 363 で足した箱の面)
L_TABLE, L_ARM, L_SERVO, L_BLOCK, L_BOXF, L_BOXW, L_JAW, L_BOXO, L_BOXR = 1, 2, 3, 4, 5, 6, 7, 8, 9
BOX_MM = {"outer": (80.0, 80.0), "height": 45.0, "wall": 3.0, "floor": 3.0}  # エイイチが定規で測った外寸 (2026-11-29)

# 依頼 361 の値 (腕・爪・机はこのまま)
SUN_ANGLE_DEG = 15.0
SSS = {L_JAW: (0.6, 0.003), L_ARM: (0.15, 0.002)}
ROUGH = {L_TABLE: 0.8, L_ARM: 0.55, L_SERVO: 0.45, L_JAW: 0.7}
SPEC = {L_TABLE: 0.1, L_ARM: 0.3, L_SERVO: 0.4, L_JAW: 0.2}

# 値の組. 指定しないものは base (= 依頼 361 の箱・ブロック・光) のまま
BASE = {
    # 箱 (色は rgb の倍率. wall_rgb・floor_rgb は look.json の色の名前)
    "box_wall_rgb": "box_wall_353", "box_floor_rgb": "box_floor", "box_rgb_k": 1.0, "box_floor_k": 1.0,
    "box_sss": (1.0, 0.020), "box_floor_sss": (0.6, 0.004), "box_rough": 0.5, "box_spec": 0.3,
    "rim_k": 1.0, "rim_sss": None, "rim_rough": None, "out_k": 1.0,
    # ブロック
    "box_outer_mm": None,  # 切り分けだけ: 外寸を変える (None = 80×80)
    "block_k": 1.0, "block_rough": 0.3, "block_spec": 0.6, "block_bevel_mm": 0.0, "block_coat": 0.0, "block_coat_rough": 0.15,
    # 光 (パネル = look.json の lights[0]・後ろの柔らかい光 = lights[1:]・部屋全体 = ambient)
    "panel_k": 1.0, "back_k": 1.0, "amb_k": 1.0, "amb_top": 0.0, "amb_top_n": 2.0,
}
VARIANTS = {
    "base": {},  # 依頼 361 の材質・光で 箱の形だけ変えたもの
    # 箱 1 回目: 壁の透けを弱める・底を壁と同じ色にする・切り口を抑える
    "b1": {"box_sss": (0.3, 0.005), "box_floor_rgb": "box_wall_353", "box_floor_sss": (0.3, 0.003), "rim_k": 0.85, "rim_sss": (0.0, 0.001)},
    "b2": {"box_sss": (0.1, 0.003), "box_floor_rgb": "box_wall_353", "box_floor_sss": (0.1, 0.003), "rim_k": 0.75, "rim_sss": (0.0, 0.001),
           "amb_top": 0.5},
    "b3": {"box_sss": (0.3, 0.005), "box_floor_rgb": "box_wall_353", "box_floor_sss": (0.3, 0.003), "rim_k": 0.85, "rim_sss": (0.0, 0.001),
           "amb_top": 1.0},
    # 2 回目: 部屋全体の光の向きは変えない (b2・b3 は爪が暗くなった). 底の色を少し上げ, 切り口・外の壁を抑える. ブロックのつや (上塗り・角の丸み)
    "c1": {"box_sss": (0.1, 0.003), "box_floor_rgb": "box_wall_353", "box_floor_sss": (0.1, 0.003), "box_floor_k": 1.08,
           "rim_k": 0.65, "rim_sss": (0.0, 0.001), "out_k": 0.85, "block_coat": 0.5, "block_bevel_mm": 0.8},
    "c2": {"box_sss": (0.0, 0.001), "box_floor_rgb": "box_wall_353", "box_floor_sss": (0.0, 0.001), "box_floor_k": 1.12,
           "rim_k": 0.6, "rim_sss": (0.0, 0.001), "out_k": 0.8, "block_coat": 1.0, "block_spec": 0.8, "block_rough": 0.25,
           "block_bevel_mm": 1.0},
    "c3": {"box_sss": (0.0, 0.001), "box_floor_rgb": "box_wall_353", "box_floor_sss": (0.0, 0.001), "box_floor_k": 1.12,
           "rim_k": 0.6, "rim_sss": (0.0, 0.001), "out_k": 0.8, "block_coat": 1.0, "block_spec": 0.8, "block_rough": 0.25,
           "block_bevel_mm": 1.0, "panel_k": 1.2, "amb_k": 0.9},
    # 3 回目: c2 から 底の色を壁と同じ (倍率 1) に戻し, 外の壁を 0.75 に. ブロックの上塗りを鋭く (v1) / さらにブロック自体のつやも (v2)
    "v1": {"box_sss": (0.0, 0.001), "box_floor_rgb": "box_wall_353", "box_floor_sss": (0.0, 0.001), "box_floor_k": 1.0,
           "rim_k": 0.6, "rim_sss": (0.0, 0.001), "out_k": 0.75, "block_coat": 1.0, "block_coat_rough": 0.05, "block_spec": 0.8,
           "block_rough": 0.25, "block_bevel_mm": 1.0},
    "v2": {"box_sss": (0.0, 0.001), "box_floor_rgb": "box_wall_353", "box_floor_sss": (0.0, 0.001), "box_floor_k": 1.0,
           "rim_k": 0.6, "rim_sss": (0.0, 0.001), "out_k": 0.75, "block_coat": 1.0, "block_coat_rough": 0.05, "block_spec": 1.0,
           "block_rough": 0.15, "block_bevel_mm": 1.0},
    # 切り分け: base の箱の外寸を 依頼 361 (box_336 の 95.7×89.4mm) に戻したもの
    "base95": {"box_outer_mm": (95.7, 89.4)},
    # 切り分け: v2 の箱だけ (ブロックは依頼 361 のまま)
    "v2box": {"box_sss": (0.0, 0.001), "box_floor_rgb": "box_wall_353", "box_floor_sss": (0.0, 0.001), "box_floor_k": 1.0,
              "rim_k": 0.6, "rim_sss": (0.0, 0.001), "out_k": 0.75},
}


def arg(name, default):
    a = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
    return a[a.index(name) + 1] if name in a else default


def flag(name):
    a = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
    return name in a


def variant():
    nm = arg("--var", "base")
    V = dict(BASE)
    if nm in VARIANTS:
        V.update(VARIANTS[nm])
    else:  # その場で足す値 (JSON)
        V.update(json.loads(Path(nm).read_text()) if nm.endswith(".json") else {})
    if arg("--set", ""):
        V.update(json.loads(arg("--set", "")))
    return nm, V


def principled(name, rgb, rough, spec, sss=None, image=None):
    m = bpy.data.materials.new(name)
    m.use_nodes = True
    nt = m.node_tree
    b = nt.nodes["Principled BSDF"]
    b.inputs["Base Color"].default_value = (*rgb, 1)
    b.inputs["Roughness"].default_value = rough
    b.inputs["Specular IOR Level"].default_value = spec
    if sss is not None and sss[0] > 0:
        w, r = sss
        b.inputs["Subsurface Weight"].default_value = w
        b.inputs["Subsurface Scale"].default_value = r
        b.inputs["Subsurface Radius"].default_value = (1.0, 1.0, 1.0)
    if image is not None:
        tx = nt.nodes.new("ShaderNodeTexImage")
        tx.image = image
        tx.interpolation = "Linear"
        nt.links.new(tx.outputs["Color"], b.inputs["Base Color"])
    return m


def block_material(C, V):
    m = principled("block", [c * V["block_k"] for c in C["block"]], V["block_rough"], V["block_spec"])
    nt = m.node_tree
    b = nt.nodes["Principled BSDF"]
    if V["block_coat"] > 0:
        b.inputs["Coat Weight"].default_value = V["block_coat"]
        b.inputs["Coat Roughness"].default_value = V["block_coat_rough"]
    if V["block_bevel_mm"] > 0:  # 角の丸み (形は変えず 面の向きだけを丸める)
        bv = nt.nodes.new("ShaderNodeBevel")
        bv.samples = 8
        bv.inputs["Radius"].default_value = V["block_bevel_mm"] / 1000
        nt.links.new(bv.outputs["Normal"], b.inputs["Normal"])
        if V["block_coat"] > 0:
            nt.links.new(bv.outputs["Normal"], b.inputs["Coat Normal"])
    return m


def box_mesh(outer=None):
    """外寸 80×80・高さ 45・壁 3・底 3 (mm) の 上が開いた箱. 箱の座標 (中心・机の面が z=0). 面ごとに 材質の番号 と ラベル."""
    ox, oy = outer or BOX_MM["outer"]
    lx, ly = ox / 2000, oy / 2000
    h, t, tf = BOX_MM["height"] / 1000, BOX_MM["wall"] / 1000, BOX_MM["floor"] / 1000
    ix, iy = lx - t, ly - t
    bm = bmesh.new()

    def sq(x, y, z):
        return [bm.verts.new(p) for p in ((-x, -y, z), (x, -y, z), (x, y, z), (-x, y, z))]

    ob, ot = sq(lx, ly, 0), sq(lx, ly, h)  # 外の下・外の上
    it, ib = sq(ix, iy, h), sq(ix, iy, tf)  # 内の上・内の底
    faces = [(list(reversed(ob)), 0, L_BOXO)]  # 裏
    for k in range(4):
        j = (k + 1) % 4
        faces.append(([ob[k], ob[j], ot[j], ot[k]], 0, L_BOXO))  # 外の壁
        faces.append(([ot[k], ot[j], it[j], it[k]], 1, L_BOXR))  # 上の切り口
        faces.append(([it[k], it[j], ib[j], ib[k]], 2, L_BOXW))  # 内の壁
    faces.append((list(ib), 3, L_BOXF))  # 底の内側
    lay = bm.faces.layers.float.new("sublab")
    for vs, mi, lab in faces:
        f = bm.faces.new(vs)
        f.material_index = mi
        f[lay] = lab / 10.0
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    me = bpy.data.meshes.new("box363")
    bm.to_mesh(me)
    bm.free()
    return me


def build(V, block_mm):
    bpy.ops.wm.read_factory_settings(use_empty=True)
    sc = bpy.context.scene
    look = json.loads((SCN / "look.json").read_text())
    geoms = json.loads((SCN / "geoms.json").read_text())
    meshes = np.load(SCN / "meshes.npz")
    C = look["colors"]
    img = bpy.data.images.load(look["table_texture"])
    img.colorspace_settings.name = "Non-Color"
    mats = {
        "table": principled("table", C["table_outside"], ROUGH[L_TABLE], SPEC[L_TABLE]),
        "table_tex": principled("table_tex", (1, 1, 1), ROUGH[L_TABLE], SPEC[L_TABLE], image=img),
        L_ARM: principled("printed", C["printed"], ROUGH[L_ARM], SPEC[L_ARM], SSS[L_ARM]),
        L_SERVO: principled("servo", C["servo"], ROUGH[L_SERVO], SPEC[L_SERVO]),
        L_JAW: principled("jaw", C["jaw_353"], ROUGH[L_JAW], SPEC[L_JAW], SSS[L_JAW]),
        L_BLOCK: block_material(C, V),
    }
    wall = [c * V["box_rgb_k"] for c in C[V["box_wall_rgb"]]]
    floor = [c * V["box_floor_k"] for c in C[V["box_floor_rgb"]]]
    box_mats = [principled("box_out", [c * V["out_k"] for c in wall], V["box_rough"], V["box_spec"], V["box_sss"]),
                principled("box_rim", [c * V["rim_k"] for c in wall], V["rim_rough"] or V["box_rough"], V["box_spec"],
                           V["rim_sss"] if V["rim_sss"] is not None else V["box_sss"]),
                principled("box_in", wall, V["box_rough"], V["box_spec"], V["box_sss"]),
                principled("box_floor", floor, V["box_rough"], V["box_spec"], V["box_floor_sss"])]
    objs = {}
    for r in geoms:
        nm, lab = r["name"], r["label"]
        if nm.startswith("box_"):
            continue  # 箱は下で 1 つの形として足す
        if r["type"] == "mesh":
            me = bpy.data.meshes.get(r["mesh"])
            if me is None:
                v = meshes[r["mesh"] + "_v"].astype(float)
                f = meshes[r["mesh"] + "_f"].astype(int)
                me = bpy.data.meshes.new(r["mesh"])
                me.from_pydata(v.tolist(), [], f.tolist())
                me.update()
                me.shade_smooth()
                me.set_sharp_from_angle(angle=math.radians(30))
            scale = (1, 1, 1)
        elif r["type"] == "box":
            me = bpy.data.meshes.new(nm)
            v = [(x, y, z) for x in (-1, 1) for y in (-1, 1) for z in (-1, 1)]
            f = [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)]
            me.from_pydata(v, [], f)
            me.update()
            scale = tuple(r["size"]) if nm != "block" else (block_mm / 2000,) * 3
        else:  # 平面 (机に貼る絵)
            me = bpy.data.meshes.new(nm)
            me.from_pydata([(-1, -1, 0), (1, -1, 0), (1, 1, 0), (-1, 1, 0)], [], [(0, 1, 2, 3)])
            uv = me.uv_layers.new(name="UVMap")
            for li, vi in enumerate(me.loops):
                x, y, _ = me.vertices[vi.vertex_index].co
                uv.data[li].uv = ((x + 1) / 2, (y + 1) / 2)
            me.update()
            scale = (r["size"][0], r["size"][1], 1)
        o = bpy.data.objects.new(nm, me)
        sc.collection.objects.link(o)
        if r["type"] != "mesh" or not o.data.materials:
            key = nm if nm in ("table", "table_tex") else lab
            if o.data.materials:
                o.data.materials[0] = mats[key]
            else:
                o.data.materials.append(mats[key])
        o.color = (lab / 10.0, 0.0, 0.0, 1)
        objs[nm] = (o, Matrix.Diagonal((*scale, 1)), r["group"], nm)
    # 箱 (box_floor の位置と向き → 箱の座標: 底の中心は 箱の座標の z = 底の厚さの半分 (MuJoCo の箱と同じ))
    me = box_mesh(V["box_outer_mm"])
    for m in box_mats:
        me.materials.append(m)
    o = bpy.data.objects.new("box363", me)
    sc.collection.objects.link(o)
    o.color = (0, 0, 0, 1)
    t_mj = geoms[[g["name"] for g in geoms].index("box_floor")]["size"][2]  # MuJoCo の底の厚さの半分
    objs["box363"] = (o, Matrix.Translation((0, 0, -t_mj)), 0, "box_floor")
    # 光
    for j, L in enumerate(look["lights"]):
        u = L["u"]
        mx = max(L["rgb"])
        ld = bpy.data.lights.new(f"sun{j}", type="SUN")
        ld.energy = math.pi * mx * (V["panel_k"] if j == 0 else V["back_k"])
        ld.color = tuple(c / mx for c in L["rgb"])
        ld.angle = math.radians(SUN_ANGLE_DEG)
        ld.use_shadow = bool(L["shadow"])
        lo = bpy.data.objects.new(f"sun{j}", ld)
        zz = np.asarray(u, float) / np.linalg.norm(u)  # 太陽の +Z = 光の来る向き
        xx = np.cross([0, 0, 1.0], zz) if abs(zz[2]) < 0.999 else np.array([1.0, 0, 0])
        xx /= np.linalg.norm(xx)
        yy = np.cross(zz, xx)
        lo.matrix_world = Matrix([[xx[0], yy[0], zz[0], 0], [xx[1], yy[1], zz[1], 0], [xx[2], yy[2], zz[2], 0], [0, 0, 0, 1]])
        sc.collection.objects.link(lo)
    world(sc, look, V)
    cams = {}
    for k, cv in look["cams"].items():
        cd = bpy.data.cameras.new(k)
        cd.sensor_fit = "VERTICAL"
        cd.sensor_height = 24.0
        cd.lens = 12.0 / math.tan(math.radians(cv["fovy_deg"]) / 2)
        cd.clip_start = 0.001
        cd.clip_end = 10.0
        co = bpy.data.objects.new(k, cd)
        sc.collection.objects.link(co)
        cams[k] = (co, cv["w"], cv["h"])
    sc.view_settings.view_transform = "Raw"
    sc.view_settings.look = "None"
    sc.render.image_settings.file_format = "PNG"
    sc.render.image_settings.color_mode = "RGB"
    sc.render.image_settings.color_depth = "16"
    sc.render.use_persistent_data = True
    return sc, objs, cams


def world(sc, look, V):
    """部屋全体の光. amb_top = 0 で 依頼 361 と同じ (どの向きからも同じ). amb_top = f で
    (1−f) × 一様 + f × 上からの光 (z^n. 上向きの面の受ける光は一様のときと同じになるよう (n+2)/2 倍)."""
    w = bpy.data.worlds.new("room")
    w.use_nodes = True
    nt = w.node_tree
    bg = nt.nodes["Background"]
    amb = [c * V["amb_k"] for c in look["ambient_rgb"]]
    bg.inputs["Color"].default_value = (*amb, 1)
    f, n = V["amb_top"], V["amb_top_n"]
    if f > 0:
        tc = nt.nodes.new("ShaderNodeTexCoord")
        sp = nt.nodes.new("ShaderNodeSeparateXYZ")
        nt.links.new(tc.outputs["Generated"], sp.inputs["Vector"])
        mz = nt.nodes.new("ShaderNodeMath")
        mz.operation = "MAXIMUM"
        mz.inputs[1].default_value = 0.0
        nt.links.new(sp.outputs["Z"], mz.inputs[0])
        pw = nt.nodes.new("ShaderNodeMath")
        pw.operation = "POWER"
        pw.inputs[1].default_value = n
        nt.links.new(mz.outputs[0], pw.inputs[0])
        mad = nt.nodes.new("ShaderNodeMath")
        mad.operation = "MULTIPLY_ADD"
        mad.inputs[1].default_value = f * (n + 2) / 2
        mad.inputs[2].default_value = 1 - f
        nt.links.new(pw.outputs[0], mad.inputs[0])
        nt.links.new(mad.outputs[0], bg.inputs["Strength"])
    else:
        bg.inputs["Strength"].default_value = 1.0
    lp = nt.nodes.new("ShaderNodeLightPath")
    blk = nt.nodes.new("ShaderNodeBackground")
    blk.inputs["Color"].default_value = (0, 0, 0, 1)
    mix = nt.nodes.new("ShaderNodeMixShader")
    nt.links.new(lp.outputs["Is Camera Ray"], mix.inputs["Fac"])
    nt.links.new(bg.outputs["Background"], mix.inputs[1])
    nt.links.new(blk.outputs["Background"], mix.inputs[2])
    nt.links.new(mix.outputs["Shader"], nt.nodes["World Output"].inputs["Surface"])
    sc.world = w


def set_device(sc):
    sc.render.engine = "CYCLES"
    prefs = bpy.context.preferences.addons["cycles"].preferences
    prefs.compute_device_type = "METAL"
    prefs.get_devices()
    for d in prefs.devices:
        d.use = d.type == "METAL"
    sc.cycles.device = "GPU"
    cy = sc.cycles
    cy.use_adaptive_sampling = False
    cy.use_denoising = True
    cy.denoiser = "OPENIMAGEDENOISE"
    cy.denoising_use_gpu = True
    cy.max_bounces, cy.diffuse_bounces, cy.glossy_bounces, cy.transmission_bounces = 8, 3, 2, 4
    cy.caustics_reflective = cy.caustics_refractive = False
    return [d.name for d in prefs.devices if d.use]


def apply_frame(objs, cams, fr):
    for o, S, _, src in objs.values():
        o.matrix_world = Matrix(np.asarray(fr["geoms"][src]).reshape(4, 4).tolist()) @ S
    for k, (co, _, _) in cams.items():
        co.matrix_world = Matrix(np.asarray(fr["cams"][k]).reshape(4, 4).tolist())


def render(sc, objs, cams, key, path):
    co, w, h = cams[key]
    for o, _, grp, _ in objs.values():
        o.hide_render = grp == 4 and key == "wrist"  # 手首カメラの台座は 手首の絵では描かない (MuJoCo と同じ)
    sc.camera = co
    sc.render.resolution_x, sc.render.resolution_y = w, h
    sc.render.resolution_percentage = 100
    sc.render.filepath = str(path)
    t0 = time.perf_counter()
    bpy.ops.render.render(write_still=True)
    return time.perf_counter() - t0


def label_mode(sc):
    """ラベルの絵: 赤 = ラベル ÷ 10 (物の色 + 箱の面の sublab), 緑 = 0.5 + 法線の z / 2. 1 サンプル・ノイズ除去なし."""
    m = bpy.data.materials.new("label")
    m.use_nodes = True
    nt = m.node_tree
    for n in list(nt.nodes):
        nt.nodes.remove(n)
    oi = nt.nodes.new("ShaderNodeObjectInfo")
    at = nt.nodes.new("ShaderNodeAttribute")
    at.attribute_type = "GEOMETRY"
    at.attribute_name = "sublab"
    sr = nt.nodes.new("ShaderNodeSeparateColor")
    nt.links.new(oi.outputs["Color"], sr.inputs["Color"])
    add = nt.nodes.new("ShaderNodeMath")
    add.operation = "ADD"
    nt.links.new(sr.outputs[0], add.inputs[0])
    nt.links.new(at.outputs["Fac"], add.inputs[1])
    geo = nt.nodes.new("ShaderNodeNewGeometry")
    sn = nt.nodes.new("ShaderNodeSeparateXYZ")
    nt.links.new(geo.outputs["Normal"], sn.inputs["Vector"])
    gz = nt.nodes.new("ShaderNodeMath")
    gz.operation = "MULTIPLY_ADD"
    gz.inputs[1].default_value = 0.5
    gz.inputs[2].default_value = 0.5
    nt.links.new(sn.outputs["Z"], gz.inputs[0])
    cc = nt.nodes.new("ShaderNodeCombineColor")
    nt.links.new(add.outputs[0], cc.inputs[0])
    nt.links.new(gz.outputs[0], cc.inputs[1])
    em = nt.nodes.new("ShaderNodeEmission")
    out = nt.nodes.new("ShaderNodeOutputMaterial")
    nt.links.new(cc.outputs["Color"], em.inputs["Color"])
    nt.links.new(em.outputs["Emission"], out.inputs["Surface"])
    bpy.context.view_layer.material_override = m
    sc.cycles.samples = 1
    sc.cycles.use_denoising = False
    sc.cycles.filter_width = 0.01
    sc.world.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.0
    for lk in list(sc.world.node_tree.links):
        if lk.to_socket == sc.world.node_tree.nodes["Background"].inputs["Strength"]:
            sc.world.node_tree.links.remove(lk)


def main():
    src = SO101 / arg("--src", "check_361/ep00")
    out = SO101 / arg("--out", "check_363/ep00")
    samples = [int(x) for x in arg("--samples", "32").split(",") if x]
    nm, V = variant()
    tag = Path(nm).stem
    P = json.loads((src / "poses.json").read_text())
    sc, objs, cams = build(V, float(P["block_size_mm"]))
    used = set_device(sc)
    frames = P["frames"]
    if arg("--frames", ""):
        want = {int(x) for x in arg("--frames", "").split(",")}
        frames = [f for f in frames if f["frame"] in want]
    times = {"src": str(src.relative_to(SO101)), "var": nm, "values": V, "devices": used, "blender": bpy.app.version_string, "samples": {}}
    out.mkdir(parents=True, exist_ok=True)
    if not flag("--labels-only"):
        for s in samples:
            sc.cycles.samples = s
            d = out / f"bl_{tag}_s{s}"
            d.mkdir(parents=True, exist_ok=True)
            ts = {"desk": [], "wrist": []}
            for fr in frames:
                apply_frame(objs, cams, fr)
                for key in ("desk", "wrist"):
                    ts[key].append(round(render(sc, objs, cams, key, d / f"{fr['frame']:03d}_{key}.png"), 3))
                print("frame", out.name, tag, s, fr["frame"], ts["desk"][-1], ts["wrist"][-1], flush=True)
            times["samples"][str(s)] = ts
        (out / f"times_{tag}.json").write_text(json.dumps(times, indent=1, default=list))
    if flag("--labels") or flag("--labels-only"):
        label_mode(sc)
        d = out / "bl363_lab"
        d.mkdir(parents=True, exist_ok=True)
        for fr in frames:
            apply_frame(objs, cams, fr)
            for key in ("desk", "wrist"):
                render(sc, objs, cams, key, d / f"{fr['frame']:03d}_{key}.png")


main()
