import math, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import bpy
import v4lib as v4
from mathutils import Vector, Matrix

v4.reset()
# Materials
paint = v4.painted('forestry_yellow', (0.88, 0.47, 0.035), roughness=0.28, coat=0.35)
paint_light = v4.painted('boom_highlight_yellow', (0.98, 0.66, 0.08), roughness=0.3, coat=0.3)
dark = v4.painted('graphite_enamel', (0.095, 0.115, 0.12), roughness=0.42, coat=0.15)
steel = v4.metal('satin_hydraulic_steel', (0.68, 0.72, 0.74), roughness=0.26, brushed=True)
steel_dark = v4.metal('dark_cast_steel', (0.29, 0.32, 0.33), roughness=0.38, brushed=False)
rubber = v4.rubber('track_rubber', (0.045, 0.05, 0.048))
glass = v4.glass('cab_tinted_glass', (0.18, 0.42, 0.52), roughness=0.12)
black = v4.rubber('hose_black', (0.018, 0.022, 0.022))
red = v4.painted('safety_red', (0.78, 0.08, 0.025), roughness=0.42)
wood = v4.mat('fresh_log_wood', (0.52, 0.34, 0.16), roughness=0.8)
bark = v4.mat('rough_bark', (0.19, 0.12, 0.065), roughness=0.93)
endwood = v4.mat('cut_end_grain', (0.66, 0.46, 0.23), roughness=0.88)
wood_light = v4.mat('sunlit_sapwood', (0.62, 0.43, 0.23), roughness=0.84)
wood_dark = v4.mat('weathered_bark', (0.13, 0.085, 0.045), roughness=0.96)

# Helpers
def bolt(name, p, axis, body, r=0.018, length=0.012, material=steel):
    a=Vector(axis).normalized(); c=Vector(p)
    v4.cylinder(name,r,length,c,rot=Vector((0,0,1)).rotation_difference(a).to_euler(),segments=12,bevel=0.001,material=material,body=body)
def bar(name,p0,p1,r,body,material=paint_light):
    v4.rod(name,p0,p1,r,material=material,body=body)
def panel_box(name,size,loc,body,material=paint,bev=0.012):
    v4.box(name,size,loc,bevel=bev,material=material,body=body)
def hose(name, pts, body, radius=.018):
    v4.tube(name,pts,radius,material=black,body=body,resolution=10)
def axial_cylinder(name,p0,p1,r,body,material=steel_dark):
    a=Vector(p0); b=Vector(p1); d=b-a
    v4.cylinder(name,r,d.length,(a+b)*.5,rot=Vector((0,0,1)).rotation_difference(d.normalized()).to_euler(),segments=24,bevel=.008,material=material,body=body)

# Bodies
base=v4.body('undercarriage')
lt=v4.body('left_track'); rt=v4.body('right_track')
upper=v4.body('upper_house'); boom=v4.body('boom'); stick=v4.body('stick')
rot=v4.body('rotator'); head=v4.body('grapple_head'); tine_l=v4.body('left_tine'); tine_r=v4.body('right_tine'); logs=v4.body('log_bundle')

# Fixed undercarriage and track frames. Machine spans x=-2.2..2.2, width 3.05.
panel_box('belly_chassis',(3.35,1.72,.48),(0,0,.78),base,dark,.08)
panel_box('lower_belly_skid',(2.65,1.42,.12),(-.12,0,.50),base,steel_dark,.035)
v4.cylinder('lower_slew_race',.88,.12,(0,0,1.045),material=steel_dark,body=base)
# Track frame beams and suspension towers
for sy,lab in [(-1,'R'),(1,'L')]:
    y=sy*1.19
    panel_box(f'track_frame_{lab}',(3.95,.34,.48),(-.10,y,.60),base,dark,.09)
    panel_box(f'upper_track_guard_{lab}',(3.55,.12,.16),(-.12,sy*1.36,.91),base,paint,.035)
    panel_box(f'guard_mount_{lab}',(2.80,.18,.18),(-.12,sy*1.30,.83),base,dark,.025)
    # inner axle brackets
    for x in (-1.65,-.65,.35,1.35):
        panel_box(f'suspension_pedestal_{lab}_{x}',(.22,.38,.28),(x,sy*.99,.56),base,steel_dark,.035)
# lower central service details
for x in (-1.1,-.35,.4,1.15):
    panel_box(f'belly_rib_{x}',(.12,1.26,.08),(x,0,.48),base,steel_dark,.02)
# front/rear tow eyes
for x in (-1.50,1.42):
    for sy in (-1,1):
        v4.torus(f'tow_eye_{x}_{sy}',.055,.012,(x,sy*.80,.74),rot=(math.pi/2,0,0),material=steel_dark,body=base)

# track belt shaped like a thick oval loop, mesh in X-Z and extruded across y
# profile is a 20-point rounded capsule with flat-ish top and bottom
def capsule_points(cx,cz,rx,rz,n=28):
    pts=[]
    for i in range(n):
        a=2*math.pi*i/n
        pts.append((cx+rx*math.cos(a),cz+rz*math.sin(a)))
    return pts
def belt_mesh(name,yc,body):
    outer=capsule_points(-.10,.60,2.10,.57,40); inner=capsule_points(-.10,.60,1.78,.36,40)
    verts=[]; faces=[]; N=len(outer)
    for y in (yc-.13,yc+.13):
        for loop in (outer,inner): verts.extend([(x,y,z) for x,z in loop])
    # rings on each side and connect outer/inner walls
    for side in (0,1):
        off=side*2*N
        for i in range(N):
            j=(i+1)%N
            faces.append((off+i,off+j,off+N+j,off+N+i))
    for i in range(N):
        j=(i+1)%N
        # outside side wall and inside wall
        faces.append((i,j,2*N+j,2*N+i))
        faces.append((N+i,3*N+i,3*N+j,N+j))
    mesh=bpy.data.meshes.new(name+'_mesh'); mesh.from_pydata(verts,[],faces); mesh.materials.append(rubber); mesh.update()
    obj=bpy.data.objects.new(name,mesh); bpy.context.scene.collection.objects.link(obj); v4.part(obj,base)
    for p in mesh.polygons:p.use_smooth=True
    # Individual rubber-faced shoes sit on the continuous belt carcass.
    for i in range(30):
        a=2*math.pi*i/30; x=-.10+2.10*math.cos(a); z=.60+.57*math.sin(a)
        v4.box(f'{name}_grouser_{i}',(.29,.35,.085),(x,yc,z),rot=(0,-a,0),bevel=.025,material=rubber,body=base)
    # Recessed road wheels with stepped rims, hubs and a visible bolt circle.
    side=1 if yc>0 else -1
    face_y=yc+side*.18
    wheel_set=[(-1.84,.37),(-1.14,.285),(-.48,.285),(.18,.285),(.84,.285),(1.64,.37)]
    for wi,(xx,rr) in enumerate(wheel_set):
        # Axle shafts bridge each road wheel back to its welded track frame.
        axial_cylinder(f'{name}_roller_axle_{wi}',(xx,yc-side*.13,.60),(xx,yc+side*.03,.60),.085,base,steel_dark)
        v4.cylinder(f'{name}_roller_{wi}',rr,.16,(xx,yc+side*.10,.60),rot=(math.pi/2,0,0),segments=40,bevel=.022,material=dark,body=base)
        v4.torus(f'{name}_roller_rim_{wi}',rr*.84,.018,(xx,face_y,.60),rot=(math.pi/2,0,0),material=steel_dark,body=base)
        v4.cylinder(f'{name}_roller_hub_{wi}',rr*.38,.12,(xx,yc+side*.14,.60),rot=(math.pi/2,0,0),segments=32,bevel=.01,material=steel_dark,body=base)
        v4.cylinder(f'{name}_roller_cap_{wi}',rr*.20,.08,(xx,yc+side*.21,.60),rot=(math.pi/2,0,0),segments=24,bevel=.008,material=steel,body=base)
        for bi in range(6):
            a=2*math.pi*bi/6
            bolt(f'{name}_roller_bolt_{wi}_{bi}',(xx+rr*.57*math.cos(a),yc+side*.19,.60+rr*.57*math.sin(a)),(0,side,0),base,r=.012,length=.04,material=steel)
    # Top return rollers are partially tucked under the upper guards.
    for ri,xx in enumerate((-.95,.20,1.15)):
        axial_cylinder(f'{name}_return_axle_{ri}',(xx,yc-side*.13,1.035),(xx,yc+side*.03,1.035),.045,base,steel_dark)
        v4.cylinder(f'{name}_return_roller_{ri}',.13,.15,(xx,yc+side*.10,1.035),rot=(math.pi/2,0,0),segments=32,bevel=.015,material=dark,body=base)
        v4.cylinder(f'{name}_return_hub_{ri}',.055,.06,(xx,yc+side*.17,1.035),rot=(math.pi/2,0,0),segments=24,bevel=.008,material=steel_dark,body=base)
    # Driven toothed sprocket and layered hub rotate on the track drive joint.
    dx=-1.50
    v4.cylinder(name+'_drive_sprocket',.405,.23,(dx,yc,.60),rot=(math.pi/2,0,0),segments=48,bevel=.02,material=steel_dark,body=body)
    for ti in range(14):
        a=2*math.pi*ti/14
        v4.box(f'{name}_sprocket_tooth_{ti}',(.13,.27,.09),(dx+.39*math.cos(a),yc,.60+.39*math.sin(a)),rot=(0,-a,0),bevel=.015,material=steel_dark,body=body)
    v4.torus(name+'_sprocket_rim',.32,.025,(dx,yc+side*.13,.60),rot=(math.pi/2,0,0),material=steel,body=body)
    v4.cylinder(name+'_sprocket_hub',.19,.12,(dx,yc+side*.12,.60),rot=(math.pi/2,0,0),segments=40,bevel=.014,material=dark,body=body)
    v4.cylinder(name+'_sprocket_cap',.105,.06,(dx,yc+side*.17,.60),rot=(math.pi/2,0,0),segments=32,bevel=.012,material=steel,body=body)
    for bi in range(8):
        a=2*math.pi*bi/8
        bolt(f'{name}_sprocket_bolt_{bi}',(dx+.072*math.cos(a),yc+side*.19,.60+.072*math.sin(a)),(0,side,0),body,r=.012,length=.08,material=steel)
    return
belt_mesh('left_track_belt',1.48,lt); belt_mesh('right_track_belt',-1.48,rt)
# undercarriage rails close to track assemblies
for sy,lab in [(-1,'R'),(1,'L')]:
    for x in (-1.50,1.55):
        v4.cylinder(f'fixed_axle_{lab}_{x}',.10,.30,(x,sy*1.25,.60),rot=(math.pi/2,0,0),material=steel_dark,body=base)

# Upper slewing deck and cab, all carried by upper_house
v4.cylinder('slew_bearing_outer',.94,.20,(0,0,1.205),material=steel_dark,body=upper)
v4.torus('slew_bearing_race',.78,.035,(0,0,1.28),material=steel,body=upper)
panel_box('upper_deck',(2.20,1.90,.30),(.05,0,1.46),upper,dark,.08)
# rear counterweight sculpted stacked forms
panel_box('counterweight_main',(1.22,1.92,.82),(-.92,0,1.93),upper,paint,.16)
panel_box('counterweight_top',(1.04,1.72,.20),(-.96,0,2.42),upper,paint_light,.09)
panel_box('counterweight_rear_guard',(0.14,1.60,.48),(-1.57,0,1.90),upper,dark,.045)
for y in (-.62,-.31,0,.31,.62):
    panel_box(f'counterweight_vent_{y}',(.025,.20,.38),(-1.642,y,1.91),upper,steel_dark,.012)
# side engine enclosure and service doors
for sy in (-1,1):
    panel_box(f'engine_side_panel_{sy}',(1.36,.06,.52),(-.15,sy*.99,1.86),upper,paint,.035)
    for k in range(5):
        panel_box(f'engine_vent_{sy}_{k}',(.035,.012,.33),(-.42+k*.12,sy*1.027,1.86),upper,dark,.008)
    # side grab handles and step plates
    # cab floor at front-left side
panel_box('cab_floor',(1.15,1.18,.13),(.43,.52,1.62),upper,dark,.035)
# glazed cab frame: rear/side pillars, roof, front windshield, glazing panels
panel_box('cab_roof',(1.26,1.34,.14),(.45,.55,3.12),upper,paint,.07)
# cab lower sill
panel_box('cab_sill',(1.20,1.30,.20),(.45,.55,1.78),upper,paint,.045)
# frame pillars and glazing sheets
for xx in (-.12,1.02):
    for yy in (-.03,1.13):
        v4.rod(f'cab_post_{xx}_{yy}',(xx,yy,1.86),(xx,yy,3.09),.055,material=paint,body=upper)
# side windows on both sides (panels glass)
for sy in (-1,1):
    y=.55+sy*.61
    panel_box(f'cab_side_glass_{sy}',(1.12,.018,1.02),(.45,y,2.48),upper,glass,.008)
# windshield broad front and rear glazing
panel_box('cab_front_windshield',(1.02,.018,1.04),(.98,.55,2.48),upper,glass,.008)
panel_box('cab_rear_glass',(1.02,.018,.82),(-.09,.55,2.46),upper,glass,.008)
# dash, seat and controls
panel_box('dashboard',(0.42,.92,.13),(.72,.55,2.14),upper,dark,.035)
panel_box('seat_base',(.38,.38,.10),(.18,.55,2.08),upper,steel_dark,.025)
panel_box('seat_cushion',(.40,.42,.15),(.18,.55,2.19),upper,black,.04)
panel_box('seat_back',(.16,.42,.52),(-.01,.55,2.48),upper,black,.05)
for sy in (.23,.87):
    v4.rod(f'joystick_{sy}',(.61,sy,2.20),(.62,sy,2.47),.014,material=steel_dark,body=upper)
    v4.sphere(f'joystick_knob_{sy}',.032,(.62,sy,2.48),material=black,body=upper)
# wiper and front work lights
v4.rod('windshield_wiper',(.49,.55,2.87),(1.34,.55,2.80),.012,material=dark,body=upper)
for sy in (.16,.94):
    v4.box(f'cab_work_light_{sy}',(.18,.12,.14),(1.02,sy,3.17),bevel=.035,material=steel,body=upper)
    v4.box(f'cab_lamp_lens_{sy}',(.12,.025,.08),(1.12,sy,3.17),bevel=.02,material=glass,body=upper)
# Forestry FOPS/ROPS cage around windshield, side glazing and roof perimeter.
for sy in (-1,1):
    ylo,yhi=.02,1.08
    xedge=1.13 if sy>0 else 1.13
    v4.rod(f'cab_guard_front_post_{sy}',(xedge,ylo,1.94),(xedge,ylo,3.12),.035,material=dark,body=upper)
    v4.rod(f'cab_guard_front_post_outer_{sy}',(xedge,yhi,1.94),(xedge,yhi,3.12),.035,material=dark,body=upper)
    # exterior side rails join the front cage back to the roof hoop
    yside=-.12 if sy<0 else 1.22
    v4.rod(f'cab_guard_side_lower_{sy}',(-.12,yside,2.02),(1.13,yside,2.02),.024,material=dark,body=upper)
    v4.rod(f'cab_guard_side_mid_{sy}',(-.12,yside,2.52),(1.13,yside,2.52),.024,material=dark,body=upper)
    v4.rod(f'cab_guard_side_roof_{sy}',(-.12,yside,3.18),(1.13,yside,3.18),.032,material=dark,body=upper)
    for xx in (-.08,.32,.72,1.08):
        v4.rod(f'cab_guard_side_bar_{sy}_{xx}',(xx,yside,2.02),(xx,yside,3.14),.018,material=dark,body=upper)
# Protective windshield grid and roof crossbars.
for y in (.20,.38,.56,.74,.92):
    v4.rod(f'cab_guard_windshield_bar_{y}',(1.135,y,2.02),(1.135,y,3.10),.018,material=dark,body=upper)
for z in (2.03,2.57,3.13):
    v4.rod(f'cab_guard_windshield_cross_{z}',(1.135,.02,z),(1.135,1.08,z),.024,material=dark,body=upper)
for xx in (-.08,.28,.64,1.0):
    v4.rod(f'cab_roof_grille_{xx}',(xx,-.12,3.19),(xx,1.22,3.19),.018,material=dark,body=upper)
# Small raised forestry equipment ID plate on the engine enclosure.
v4.box('engine_id_badge',(.48,.018,.13),(-.16,1.028,1.76),bevel=.018,material=dark,body=upper)
for k in range(6):
    v4.box(f'engine_badge_mark_{k}',(.035,.012,.075),(-.27+k*.044,1.034,1.76),bevel=.004,material=steel,body=upper)
# exhaust stack
v4.cylinder('exhaust_base',.075,.18,(-.76,-.68,2.18),material=dark,body=upper)
v4.cylinder('exhaust_pipe',.045,.72,(-.76,-.68,2.58),material=steel_dark,body=upper)
v4.cylinder('exhaust_tip',.065,.16,(-.76,-.68,2.96),material=steel_dark,body=upper)

# Boom assembly (rest horizontal, heavy twin cheeks around centerline)
# pin collars at heel
for sy in (-1,1):
    v4.cylinder(f'boom_heel_boss_{sy}',.18,.12,(.78,sy*.34,2.14),rot=(math.pi/2,0,0),material=steel_dark,body=boom)
    v4.cylinder(f'boom_heel_cap_{sy}',.095,.14,(.78,sy*.41,2.14),rot=(math.pi/2,0,0),material=steel,body=boom)
# tapered boom cheek plates along XZ via extrude (XY outline becomes XZ after rot X=90)
outline=[(0,-.26),(.30,-.40),(1.55,-.37),(2.00,-.22),(2.00,.22),(1.55,.37),(.30,.40),(0,.26)]
for sy in (-1,1):
    v4.extrude(f'boom_cheek_{sy}',outline,.18,loc=(.78,sy*.30+.09,2.14),rot=(math.pi/2,0,0),bevel=.035,material=paint,body=boom)
panel_box('boom_center_spine',(1.55,.46,.28),(1.72,0,2.14),boom,paint_light,.08)
# heel/nose transverse pivot tubes
v4.cylinder('boom_heel_cross_pin',.11,.82,(.78,0,2.14),rot=(math.pi/2,0,0),material=steel,body=boom)
v4.cylinder('boom_nose_cross_pin',.12,.84,(2.78,0,2.14),rot=(math.pi/2,0,0),material=steel_dark,body=boom)
# hydraulic boom cylinder barrel mounted to upper body and boom, decorative but telescoping representation
v4.rod('boom_cyl_barrel',(.28,-.30,1.58),(1.38,-.30,1.93),.10,material=steel_dark,body=upper)
v4.rod('boom_cyl_rod', (1.25,-.30,1.89),(2.07,-.30,2.10),.047,material=steel,body=boom)
for x,z in ((.28,1.58),(1.38,1.93),(2.07,2.10)):
    # cylinders/pin collars
    v4.cylinder(f'boom_cylinder_eye_{x}',.09,.10,(x,-.30,z),rot=(math.pi/2,0,0),material=steel_dark,body=upper if x<1 else boom)
# Machined barrel collars and rod gland make the telescoping cylinder legible.
boom_axis=Vector((1.10,0,.35)).normalized()
for ti,body_ref in ((.12,upper),(.87,upper)):
    c=Vector((.28,-.30,1.58))+Vector((1.10,0,.35))*ti
    axial_cylinder(f'boom_barrel_collar_{ti}',c-boom_axis*.035,c+boom_axis*.035,.118,body_ref,steel)
rod_c=Vector((1.38,-.30,1.93))
axial_cylinder('boom_rod_gland',rod_c-boom_axis*.045,rod_c+boom_axis*.045,.073,boom,steel_dark)
# guard plates, bolts and hoses
for sy in (-1,1):
    for k in range(5):
        x=.99+k*.34
        bolt(f'boom_cheek_bolt_{sy}_{k}',(x,sy*.298,2.14), (0,sy,0),boom,r=.025,length=.018)
# Raised tapered crown rails and inspection plates break up the broad flat boom cheeks.
for sy in (-1,1):
    v4.rod(f'boom_crown_rail_{sy}',(.98,sy*.31,2.48),(2.55,sy*.31,2.34),.035,material=paint_light,body=boom)
    panel_box(f'boom_service_cover_{sy}',(.62,.045,.12),(1.75,sy*.405,2.24),boom,dark,.025)
    for k in range(3):
        bolt(f'boom_service_bolt_{sy}_{k}',(1.52+k*.20,sy*.434,2.24),(0,sy,0),boom,r=.014,length=.012,material=steel)

# Stick: 2.34m tapered box boom from x2.84 to 5.18
for sy in (-1,1):
    v4.cylinder(f'stick_heel_boss_{sy}',.14,.12,(2.84,sy*.34,2.14),rot=(math.pi/2,0,0),material=steel_dark,body=stick)
    v4.cylinder(f'stick_heel_cap_{sy}',.085,.13,(2.84,sy*.41,2.14),rot=(math.pi/2,0,0),material=steel,body=stick)
stick_outline=[(0,-.21),(.28,-.26),(1.95,-.19),(2.34,-.12),(2.34,.12),(1.95,.19),(.28,.26),(0,.21)]
for sy in (-1,1):
    v4.extrude(f'stick_cheek_{sy}',stick_outline,.14,loc=(2.84,sy*.26+.07,2.14),rot=(math.pi/2,0,0),bevel=.025,material=paint,body=stick)
panel_box('stick_spine',(1.78,.50,.20),(3.96,0,2.14),stick,paint_light,.06)
v4.cylinder('stick_wrist_cross_pin',.05,.78,(5.18,0,1.91),rot=(math.pi/2,0,0),material=steel_dark,body=stick)
# slight arm drop is represented in side silhouette with end knuckle
for sy in (-1,1):
    v4.cylinder(f'stick_wrist_boss_{sy}',.16,.10,(5.18,sy*.34,1.91),rot=(math.pi/2,0,0),material=steel_dark,body=stick)
    bolt(f'stick_wrist_bolt_{sy}',(5.18,sy*.39,1.91),(0,sy,0),stick,r=.065,length=.028)
# stick cylinder and hoses
v4.rod('stick_cylinder_barrel',(2.38,.30,1.76),(3.77,.30,1.89),.083,material=steel_dark,body=boom)
v4.rod('stick_cylinder_rod',(3.54,.30,1.87),(4.50,.30,1.90),.040,material=steel,body=stick)
stick_axis=Vector((1.39,0,.13)).normalized()
stick_barrel_start=Vector((2.38,.30,1.76)); stick_barrel_delta=Vector((1.39,0,.13))
for ti in (.12,.88):
    c=stick_barrel_start+stick_barrel_delta*ti
    axial_cylinder(f'stick_barrel_collar_{ti}',c-stick_axis*.032,c+stick_axis*.032,.098,boom,steel)
stick_gland=Vector((3.77,.30,1.89))
axial_cylinder('stick_rod_gland',stick_gland-stick_axis*.04,stick_gland+stick_axis*.04,.061,stick,steel_dark)
for sy in (-1,1):
    for k in range(4):
        bolt(f'stick_bolt_{sy}_{k}',(3.15+k*.48,sy*.32,2.17),(0,sy,0),stick,r=.021,length=.016)

# Rotator, initially modelled along X then turned vertical below the wrist.
v4.cylinder('rotator_upper_flange',.28,.14,(5.30,0,1.91),rot=(0,math.pi/2,0),material=steel_dark,body=rot)
v4.cylinder('rotator_motor_can',.20,.56,(5.55,0,1.91),rot=(0,math.pi/2,0),material=dark,body=rot)
v4.cylinder('rotator_lower_flange',.29,.18,(5.82,0,1.91),rot=(0,math.pi/2,0),material=steel_dark,body=rot)
# ports and ribbing
for sy in (-1,1):
    v4.cylinder(f'rotator_port_{sy}',.045,.14,(5.53,sy*.20,2.07),rot=(math.pi/2,0,0),material=steel,body=rot)
for xx in (5.40,5.68):
    v4.torus(f'rotator_casing_seam_{xx}',.205,.012,(xx,0,1.91),rot=(0,math.pi/2,0),material=steel_dark,body=rot)
# grapple head cross-y yoke and pivot bosses
panel_box('grapple_top_adapter',(.22,.62,.15),(5.84,0,1.69),head,steel_dark,.04)
panel_box('grapple_crossbeam',(.34,1.02,.20),(5.95,0,1.54),head,paint,.055)
for sy in (-1,1):
    # cheek plates extend down to tine pivot
    panel_box(f'grapple_cheek_{sy}',(.24,.20,.26),(5.98,sy*.28,1.56),head,dark,.035)
    v4.cylinder(f'grapple_tine_boss_{sy}',.16,.30,(5.98,sy*.22,1.55),rot=(math.pi/2,0,0),material=steel_dark,body=head)
    v4.cylinder(f'grapple_pivot_cap_{sy}',.14,.07,(5.98,sy*.42,1.55),rot=(math.pi/2,0,0),material=steel,body=head)
    v4.cylinder(f'grapple_pivot_outer_washer_{sy}',.16,.045,(5.98,sy*.475,1.55),rot=(math.pi/2,0,0),material=dark,body=head)
    for bi in range(6):
        a=2*math.pi*bi/6
        bolt(f'grapple_boss_bolt_{sy}_{bi}',(5.98+.105*math.cos(a),sy*.51,1.55+.105*math.sin(a)),(0,sy,0),head,r=.024,length=.028,material=steel)
# manifold and protective guard
panel_box('grapple_hose_guard',(.16,.80,.09),(6.08,0,1.65),head,dark,.025)

# Tines: long curved jaws, open at rest; shape outlines in local x/z plane about pivot.
# Each claw sweeps down and inward toward the log bundle; opposed rotation closes them.
# Right-side (positive X) tine curves inward/left; left-side mirrored.
# y centers separated to show two robust opposing jaws in paired side plates
# contour local coords referenced to pivot (x=5.98,z=1.55)
closed_right_path=[(0,0),(.36,.06),(.58,-.17),(.69,-.48),(.62,-.70),(.20,-.95)]
closed_left_path=[(-x,z) for x,z in closed_right_path]
def rest_profile_from_closed(profile, angle):
    # Joint motion uses this signed angle to put the narrow hook outside and
    # beneath the bundle. Invert that rotation to author its open rest shape.
    c=math.cos(angle); s=math.sin(angle)
    return [(c*x-s*z,s*x+c*z) for x,z in profile]
def ribbon_profile(path,half_width=.038):
    left=[]; right=[]
    for i,(x,z) in enumerate(path):
        a=path[max(0,i-1)]; b=path[min(len(path)-1,i+1)]
        dx=b[0]-a[0]; dz=b[1]-a[1]; ln=math.hypot(dx,dz) or 1.0
        nx=-dz/ln; nz=dx/ln
        left.append((x+nx*half_width,z+nz*half_width))
        right.append((x-nx*half_width,z-nz*half_width))
    return left+list(reversed(right))
prof_r=rest_profile_from_closed(ribbon_profile(closed_right_path),math.radians(-32))
prof_l=rest_profile_from_closed(ribbon_profile(closed_left_path),math.radians(32))
# inner and outer jaw plates each thick plate across y
for name,body,sy,outline,closed_path,close_angle in [('right',tine_r,-.22,prof_r,closed_right_path,math.radians(-32)),('left',tine_l,.22,prof_l,closed_left_path,math.radians(32))]:
    v4.extrude(f'{name}_forged_jaw',outline,.28,loc=(5.98,sy+.14,1.55),rot=(math.pi/2,0,0),bevel=.045,material=paint,body=body)
    # Reinforcing spine follows the curved hook path in its open rest pose.
    rest_path=rest_profile_from_closed(closed_path,close_angle)
    for k in range(1,len(rest_path)-1):
        p0,p1=rest_path[k],rest_path[k+1]
        v4.rod(f'{name}_jaw_rib_{k}',(5.98+p0[0],sy,1.55+p0[1]),(5.98+p1[0],sy,1.55+p1[1]),.045,material=paint_light,body=body)
    # Two replaceable teeth sit on the hook tip, below the bundle when closed.
    tip=rest_path[-1]; prev=rest_path[-2]
    tooth_base=(prev[0]*.30+tip[0]*.70,prev[1]*.30+tip[1]*.70)
    for j in (-1,1):
        v4.rod(f'{name}_tooth_{j}',(5.98+tooth_base[0],sy+j*.055,1.55+tooth_base[1]),(5.98+tip[0],sy+j*.055,1.55+tip[1]),.022,material=steel,body=body)
    v4.cylinder(f'{name}_pivot_sleeve',.15,.30,(5.98,sy,1.55),rot=(math.pi/2,0,0),material=steel_dark,body=body)
    v4.cylinder(f'{name}_pivot_face',.105,.04,(5.98,sy+(.16 if sy>0 else -.16),1.55),rot=(math.pi/2,0,0),material=steel,body=body)
    bolt(f'{name}_pivot_bolt',(5.98,sy+(.19 if sy>0 else -.19),1.55),(0,1 if sy>0 else -1,0),body,r=.078,length=.05)

# Three peeled logs vary in diameter and length, with irregular bark ridges and end grain.
# Their native cylinder axis is Z; rotate 90 degrees so trunks run along Y.
log_specs=[(5.06,.34,.22,2.18,wood),(5.40,.28,.16,2.04,wood_dark),(5.23,.635,.145,2.25,wood_light)]
for i,(x,z,r,length,woodmat) in enumerate(log_specs):
    v4.cylinder(f'log_{i}_core',r,length,(x,0,z),rot=(math.pi/2,0,0),segments=40,bevel=.022,material=woodmat,body=logs)
    # Uneven bark collars vary in spacing and radius rather than forming a repeated pattern.
    for k,(frac,scale) in enumerate([(-.43,.99),(-.29,1.02),(-.08,.98),(.19,1.015),(.39,.985)]):
        yy=frac*length
        v4.torus(f'log_{i}_bark_collar_{k}',r*scale,.009+0.002*(k%2),(x,yy,z),rot=(math.pi/2,0,0),material=bark if k%2==0 else wood_dark,body=logs)
    # Longitudinal bark fissures follow the log's round surface with slight waviness.
    for gi,ang in enumerate((.25,1.55,2.8,4.35,5.55)):
        pts=[]
        for j in range(11):
            yy=-.46*length+j*(.92*length/10)
            phase=ang+.035*math.sin(j*.9+i)
            pts.append((x+(r+.003)*math.cos(phase),yy,z+(r+.003)*math.sin(phase)))
        v4.tube(f'log_{i}_bark_fissure_{gi}',pts,.006 if gi%2 else .008,material=wood_dark if gi%2 else bark,body=logs,resolution=6)
    for side in (-1,1):
        end_y=side*(length*.5+.003)
        v4.cylinder(f'log_{i}_cut_end_{side}',r*.97,.008,(x,end_y,z),rot=(math.pi/2,0,0),segments=40,material=endwood if i!=1 else wood,body=logs)
        # Slightly eccentric growth rings and a dark heartwood center.
        for ri,rr in enumerate((r*.30,r*.56,r*.78)):
            v4.torus(f'log_{i}_growth_{side}_{ri}',rr,.0035,(x+(.006 if ri%2 else -.004),end_y+side*.005,z),rot=(math.pi/2,0,0),material=bark if ri!=1 else wood_dark,body=logs)
        v4.cylinder(f'log_{i}_heart_{side}',r*.11,.008,(x-.006,end_y+side*.003,z+.004),rot=(math.pi/2,0,0),segments=20,material=wood_dark,body=logs)
# Three red steel-belted binders wrap around the cross-section at separate trunk stations.
for bi,yy in enumerate((-.74,0,.74)):
    v4.torus(f'bundle_binder_{bi}',.40,.018,(5.23,yy,.45),rot=(math.pi/2,0,0),material=red,body=logs)

# Reorient the complete hydraulic rotator so its suspension axis is vertical.
# The attached head and tines move down and in to meet the new lower flange.
rot_anchor=Vector((5.18,0,1.91))
rot_turn=Matrix.Rotation(math.pi/2,4,'Y')
rot_xform=Matrix.Translation(rot_anchor) @ rot_turn @ Matrix.Translation(-rot_anchor)
for obj in list(rot.children):
    if obj.type == 'MESH':
        obj.matrix_world=rot_xform @ obj.matrix_world
head_shift=Matrix.Translation(Vector((-.66,0,-.585)))
for body in (head,tine_l,tine_r):
    for obj in list(body.children):
        if obj.type == 'MESH':
            obj.matrix_world=head_shift @ obj.matrix_world

# Joint graph
v4.joint('left_track_drive','continuous',base,lt,origin=(-1.50,1.48,.60),axis=(0,1,0))
v4.joint('right_track_drive','continuous',base,rt,origin=(-1.50,-1.48,.60),axis=(0,1,0))
v4.joint('upper_slew','continuous',base,upper,origin=(0,0,1.18),axis=(0,0,1))
v4.joint('boom_foot','revolute',upper,boom,origin=(.78,0,2.14),axis=(0,1,0),limits=(-.12,0))
v4.joint('stick_pin','revolute',boom,stick,origin=(2.84,0,2.14),axis=(0,1,0),limits=(-.12,.05))
v4.joint('rotator_spin','continuous',stick,rot,origin=(5.18,0,1.91),axis=(0,0,1))
v4.joint('grapple_mount','fixed',rot,head,origin=(5.18,0,1.18),axis=(0,0,1))
v4.joint('left_tine_pin','revolute',head,tine_l,origin=(5.32,.22,.965),axis=(0,1,0),limits=(0,.559))
v4.joint('right_tine_pin','revolute',head,tine_r,origin=(5.32,-.22,.965),axis=(0,1,0),limits=(-.559,0))
# At the displayed rest pose the load rests on the ground beneath the grapple.
# The fixed grapple-head mount carries it when the rotator and arm move.
v4.joint('log_bundle_mount','fixed',head,logs,origin=(5.23,0,.40),axis=(0,0,1))

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