import bpy, math, os, sys
from mathutils import Matrix, Vector
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4
v4.reset()
ARM_OFFSET = 1.20
CAB_X = -0.30

# Forestry machine finishes
orange = v4.painted('forestry_safety_orange', (0.91,0.27,0.035), roughness=.27, coat=.65)
yellow = v4.painted('boom_yellow', (0.96,0.52,0.035), roughness=.29, coat=.55)
charcoal = v4.painted('chassis_charcoal', (.105,.12,.12), roughness=.38, coat=.25)
black = v4.rubber('track_rubber', (.035,.043,.04))
steel = v4.metal('machined_steel', (.67,.70,.70), roughness=.27)
darksteel = v4.metal('dark_hardened_steel', (.20,.23,.23), roughness=.38, brushed=False)
glass = v4.glass('cab_safety_glass', (.30,.56,.66), roughness=.12)
seatmat = v4.fabric('seat_fabric', (.09,.105,.095))
wood = v4.wood('fresh_bark', light=(.42,.30,.17), dark=(.16,.105,.055), grain_scale=10)
endwood = v4.wood('cut_end', light=(.70,.54,.31), dark=(.32,.19,.09), grain_scale=14)
white = v4.mat('warm_white', (.88,.88,.82), roughness=.4)
red = v4.emissive('tail_lamp_red', (.9,.035,.015), 1.5)

# Dimensions: 4.6 m crawler base, 2.9 m overall width, 3.25 m cab height.
base = v4.body('undercarriage')
left = v4.body('left_track')
right = v4.body('right_track')
upper = v4.body('upper')
boom = v4.body('boom')
stick = v4.body('stick')
head = v4.body('rotator_grapple')
jawL = v4.body('left_tine')
jawR = v4.body('right_tine')
logs = v4.body('log_bundle')

# Lower chassis, slew bearing and robust side frames (X width, Y front/rear).
v4.box('central_lower_carriage',(1.72,3.65,.60),(0,0,.82), bevel=.09, material=charcoal, body=base)
v4.box('front_cross_member',(2.08,.34,.38),(0,-1.65,.76), bevel=.06, material=charcoal, body=base)
v4.box('rear_cross_member',(2.08,.34,.38),(0,1.65,.76), bevel=.06, material=charcoal, body=base)
for sx in (-1,1):
    x=sx*1.18
    v4.box('track_frame_'+str(sx),(.50,4.35,.48),(x,0,.58), bevel=.10, material=charcoal, body=base)
    v4.cylinder('slew_bearing_lower_'+str(sx),.70,.10,(0,.48,1.16), material=darksteel, body=base)
v4.cylinder('slew_bearing_race',.70,.13,(0,.48,1.27), material=steel, body=base)
v4.torus('bearing_race_detail',.62,.025,(0,.48,1.345), material=darksteel, body=base)
# Visible track frames carry separate revolving belt assemblies.
for sx,b in [(-1,left),(1,right)]:
    x=sx*1.22
    # Exposed undercarriage hardware and individual shoes make the crawler loop legible.
    for yy in (-1.68,1.68):
        v4.cylinder('track_end_drum_'+str(sx)+'_'+str(yy),.52,.48,(x,yy,.70),rot=(0,math.pi/2,0), material=darksteel, body=base)
        v4.torus('end_drum_rim_'+str(sx)+'_'+str(yy),.43,.032,(x+sx*.245,yy,.70),rot=(0,math.pi/2,0),material=steel,body=base)
    # Top and lower track shoes with raised grouser bars and paired pin heads.
    for k in range(17):
        yy=-1.63+k*.204
        for z in (.23,1.21):
            v4.box('track_shoe_'+str(sx)+'_'+str(k)+'_'+str(z),(.70,.19,.105),(x,yy,z),bevel=.018,material=darksteel,body=base)
            v4.box('track_grouser_'+str(sx)+'_'+str(k)+'_'+str(z),(.70,.045,.045),(x,yy,z+(.040 if z>0.7 else -.040)),bevel=.012,material=charcoal,body=base)
            for dx in (-.255,.255):
                v4.cylinder('track_pin_'+str(sx)+'_'+str(k)+'_'+str(z)+'_'+str(dx),.027,.018,(x+dx,yy,z+(.055 if z>0.7 else -.055)),rot=(0,math.pi/2,0),material=steel,body=base)
    # Curved links wrap over the front idler and rear drive end.
    for side,cy in [('front',-1.68),('rear',1.68)]:
        for k in range(9):
            a=-math.pi/2+k*math.pi/8
            sign=-1 if side=='front' else 1
            yy=cy+sign*.52*math.cos(a)
            zz=.70+.52*math.sin(a)
            rx=(a-math.pi/2) if side=='rear' else (math.pi/2-a)
            v4.box('track_wrap_shoe_'+str(sx)+'_'+side+'_'+str(k),(.70,.19,.105),(x,yy,zz),rot=(rx,0,0),bevel=.018,material=darksteel,body=base)
            v4.box('track_wrap_grouser_'+str(sx)+'_'+side+'_'+str(k),(.70,.045,.045),(x,yy,zz),rot=(rx,0,0),bevel=.012,material=charcoal,body=base)
    # Continuous rubber carcass ties the individual metal shoes into a real loop.
    belt_path=[]
    for k in range(17):
        a=-math.pi/2+k*math.pi/16
        belt_path.append((x,-1.68-.52*math.cos(a),.70+.52*math.sin(a)))
    for k in range(1,33):
        belt_path.append((x,-1.68+3.36*k/32,1.22))
    for k in range(1,33):
        a=math.pi/2-k*math.pi/32
        belt_path.append((x,1.68+.52*math.cos(a),.70+.52*math.sin(a)))
    for k in range(1,33):
        belt_path.append((x,1.68-3.36*k/32,.18))
    v4.tube('track_inner_carcass_'+str(sx),belt_path,.075,material=black,body=base,cyclic=True)
    # Seven lower rollers and three return rollers sit within the open crawler frame.
    for k in range(7):
        yy=-1.35+k*.45
        v4.cylinder('lower_roller_'+str(sx)+'_'+str(k),.20,.54,(x,yy,.62),rot=(0,math.pi/2,0),material=charcoal,body=base)
        v4.cylinder('roller_cap_'+str(sx)+'_'+str(k),.09,.012,(x+sx*.277,yy,.62),rot=(0,math.pi/2,0),material=steel,body=base)
    for k,yy in enumerate((-.88,0,.88)):
        v4.cylinder('return_roller_'+str(sx)+'_'+str(k),.085,.48,(x,yy,1.035),rot=(0,math.pi/2,0),material=charcoal,body=base)
        v4.cylinder('return_roller_cap_'+str(sx)+'_'+str(k),.042,.014,(x+sx*.23,yy,1.035),rot=(0,math.pi/2,0),material=steel,body=base)
        v4.rod('return_roller_hanger_'+str(sx)+'_'+str(k),(x,yy,.78),(x,yy,.98),.034,material=darksteel,body=base)
    v4.cylinder('drive_hub_'+str(sx),.25,.32,(x+sx*.10,1.68,.70),rot=(0,math.pi/2,0),material=charcoal,body=b)
    v4.cylinder('drive_sprocket_core_'+str(sx),.38,.20,(x+sx*.10,1.68,.70),rot=(0,math.pi/2,0),material=darksteel,body=b)
    v4.cylinder('drive_cap_'+str(sx),.15,.022,(x+sx*.27,1.68,.70),rot=(0,math.pi/2,0),material=steel,body=b)
    for k in range(14):
        a=2*math.pi*k/14
        yy=1.68+.405*math.cos(a); zz=.70+.405*math.sin(a)
        v4.box('drive_sprocket_tooth_'+str(sx)+'_'+str(k),(.20,.10,.075),(x+sx*.10,yy,zz),rot=(a-math.pi/2,0,0),bevel=.012,material=steel,body=b)
    for k in range(8):
        a=2*math.pi*k/8
        v4.cylinder('drive_cap_bolt_'+str(sx)+'_'+str(k),.026,.02,(x+sx*.28,1.68+.11*math.cos(a),.70+.11*math.sin(a)),rot=(0,math.pi/2,0),material=darksteel,body=b)
    v4.joint(('left' if sx<0 else 'right')+'_track_drive','continuous',base,b,(x,1.68,.70),(1,0,0))

# Upper structure at rear half with engine bay, counterweight, rotary deck, and glazed cab.
v4.box('slew_deck',(2.25,2.75,.25),(0,.43,1.49),bevel=.07,material=charcoal,body=upper)
v4.box('engine_service_cover',(1.62,1.60,.90),(0,1.22,2.05),bevel=.08,material=orange,body=upper)
v4.box('engine_cover_top',(1.48,1.34,.12),(0,1.19,2.55),bevel=.035,material=orange,body=upper)
# Tail counterweight with cast rounded shoulders and lower bumper.
v4.box('counterweight_core',(1.98,.73,.92),(0,2.15,1.94),bevel=.10,material=orange,body=upper)
v4.box('counterweight_lower_lip',(2.06,.56,.18),(0,2.16,1.52),bevel=.04,material=charcoal,body=upper)
v4.box('counterweight_badge',(0.70,.035,.19),(0,1.774,2.08),bevel=.025,material=white,body=upper)
# Engine cooling grilles, louvers and service fasteners.
for sx in (-1,1):
    x=sx*.818
    v4.box('engine_vent_gasket_'+str(sx),(.025,.92,.54),(x,1.22,2.04),bevel=.025,material=charcoal,body=upper)
    for k in range(8):
        z=1.81+k*.066
        v4.box('engine_vent_slats_'+str(sx)+'_'+str(k),(.035,.80,.027),(x+sx*.018,1.22,z),bevel=.009,material=darksteel,body=upper)
    for yy in (.79,1.65):
        for z in (1.79,2.29):
            v4.cylinder('engine_vent_fastener_'+str(sx)+'_'+str(yy)+'_'+str(z),.018,.015,(sx*.84,yy,z),rot=(0,math.pi/2,0),material=steel,body=upper)
# Black top-deck cooling louvers sit flush in the engine lid.
for k in range(7):
    xx=-.48+k*.16
    v4.box('engine_top_louver_'+str(k),(.055,.73,.025),(xx,.98,2.611),bevel=.008,material=darksteel,body=upper)
    v4.box('engine_top_louver_shadow_'+str(k),(.025,.70,.012),(xx,.98,2.592),bevel=.004,material=charcoal,body=upper)
for sx in (-1,1):
    # rear tail lamps mounted flush on counterweight back corners
    v4.box('tail_lamp_housing_'+str(sx),(.20,.045,.24),(sx*.78,2.524,1.90),bevel=.045,material=darksteel,body=upper)
    v4.box('tail_lens_'+str(sx),(.13,.014,.15),(sx*.78,2.552,1.91),bevel=.035,material=red,body=upper)
# Cab lower tub, A/B pillars, glazing and roof; front faces toward -Y.
v4.box('cab_floor',(1.44,1.30,.16),(CAB_X,-.47,1.90),bevel=.07,material=charcoal,body=upper)
# Twin cab isolator pedestals bridge the cab floor down to the slew deck.
for sx in (-1,1):
    v4.box('cab_mount_pedestal_'+str(sx),(.18,.42,.25),(CAB_X+sx*.48,-.42,1.70),bevel=.035,material=darksteel,body=upper)
v4.box('cab_rear_panel',(1.38,.10,1.16),(CAB_X,.18,2.51),bevel=.03,material=orange,body=upper)
v4.box('cab_roof',(1.62,1.47,.17),(CAB_X,-.43,3.13),bevel=.045,material=orange,body=upper)
# Safety glazing panels touch their pillars and floor/roof edges.
v4.box('front_windshield',(1.24,.035,.92),(CAB_X,-1.016,2.59),bevel=.025,material=glass,body=upper)
v4.box('rear_glass',(1.18,.03,.72),(CAB_X,.125,2.55),bevel=.02,material=glass,body=upper)
for sx in (-1,1):
    x=CAB_X+sx*.70
    v4.box('cab_side_glass_'+str(sx),(.03,.93,.83),(x,-.435,2.64),bevel=.025,material=glass,body=upper)
    v4.box('cab_front_pillar_'+str(sx),(.075,.10,1.10),(CAB_X+sx*.66,-.99,2.59),bevel=.032,material=orange,body=upper)
    v4.box('cab_rear_pillar_'+str(sx),(.09,.11,1.08),(CAB_X+sx*.66,.09,2.59),bevel=.035,material=orange,body=upper)
    # exterior mirror on short steel arm
    v4.rod('mirror_arm_'+str(sx),(CAB_X+sx*.72,-.83,2.76),(CAB_X+sx*.87,-.88,2.83),.018,material=steel,body=upper)
    v4.box('mirror_'+str(sx),(.16,.08,.13),(CAB_X+sx*.74,-.88,2.85),bevel=.035,material=charcoal,body=upper)
    # Door frame rails and hardware are fixed to the right-side cab shell.
    if sx > 0:
        side_x=CAB_X+.725
        for yy in (-.91,.04):
            v4.rod('door_frame_rail_y_'+str(yy),(side_x,yy,2.19),(side_x,yy,3.08),.024,material=charcoal,body=upper)
        for zz in (2.19,3.08):
            v4.rod('door_frame_rail_z_'+str(zz),(side_x,-.91,zz),(side_x,.04,zz),.024,material=charcoal,body=upper)
        for yy in (-.79,-.08):
            for zz in (2.38,2.79):
                v4.cylinder('door_hinge_'+str(yy)+'_'+str(zz),.035,.08,(side_x,yy,zz),rot=(math.pi/2,0,0),material=steel,body=upper)
        v4.rod('door_handle_stand_a',(side_x,-.29,2.205),(side_x+.055,-.29,2.205),.018,material=steel,body=upper)
        v4.rod('door_handle_stand_b',(side_x,-.13,2.205),(side_x+.055,-.13,2.205),.018,material=steel,body=upper)
        v4.rod('door_handle_grip',(side_x+.048,-.29,2.205),(side_x+.048,-.13,2.205),.022,material=charcoal,body=upper)
        v4.tube('cab_entry_grab_rail',[(side_x,-.81,2.20),(side_x+.08,-.81,2.25),(side_x+.08,-.81,2.82),(side_x,-.81,2.87)],.022,material=steel,body=upper)
# Wiper blades and washer nozzles touch the windshield face.
for sx in (-1,1):
    v4.rod('windshield_wiper_'+str(sx),(CAB_X+sx*.06,-1.040,2.28),(CAB_X+sx*.48,-1.040,2.35),.012,material=darksteel,body=upper)
    v4.cylinder('washer_nozzle_'+str(sx),.018,.012,(CAB_X+sx*.40,-1.039,2.24),rot=(math.pi/2,0,0),material=steel,body=upper)
# Interior controls visible through windshield.
v4.box('operator_seat_base',(.36,.35,.18),(CAB_X,-.03,2.12),bevel=.06,material=charcoal,body=upper)
v4.box('operator_seat_cushion',(.48,.43,.16),(CAB_X,-.03,2.27),bevel=.075,material=seatmat,body=upper)
v4.box('operator_seat_back',(.46,.13,.56),(CAB_X,.13,2.56),rot=(math.radians(-8),0,0),bevel=.08,material=seatmat,body=upper)
for sx in (-1,1):
    v4.rod('joystick_'+str(sx),(CAB_X+sx*.30,-.53,1.96),(CAB_X+sx*.30,-.53,2.38),.018,material=darksteel,body=upper)
    v4.sphere('joystick_grip_'+str(sx),.048,(CAB_X+sx*.30,-.53,2.36),material=charcoal,body=upper)
v4.box('instrument_console',(.30,.34,.13),(CAB_X+.54,-.64,2.45),rot=(math.radians(-18),0,0),bevel=.045,material=charcoal,body=upper)
v4.box('console_mount',(.12,.12,.47),(CAB_X+.54,-.64,2.20),bevel=.025,material=darksteel,body=upper)
# Roof work lamps, wiper and grab rails.
for sx in (-1,1):
    v4.box('roof_worklamp_housing_'+str(sx),(.23,.12,.12),(CAB_X+sx*.57,-1.13,3.08),bevel=.03,material=charcoal,body=upper)
    v4.box('roof_worklamp_lens_'+str(sx),(.17,.025,.07),(CAB_X+sx*.57,-1.194,3.08),bevel=.02,material=white,body=upper)
# Upper body slew pivot and boom mounting pedestal.
v4.cylinder('slew_pivot_shaft',.30,.34,(0,.48,1.49),material=steel,body=upper)
v4.box('boom_pedestal',(1.16,.45,.82),(ARM_OFFSET,-.30,2.02),bevel=.15,material=orange,body=upper)
for sx in (-1,1):
    v4.cylinder('boom_mount_boss_'+str(sx),.25,.15,(ARM_OFFSET+sx*.53,-.20,2.28),rot=(0,math.pi/2,0),material=darksteel,body=upper)
v4.joint('upper_slew','revolute',base,upper,(0,.48,1.48),(0,0,1),limits=(-math.radians(90),math.radians(90)))

# Boom welded box/plate structure from heel to nose, axis in the YZ plane.
v4.extrude('boom_left_cheek',[(-.22,0),(.22,0),(.18,1.18),(.11,1.46),(-.11,1.46),(-.18,1.18)],.16,
           loc=(-.10,-.28,2.10),rot=(math.pi/2,0,0),bevel=.045,material=yellow,body=boom)
# Alternative box section and cross plates ensure a thick closed fabrication.
v4.rod('boom_main_box',(0,-.34,2.24),(0,-1.52,3.53),.20,square=True,bevel=.045,material=yellow,body=boom)
v4.rod('boom_cross_root',(-.40,-.30,2.34),(.40,-.30,2.34),.105,material=yellow,body=boom)
v4.rod('boom_cross_head',(-.29,-1.48,3.48),(.29,-1.48,3.48),.09,material=yellow,body=boom)
for sx in (-1,1):
    v4.cylinder('boom_heel_pin_'+str(sx),.14,.18,(sx*.43,-.20,2.28),rot=(0,math.pi/2,0),material=steel,body=boom)
    v4.cylinder('boom_tip_pin_'+str(sx),.12,.14,(sx*.30,-1.58,3.64),rot=(0,math.pi/2,0),material=darksteel,body=boom)
v4.joint('boom_foot','revolute',upper,boom,(0,-.20,2.28),(1,0,0),limits=(math.radians(-4),math.radians(14)))
# Paired lift cylinders use a hinged barrel, sliding polished rod, and boom-end pin.
barrel=v4.body('lift_barrel_pair')
rod=v4.body('lift_rod_pair')
for sx in (-1,1):
    # The twin actuators share transverse pins and a matched piston stroke.
    p0=(sx*.52,.12,1.72)
    p1=(sx*.52,-.82,2.87)
    p2=(sx*.52,-1.18,3.25)
    v4.rod('boom_cylinder_barrel_'+str(sx),p0,p1,.105,material=darksteel,body=barrel)
    v4.cylinder('boom_cylinder_gland_'+str(sx),.08,.12,p1,rot=(math.radians(40),0,0),material=steel,body=barrel)
    v4.rod('boom_cylinder_rod_'+str(sx),p1,p2,.052,material=steel,body=rod)
    v4.cylinder('boom_cylinder_eye_'+str(sx),.09,.15,p2,rot=(0,math.pi/2,0),material=darksteel,body=rod)
    v4.rod('boom_hose_'+str(sx),(sx*.16,-.38,2.48),(sx*.16,-1.40,3.47),.018,material=black,body=boom)
# One common pair of transverse pivots and a common matched piston stroke.
slide_axis=Vector((0,-.94,1.15)).normalized()
v4.rod('lift_barrel_base_pin',(-.70,.12,1.72),(.70,.12,1.72),.055,material=steel,body=barrel)
v4.joint('lift_barrel_pin','revolute',upper,barrel,(0,.12,1.72),(1,0,0),limits=(-math.radians(8),math.radians(5)))
v4.joint('lift_rod_slide','prismatic',barrel,rod,(0,-.82,2.87),slide_axis,limits=(-.30,.48))
v4.rod('lift_rod_cross_eye',(-.70,-1.18,3.25),(.70,-1.18,3.25),.045,material=darksteel,body=rod)
# The rod eye is pinned through both lugs on the boom at the shared transverse line.
v4.joint('lift_rod_boom_pin','revolute',rod,boom,(0,-1.18,3.25),(1,0,0),limits=(-math.pi,math.pi))

# Stick / dipper with tapered cheeks, hard pin bosses, hydraulic lines and cylinder.
v4.rod('stick_box_section',(0,-1.58,3.64),(0,-3.17,3.31),.145,square=True,bevel=.036,material=orange,body=stick)
v4.rod('stick_reinforcement',(-.12,-1.70,3.59),(-.12,-3.12,3.30),.053,square=True,bevel=.018,material=yellow,body=stick)
for sx in (-1,1):
    v4.cylinder('stick_heel_boss_'+str(sx),.16,.16,(sx*.18,-1.58,3.64),rot=(0,math.pi/2,0),material=darksteel,body=stick)
    v4.cylinder('stick_tip_boss_'+str(sx),.13,.14,(sx*.17,-3.17,3.31),rot=(0,math.pi/2,0),material=steel,body=stick)
v4.joint('stick_heel','revolute',boom,stick,(0,-1.58,3.64),(1,0,0),limits=(math.radians(-12),math.radians(12)))

# Forestry rotator: upper hitch, bearing stack, hydraulic swivel and reinforced grapple head.
v4.cylinder('rotator_neck',.17,.28,(0,-3.25,3.31),material=charcoal,body=head)
v4.cylinder('rotator_bearing_upper',.27,.18,(0,-3.27,3.08),material=steel,body=head)
v4.torus('rotator_bearing_race',.22,.035,(0,-3.27,3.08),material=darksteel,body=head)
v4.cylinder('rotator_shell',.23,.43,(0,-3.27,2.80),material=orange,body=head)
v4.cylinder('rotator_lower_flange',.31,.12,(0,-3.27,2.56),material=darksteel,body=head)
v4.torus('rotator_lower_seal',.26,.026,(0,-3.27,2.49),material=black,body=head)
# Frame crossbeam and cheek plates; tine pivots at x +/- 0.39.
v4.box('grapple_crossbeam',(1.06,.30,.20),(0,-3.44,2.39),bevel=.09,material=orange,body=head)
for sx in (-1,1):
    v4.rod('jaw_mount_strut_'+str(sx),(sx*.47,-3.31,2.47),(sx*.98,-3.31,2.91),.055,material=yellow,body=head)
    v4.cylinder('head_side_pivot_'+str(sx),.07,.18,(sx*.98,-3.40,2.91),rot=(math.pi/2,0,0),material=darksteel,body=head)
# Teeth/jaws: curled steel forgings in the XZ plane, with separate narrow wear tips integral to jaw body.
for sx,b in [(-1,jawL),(1,jawR)]:
    pivot=(sx*.98,-3.49,2.91)
    # Each jaw is made as joined thick forged links with a hooked inward tip.
    # Wide forged cheeks follow the tine curvature. Their inner edge tracks the
    # existing centerline while the outer edge adds real section width.
    cheek=[(sx*.98,2.91),(sx*1.20,2.66),(sx*1.19,2.36),(sx*1.13,2.12),
           (sx*.99,1.99),(sx*.82,1.85),(sx*.57,1.71),(sx*.48,1.78),
           (sx*.67,1.98),(sx*.84,2.18),(sx*.94,2.46),(sx*.99,2.68)]
    v4.extrude('forged_tine_cheek_'+str(sx),cheek,.12,loc=(0,-3.43,0),rot=(math.pi/2,0,0),
               bevel=.022,material=charcoal,body=b)
    # The forged tine sweeps into a raised, inward-facing toe that cups the lower logs.
    pts=[(sx*.98,-3.49,2.91),(sx*1.10,-3.49,2.58),(sx*1.04,-3.49,2.28),
         (sx*.91,-3.49,2.05),(sx*.70,-3.49,1.93),(sx*.58,-3.49,1.81)]
    # Welded wear rib and replaceable nose cap reinforce the inward hook.
    v4.rod('tine_wear_rib_'+str(sx),pts[-2],pts[-1],.035,material=steel,body=b)
    v4.cylinder('tine_nose_cap_'+str(sx),.067,.13,pts[-1],rot=(0,math.pi/2,0),material=steel,body=b)
    for k in range(len(pts)-1):
        v4.rod('jaw_forging_'+str(sx)+'_'+str(k),pts[k],pts[k+1],.075 if k<2 else .060,material=darksteel,body=b)
    v4.rod('replaceable_jaw_tip_'+str(sx),pts[-2],pts[-1],.052,material=steel,body=b)
    # broad side reinforcement straps follow the outer jaw curve
    for k in range(3):
        p0=pts[k]; p1=pts[k+1]
        v4.rod('jaw_gusset_'+str(sx)+'_'+str(k),(p0[0]+sx*.05,p0[1],p0[2]),(p1[0]+sx*.05,p1[1],p1[2]),.025,material=steel,body=b)
    v4.cylinder('jaw_outer_pin_'+str(sx),.085,.055,(sx*.99,-3.49,2.91),rot=(0,math.pi/2,0),material=steel,body=b)
    v4.joint(('left' if sx<0 else 'right')+'_jaw','revolute',head,b,pivot,(0,1,0),limits=(-math.radians(9),0) if sx<0 else (0,math.radians(9)))
# Spin axis follows the stick length approximately, through the rotary bearing centre.
v4.joint('rotator_spin','continuous',stick,head,(0,-3.27,3.28),(0,0,1))

# Four grounded stems, parallel to machine length, arranged as a compact grappled bundle.
# Their bark texture is broken by low-relief longitudinal bark ridges and cut end discs.
for i,(x,z) in enumerate([(-.16,1.81),(.16,1.81),(-.16,2.13),(.16,2.13)]):
    radius=.16
    v4.cylinder('log_stem_'+str(i),radius,3.20,(x,-3.75,z),rot=(math.pi/2,0,0),segments=48,material=wood,body=logs)
    for endy in (-5.35,-2.15):
        v4.cylinder('log_cut_end_'+str(i)+'_'+str(endy),radius*.94,.012,(x,endy,z),rot=(math.pi/2,0,0),segments=48,material=endwood,body=logs)
    # Keep all four stems in contact as a tightly packed grapple load.
# Choker bands physically bind the grappled stacked stems at two stations.
for yy in (-4.65,-2.85):
    v4.tube('bundle_choker_'+str(yy),[(-.34,yy,1.82),(-.34,yy,2.12),(-.25,yy,2.35),(.25,yy,2.35),(.34,yy,2.12),(.34,yy,1.82),(.25,yy,1.60),(-.25,yy,1.60)],.018,material=steel,body=logs,cyclic=True)

# Subtle graphic details are omitted on exposed boom faces to preserve clean, continuous paint.

# The carried log bundle follows the grapple rotator and remains the jaw-closing target.
v4.joint('log_bundle_mount','fixed',head,logs,(0,0,0),(0,0,1))

# Shift the boom and its attached working group forward to clear the cab. The
# lift-cylinder branches move with it so their upper-deck anchors stay aligned.
def shift_subtree(root_name, dx):
    root=bpy.data.objects['J_'+root_name]
    stack=[root]
    objects=[]
    seen=set()
    while stack:
        obj=stack.pop()
        if obj.name in seen:
            continue
        seen.add(obj.name)
        objects.append(obj)
        stack.extend(list(obj.children))
    translate=Matrix.Translation(Vector((dx,0,0)))
    world={obj.name:obj.matrix_world.copy() for obj in objects}
    for obj in objects:
        obj.matrix_world=translate @ world[obj.name]
    for obj in objects:
        if obj.get('v4_kind')=='joint':
            obj['v4_rest']=[v for row in obj.matrix_basis for v in row]

shift_subtree('boom_foot',ARM_OFFSET)
shift_subtree('lift_barrel_pin',ARM_OFFSET)
v4.save(os.path.join(os.getcwd(),'asset.blend'))
print('saved asset.blend')
