"""Detailed articulated video tripod with bowl-mounted fluid head."""
import math, os, sys
from mathutils import Vector
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4

v4.reset()
# Materials
black = v4.painted("graphite_casting", (0.075, 0.085, 0.095), roughness=0.34)
black2 = v4.plastic("satin_black_polymer", (0.035, 0.043, 0.052), roughness=0.3)
alloy = v4.metal("satin_aluminum", color=(0.58, 0.62, 0.65), roughness=0.29, brushed=True)
bright = v4.metal("machined_steel", color=(0.78, 0.80, 0.82), roughness=0.23, brushed=False)
red = v4.painted("safety_red", (0.72, 0.035, 0.025), roughness=0.32)
rubber = v4.rubber("black_rubber")
white = v4.mat("engraving_white", (0.82, 0.84, 0.82), roughness=0.55)

# Dimensions in metres. Deployed reference pose.
ZC = 1.285
CENTER = (0.0, 0.0)
angles = [math.radians(a) for a in (30, 150, 270)]
radial = [(math.cos(a), math.sin(a)) for a in angles]
# leg centerline points down and out by 20 degrees
splay = math.radians(20)

def axis_box(name, p0, p1, width_x, width_y, offset_x=0.0, offset_y=0.0,
             up=(1, 0, 0), material=None, body=None):
    """Rectangular beam with cross-section aligned to an arbitrary leg axis."""
    p0, p1 = Vector(p0), Vector(p1)
    axis = p1 - p0
    center = (p0 + p1) * 0.5
    frame = v4._axis_matrix(center, axis, up=up)
    basis = frame.to_3x3()
    center += (basis @ Vector((1, 0, 0))) * offset_x
    center += (basis @ Vector((0, 1, 0))) * offset_y
    obj = v4.box(name, (width_x, width_y, axis.length), loc=center,
                 bevel=0.0, material=material, body=body)
    frame.translation = center
    obj.matrix_world = frame
    return obj

# Root casting, mounting bowl, leg hinge hardware.
crown = v4.body("crown")
v4.lathe("center_spider_hub", [(0,.006),(.075,.006),(.092,.018),(.094,.052),(.078,.068),(.064,.09),(.060,.12),(.072,.15),(.072,.18),(0,.18)],
         loc=(0,0,ZC-.09), material=black, body=crown)
v4.cylinder("bowl_shell", .067, .055, (0,0,ZC+.13), material=black, bevel=.004, body=crown)
v4.torus("100mm_bowl_rim", .071, .008, (0,0,ZC+.153), material=alloy, body=crown)
v4.torus("bowl_liner_seam", .062, .003, (0,0,ZC+.121), material=black2, body=crown)
# bowl clamp bridge and three tripod hinge clevises
v4.box("bowl_clamp_bridge", (.17,.035,.028), (0,0,ZC+.105), bevel=.008, material=black, body=crown)
for i,(ux,uy) in enumerate(radial):
    # clevis outward from center; two cheek blocks straddle the leg hinge plane
    px,py=ux*.085,uy*.085
    v4.box(f"leg_clevis_{i}", (.085,.048,.10), (px,py,ZC-.025), rot=(0,0,angles[i]), bevel=.009, material=black, body=crown)
    # pivot pin oriented along tangent
    tx,ty=-uy,ux
    v4.rod(f"leg_hinge_pin_{i}",(px-tx*.033,py-ty*.033,ZC-.02),(px+tx*.033,py+ty*.033,ZC-.02),.009,material=bright,body=crown)

# Three legs: upper twin tubes, lower telescoping tubes and feet.
section_bodies=[]
for i,a in enumerate(angles):
    ux,uy=radial[i]
    # axis from top pivot down/outward
    dx,dy,dz=ux*math.sin(splay),uy*math.sin(splay),-math.cos(splay)
    px,py=ux*.085,uy*.085
    p0=(px,py,ZC-.02)
    def along(t): return (p0[0]+dx*t,p0[1]+dy*t,p0[2]+dz*t)
    leg=v4.body(f"leg_{i}")
    # Twin upper tubes, rounded rectangular hinge head, and machined end sleeves
    for side in (-1,1):
        # offset twin rails perpendicular to radial plane
        ox,oy=-uy*side*.026,ux*side*.026
        q0=along(.045); q1=along(.76)
        # Four narrow wall beams form an open square guide. The smaller lower
        # tube nests through the clear 19 mm opening during the 250 mm stroke.
        up=( -uy, ux, 0 )
        rail_center=(q0[0]+ox,q0[1]+oy,q0[2])
        rail_end=(q1[0]+ox,q1[1]+oy,q1[2])
        for face, off in (("top",.0105),("bottom",-.0105)):
            axis_box(f"upper_guide_{i}_{side}_{face}",rail_center,rail_end,
                     .030,.003,offset_y=off*1.2857,up=up,material=alloy,body=leg)
        for face, off in (("near",.0105),("far",-.0105)):
            axis_box(f"upper_guide_{i}_{side}_{face}",rail_center,rail_end,
                     .003,.027,offset_x=off*1.2857,up=up,material=alloy,body=leg)
        # Compression lock plates and latch sit outside the guide opening.
        c0,c1=along(.623),along(.657)
        axis_box(f"twist_lock_collar_{i}_{side}",c0,c1,.034,.012,
                 offset_y=.020,up=up,material=black2,body=leg)
        r0,r1=along(.63),along(.65)
        axis_box(f"collar_red_marker_{i}_{side}",r0,r1,.034,.003,
                 offset_y=.025,up=up,material=red,body=leg)
        l0,l1=along(.628),along(.652)
        axis_box(f"twist_lock_latch_{i}_{side}",l0,l1,.018,.018,
                 offset_x=.004,offset_y=.035,up=up,material=black,body=leg)
    # width tie at lower end of upper leg / bridge between twin rails
    q=along(.10)
    v4.rod(f"upper_tube_cross_tie_{i}",(q[0]-uy*.035,q[1]+ux*.035,q[2]),(q[0]+uy*.035,q[1]-ux*.035,q[2]),.009,square=True,material=black,body=leg)
    # slider starts just below upper tube end; lower twin tubes telescoping on same angled axis
    sec=v4.body(f"section_{i}")
    section_bodies.append(sec)
    for side in (-1,1):
        ox,oy=-uy*side*.026,ux*side*.026
        q0=along(.75); q1=along(1.27)
        axis_box(f"lower_section_{i}_{side}",(q0[0]+ox,q0[1]+oy,q0[2]),(q1[0]+ox,q1[1]+oy,q1[2]),
                 .021,.021,up=(-uy,ux,0),material=alloy,body=sec)
        q=along(.765)
        f0,f1=along(.75),along(.78)
        axis_box(f"lower_tube_ferrule_{i}_{side}",
                 (f0[0]+ox,f0[1]+oy,f0[2]),(f1[0]+ox,f1[1]+oy,f1[2]),
                 .021,.021,up=(-uy,ux,0),material=bright,body=sec)
    # one broad central foot block, swivel stem and tread
    q=along(1.25)
    v4.box(f"foot_yoke_{i}",(.086,.062,.060),q,rot=(0,math.acos(abs(dz)),a),bevel=.010,material=black,body=sec)
    pad=along(1.35)
    v4.rod(f"foot_swivel_stem_{i}",along(1.27),(pad[0],pad[1],pad[2]+.006),.012,material=bright,body=sec)
    v4.lathe(f"rubber_foot_{i}",[(0,0),(.036,0),(.044,.004),(.046,.010),(.041,.022),(.032,.032),(.014,.036),(0,.036)],loc=(pad[0],pad[1],pad[2]-.036),material=rubber,body=sec)
    # molded tread bars on pad underside
    # joint axes: hinge tangent to tripod circumference; slide along leg axis
    ax=(-uy,ux,0)
    v4.joint(f"leg_spread_{i}","revolute",crown,leg,origin=p0,axis=ax,limits=(-math.radians(12),math.radians(12)))
    v4.joint(f"telescoping_{i}","prismatic",leg,sec,origin=along(.75),axis=(dx,dy,dz),limits=(-.25,0.0))

# Fluid head body: bowl base, pan bearing, tilt yoke and locks, platform.
head=v4.body("fluid_head")
# spherical bowl foot nest seated inside rim
v4.lathe("hemispherical_bowl_foot",[(0,-.018),(.045,-.018),(.058,-.006),(.064,.014),(.059,.035),(.047,.049),(0,.052)],loc=(0,0,ZC+.14),material=black2,body=head)
v4.cylinder("pan_cartridge",.048,.035,(0,0,ZC+.21),material=black,bevel=.004,body=head)
v4.cylinder("pan_bearing_cap",.052,.008,(0,0,ZC+.2315),material=alloy,bevel=.002,body=head)
v4.cylinder("head_neck",.042,.012,(0,0,ZC+.238),material=black,bevel=.003,body=head)
# head housing
v4.box("head_base_casting",(.18,.17,.11),(0,0,ZC+.25),bevel=.022,material=black,body=head)
# Front service fascia with recessed vent slots and a small model badge.
v4.box("front_service_fascia",(.15,.008,.074),(0,-.085,ZC+.25),bevel=.007,material=black2,body=head)
for n in range(3):
    v4.box(f"front_vent_slot_{n}",(.031,.003,.003),(.037,-.090,ZC+.238+n*.009),bevel=.001,material=black,body=head)
v4.box("fluid_head_nameplate",(.052,.004,.021),(-.030,-.0905,ZC+.255),bevel=.002,material=alloy,body=head)
for n in range(3):
    v4.box(f"nameplate_mark_{n}",(.026-n*.004,.003,.0015),(-.030,-.092,ZC+.250+n*.004),bevel=.0005,material=black2,body=head)
for x in (-.064,.064):
    for z in (ZC+.222,ZC+.278):
        v4.cylinder(f"fascia_screw_{x}_{z}",.0035,.005,(x,-.090,z),rot=(math.pi/2,0,0),material=bright,bevel=.0005,body=head)
# Paired stationary trunnion pedestals support the moving yoke at its axis.
# Their outboard faces meet the tilt cheeks on the X-axis pivot plane, leaving
# the yoke free to rotate while keeping the head assemblies visibly joined.
for sx in (-1,1):
    v4.box(f"trunnion_pedestal_{sx}",(.036,.078,.15),(sx*.072,.015,ZC+.36),bevel=.009,material=black,body=head)
    v4.cylinder(f"trunnion_bearing_{sx}",.034,.018,(sx*.081,.015,ZC+.435),rot=(0,math.pi/2,0),material=alloy,bevel=.003,body=head)
# four head base fasteners
for x in (-.074,.074):
    for y in (-.052,.052):
        v4.cylinder(f"base_cap_screw_{x}_{y}",.006,.003,(x,y,ZC+.307),material=bright,bevel=.001,body=head)
# Tilt yoke and camera platform are a separate rigid stage on the damped tilt axle.
tilt=v4.body("tilt_stage")
# tilt yoke side cheeks
for sx in (-1,1):
    v4.box(f"tilt_yoke_cheek_{sx}",(.024,.12,.12),(sx*.102,.015,ZC+.435),bevel=.014,material=black,body=tilt)
    v4.cylinder(f"tilt_axle_hub_{sx}",.031,.018,(sx*.116,.015,ZC+.435),rot=(0,math.pi/2,0),material=alloy,bevel=.003,body=tilt)
    v4.cylinder(f"tilt_axle_cap_{sx}",.018,.008,(sx*.129,.015,ZC+.435),rot=(0,math.pi/2,0),material=black2,bevel=.002,body=tilt)
    v4.cylinder(f"tilt_axle_bolt_{sx}",.007,.010,(sx*.136,.015,ZC+.435),rot=(0,math.pi/2,0),material=bright,bevel=.001,body=tilt)
# A low, broad saddle ties the yoke cheeks into the camera platform.
v4.box("tilt_yoke_saddle",(.19,.115,.045),(0,.005,ZC+.510),bevel=.012,material=black,body=tilt)
# cross tilt axle and upper camera platform; camera platform above yoke
v4.rod("tilt_cross_axle",(-.11,.015,ZC+.435),(.11,.015,ZC+.435),.018,material=bright,body=tilt)
v4.box("camera_platform",(.235,.19,.045),(0,0,ZC+.555),bevel=.009,material=black,body=tilt)
v4.box("platform_top_inlay",(.18,.13,.003),(0,0,ZC+.579),bevel=.003,material=alloy,body=tilt)
# front/rear raised platform lips and stop screws
for y in (-.082,.082):
    v4.box(f"plate_stop_lip_{y}",(.22,.012,.014),(0,y,ZC+.5845),bevel=.003,material=black2,body=tilt)
# left-side tilt drag and lock knobs, right side counterbalance / scale
v4.cylinder("tilt_drag_knob",.034,.026,(-.13,.015,ZC+.435),rot=(0,math.pi/2,0),material=black2,bevel=.003,body=tilt)
v4.cylinder("tilt_lock_handle_hub",.026,.025,(.13,.015,ZC+.435),rot=(0,math.pi/2,0),material=black2,bevel=.003,body=tilt)
v4.cylinder("counterbalance_dial",.027,.018,(.099,-.045,ZC+.30),rot=(0,math.pi/2,0),material=black2,bevel=.002,body=head)
# pan lock and drag dial on front-right of base
v4.cylinder("pan_drag_dial",.026,.022,(.102,-.052,ZC+.235),rot=(0,math.pi/2,0),material=black2,bevel=.003,body=head)
v4.cylinder("pan_lock_knob",.019,.024,(-.102,-.052,ZC+.235),rot=(0,math.pi/2,0),material=red,bevel=.002,body=head)
# service panel screws and white tactile buttons

# Pan bar hinged on right side of head and projecting rearward (positive Y).
# Short casting boss carries the handle socket outside the moving tilt-yoke cheek.
v4.cylinder("pan_handle_mount_boss",.026,.08,(.10,-.102,ZC+.435),rot=(0,math.pi/2,0),material=black,bevel=.003,body=tilt)
v4.rod("pan_handle_mount_bracket",(.13,.015,ZC+.435),(.13,-.102,ZC+.435),.011,material=black,body=tilt)
pan=v4.body("pan_bar")
hp=(.16,-.12,ZC+.435)
v4.cylinder("handle_socket",.024,.05,hp,rot=(0,math.pi/2,0),material=alloy,bevel=.003,body=pan)
v4.rod("pan_handle_tube",(.16,-.10,ZC+.435),(.16,.38,ZC+.435),.009,material=alloy,body=pan)
v4.cylinder("pan_handle_grip_collar",.016,.045,(.16,.345,ZC+.435),rot=(math.pi/2,0,0),material=black,bevel=.002,body=pan)
v4.lathe("ergonomic_pan_grip",[(0,0),(.016,0),(.018,.018),(.017,.12),(.015,.15),(0,.15)],loc=(.16,.37,ZC+.435),rot=(math.pi/2,0,0),material=rubber,body=pan)
v4.joint("handle_hinge","revolute",tilt,pan,origin=hp,axis=(1,0,0),limits=(-math.radians(20),math.radians(20)))

# Quick-release plate assembly. It is fixed to the head and carries a camera screw.
plate=v4.body("quick_release")
v4.box("dovetail_plate_core",(.155,.098,.012),(0,0,ZC+.5865),bevel=.004,material=alloy,body=plate)
# bevel-like raised dovetail rails run along plate length
for x in (-.068,.068):
    v4.box(f"dovetail_rail_{x}",(.012,.09,.009),(x,0,ZC+.597),bevel=.003,material=bright,body=plate)
v4.cylinder("camera_mount_screw",.009,.015,(0,0,ZC+.600),material=bright,bevel=.001,body=plate)
# Fixed joint is explicit because the plate is a separate assembly with its own name/body.
v4.joint("plate_mount","fixed",tilt,plate,origin=(0,0,ZC+.5865),axis=(0,0,1))

# Generic spherical-leveling / fluid-head interface: local X = world X, local Z = world Z.
v4.joint("bowl_head","generic",crown,head,origin=(0,0,ZC+.14),axis=(0,0,1),xdir=(1,0,0),
         dofs=[("rotZ",(-math.radians(170),math.radians(170))),("rotX",(-math.radians(10),math.radians(10)))])
v4.joint("tilt_axis","revolute",head,tilt,origin=(0,.015,ZC+.435),axis=(1,0,0),limits=(-math.radians(35),math.radians(35)))

v4.save(os.path.join(os.getcwd(),"asset.blend"))
print("saved asset.blend")
