﻿# =====================================================================
# SONORA R-70  --  1970s portable two-reel field recorder
# Fully procedural Blender (bpy) build for industrial-design museum use.
# Run from a CLEAN startup file:
#   blender -b --python build_scene.py
# Options (after --): --no-render  --quick  --only hero|detail|exploded
# =====================================================================
import bpy, bmesh, math, os, sys, random
from math import pi, sin, cos, radians, degrees
from mathutils import Vector, Matrix, Quaternion

random.seed(70)

# ----------------------------- global layout constants (metres) ------
DECK_HW   = 0.150          # deck half width  (X)
DECK_HD   = 0.075          # deck half depth  (Y)
CHASSIS_Z0 = 0.038
CHASSIS_Z1 = 0.086
WELL_FLOOR = 0.053
TAPE_Z     = 0.0620        # tape ribbon mid-plane
TAPE_W     = 0.0064        # 1/4" tape
TAPE_T     = 0.00010
REEL_SY    = 0.032         # reel centre Y
SUP_X      = -0.052        # supply reel centre
TAK_X      =  0.052        # take-up reel centre
SUP_PACK_R = 0.0385
TAK_PACK_R = 0.0175
HUB_R      = 0.0125
FLANGE_R   = 0.042
HINGE_Y, HINGE_Z = 0.0752, 0.0845

D = {}                     # registry of built objects by key

# ----------------------------- scene reset ---------------------------
def reset_scene():
    bpy.ops.wm.read_factory_settings(use_empty=True)
    sc = bpy.context.scene
    sc.name = "R70_STUDIO"
    sc.unit_settings.system = 'METRIC'
    sc.unit_settings.scale_length = 1.0
    sc.unit_settings.length_unit = 'MILLIMETERS'
    sc.render.fps = 24
    sc.frame_start = 1
    sc.frame_end = 120
    return sc

def get_coll(name, parent=None, scene=None):
    scene = scene or bpy.context.scene
    col = bpy.data.collections.get(name)
    if not col:
        col = bpy.data.collections.new(name)
        (parent or scene.collection).children.link(col)
    return col

def link_to(obj, col):
    for c in obj.users_collection:
        c.objects.unlink(obj)
    col.objects.link(obj)
    return obj

# ----------------------------- mesh helpers --------------------------
def _obj(name, me, col, mat=None):
    ob = bpy.data.objects.new(name, me)
    if col: link_to(ob, col)
    if mat:
        me.materials.append(mat)
    D[name] = ob
    return ob

def new_mesh(name):
    me = bpy.data.meshes.new(name)
    return me

def rounded_rect_pts(sx, sy, r, seg=6):
    """2D rounded-rectangle outline (CCW), centred at origin. sx,sy = FULL sizes."""
    hx, hy, r = sx/2.0, sy/2.0, min(r, sx/2*0.98, sy/2*0.98)
    pts = []
    for cx, cy, a0 in ((hx-r, hy-r, 0), (-(hx-r), hy-r, 90),
                       (-(hx-r), -(hy-r), 180), (hx-r, -(hy-r), 270)):
        for i in range(seg+1):
            a = radians(a0 + 90.0*i/seg)
            pts.append((cx + r*cos(a), cy + r*sin(a)))
    # de-duplicate
    out = []
    for p in pts:
        if not out or (Vector(p) - Vector(out[-1])).length > 1e-6:
            out.append(p)
    return out

def prism(name, pts2d, z0, z1, col, mat=None, center=Vector((0,0,0))):
    """Vertical prism from closed 2D outline; ngons top/bottom."""
    bm = bmesh.new()
    v0 = [bm.verts.new((p[0], p[1], z0)) for p in pts2d]
    v1 = [bm.verts.new((p[0], p[1], z1)) for p in pts2d]
    n = len(v0)
    for i in range(n):
        j = (i+1) % n
        try: bm.faces.new((v0[j], v0[i], v1[i], v1[j]))
        except ValueError: pass
    try:
        bm.faces.new(list(reversed(v0)))
        bm.faces.new(v1)
    except ValueError: pass
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    me = new_mesh(name)
    bm.to_mesh(me); bm.free()
    ob = _obj(name, me, col, mat)
    ob.location = center
    return ob

def rbox(name, sx, sy, sz, loc, col, mat=None, r=0.0015, seg=2):
    """Rounded (vertical edges) box of full sizes sx,sy,sz centred on loc."""
    pts = rounded_rect_pts(sx, sy, r)
    ob = prism(name, pts, -sz/2, sz/2, col, mat, center=Vector(loc))
    if seg: add_bevel(ob, w=min(sz*0.3, 0.0012), seg=seg, angle=40)
    return ob

def box(name, sx, sy, sz, loc, col, mat=None):
    bm = bmesh.new()
    bmesh.ops.create_cube(bm, size=1.0)
    for v in bm.verts:
        v.co.x *= sx; v.co.y *= sy; v.co.z *= sz
    me = new_mesh(name)
    bm.to_mesh(me); bm.free()
    ob = _obj(name, me, col, mat)
    ob.location = Vector(loc)
    return ob

def cyl(name, r, depth, loc, col, mat=None, verts=48, r2=None, axis='Z'):
    bm = bmesh.new()
    bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=verts,
                          radius1=r, radius2=(r2 if r2 is not None else r), depth=depth)
    if axis == 'X':
        bmesh.ops.rotate(bm, verts=bm.verts,
                         cent=(0,0,0), matrix=Matrix.Rotation(radians(90), 3, 'Y'))
    elif axis == 'Y':
        bmesh.ops.rotate(bm, verts=bm.verts,
                         cent=(0,0,0), matrix=Matrix.Rotation(radians(-90), 3, 'X'))
    me = new_mesh(name)
    bm.to_mesh(me); bm.free()
    ob = _obj(name, me, col, mat)
    ob.location = Vector(loc)
    return ob

def ring(name, r_in, r_out, depth, loc, col, mat=None, steps=96):
    """Annular disc (open centre) built by spinning a rectangle."""
    bm = bmesh.new()
    h = depth / 2.0
    vs = [bm.verts.new(v) for v in ((r_in, 0, -h), (r_out, 0, -h),
                                    (r_out, 0, h), (r_in, 0, h))]
    f = bm.faces.new(vs)
    bmesh.ops.spin(bm, geom=vs + [f], cent=(0, 0, 0), axis=(0, 0, 1),
                   angle=radians(360), steps=steps, use_merge=True)
    bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-6)
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    me = new_mesh(name)
    bm.to_mesh(me); bm.free()
    ob = _obj(name, me, col, mat)
    ob.location = Vector(loc)
    return ob

def tube(name, pts, radius, col, mat=None, res_u=16, caps=True, cyclic=False):
    """Curve tube through 3D points (kept as editable curve object)."""
    cu = bpy.data.curves.new(name, 'CURVE')
    cu.dimensions = '3D'
    sp = cu.splines.new('NURBS' if len(pts) > 2 else 'POLY')
    sp.points.add(len(pts)-1)
    for p, pt in zip(sp.points, pts):
        p.co = (pt[0], pt[1], pt[2], 1)
    sp.use_endpoint_u = True
    sp.order_u = min(3, len(pts))
    cu.resolution_u = res_u
    cu.bevel_depth = radius
    cu.bevel_resolution = 6
    cu.use_fill_caps = caps
    ob = bpy.data.objects.new(name, cu)
    link_to(ob, col)
    if mat: cu.materials.append(mat)
    D[name] = ob
    return ob

def sphere(name, r, loc, col, mat=None, seg=24, ring=16):
    bm = bmesh.new()
    bmesh.ops.create_uvsphere(bm, u_segments=seg, v_segments=ring, radius=r)
    me = new_mesh(name)
    bm.to_mesh(me); bm.free()
    ob = _obj(name, me, col, mat)
    ob.location = Vector(loc)
    return ob

# ----------------------------- modifiers / shading -------------------
def add_bevel(ob, w=0.001, seg=2, angle=35, harden=False):
    m = ob.modifiers.new("Bevel", 'BEVEL')
    m.width = w; m.segments = seg
    m.limit_method = 'ANGLE'; m.angle_limit = radians(angle)
    m.miter_outer = 'MITER_ARC'
    m.harden_normals = harden
    return m

def shade_auto(ob, angle=38):
    try:
        prev_act = bpy.context.view_layer.objects.active
        prev_sel = list(bpy.context.selected_objects)
        bpy.ops.object.select_all(action='DESELECT')
        ob.select_set(True)
        bpy.context.view_layer.objects.active = ob
        bpy.ops.object.shade_auto_smooth(angle=radians(angle))
        bpy.ops.object.select_all(action='DESELECT')
        for o in prev_sel: o.select_set(True)
        bpy.context.view_layer.objects.active = prev_act
    except Exception:
        for p in ob.data.polygons: p.use_smooth = True

def set_smooth(ob, val=True):
    if ob.type == 'MESH':
        for p in ob.data.polygons: p.use_smooth = val

def add_bool(ob, cutter, op='DIFFERENCE', hidden=True):
    m = ob.modifiers.new("Bool", 'BOOLEAN')
    m.operation = op; m.solver = 'EXACT'
    m.object = cutter
    if hidden:
        cutter.hide_render = True
        cutter.hide_viewport = False
        for c in cutter.users_collection:
            c.hide_render = c.hide_render   # operand still evaluates
    return m

def parent_keep(child, parent):
    child.parent = parent
    child.matrix_parent_inverse = parent.matrix_world.inverted()

def parent_dropchild(obj, empty):
    """Parent object to empty keeping current world transform."""
    mw = obj.matrix_world.copy()
    obj.parent = empty
    obj.matrix_world = mw

# ----------------------------- screws --------------------------------
def screw(name, loc, col, mat_head, mat_dark, r=0.0021, ht=0.0013,
          slot='slot', axis='Z', rot=None):
    """Machine screw: round head + recessed slot/cross, sits proud of surface."""
    bm = bmesh.new()
    bmesh.ops.create_cone(bm, cap_ends=True, segments=24, radius1=r,
                          radius2=r*0.92, depth=ht)
    me = new_mesh(name + "_H")
    bm.to_mesh(me); bm.free()
    head = _obj(name, me, col, mat_head)
    if slot:
        cutw = r*0.30
        c1 = box(name+"_s1", 2*r*0.78, cutw, cutw*2.5, (0,0,ht*0.42), col, None)
        cutters = [c1]
        if slot == 'cross':
            c2 = box(name+"_s2", cutw, 2*r*0.78, cutw*2.5, (0,0,ht*0.42), col, None)
            cutters.append(c2)
        for c in cutters:
            mb = head.modifiers.new("sc", 'BOOLEAN')
            mb.operation = 'DIFFERENCE'; mb.solver = 'EXACT'; mb.object = c
            c.hide_render = True
            c.parent = head
            c.matrix_parent_inverse = c1.matrix_world.inverted()
    # countersink well (dark) under head
    well = cyl(name+"_w", r*1.06, ht*0.62, (0,0,-ht*0.10), col, mat_dark)
    well.hide_render = True
    well.parent = head
    head.location = Vector(loc)
    if rot: head.rotation_euler = rot
    set_smooth(head)
    return head

# ----------------------------- text ----------------------------------
def text_obj(name, body, loc, size, col, mat, rot=(0,0,0), align='CENTER',
             v_align='BOTTOM_BASELINE', curve=None, spacing=1.0, th=0.0003,
             extrude=True):
    cu = bpy.data.curves.new(name, 'FONT')
    cu.body = body
    cu.size = size
    cu.align_x = align; cu.align_y = v_align
    cu.space_character = spacing
    if extrude:
        cu.extrude = th
    ob = bpy.data.objects.new(name, cu)
    link_to(ob, col)
    ob.location = Vector(loc)
    ob.rotation_euler = [radians(a) for a in rot]
    cu.materials.append(mat)
    if curve:
        cu.follow_curve = curve
        cu.use_path = True
    D[name] = ob
    return ob

def arc_curve(name, cx, cy, r, a0, a1, z=0, seg=48, col=None):
    """Poly curve arc in XY for text-on-path."""
    cu = bpy.data.curves.new(name, 'CURVE')
    cu.dimensions = '3D'
    sp = cu.splines.new('NURBS')
    n = seg
    sp.points.add(n)
    for i in range(n+1):
        a = radians(a0 + (a1-a0)*i/n)
        sp.points[i].co = (cx + r*cos(a), cy + r*sin(a), z, 1)
    sp.use_endpoint_u = True
    cu.resolution_u = 16
    ob = bpy.data.objects.new(name, cu)
    if col: link_to(ob, col)
    ob.hide_render = True
    return ob

def aim(obj, target):
    d = Vector(target) - obj.location
    obj.rotation_euler = d.to_track_quat('-Z', 'Y').to_euler()

def circ_tangent(cx, cy, r, px, py, sign=1):
    """Tangent point on circle (cx,cy,r) seen from outside point p; sign=Â±1."""
    vx, vy = cx-px, cy-py
    phi = math.atan2(vy, vx)
    d = math.hypot(vx, vy)
    a = math.acos(max(-1, min(1, r/d)))
    # angle from centre toward p:
    psi = math.atan2(py-cy, px-cx)
    t = psi + sign*a
    return (cx + r*cos(t), cy + r*sin(t))

# ----------------------------- Catmull-Rom ---------------------------
def catmull_rom(points, samples=14, closed=False):
    if len(points) < 3: return points[:]
    pts = points[:]
    if closed:
        pts = pts + pts[:1]
    P = [pts[0]] + pts + [pts[-1]]
    out = []
    n = len(P)
    for i in range(1, n-2):
        p0, p1, p2, p3 = P[i-1], P[i], P[i+1], P[i+2]
        for s in range(samples):
            t = s / samples
            t2, t3 = t*t, t*t*t
            x = 0.5*((2*p1[0]) + (-p0[0]+p2[0])*t + (2*p0[0]-5*p1[0]+4*p2[0]-p3[0])*t2 + (-p0[0]+3*p1[0]-3*p2[0]+p3[0])*t3)
            y = 0.5*((2*p1[1]) + (-p0[1]+p2[1])*t + (2*p0[1]-5*p1[1]+4*p2[1]-p3[1])*t2 + (-p0[1]+3*p1[1]-3*p2[1]+p3[1])*t3)
            out.append((x, y))
    out.append(pts[-1])
    return out
# =====================================================================
# MATERIALS  --  all procedural node setups, reused across parts
# =====================================================================
M = {}

def _mat(name):
    m = bpy.data.materials.new(name)
    m.use_nodes = True
    nt = m.node_tree
    nt.nodes.clear()
    out = nt.nodes.new('ShaderNodeOutputMaterial'); out.location = (600, 0)
    bsdf = nt.nodes.new('ShaderNodeBsdfPrincipled'); bsdf.location = (280, 0)
    nt.links.new(bsdf.outputs['BSDF'], out.inputs['Surface'])
    M[name] = m
    return m, nt, bsdf

def _n(nt, t, x, y, **props):
    nd = nt.nodes.new(t); nd.location = (x, y)
    for k, v in props.items():
        try:
            setattr(nd, k, v)
        except AttributeError:
            sock = nd.inputs.get(k)
            if sock is not None:
                sock.default_value = v
    return nd

def _l(nt, a, b):
    nt.links.new(a, b)

def _mapping(nt, x, y, scale):
    nd = nt.nodes.new('ShaderNodeMapping'); nd.location = (x, y)
    nd.inputs['Scale'].default_value = scale
    return nd

def build_materials():
    # ---- 1. Brushed anodised aluminium (housing) -------------------
    m, nt, b = _mat("ALU_Brushed")
    b.inputs['Base Color'].default_value = (0.58, 0.59, 0.61, 1)
    b.inputs['Metallic'].default_value = 1.0
    b.inputs['Anisotropic'].default_value = 0.62
    tc  = _n(nt, 'ShaderNodeTexCoord', -900, 0)
    mp  = _mapping(nt, -700, 0, (3.0, 900.0, 3.0))
    _l(nt, tc.outputs['Object'], mp.inputs['Vector'])
    nz  = _n(nt, 'ShaderNodeTexNoise', -500, 0, inputs_min=1, noise_scale=26.0,
             detail=1.0, roughness=0.3)
    _l(nt, mp.outputs['Vector'], nz.inputs['Vector'])
    mr  = _n(nt, 'ShaderNodeMapRange', -260, 60,
             from_min=0.32, from_max=0.68, to_min=0.16, to_max=0.30)
    _l(nt, nz.outputs['Fac'], mr.inputs['Value'])
    _l(nt, mr.outputs['Result'], b.inputs['Roughness'])
    nzc = _n(nt, 'ShaderNodeTexCoord', -900, -320)
    nz2 = _n(nt, 'ShaderNodeTexNoise', -700, -320, inputs_min=1,
             noise_scale=4000.0, detail=1.0, roughness=0.3)
    _l(nt, nzc.outputs['Object'], nz2.inputs['Vector'])
    bp  = _n(nt, 'ShaderNodeBump', -300, -320, strength=0.012, distance=0.0)
    _l(nt, nz2.outputs['Fac'], bp.inputs['Height'])
    _l(nt, bp.outputs['Normal'], b.inputs['Normal'])

    # ---- 2. Champagne anodised control panel ------------------------
    m, nt, b = _mat("ALU_Champagne")
    b.inputs['Base Color'].default_value = (0.52, 0.45, 0.345, 1)
    b.inputs['Metallic'].default_value = 0.92
    b.inputs['Anisotropic'].default_value = 0.35
    tc  = _n(nt, 'ShaderNodeTexCoord', -900, 0)
    mp  = _mapping(nt, -700, 0, (2.0, 1400.0, 2.0))
    _l(nt, tc.outputs['Object'], mp.inputs['Vector'])
    nz  = _n(nt, 'ShaderNodeTexNoise', -500, 0, inputs_min=1, noise_scale=16.0,
             detail=1.0)
    _l(nt, mp.outputs['Vector'], nz.inputs['Vector'])
    mr  = _n(nt, 'ShaderNodeMapRange', -260, 0, from_min=0.30, from_max=0.72,
             to_min=0.25, to_max=0.40)
    _l(nt, nz.outputs['Fac'], mr.inputs['Value'])
    _l(nt, mr.outputs['Result'], b.inputs['Roughness'])
    nz2 = _n(nt, 'ShaderNodeTexNoise', -500, -300, inputs_min=1, noise_scale=5000.0)
    bp  = _n(nt, 'ShaderNodeBump', -260, -300, strength=0.007, distance=0.0)
    _l(nt, nz2.outputs['Fac'], bp.inputs['Height'])
    _l(nt, bp.outputs['Normal'], b.inputs['Normal'])

    # ---- 3. Polished steel (capstan, posts, spindles) ---------------
    m, nt, b = _mat("Steel_Polished")
    b.inputs['Base Color'].default_value = (0.72, 0.72, 0.74, 1)
    b.inputs['Metallic'].default_value = 1.0
    b.inputs['Roughness'].default_value = 0.07
    b.inputs['Anisotropic'].default_value = 0.30

    # ---- 4. Hard chrome (latch bail, handle, bezels) ----------------
    m, nt, b = _mat("Chrome")
    b.inputs['Base Color'].default_value = (0.85, 0.86, 0.88, 1)
    b.inputs['Metallic'].default_value = 1.0
    b.inputs['Roughness'].default_value = 0.045

    # ---- 5. Brass (bushings, needle, screws accents) ---------------
    m, nt, b = _mat("Brass")
    b.inputs['Base Color'].default_value = (0.72, 0.51, 0.22, 1)
    b.inputs['Metallic'].default_value = 1.0
    b.inputs['Roughness'].default_value = 0.21
    nz = _n(nt, 'ShaderNodeTexNoise', -500, -200, inputs_min=1, noise_scale=600)
    mr = _n(nt, 'ShaderNodeMapRange', -260, -200, from_min=0.3, from_max=0.7,
            to_min=0.14, to_max=0.30)
    _l(nt, nz.outputs['Fac'], mr.inputs['Value'])
    _l(nt, mr.outputs['Result'], b.inputs['Roughness'])

    # ---- 6. Black bakelite (keys, knob bodies) ---------------------
    m, nt, b = _mat("Bakelite_Black")
    b.inputs['Base Color'].default_value = (0.017, 0.016, 0.015, 1)
    b.inputs['Metallic'].default_value = 0.0
    b.inputs['Roughness'].default_value = 0.34
    if 'Coat Weight' in b.inputs:
        b.inputs['Coat Weight'].default_value = 0.45
        b.inputs['Coat Roughness'].default_value = 0.18
    nz = _n(nt, 'ShaderNodeTexNoise', -500, -240, inputs_min=1, noise_scale=3000)
    bp = _n(nt, 'ShaderNodeBump', -260, -240, strength=0.012, distance=0.0)
    _l(nt, nz.outputs['Fac'], bp.inputs['Height'])
    _l(nt, bp.outputs['Normal'], b.inputs['Normal'])

    # ---- 7. Red phenolic (REC key cap) -----------------------------
    m, nt, b = _mat("Phenolic_Red")
    b.inputs['Base Color'].default_value = (0.42, 0.020, 0.016, 1)
    b.inputs['Roughness'].default_value = 0.28
    if 'Coat Weight' in b.inputs:
        b.inputs['Coat Weight'].default_value = 0.6
        b.inputs['Coat Roughness'].default_value = 0.12

    # ---- 8. Rubber (feet, pinch tyre) -------------------------------
    m, nt, b = _mat("Rubber_Black")
    b.inputs['Base Color'].default_value = (0.014, 0.014, 0.014, 1)
    b.inputs['Roughness'].default_value = 0.88
    b.inputs['Specular IOR Level'].default_value = 0.28
    nz = _n(nt, 'ShaderNodeTexNoise', -700, -100, inputs_min=1, noise_scale=2600,
            detail=3.0)
    bp = _n(nt, 'ShaderNodeBump', -400, -100, strength=0.18, distance=0.00025)
    _l(nt, nz.outputs['Fac'], bp.inputs['Height'])
    _l(nt, bp.outputs['Normal'], b.inputs['Normal'])
    vnr = _n(nt, 'ShaderNodeTexVoronoi', -700, -380, inputs_min=1, scale=1800)
    mr = _n(nt, 'ShaderNodeMapRange', -420, -380, from_min=0.0, from_max=1.0,
            to_min=0.80, to_max=0.95)
    _l(nt, vnr.outputs['Distance'], mr.inputs['Value'])
    _l(nt, mr.outputs['Result'], b.inputs['Roughness'])

    # ---- 9. Ferric tape ribbon -------------------------------------
    m, nt, b = _mat("Tape_Oxide")
    b.inputs['Base Color'].default_value = (0.140, 0.055, 0.026, 1)
    b.inputs['Metallic'].default_value = 0.05
    b.inputs['Roughness'].default_value = 0.46
    b.inputs['Anisotropic'].default_value = 0.20
    if 'Specular IOR Level' in b.inputs:
        b.inputs['Specular IOR Level'].default_value = 0.18

    # ---- 10. Tape pack side (concentric ring micro-bump) -----------
    m, nt, b = _mat("Tape_Pack")
    b.inputs['Base Color'].default_value = (0.070, 0.034, 0.020, 1)
    b.inputs['Metallic'].default_value = 0.06
    b.inputs['Roughness'].default_value = 0.50
    if 'Specular IOR Level' in b.inputs:
        b.inputs['Specular IOR Level'].default_value = 0.20
    tc = _n(nt, 'ShaderNodeTexCoord', -900, 0)
    wv = _n(nt, 'ShaderNodeTexWave', -620, 0, wave_type='RINGS',
            wave_profile='SAW', scale=3000.0, distortion=0.0)
    _l(nt, tc.outputs['Object'], wv.inputs['Vector'])
    bp = _n(nt, 'ShaderNodeBump', -300, -100, strength=0.10, distance=0.00005)
    _l(nt, wv.outputs['Fac'], bp.inputs['Height'])
    _l(nt, bp.outputs['Normal'], b.inputs['Normal'])

    # ---- 11. Acrylic lens glass ------------------------------------
    m, nt, b = _mat("Acrylic_Lens")
    b.inputs['Base Color'].default_value = (0.94, 0.97, 0.95, 1)
    b.inputs['Roughness'].default_value = 0.02
    b.inputs['Transmission Weight'].default_value = 1.0
    b.inputs['IOR'].default_value = 1.49

    # ---- 12. Cream meter paint -------------------------------------
    m, nt, b = _mat("Paint_Cream")
    b.inputs['Base Color'].default_value = (0.795, 0.755, 0.645, 1)
    b.inputs['Roughness'].default_value = 0.42
    if 'Coat Weight' in b.inputs:
        b.inputs['Coat Weight'].default_value = 0.30
        b.inputs['Coat Roughness'].default_value = 0.25
    nz = _n(nt, 'ShaderNodeTexNoise', -500, -240, inputs_min=1, noise_scale=1500)
    bp = _n(nt, 'ShaderNodeBump', -260, -240, strength=0.015, distance=0.0)
    _l(nt, nz.outputs['Fac'], bp.inputs['Height'])
    _l(nt, bp.outputs['Normal'], b.inputs['Normal'])

    # ---- 13. Engraved dark enamel (markings) ------------------------
    m, nt, b = _mat("Enamel_Mark")
    b.inputs['Base Color'].default_value = (0.011, 0.011, 0.011, 1)
    b.inputs['Roughness'].default_value = 0.26
    if 'Coat Weight' in b.inputs:
        b.inputs['Coat Weight'].default_value = 0.5

    # ---- 14. Dark cavity / recess ----------------------------------
    m, nt, b = _mat("Cavity_Black")
    b.inputs['Base Color'].default_value = (0.052, 0.051, 0.050, 1)
    b.inputs['Roughness'].default_value = 0.90

    # ---- 15. Lid lining felt ----------------------------------------
    m, nt, b = _mat("Felt_Grey")
    b.inputs['Base Color'].default_value = (0.028, 0.028, 0.030, 1)
    b.inputs['Roughness'].default_value = 1.0
    if 'Sheen Weight' in b.inputs:
        b.inputs['Sheen Weight'].default_value = 0.9
    nz = _n(nt, 'ShaderNodeTexNoise', -700, -100, inputs_min=1, noise_scale=3800,
            detail=4.0)
    bp = _n(nt, 'ShaderNodeBump', -400, -100, strength=0.35, distance=0.0003)
    _l(nt, nz.outputs['Fac'], bp.inputs['Height'])
    _l(nt, bp.outputs['Normal'], b.inputs['Normal'])

    # ---- 16. Studio backdrop ----------------------------------------
    m, nt, b = _mat("Backdrop_Grey")
    b.inputs['Base Color'].default_value = (0.40, 0.40, 0.41, 1)
    b.inputs['Roughness'].default_value = 0.55
    nz = _n(nt, 'ShaderNodeTexNoise', -500, -200, inputs_min=1, noise_scale=90)
    mr = _n(nt, 'ShaderNodeMapRange', -260, -200, from_min=0.3, from_max=0.7,
            to_min=0.48, to_max=0.62)
    _l(nt, nz.outputs['Fac'], mr.inputs['Value'])
    _l(nt, mr.outputs['Result'], b.inputs['Roughness'])

    # ---- 17. Dark plastic (meter housing, keybase) -----------------
    m, nt, b = _mat("Plastic_Dark")
    b.inputs['Base Color'].default_value = (0.02, 0.02, 0.021, 1)
    b.inputs['Roughness'].default_value = 0.5

    # ---- 18. Needle black -------------------------------------------
    m, nt, b = _mat("Needle_Black")
    b.inputs['Base Color'].default_value = (0.01, 0.01, 0.01, 1)
    b.inputs['Roughness'].default_value = 0.4

    # ---- 19. Red accent (VU red zone, REC marking) ------------------
    m, nt, b = _mat("Mark_Red")
    b.inputs['Base Color'].default_value = (0.45, 0.02, 0.015, 1)
    b.inputs['Roughness'].default_value = 0.3

    return M
# =====================================================================
# HOUSING  --  chassis, wells, bottom cover, feet, vent, handle,
#              hinge brackets, latch bases, seam screws
# =====================================================================
def build_housing(col_all):
    C_HSG   = get_coll("REC_Housing", col_all)
    C_INT   = get_coll("REC_Internal", col_all)
    C_HSG.hide_viewport = False

    # ---------------- chassis body ----------------
    ch = rbox("HSG_Chassis", 2*DECK_HW, 2*DECK_HD, CHASSIS_Z1-CHASSIS_Z0,
              (0, 0, (CHASSIS_Z1+CHASSIS_Z0)/2), C_HSG, M["ALU_Brushed"],
              r=0.008, seg=3)
    add_bevel(ch, w=0.0006, seg=2, angle=40)
    shade_auto(ch, 35)
    # top edge small chamfer is handled by bevel; add machined seam reveal:
    reveal = rbox("HSG_SeamReveal", 2*DECK_HW+0.0012, 2*DECK_HD+0.0012, 0.0006,
                  (0, 0, CHASSIS_Z0+0.0003), C_INT, None, r=0.008, seg=1)
    add_bool(ch, reveal)

    # ---------------- well + recess cutters ----------------
    cut_sup = cyl("CUT_WellSup", 0.046, 0.05, (SUP_X, REEL_SY, WELL_FLOOR+0.025),
                  C_INT, None, verts=64)
    add_bool(ch, cut_sup)
    cut_tak = cyl("CUT_WellTak", 0.046, 0.05, (TAK_X, REEL_SY, WELL_FLOOR+0.025),
                  C_INT, None, verts=64)
    add_bool(ch, cut_tak)
    # window front edge y = -0.033 so the full tape route is visible
    win_pts = rounded_rect_pts(0.090, 0.077, 0.006)
    cut_win = prism("CUT_Window", win_pts, WELL_FLOOR, CHASSIS_Z1+0.01, C_INT,
                    center=Vector((0, 0.0055, 0)))
    add_bevel(cut_win, w=0.0012, seg=2)
    add_bool(ch, cut_win)
    # control-plate recess
    rec_pts = rounded_rect_pts(0.292, 0.0439, 0.0025)
    cut_rec = prism("CUT_PlateRecess", rec_pts, 0.0845, CHASSIS_Z1+0.005, C_INT)
    cut_rec.location = (0, -0.04935, 0)
    add_bool(ch, cut_rec)
    # machined rail spanning the window cut, supports the plate's rear lip
    rail = box("HSG_PlateRail", 0.2890, 0.0104, 0.0027,
               (0, -0.0328, 0.08335), C_HSG, M["ALU_Brushed"])
    # well floors (machined discs slightly proud)
    for nm, xx in (("HSG_WellFloorSup", SUP_X), ("HSG_WellFloorTak", TAK_X)):
        f = cyl(nm, 0.0459, 0.0012, (xx, REEL_SY, WELL_FLOOR+0.0006), C_HSG,
                M["ALU_Champagne"], verts=64)
        set_smooth(f)
    # window floor
    wf = prism("HSG_WindowFloor", rounded_rect_pts(0.090, 0.077, 0.006),
               WELL_FLOOR, WELL_FLOOR+0.0012, C_HSG, M["Cavity_Black"],
               center=Vector((0, 0.0055, 0)))
    # ---------------- bottom cover ----------------
    bc = rbox("HSG_BottomCover", 0.2985, 0.1485, 0.0298,
              (0, 0, CHASSIS_Z0-0.0148-0.0002), C_HSG, M["ALU_Brushed"],
              r=0.0075, seg=3)
    shade_auto(bc, 35)
    # battery-hatch outline on underside (thin raised frame lines)
    hatch = rbox("HSG_BatteryHatchSeam", 0.115, 0.075, 0.0006, (-0.06, 0.005, 0.0092),
                 C_HSG, None, r=0.003, seg=1)
    add_bevel(hatch, w=0.0003, seg=1)

    # ---------------- rubber feet ----------------
    for i, (xx, yy) in enumerate([(-0.128, -0.058), (0.128, -0.058),
                                  (-0.128, 0.058), (0.128, 0.058)]):
        ft = cyl(f"HSG_Foot_{i}", 0.0092, 0.0090, (xx, yy, 0.0045), C_HSG,
                 M["Rubber_Black"], verts=32)
        add_bevel(ft, w=0.0012, seg=2)
        shade_auto(ft, 40)
        ws = cyl(f"HSG_FootWasher_{i}", 0.0115, 0.0016, (xx, yy, 0.0097), C_HSG,
                 M["ALU_Champagne"], verts=32)
        shade_auto(ws)

    # ---------------- rear ventilation grille ----------------
    vx, vz = 0.0, 0.0615
    frame_pts = rounded_rect_pts(0.056, 0.020, 0.002)
    fr = prism("HSG_VentFrame", frame_pts, -0.0012, 0.0012, C_HSG,
               M["ALU_Champagne"], center=Vector((vx, DECK_HD-0.0012, vz)))
    cavity = box("HSG_VentCavity", 0.052, 0.006, 0.0165,
                 (vx, DECK_HD-0.0055, vz), C_HSG, M["Cavity_Black"])
    fin_y = DECK_HD-0.0028
    for k in range(7):
        fz = vz - 0.0068 + k*0.00226
        fin = box(f"HSG_VentFin_{k}", 0.0495, 0.0011, 0.00115,
                  (vx, fin_y, fz), C_HSG, M["Steel_Polished"])
        set_smooth(fin)
    # screws clamping vent
    screw("SCR_Vent_L", (vx-0.0255, DECK_HD-0.0012, vz), C_HSG,
          M["Steel_Polished"], M["Cavity_Black"], r=0.0016, slot='slot',
          rot=(radians(90), 0, 0))
    screw("SCR_Vent_R", (vx+0.0255, DECK_HD-0.0012, vz), C_HSG,
          M["Steel_Polished"], M["Cavity_Black"], r=0.0016, rot=(radians(90), 0, 0))

    # ---------------- folding side handle (right, stowed) ------------
    lug1 = rbox("HSG_HandleLug_F", 0.006, 0.013, 0.017, (DECK_HW+0.0018, -0.0475, 0.062),
                C_HSG, M["ALU_Brushed"], r=0.0018, seg=2)
    lug2 = rbox("HSG_HandleLug_R", 0.006, 0.013, 0.017, (DECK_HW+0.0018, 0.0475, 0.062),
                C_HSG, M["ALU_Brushed"], r=0.0018, seg=2)
    tube("HSG_HandleBail",
         [(DECK_HW+0.0035, -0.0475, 0.062), (DECK_HW+0.0068, -0.0435, 0.062),
          (DECK_HW+0.0068, 0.0435, 0.062), (DECK_HW+0.0035, 0.0475, 0.062)],
         0.0030, C_HSG, M["Chrome"], res_u=24)
    for nm, yy in (("SCR_HandleF", -0.0475), ("SCR_HandleR", 0.0475)):
        screw(nm, (DECK_HW+0.0049, yy, 0.062), C_HSG, M["Brass"], M["Cavity_Black"],
              r=0.0017, rot=(0, radians(90), 0))

    # ---------------- hinge brackets (chassis side) ------------------
    for i, xx in enumerate((-0.100, 0.0, 0.100)):
        br = rbox(f"HSG_HingeBracket_{i}", 0.018, 0.006, 0.011,
                  (xx, HINGE_Y-0.0022, CHASSIS_Z1-0.0035), C_HSG,
                  M["ALU_Brushed"], r=0.0012, seg=2)
        kn = cyl(f"HSG_HingeKnuckle_{i}", 0.0026, 0.018,
                 (xx, HINGE_Y, HINGE_Z), C_HSG, M["Steel_Polished"], axis='X', verts=24)
        set_smooth(kn)
    # hinge pin (fixed to chassis), spans full hinge line
    pin = cyl("HSG_HingePin", 0.00145, 0.242, (0, HINGE_Y, HINGE_Z), C_HSG,
              M["Steel_Polished"], axis='X', verts=16)
    set_smooth(pin)
    for sx in (-0.1215, 0.1215):
        cap = sphere(f"HSG_HingePinCap_{sx}", 0.0021, (sx, HINGE_Y, HINGE_Z),
                     C_HSG, M["Brass"])
        set_smooth(cap)

    # ---------------- latch bases (chassis side) ---------------------
    for sgn, nm in ((-1, 'L'), (1, 'R')):
        lx = sgn*0.100
        base = rbox(f"HSG_LatchBase_{nm}", 0.014, 0.0095, 0.0026,
                    (lx, -0.0716, CHASSIS_Z1+0.0013), C_HSG, M["ALU_Champagne"],
                    r=0.0012, seg=2)
        pvp = cyl(f"HSG_LatchPivot_{nm}", 0.0014, 0.0155,
                  (lx, -0.0690, CHASSIS_Z1+0.0030), C_HSG, M["Steel_Polished"],
                  axis='X', verts=16)
        set_smooth(pvp)
        screw(f"SCR_Latch_{nm}a", (lx-0.0045, -0.0716, CHASSIS_Z1+0.0027), C_HSG,
              M["Steel_Polished"], M["Cavity_Black"], r=0.0015, slot='cross')
        screw(f"SCR_Latch_{nm}b", (lx+0.0045, -0.0716, CHASSIS_Z1+0.0027), C_HSG,
              M["Steel_Polished"], M["Cavity_Black"], r=0.0015, slot='cross')

    # ---------------- seam screws (front of bottom cover) ------------
    for sgn in (-1, 1):
        screw(f"SCR_Seam_{sgn}", (sgn*0.121, -0.0740, 0.0232), C_HSG,
              M["Brass"], M["Cavity_Black"], r=0.0018, rot=(radians(90), 0, 0))

    # ---------------- cover screws on deck corners -------------------
    for i, (xx, yy) in enumerate([(-0.140, 0.066), (0.140, 0.066)]):
        screw(f"SCR_Corner_{i}", (xx, yy, CHASSIS_Z1), C_HSG,
              M["Steel_Polished"], M["Cavity_Black"], r=0.0019, slot='cross')

    return C_HSG
# =====================================================================
# LID  --  hinged cover (built closed, animated open about hinge pin),
#          inner felt lining, exterior nameplate + pinstripes,
#          lid hinge tabs, latch keeps.  Parented to LID_PIVOT empty.
# =====================================================================
def build_lid(col_all):
    C_LID = get_coll("REC_Lid", col_all)
    LID_TOP_Z  = 0.0938
    PLATE_T    = 0.0042
    SKIRT_Z0   = 0.0786
    wall_t     = 0.0024

    # pivot empty at hinge axis
    piv = bpy.data.objects.new("LID_Pivot", None)
    piv.empty_display_type = 'PLAIN_AXES'; piv.empty_display_size = 0.02
    link_to(piv, C_LID)
    piv.location = (0, HINGE_Y, HINGE_Z)
    D['LID_Pivot'] = piv

    lid_pts = rounded_rect_pts(2*DECK_HW+0.0024, 2*DECK_HD+0.0024, 0.0082)
    plate = prism("LID_OuterPlate", lid_pts, 0, PLATE_T, C_LID, M["ALU_Brushed"],
                  center=Vector((0, 0, LID_TOP_Z-PLATE_T)))
    add_bevel(plate, w=0.0008, seg=2, angle=40)
    shade_auto(plate, 35)

    # skirts: front, left, right walls (open at rear where hinge is)
    sy0, sy1 = -DECK_HD-0.0012, DECK_HD+0.0012
    fz = rbox("LID_SkirtFront", 2*DECK_HW+0.0024, wall_t, LID_TOP_Z-PLATE_T-SKIRT_Z0,
              (0, -DECK_HD-0.0012+wall_t/2, (LID_TOP_Z-PLATE_T+SKIRT_Z0)/2),
              C_LID, M["ALU_Brushed"], r=0.0015, seg=2)
    lx = rbox("LID_SkirtLeft",  wall_t, 2*DECK_HD+0.0024-2*wall_t, LID_TOP_Z-PLATE_T-SKIRT_Z0,
              (-DECK_HW-0.0012+wall_t/2, 0, (LID_TOP_Z-PLATE_T+SKIRT_Z0)/2),
              C_LID, M["ALU_Brushed"], r=0.0015, seg=2)
    rx = rbox("LID_SkirtRight", wall_t, 2*DECK_HD+0.0024-2*wall_t, LID_TOP_Z-PLATE_T-SKIRT_Z0,
              (DECK_HW+0.0012-wall_t/2, 0, (LID_TOP_Z-PLATE_T+SKIRT_Z0)/2),
              C_LID, M["ALU_Brushed"], r=0.0015, seg=2)
    rear = rbox("LID_SkirtRear", 2*DECK_HW+0.0024, wall_t*0.8, LID_TOP_Z-PLATE_T-SKIRT_Z0,
                (0, DECK_HD+0.0012-wall_t*0.4, (LID_TOP_Z-PLATE_T+SKIRT_Z0)/2),
                C_LID, M["ALU_Brushed"], r=0.0015, seg=1)

    # inner lining tray + felt pads (pressure pad over head zone)
    inner = prism("LID_InnerPlate", rounded_rect_pts(2*DECK_HW-0.002, 2*DECK_HD-0.002, 0.006),
                  0, 0.0010, C_LID, M["Plastic_Dark"],
                  center=Vector((0, 0, LID_TOP_Z-PLATE_T-0.0010)))
    felt_band = prism("LID_FeltBand",
                      rounded_rect_pts(0.118, 0.106, 0.004), 0, 0.0011, C_LID,
                      M["Felt_Grey"], center=Vector((0, REEL_SY, LID_TOP_Z-PLATE_T-0.0021)))
    pad = rbox("LID_FeltPressurePad", 0.052, 0.030, 0.0026,
               (0.0255, 0.0005, LID_TOP_Z-PLATE_T-0.0028), C_LID, M["Felt_Grey"],
               r=0.004, seg=2)

    # exterior nameplate + pinstripes (on top of lid plate)
    zt = LID_TOP_Z + 0.00025
    text_obj("TXT_Brand_Lid", "SONORA", (0, -0.020, zt), 0.0105, C_LID,
             M["Enamel_Mark"], spacing=1.32)
    text_obj("TXT_Model_Lid", "R-70  PROFESSIONAL  FIELD  RECORDER",
             (0, -0.0405, zt), 0.0030, C_LID, M["Enamel_Mark"], spacing=1.15)
    for dy in (-0.0335, 0.0475):
        st = box(f"LID_Pinstripe_{dy}", 0.200, 0.00055, 0.00035,
                 (0, dy, LID_TOP_Z+0.00018), C_LID, M["Brass"])
    st2 = box("LID_Pinstripe2", 0.200, 0.00035, 0.00035,
              (0, 0.0498, LID_TOP_Z+0.00018), C_LID, M["Brass"])

    # lid hinge tabs (between chassis knuckles)
    for i, xx in enumerate((-0.100, 0.0, 0.100)):
        tab = rbox(f"LID_HingeTab_{i}", 0.012, 0.0055, 0.010,
                   (xx, HINGE_Y-0.0018, HINGE_Z-0.0046), C_LID,
                   M["ALU_Brushed"], r=0.0010, seg=2)
    # latch keeps on lid skirt front
    for sgn, nm in ((-1, 'L'), (1, 'R')):
        keep = rbox(f"LID_LatchKeep_{nm}", 0.010, 0.0028, 0.0075,
                    (sgn*0.100, -DECK_HD-0.0035, SKIRT_Z0+0.0042),
                    C_LID, M["Steel_Polished"], r=0.0012, seg=2)

    # ---------------- latch bails (open position) -------------------
    for sgn, nm in ((-1, 'L'), (1, 'R')):
        lx = sgn*0.100
        bail = bpy.data.objects.new(f"LATCH_Bail_{nm}", None)
        bail.empty_display_type = 'SINGLE_ARROW'; bail.empty_display_size = 0.008
        link_to(bail, bpy.data.collections["REC_Housing"])
        bail.location = (lx, -0.0690, CHASSIS_Z1+0.0030)
        pts_local = [(0.0, 0.0016, 0.0000), (0.0, -0.0042, -0.0016),
                     (0.0, -0.0082, -0.0050), (0.0, -0.0092, -0.0116),
                     (0.0, -0.0060, -0.0150), (0.0, -0.0016, -0.0152)]
        C_HSGc = bpy.data.collections["REC_Housing"]
        w = tube(f"LATCH_Wire_{nm}",
                 [(bail.location.x + p[0], bail.location.y + p[1], bail.location.z + p[2])
                  for p in pts_local], 0.00095, C_HSGc, M["Chrome"], res_u=20)
        grip = cyl(f"LATCH_Grip_{nm}", 0.0017, 0.0075,
                   (bail.location.x, bail.location.y-0.0068, bail.location.z-0.0148),
                   C_HSGc, M["Bakelite_Black"], axis='X', verts=20)
        set_smooth(grip)
        bpy.context.view_layer.update()
        for o in (w, grip):
            parent_dropchild(o, bail)
        bail.rotation_euler = (radians(-108), 0, 0)   # swung open

    # parent everything in lid collection to pivot (in world space)
    bpy.context.view_layer.update()
    for ob in list(C_LID.objects):
        if ob is not piv and ob.parent is None:
            parent_dropchild(ob, piv)
    return piv
# =====================================================================
# REELS + TAPE TRANSPORT
# =====================================================================
FLANGE_BOT = (0.0535, 0.0547)
FLANGE_TOP = (0.0660, 0.0672)
PACK_Z0, PACK_Z1 = 0.0588, 0.0652

def build_reel(col, name, cx, pack_r):
    grp = bpy.data.objects.new(f"GRP_Reel_{name}", None)
    grp.empty_display_type = 'PLAIN_AXES'; grp.empty_display_size = 0.02
    link_to(grp, col)
    D[grp.name] = grp
    grp.location = (cx, REEL_SY, 0)

    for nm, (z0, z1) in (("Bot", FLANGE_BOT), ("Top", FLANGE_TOP)):
        if nm == "Top":
            # open-centre ring so the hub is visible and faces never coincide
            fl = ring(f"REEL_{name}_Flange{nm}", HUB_R + 0.004, FLANGE_R,
                      z1 - z0, (cx, REEL_SY, (z0+z1)/2), col,
                      M["ALU_Brushed"], steps=96)
        else:
            fl = cyl(f"REEL_{name}_Flange{nm}", FLANGE_R, z1-z0,
                     (cx, REEL_SY, (z0+z1)/2), col, M["ALU_Brushed"], verts=96)
        add_bevel(fl, w=0.00045, seg=2, angle=40)
        shade_auto(fl, 35)
    hub = cyl(f"REEL_{name}_Hub", HUB_R, FLANGE_TOP[1]+0.0022-FLANGE_BOT[0],
              (cx, REEL_SY, (FLANGE_TOP[1]+0.0022+FLANGE_BOT[0])/2), col,
              M["ALU_Champagne"], verts=48)
    add_bevel(hub, w=0.0004, seg=2)
    shade_auto(hub)
    boss = cyl(f"REEL_{name}_HubBoss", 0.0062, 0.0012,
               (cx, REEL_SY, FLANGE_TOP[1]+0.0022+0.0006), col, M["Brass"], verts=32)
    shade_auto(boss)
    # three spokes carrying the top flange (just under it, clear of pack)
    for k in range(3):
        a = radians(90 + 120*k)
        sx, sy = cx + 0.0262*cos(a), REEL_SY + 0.0262*sin(a)
        sp = box(f"REEL_{name}_Spoke{k}", 0.0295, 0.0034, 0.0010,
                 (sx, sy, FLANGE_TOP[0] - 0.00055), col,
                 M["ALU_Brushed"])
        sp.rotation_euler = (0, 0, a)
    # wound tape pack
    pack = cyl(f"REEL_{name}_TapePack", pack_r, PACK_Z1-PACK_Z0,
               (cx, REEL_SY, (PACK_Z0+PACK_Z1)/2), col, M["Tape_Pack"], verts=128)
    add_bevel(pack, w=0.0006, seg=2, angle=45)
    shade_auto(pack, 50)
    # spindle (fixed, belongs to deck)
    sp_ = cyl(f"SPINDLE_{name}", 0.003, 0.0275, (cx, REEL_SY, 0.0535+0.01375),
              col, M["Steel_Polished"], verts=24)
    set_smooth(sp_)
    dome = sphere(f"SPINDLE_{name}_Tip", 0.003, (cx, REEL_SY, 0.0812), col,
                  M["Steel_Polished"])
    set_smooth(dome)
    bpy.context.view_layer.update()
    for ob in list(col.objects):
        if ob.name.startswith(f"REEL_{name}") and ob.parent is None:
            parent_dropchild(ob, grp)
    return grp

# ---------------- tape route & ribbon ----------------
ROUTE_2D = [
    (-0.0776,  0.0034),
    (-0.0610, -0.0050),
    (-0.0470, -0.0062),
    (-0.0395, -0.0135),
    (-0.0345, -0.0170),
    (-0.0290, -0.0183),
    (-0.0204, -0.0187),
    (-0.00790,-0.02155),
    (-0.00801,-0.02374),
    (-0.00683,-0.02557),
    (-0.00513,-0.02636),
    (-0.00297,-0.02606),
    (-0.00136,-0.02461),
    (-0.00110,-0.02156),
    ( 0.00600,-0.02030),
    ( 0.01150,-0.01720),
    ( 0.01500,-0.01220),
    ( 0.0190, -0.0062),
    ( 0.0225, -0.0062),
    ( 0.0260, -0.0062),
    ( 0.0300, -0.0062),
    ( 0.0345, -0.0052),
    ( 0.0356, -0.0030),
    ( 0.0357,  0.0000),
    ( 0.0392,  0.0031),
    ( 0.0392,  0.0031),
    # wrap capstan C=(0.0455,0.0075) r=0.0025 at centerline R=0.0026,
    # 225 deg -> 315 deg (through the bottom, out at the pinch nip)
    ( 0.04366, 0.00566),
    ( 0.04420, 0.00525),
    ( 0.04483, 0.00499),
    ( 0.04550, 0.00490),
    ( 0.04617, 0.00499),
    ( 0.04680, 0.00525),
    ( 0.04734, 0.00566),
    # wrap right-angle roller R2=(0.05969,0.01312) r=0.003 at R=0.0032
    ( 0.05743, 0.01538),
    ( 0.05809, 0.01589),
    ( 0.05886, 0.01621),
    ( 0.05969, 0.01632),
    ( 0.06052, 0.01621),
    ( 0.06845, 0.02601),
    ( 0.06922, 0.03503),
    ( 0.06540, 0.04325),
]

def build_tape_ribbon(col):
    pts2 = catmull_rom(ROUTE_2D, samples=16)
    me = new_mesh("TAPE_Ribbon")
    bm = bmesh.new()
    hw = TAPE_W/2
    n = len(pts2)
    rows = []
    for i, (x, y) in enumerate(pts2):
        # horizontal cross-section: tape lies flat, width normal to travel
        px, py = pts2[max(i-1, 0)]
        nx, ny = pts2[min(i+1, n-1)]
        tx, ty = nx-px, ny-py
        ln = math.hypot(tx, ty) or 1.0
        lx, ly = -ty/ln*hw, tx/ln*hw
        v1 = bm.verts.new((x-lx, y-ly, TAPE_Z))
        v2 = bm.verts.new((x+lx, y+ly, TAPE_Z))
        rows.append((v1, v2))
    for i in range(len(rows)-1):
        a1, a2 = rows[i]; b1, b2 = rows[i+1]
        try: bm.faces.new((a1, a2, b2, b1))
        except ValueError: pass
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    bm.to_mesh(me); bm.free()
    ob = _obj("TAPE_Ribbon", me, col, M["Tape_Oxide"])
    sm = ob.modifiers.new("Solidify", 'SOLIDIFY')
    sm.thickness = TAPE_T; sm.offset = 0
    ob.visible_shadow = True
    return ob

def build_transport(col_all):
    C_TP = get_coll("REC_Transport", col_all)
    C_HSG = bpy.data.collections["REC_Housing"]

    # ---------------- head stack ----------------
    base = rbox("HEAD_BasePlate", 0.021, 0.017, 0.0016,
                (0.0255, 0.0005, WELL_FLOOR+0.0008), C_TP, M["Brass"], r=0.0012, seg=1)
    screw("SCR_Head_L", (0.0255, 0.0072, WELL_FLOOR+0.0018), C_TP,
          M["Steel_Polished"], M["Cavity_Black"], r=0.0013, slot='slot')
    screw("SCR_Head_R", (0.0255, -0.0062, WELL_FLOOR+0.0018), C_TP,
          M["Steel_Polished"], M["Cavity_Black"], r=0.0013, slot='slot')
    heads = [("HEAD_Erase", 0.0175, 0.0225, 0.0735, M["Steel_Polished"]),
             ("HEAD_Record", 0.0229, 0.0279, 0.0730, M["Bakelite_Black"]),
             ("HEAD_Play", 0.0283, 0.0335, 0.0730, M["Bakelite_Black"])]
    for nm, x0, x1, zt, mat in heads:
        blk = box(nm, x1-x0, 0.012, zt-WELL_FLOOR,
                  ((x0+x1)/2, 0.0005, (WELL_FLOOR+zt)/2), C_TP, mat)
        add_bevel(blk, w=0.0004, seg=2, angle=40)
        shade_auto(blk, 40)
        # polished contact face facing the tape (front, -Y side)
        fp = box(nm+"_Face", (x1-x0)-0.0008, 0.0007, 0.0088,
                 ((x0+x1)/2, -0.00575, TAPE_Z+0.0004), C_TP, M["Steel_Polished"])
    # rear head cover plate
    rc = box("HEAD_RearPlate", 0.017, 0.0014, 0.0155, (0.0255, 0.0069, 0.0652),
             C_TP, M["Plastic_Dark"])

    # ---------------- fixed guide posts ----------------
    for nm, (px, py) in (("GUIDE_G1", (-0.0345, -0.0123)), ("GUIDE_G2", (0.0115, -0.0123))):
        p = cyl(nm, 0.0015, 0.0205, (px, py, 0.06325), C_TP, M["Steel_Polished"], verts=24)
        set_smooth(p)
        tip = sphere(nm+"_Tip", 0.0015, (px, py, 0.0735), C_TP, M["Steel_Polished"])
        set_smooth(tip)
        ftr = cyl(nm+"_Foot", 0.0026, 0.0012, (px, py, WELL_FLOOR+0.0006), C_TP,
                  M["Brass"], verts=24)

    # ---------------- dancer / tension assembly ----------------
    dx, dy = -0.0045, -0.0228
    dw = cyl("GUIDE_DancerWheel", 0.0035, 0.008, (dx, dy, TAPE_Z), C_TP,
             M["Paint_Cream"], verts=48)
    add_bevel(dw, w=0.0008, seg=2)
    shade_auto(dw, 45)
    da = cyl("GUIDE_DancerAxle", 0.0009, 0.019, (dx, dy, 0.0625), C_TP,
             M["Steel_Polished"], verts=16)
    set_smooth(da)
    dbr = rbox("GUIDE_DancerBracket", 0.006, 0.0055, 0.0080,
               (-0.0045, -0.0228, 0.0570), C_TP, M["ALU_Brushed"], r=0.0012, seg=2)
    dart = box("GUIDE_DancerArm", 0.0022, 0.0075, 0.0014,
               (-0.0045, -0.0258, 0.0706), C_TP, M["ALU_Brushed"])
    # torsion spring (helix)
    hel = []
    for i in range(49):
        t = i/48
        a = t*4*2*pi
        hel.append((-0.0045 + 0.0014*cos(a), -0.0258 + 0.0014*sin(a),
                    0.0690 + 0.0034*t))
    tube("GUIDE_DancerSpring", hel, 0.00025, C_TP, M["Steel_Polished"], res_u=8)

    # ---------------- capstan ----------------
    cxp, cyp = 0.0455, 0.0075
    bush = cyl("CAPSTAN_Bushing", 0.004, 0.0016, (cxp, cyp, WELL_FLOOR+0.0008),
               C_TP, M["Brass"], verts=32)
    shaft = cyl("CAPSTAN_Shaft", 0.0025, 0.0245, (cxp, cyp, WELL_FLOOR+0.0016+0.01225),
                C_TP, M["Steel_Polished"], verts=48)
    add_bevel(shaft, w=0.0003, seg=2)
    shade_auto(shaft, 40)
    ctip = sphere("CAPSTAN_Tip", 0.0025, (cxp, cyp, 0.0783), C_TP, M["Steel_Polished"])
    set_smooth(ctip)

    # ---------------- pinch roller ----------------
    pxp, pyp = 0.05075, -0.00162
    pbr = rbox("PINCH_Bracket", 0.0075, 0.0075, 0.012, (pxp, pyp-0.0055, 0.060),
               C_TP, M["ALU_Brushed"], r=0.0014, seg=2)
    parf = box("PINCH_Arm", 0.0024, 0.0062, 0.0015, (pxp, pyp-0.0028, 0.0733),
               C_TP, M["ALU_Brushed"])
    pax = cyl("PINCH_Axle", 0.001, 0.0215, (pxp, pyp, 0.0635), C_TP,
              M["Steel_Polished"], verts=16)
    set_smooth(pax)
    tire = cyl("PINCH_Tyre", 0.008, 0.014, (pxp, pyp, TAPE_Z), C_TP,
               M["Rubber_Black"], verts=64)
    add_bevel(tire, w=0.0012, seg=2)
    shade_auto(tire, 45)
    phub = cyl("PINCH_Hub", 0.0036, 0.0148, (pxp, pyp, TAPE_Z), C_TP,
               M["Chrome"], verts=32)
    shade_auto(phub)

    # ---------------- right-angle guide roller near take-up ---------
    gx, gy = 0.05969, 0.01312
    gw = cyl("GUIDE_Roll2", 0.003, 0.008, (gx, gy, TAPE_Z), C_TP,
             M["Paint_Cream"], verts=48)
    add_bevel(gw, w=0.0007, seg=2)
    shade_auto(gw, 45)
    ga = cyl("GUIDE_Roll2Axle", 0.0009, 0.019, (gx, gy, 0.0625), C_TP,
             M["Steel_Polished"], verts=16)
    set_smooth(ga)
    gbr = rbox("GUIDE_Roll2Bracket", 0.005, 0.005, 0.0016, (gx, gy+0.0045, WELL_FLOOR+0.0008),
               C_TP, M["ALU_Brushed"], r=0.001, seg=1)

    # ---------------- tape ribbon ----------------
    build_tape_ribbon(C_TP)
    return C_TP
# =====================================================================
# CONTROL SURFACE  --  inset plate, transport keys, jacks, speed
# toggle, knobs, tape counter.  (VU meters in p07.)
# =====================================================================
KEY_XS = [-0.098, -0.084, -0.070, -0.056, -0.042, -0.028]
KEY_LABELS = ["REW", "PLAY", "FF", "STOP", "PAUSE", "REC"]
KEY_Y = -0.0365

def build_controls(col_all):
    C_CTL = get_coll("REC_Controls", col_all)
    PLATE_Z = CHASSIS_Z1

    # plate kept clear of the tape window: rear edge y = -0.0280
    plate = prism("CTL_Plate", rounded_rect_pts(0.2914, 0.0427, 0.0023),
                  PLATE_Z-0.0015, PLATE_Z, C_CTL, M["ALU_Champagne"],
                  center=Vector((0, -0.04935, 0)))
    add_bevel(plate, w=0.0004, seg=1, angle=40)
    shade_auto(plate, 40)
    # scribe line border on plate
    for nm, yy in (("CTL_ScribeTop", -0.04935+0.0190), ("CTL_ScribeBot", -0.04935-0.0190)):
        pass  # border scribe omitted for cleanliness

    # ---------------- transport keys ----------------
    strip = rbox("CTL_KeyBase", 0.0800, 0.0104, 0.0014,
                 (-0.063, KEY_Y, PLATE_Z+0.0007), C_CTL, M["Plastic_Dark"],
                 r=0.0015, seg=1)
    for i, kx in enumerate(KEY_XS):
        is_rec = (i == 5)
        cap = rbox(f"CTL_Key_{KEY_LABELS[i]}", 0.0098, 0.0066, 0.0020,
                   (kx, KEY_Y, PLATE_Z+0.0024), C_CTL,
                   M["Bakelite_Black"], r=0.0009, seg=2)
        add_bevel(cap, w=0.00035, seg=2, angle=40)
        if is_rec:
            inlay = rbox("CTL_KeyRec_Inlay", 0.0064, 0.0040, 0.00045,
                         (kx, KEY_Y, PLATE_Z+0.00355), C_CTL, M["Phenolic_Red"],
                         r=0.0008, seg=1)
        text_obj(f"LBL_{KEY_LABELS[i]}", KEY_LABELS[i], (kx, -0.0440, PLATE_Z+0.0002),
                 0.0019, C_CTL, M["Enamel_Mark"])

    # ---------------- mic input jacks ----------------
    for j, (jx, lbl) in enumerate([(0.030, "MIC L"), (0.050, "MIC R")]):
        collar = cyl(f"CTL_Jack_{lbl}", 0.0046, 0.0026, (jx, KEY_Y, PLATE_Z+0.0013),
                     C_CTL, M["Chrome"], verts=48)
        add_bevel(collar, w=0.0005, seg=2)
        shade_auto(collar, 40)
        sock = cyl(f"CTL_Jack_{lbl}_Socket", 0.0021, 0.0022, (jx, KEY_Y, PLATE_Z+0.0019),
                   C_CTL, M["Cavity_Black"], verts=32)
        pin = cyl(f"CTL_Jack_{lbl}_Pin", 0.0006, 0.0016, (jx, KEY_Y, PLATE_Z+0.0026),
                  C_CTL, M["Brass"], verts=12)
        text_obj(f"LBL_{lbl}", lbl, (jx, -0.0440, PLATE_Z+0.0002), 0.0019,
                 C_CTL, M["Enamel_Mark"])

    # ---------------- speed toggle ----------------
    tx, ty = 0.115, KEY_Y
    tb = cyl("CTL_ToggleBase", 0.0033, 0.0024, (tx, ty, PLATE_Z+0.0012), C_CTL,
             M["Bakelite_Black"], verts=32)
    shade_auto(tb)
    collar = cyl("CTL_ToggleCollar", 0.0021, 0.0014, (tx, ty, PLATE_Z+0.0028), C_CTL,
                 M["Chrome"], verts=24)
    lever_pts = [(tx, ty, PLATE_Z+0.0034),
                 (tx, ty-0.0022, PLATE_Z+0.0090)]
    tube("CTL_ToggleLever", lever_pts, 0.00095, C_CTL, M["Chrome"])
    tip = sphere("CTL_ToggleTip", 0.00135, (tx, ty-0.0026, PLATE_Z+0.0092), C_CTL,
                 M["Bakelite_Black"])
    set_smooth(tip)
    text_obj("LBL_SP1", "7.5", (tx-0.0148, ty, PLATE_Z+0.0002), 0.0017, C_CTL, M["Enamel_Mark"])
    text_obj("LBL_SP2", "15", (tx+0.0148, ty, PLATE_Z+0.0002), 0.0017, C_CTL, M["Enamel_Mark"])
    text_obj("LBL_SPEED", "IPS", (tx, -0.0440, PLATE_Z+0.0002), 0.0019, C_CTL, M["Enamel_Mark"])

    # ---------------- knobs ----------------
    def knob(kx, label, ang):
        base = cyl(f"CTL_Knob_{label}_Base", 0.0059, 0.0016, (kx, -0.0560, PLATE_Z+0.0008),
                   C_CTL, M["Bakelite_Black"], verts=48)
        add_bevel(base, w=0.0005, seg=2); shade_auto(base, 40)
        cap = cyl(f"CTL_Knob_{label}_Cap", 0.0047, 0.0030, (kx, -0.0560, PLATE_Z+0.0031),
                  C_CTL, M["Bakelite_Black"], verts=48)
        add_bevel(cap, w=0.0006, seg=2); shade_auto(cap, 40)
        inlay = box(f"CTL_Knob_{label}_Pt", 0.0042, 0.0008, 0.0004,
                    (kx, -0.0560-0.0028, PLATE_Z+0.00465), C_CTL, M["Paint_Cream"])
        parent_keep(inlay, cap)
        cap.rotation_euler = (0, 0, radians(ang))
        for i in range(9):
            a = radians(200 + 140*i/8)
            tk = box(f"CTL_Knob_{label}_Tick{i}", 0.00035, 0.0013, 0.00025,
                     (kx+0.0079*cos(a), -0.0560+0.0079*sin(a), PLATE_Z+0.0003),
                     C_CTL, M["Enamel_Mark"])
            tk.rotation_euler = (0, 0, a+radians(90))
        text_obj(f"CTL_Knob_{label}_0", "0", (kx+0.0104*cos(radians(200)),
                 -0.0560+0.0104*sin(radians(200)), PLATE_Z+0.0002), 0.0013, C_CTL, M["Enamel_Mark"])
        text_obj(f"CTL_Knob_{label}_10", "10", (kx+0.0112*cos(radians(340)),
                 -0.0560+0.0112*sin(radians(340)), PLATE_Z+0.0002), 0.0013, C_CTL, M["Enamel_Mark"])
        text_obj(f"LBL_{label}", label, (kx, -0.0668, PLATE_Z+0.0002), 0.0017,
                 C_CTL, M["Enamel_Mark"], spacing=1.06)
    knob(0.070, "MONITOR", -35)
    knob(0.094, "TREBLE", 60)
    knob(0.118, "BASS", 10)

    # ---------------- tape counter ----------------
    cx0, cy0 = 0.036, -0.0560
    cf = rbox("CTL_CounterFrame", 0.0190, 0.0092, 0.0020,
              (cx0, cy0, PLATE_Z+0.0010), C_CTL, M["Plastic_Dark"], r=0.0012, seg=2)
    cfl = box("CTL_CounterFloor", 0.0158, 0.0066, 0.0006,
              (cx0, cy0, PLATE_Z+0.0020), C_CTL, M["Cavity_Black"])
    text_obj("CTL_CounterDigits", "0 3 7 6", (cx0-0.0008, cy0-0.0024, PLATE_Z+0.0024),
             0.0044, C_CTL, M["Paint_Cream"])
    text_obj("CTL_CounterM", "m", (cx0+0.0076, cy0-0.0026, PLATE_Z+0.0024),
             0.0016, C_CTL, M["Paint_Cream"])
    lens = prism("CTL_CounterLens", rounded_rect_pts(0.0162, 0.0070, 0.0008),
                 PLATE_Z+0.0024, PLATE_Z+0.0036, C_CTL, M["Acrylic_Lens"],
                 center=Vector((cx0, cy0, 0)))
    text_obj("LBL_METRES", "TAPE  METRES", (cx0, -0.0662, PLATE_Z+0.0002),
             0.0017, C_CTL, M["Enamel_Mark"])
    return C_CTL
# =====================================================================
# VU METERS  --  physically built meters: bezel, cavity, cream face,
# arc scale (text-on-curve), tick marks, red overload zone, brass
# needle at rest, glass lens.
# =====================================================================
def build_vu(col, nm, cx, cy, rest_ang=108.0):
    PL = CHASSIS_Z1
    HW, HH = 0.041/2, 0.018/2
    # pockets: open the control plate and chassis recess floor so the
    # meter face, scale, and needle stay visible through the bezel
    plate = bpy.data.objects.get("CTL_Plate")
    chas  = bpy.data.objects.get("HSG_Chassis")
    cpx = box(f"VU_{nm}_CUTPlate", 2*(HW-0.0016), 2*(HH-0.0016), 0.0025,
              (cx, cy, PL-0.00075), col, None)
    ccx = box(f"VU_{nm}_CUTChassis", 2*(HW-0.0016), 2*(HH-0.0016), 0.0038,
              (cx, cy, PL-0.0026), col, None)
    if plate: add_bool(plate, cpx)
    if chas:  add_bool(chas, ccx)
    # bezel frame (ring of 4 walls)
    fz1 = rbox(f"VU_{nm}_BezelF", 2*HW, 0.0016, 0.0022, (cx, cy-HH+0.0008, PL+0.0011), col, M["ALU_Champagne"])
    fz2 = rbox(f"VU_{nm}_BezelB", 2*HW, 0.0016, 0.0022, (cx, cy+HH-0.0008, PL+0.0011), col, M["ALU_Champagne"])
    fx1 = rbox(f"VU_{nm}_BezelL", 0.0016, 2*HH-0.0032, 0.0022, (cx-HW+0.0008, cy, PL+0.0011), col, M["ALU_Champagne"])
    fx2 = rbox(f"VU_{nm}_BezelR", 0.0016, 2*HH-0.0032, 0.0022, (cx+HW-0.0008, cy, PL+0.0011), col, M["ALU_Champagne"])
    # cavity floor + walls
    cf = box(f"VU_{nm}_Floor", 2*HW-0.002, 2*HH-0.002, 0.0008,
             (cx, cy, PL-0.0040), col, M["Cavity_Black"])
    # cream face
    face = box(f"VU_{nm}_Face", 2*HW-0.0034, 2*HH-0.0034, 0.0010,
               (cx, cy, PL-0.0031), col, M["Paint_Cream"])
    arcx, arcy = cx, cy-0.0125
    # scale numerals placed radially, upright to their radius
    lab_ang = [(150, "-20"), (120, "-10"), (97, "-5"), (63, "0"), (30, "+3")]
    for i, (a, lab) in enumerate(lab_ang):
        rad = radians(a)
        lx = arcx + 0.0162*cos(rad)
        ly = arcy + 0.0162*sin(rad)
        text_obj(f"VU_{nm}_Num{i}", lab, (lx, ly, PL-0.0023), 0.0019, col,
                 M["Enamel_Mark"], rot=(0, 0, a-90))
    # ticks
    majors = [150, 120, 97, 77, 55, 30]
    minors = [135, 108.5, 87, 66, 42.5]
    for i, a in enumerate(majors):
        r0, r1 = 0.0112, 0.0133
        rad = radians(a)
        tk = box(f"VU_{nm}_Maj{i}", 0.00028, r1-r0, 0.0002,
                 (arcx+((r0+r1)/2)*cos(rad), arcy+((r0+r1)/2)*sin(rad), PL-0.0022),
                 col, M["Enamel_Mark"])
        tk.rotation_euler = (0, 0, rad+radians(90))
    for i, a in enumerate(minors):
        r0, r1 = 0.0121, 0.0133
        rad = radians(a)
        tk = box(f"VU_{nm}_Min{i}", 0.00022, r1-r0, 0.0002,
                 (arcx+((r0+r1)/2)*cos(rad), arcy+((r0+r1)/2)*sin(rad), PL-0.0022),
                 col, M["Enamel_Mark"])
        tk.rotation_euler = (0, 0, rad+radians(90))
    # red overload zone band 55..30 deg
    bm = bmesh.new()
    seg = 12; r0, r1 = 0.0100, 0.0109
    va, vb = [], []
    for i in range(seg+1):
        a = radians(30 + 25*i/seg)
        va.append(bm.verts.new((arcx+r0*cos(a), arcy+r0*sin(a), PL-0.00255)))
        vb.append(bm.verts.new((arcx+r1*cos(a), arcy+r1*sin(a), PL-0.00255)))
    for i in range(seg):
        bm.faces.new((va[i], va[i+1], vb[i+1], vb[i]))
    bmesh.ops.solidify(bm, geom=bm.faces[:], thickness=0.00025)
    me = new_mesh(f"VU_{nm}_RedZone"); bm.to_mesh(me); bm.free()
    rz = _obj(f"VU_{nm}_RedZone", me, col, M["Mark_Red"])
    # "VU" legend
    text_obj(f"VU_{nm}_VU", "VU", (cx, cy-0.0058, PL-0.0022), 0.0023, col,
             M["Enamel_Mark"])
    text_obj(f"VU_{nm}_Ch", "CHANNEL " + ("1" if nm == "L" else "2"),
             (cx, cy+0.0056, PL-0.0024), 0.0013, col, M["Enamel_Mark"])
    # needle (brass blade + black tip), rest angle
    pivot = Vector((arcx, arcy, PL-0.0020))
    nd = box(f"VU_{nm}_Needle", 0.0135, 0.00045, 0.00022,
             (pivot.x + 0.0135/2 - 0.0025, pivot.y, pivot.z), col, M["Needle_Black"])
    tail = cyl(f"VU_{nm}_NeedleTail", 0.0010, 0.0004, (pivot.x, pivot.y, pivot.z-0.00025),
               col, M["Needle_Black"], verts=12)
    hub = cyl(f"VU_{nm}_NeedleHub", 0.0012, 0.0005, (pivot.x, pivot.y, pivot.z+0.0001),
              col, M["Brass"], verts=20)
    rot = Matrix.Translation(pivot) @ Matrix.Rotation(radians(rest_ang), 4, 'Z') \
        @ Matrix.Translation(-pivot)
    for o in (nd, tail, hub):
        o.matrix_basis = rot @ o.matrix_basis
    # glass lens + bezel screws
    lens = prism(f"VU_{nm}_Lens", rounded_rect_pts(2*HW-0.0014, 2*HH-0.0014, 0.0010),
                 PL+0.0002, PL+0.0012, col, M["Acrylic_Lens"], center=Vector((cx, cy, 0)))
    add_bevel(lens, w=0.00035, seg=2)
    shade_auto(lens, 50)
    for i, sx in enumerate((-HW+0.0008, HW-0.0008)):
        screw(f"VU_{nm}_SCR{i}", (sx, cy, PL+0.0022), col, M["Steel_Polished"],
              M["Cavity_Black"], r=0.0011, slot='slot')

def build_meters(col_all):
    C_VU = get_coll("REC_Meters", col_all)
    build_vu(C_VU, "L", -0.052, -0.0560, rest_ang=104.0)
    build_vu(C_VU, "R", -0.006, -0.0560, rest_ang=86.0)
    return C_VU
# =====================================================================
# MARKINGS + STUDIO (backdrop, world, lights) + CAMERAS
# =====================================================================
def build_markings(col_all):
    C_MK = get_coll("REC_Markings", col_all)
    PL = CHASSIS_Z1
    # front face brand (faces -Y)
    text_obj("MK_Brand_Front", "SONORA", (0, -0.0754, 0.0685), 0.0058, C_MK,
             M["Enamel_Mark"], rot=(90, 0, 0), spacing=1.30)
    text_obj("MK_Front_Sl", "PROFESSIONAL FIELD RECORDER  -  R-70",
             (0, -0.0754, 0.0575), 0.0019, C_MK, M["Enamel_Mark"], rot=(90, 0, 0))
    # quarter-track legend left of meters
    text_obj("MK_QT1", "QUARTER TRACK", (-0.1105, -0.0508, PL+0.0002), 0.0016,
             C_MK, M["Enamel_Mark"])
    text_obj("MK_QT2", "STEREO", (-0.1105, -0.0558, PL+0.0002), 0.0016,
             C_MK, M["Enamel_Mark"])
    return C_MK

def _area_light(name, loc, target, size_x, size_y, power, color=(1,1,1),
                col=None, spread=None):
    ld = bpy.data.lights.new(name, 'AREA')
    ld.shape = 'RECTANGLE'
    ld.size = size_x; ld.size_y = size_y
    ld.energy = power
    ld.color = color
    if spread: ld.spread = radians(spread)
    ob = bpy.data.objects.new(name, ld)
    if col: link_to(ob, col)
    ob.location = loc
    aim(ob, target)
    D[name] = ob
    return ob

def build_studio(col_all):
    C_ST = get_coll("STUDIO", col_all)
    # world
    w = bpy.data.worlds.get("World") or bpy.data.worlds.new("World")
    bpy.context.scene.world = w
    w.use_nodes = True
    bg = w.node_tree.nodes.get("Background")
    bg.inputs[0].default_value = (0.028, 0.030, 0.033, 1)
    bg.inputs[1].default_value = 1.0

    # cyclorama sweep (floor -> curved wall behind)
    prof = [(-1.40, 0.0)]
    prof.append((0.40, 0.0))
    for i in range(1, 13):
        a = radians(90.0*i/12)
        prof.append((0.40 + 0.38*sin(a), 0.38 - 0.38*cos(a)))
    prof.append((0.78, 1.10))
    me = new_mesh("STU_Backdrop")
    bm = bmesh.new()
    rows = []
    for x in (-1.45, 1.45):
        vs = [bm.verts.new((x, p[0], p[1])) for p in prof]
        rows.append(vs)
    for i in range(len(prof)-1):
        bm.faces.new((rows[0][i], rows[0][i+1], rows[1][i+1], rows[1][i]))
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    bm.to_mesh(me); bm.free()
    bd = _obj("STU_Backdrop", me, C_ST, M["Backdrop_Grey"])
    set_smooth(bd)

    _area_light("LGT_Key",  (-0.42, -0.30, 0.40), (0.0, 0.0, 0.07), 0.60, 0.45,
                5.0, (1.0, 0.975, 0.93), C_ST, spread=70)
    _area_light("LGT_Fill", (0.52, -0.28, 0.20), (0.0, 0.0, 0.07), 0.70, 0.70,
                1.3, (0.92, 0.96, 1.0), C_ST, spread=90)
    _area_light("LGT_Rim",  (0.06, 0.36, 0.30), (0.0, 0.02, 0.10), 0.09, 0.70,
                5.5, (1.0, 1.0, 1.0), C_ST, spread=60)
    _area_light("LGT_TopBar", (0.03, -0.03, 0.50), (0.0, 0.01, 0.09), 0.55, 0.07,
                1.2, (1.0, 0.99, 0.97), C_ST, spread=50)

    soft = _area_light("LGT_DeckFill", (0.02, -0.05, 0.30), (0.01, 0.01, 0.05),
                       0.26, 0.30, 1.5, (1.0, 0.99, 0.97), C_ST, spread=70)

    # cameras
    cam1_d = bpy.data.cameras.new("CAM_Hero")
    cam1_d.lens = 50.0; cam1_d.sensor_width = 36.0
    cam1_d.clip_start = 0.004
    cam1 = bpy.data.objects.new("CAM_Hero", cam1_d)
    link_to(cam1, C_ST)
    cam1.location = (-0.159, -0.1855, 0.4985)
    aim(cam1, (0.010, 0.012, 0.040))
    foc = bpy.data.objects.new("CAM_Hero_Focus", None)
    foc.empty_display_size = 0.006; link_to(foc, C_ST)
    foc.location = (-0.010, 0.010, 0.060)
    cam1_d.dof.use_dof = True
    cam1_d.dof.focus_object = foc
    cam1_d.dof.aperture_fstop = 8.0
    D['CAM_Hero'] = cam1

    cam2_d = bpy.data.cameras.new("CAM_Detail")
    cam2_d.lens = 50.0; cam2_d.sensor_width = 36.0
    cam2_d.clip_start = 0.002
    cam2 = bpy.data.objects.new("CAM_Detail", cam2_d)
    link_to(cam2, C_ST)
    cam2.location = (0.017, -0.070, 0.300)
    aim(cam2, (0.020, 0.012, 0.054))
    foc2 = bpy.data.objects.new("CAM_Detail_Focus", None)
    foc2.empty_display_size = 0.006; link_to(foc2, C_ST)
    foc2.location = (0.020, 0.002, 0.060)
    cam2_d.dof.use_dof = True
    cam2_d.dof.focus_object = foc2
    cam2_d.dof.aperture_fstop = 6.5
    D['CAM_Detail'] = cam2
    bpy.context.scene.camera = cam1
    return C_ST

# =====================================================================
# ANIMATION, EXPLODED VIEW (geometry-nodes leader lines),
# RENDER SETTINGS, MAIN
# =====================================================================
def build_animation(sc):
    piv = D['LID_Pivot']
    piv.rotation_euler = (0, 0, 0)
    piv.keyframe_insert('rotation_euler', index=0, frame=1)
    piv.rotation_euler = (radians(-58), 0, 0)
    piv.keyframe_insert('rotation_euler', index=0, frame=46)
    for fc in piv.animation_data.action.fcurves:
        for kp in fc.keyframe_points:
            kp.interpolation = 'BEZIER'
            kp.easing = 'EASE_OUT' if kp.co.x < 30 else 'EASE_IN'
        fc.keyframe_points[0].handle_left_type = 'FREE'
        fc.keyframe_points[-1].handle_right_type = 'FREE'
    sc.frame_set(1)   # cache closed pose for later copies
    for nm, revs in (("Supply", 2.5), ("Tak", 5.0)):
        g = D.get(f"GRP_Reel_{nm}")
        g.rotation_euler = (0, 0, 0)
        g.keyframe_insert('rotation_euler', index=2, frame=44)
        g.rotation_euler = (0, 0, revs*2*pi)
        g.keyframe_insert('rotation_euler', index=2, frame=120)
        for fc in g.animation_data.action.fcurves:
            for kp in fc.keyframe_points:
                kp.interpolation = 'LINEAR'
    sc.frame_set(1)

def gn_dash_lines(col):
    ng = bpy.data.node_groups.get("GN_DashLine")
    if not ng:
        ng = bpy.data.node_groups.new("GN_DashLine", 'GeometryNodeTree')
        ng.interface.new_socket("Geometry", in_out='OUTPUT',
                                socket_type='NodeSocketGeometry')
        n = ng.nodes
        ln = n.new('GeometryNodeMeshLine'); ln.inputs['Count'].default_value = 60
        ln.inputs['Start Location'].default_value = (0, 0, 0)
        ln.inputs['Offset'].default_value = (0, 0, 0.00385)
        m2c = n.new('GeometryNodeMeshToCurve')
        c2p = n.new('GeometryNodeCurveToPoints'); c2p.mode = 'COUNT'
        c2p.inputs['Count'].default_value = 34
        cyl = n.new('GeometryNodeMeshCylinder')
        cyl.inputs['Vertices'].default_value = 6
        cyl.inputs['Radius'].default_value = 0.00035
        cyl.inputs['Depth'].default_value = 0.0021
        iop = n.new('GeometryNodeInstanceOnPoints')
        rz = n.new('GeometryNodeRealizeInstances')
        sm = n.new('GeometryNodeSetMaterial')
        sm.inputs['Material'].default_value = M["Paint_Cream"]
        out = n.new('NodeGroupOutput')
        L = ng.links.new
        L(ln.outputs['Mesh'], m2c.inputs['Mesh'])
        L(m2c.outputs['Curve'], c2p.inputs['Curve'])
        L(c2p.outputs['Points'], iop.inputs['Points'])
        L(cyl.outputs['Mesh'], iop.inputs['Instance'])
        L(iop.outputs['Instances'], rz.inputs['Geometry'])
        L(rz.outputs['Geometry'], sm.inputs['Geometry'])
        L(sm.outputs['Geometry'], out.inputs['Geometry'])
    for i, loc in enumerate([(-0.052, 0.032, -0.055), (0.052, 0.032, -0.055),
                             (-0.052, 0.032, 0.125), (0.110, -0.040, -0.100)]):
        ob = bpy.data.objects.new(f"EXPO_Guide_{i}", None)
        me = bpy.data.meshes.new(f"EXPO_Guide_{i}")
        ob = bpy.data.objects.new(f"EXPO_Guide_{i}", me)
        link_to(ob, col)
        md = ob.modifiers.new("GN", 'NODES')
        md.node_group = ng
        ob.location = loc
        ob.visible_shadow = False

def build_exploded(sc):
    # snapshot closed pose
    sc.frame_set(1)
    bpy.context.view_layer.update()
    sc_ex = bpy.data.scenes.new("R70_EXPLODED")
    sc_ex.render.fps = 24
    sc_ex.frame_start = 1; sc_ex.frame_end = 1
    col = get_coll("EXPLODED", None, sc_ex)
    off_map = {
        "REC_Housing":  (0, 0, 0),
        "REC_Internal": (0, 0, 0),
        "REC_Lid":      (0, 0.008, 0.175),
        "REC_Reels":    (0, 0.006, 0.095),
        "REC_Transport":(0, 0.004, 0.038),
        "REC_Controls": (0, -0.060, -0.020),
        "REC_Meters":   (0, -0.095, -0.045),
        "REC_Markings": (0, 0.0, 0.0),
    }
    with_controls = {"MK_QT1", "MK_QT2"}
    for cname, off in off_map.items():
        src = bpy.data.collections.get(cname)
        if not src: continue
        for ob in src.all_objects:
            if ob.hide_render or ob.type in ('LIGHT', 'CAMERA', 'EMPTY'):
                continue
            o = off
            if ob.name in with_controls:
                o = off_map["REC_Controls"]
            cp = ob.copy()
            cp.name = "EX_" + ob.name
            cp.parent = None
            cp.matrix_world = (Matrix.Translation(Vector(o)) @
                               ob.matrix_world)
            col.objects.link(cp)
    gn_dash_lines(col)
    # simple flat studio for the technical view
    ld = bpy.data.lights.new("EXPO_Key", 'AREA')
    ld.energy = 120; ld.size = 1.6; ld.size_y = 1.2
    lo = bpy.data.objects.new("EXPO_Key", ld)
    col.objects.link(lo); lo.location = (-0.5, -0.5, 0.9); aim(lo, (0, 0, 0.05))
    ld2 = bpy.data.lights.new("EXPO_Fill", 'AREA')
    ld2.energy = 45; ld2.size = 1.6; ld2.size_y = 1.6
    lo2 = bpy.data.objects.new("EXPO_Fill", ld2)
    col.objects.link(lo2); lo2.location = (0.7, -0.3, 0.5); aim(lo2, (0, 0, 0.05))
    cd = bpy.data.cameras.new("CAM_Exploded")
    cd.type = 'ORTHO'; cd.ortho_scale = 0.60; cd.clip_start = 0.01
    cam = bpy.data.objects.new("CAM_Exploded", cd)
    col.objects.link(cam)
    cam.location = (-0.66, -0.66, 0.48); aim(cam, (0, -0.005, 0.090))
    sc_ex.camera = cam
    return sc_ex

def setup_render(sc, quick=False):
    sc.render.engine = 'CYCLES'
    prefs = bpy.context.preferences.addons.get('cycles')
    dev = 'CPU'
    if prefs:
        cp = prefs.preferences
        for dt in ('OPTIX', 'CUDA', 'HIP', 'METAL', 'ONEAPI'):
            try:
                cp.compute_device_type = dt
                cp.get_devices_for_type(dt)
                devs = cp.get_devices_for_type(dt)
                if any(d.type == dt for d in devs):
                    for d in cp.devices:
                        d.use = True
                    dev = 'GPU'
                    break
            except Exception:
                continue
    try:
        sc.cycles.device = dev
    except Exception:
        sc.cycles.device = 'CPU'
    sc.cycles.samples = 48 if quick else 128
    sc.cycles.use_adaptive_sampling = True
    sc.cycles.adaptive_threshold = 0.012 if quick else 0.006
    sc.cycles.use_denoising = True
    sc.cycles.denoiser = 'OPENIMAGEDENOISE'
    sc.cycles.max_bounces = 8
    sc.cycles.transmission_bounces = 8
    sc.cycles.transparent_max_bounces = 12
    sc.render.resolution_x = 1920
    sc.render.resolution_y = 1080
    sc.render.resolution_percentage = 60 if quick else 100
    sc.render.image_settings.file_format = 'PNG'
    sc.view_settings.view_transform = 'AgX'
    try:
        sc.view_settings.look = 'AgX - Medium High Contrast'
    except TypeError:
        pass
    sc.render.film_transparent = False
    sc.view_settings.exposure = -1.2
    return dev

# =====================================================================
def main():
    argv = sys.argv
    argv = argv[argv.index("--")+1:] if "--" in argv else []
    quick  = "--quick" in argv
    no_render = "--no-render" in argv
    only = None
    if "--only" in argv:
        only = argv[argv.index("--only")+1]

    sc = reset_scene()
    build_materials()
    root = sc.collection
    build_housing(root)
    build_lid(root)
    C_RL = get_coll("REC_Reels", root)
    build_reel(C_RL, "Supply", SUP_X, SUP_PACK_R)
    build_reel(C_RL, "Tak", TAK_X, TAK_PACK_R)
    build_transport(root)
    build_controls(root)
    build_meters(root)
    build_markings(root)
    build_studio(root)
    build_animation(sc)
    bpy.context.view_layer.update()
    build_exploded(sc)

    dev = setup_render(sc, quick)
    setup_render(bpy.data.scenes["R70_EXPLODED"], quick)
    print("R70: built", len(bpy.data.objects), "objects; Cycles device:", dev)

    base = os.path.dirname(os.path.abspath(__file__))
    blend_path = os.path.abspath(os.path.join(base, "field_recorder.blend"))
    bpy.ops.wm.save_as_mainfile(filepath=blend_path)
    print("R70: saved", blend_path)

    if no_render:
        return
    renders = []
    if only in (None, "hero"):
        renders.append(("hero.png", sc, D['CAM_Hero'], 75))
    if only in (None, "detail"):
        renders.append(("detail.png", sc, D['CAM_Detail'], 75))
    if only in (None, "exploded"):
        renders.append(("exploded.png", bpy.data.scenes["R70_EXPLODED"],
                        bpy.data.objects["CAM_Exploded"], 1))
    for fname, scene, cam, fr in renders:
        bpy.context.window.scene = scene   # ops.render uses the CONTEXT scene
        scene.camera = cam
        scene.frame_set(fr)
        scene.render.filepath = os.path.abspath(os.path.join(base, fname))
        bpy.ops.render.render(write_still=True)
        print("R70: rendered", scene.render.filepath)

    bpy.context.window.scene = sc
    bpy.ops.wm.save_as_mainfile(filepath=blend_path)
    print("R70: done")

main()

