"""Detailed tracked forestry log loader. Run with Blender: blender -b --python build.py"""
import math
import os
import sys

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

v4.reset()

# ---- finishes ----------------------------------------------------------------------
orange = v4.painted("forestry_orange", (0.96, 0.31, 0.035), roughness=0.27, coat=0.55)
yellow = v4.painted("safety_yellow", (0.98, 0.69, 0.08), roughness=0.30, coat=0.42)
charcoal = v4.painted("chassis_charcoal", (0.095, 0.11, 0.12), roughness=0.42, coat=0.25)
black = v4.rubber("hose_rubber", (0.022, 0.027, 0.03), roughness=0.82)
tread = v4.metal("track_shoe_steel", (0.27, 0.29, 0.30), roughness=0.44, brushed=False)
tread_edge = v4.metal("grouser_wear_steel", (0.43, 0.45, 0.45), roughness=0.36, brushed=False)
steel = v4.metal("pin_steel", (0.70, 0.72, 0.73), roughness=0.27, brushed=True)
dark_steel = v4.metal("cast_steel", (0.20, 0.22, 0.23), roughness=0.46, brushed=False)
rod_chrome = v4.metal("hydraulic_rod_chrome", (0.79, 0.82, 0.84), roughness=0.20, brushed=True)
glass = v4.glass("cab_safety_glass", (0.20, 0.34, 0.43), roughness=0.055)
gasket = v4.rubber("window_gasket", (0.018, 0.025, 0.031))
seat_mat = v4.fabric("seat_fabric", (0.12, 0.14, 0.15), weave_scale=120)
interior = v4.mat("cab_interior", (0.09, 0.10, 0.105), roughness=0.72)
light_lens = v4.mat("work_light_lens", (0.72, 0.81, 0.84), metallic=0.12, roughness=0.18)
red_lens = v4.mat("tail_lamp_red", (0.72, 0.055, 0.025), metallic=0.0, roughness=0.22)
label_white = v4.mat("safety_label_cream", (0.92, 0.86, 0.67), roughness=0.68)
bark = v4.wood("bark_brown", light=(0.39, 0.25, 0.14), dark=(0.15, 0.085, 0.045), grain_scale=4.2, roughness=0.82, coat=0.04)
endgrain = v4.wood("log_endgrain", light=(0.63, 0.43, 0.27), dark=(0.31, 0.19, 0.10), grain_scale=8.0, roughness=0.7, coat=0.08)

# ---- mesh helpers: profiles extruded in a real plane --------------------------------
def prism_xz(name, outline, depth, yc, material, body, bevel=0.005):
    # extrude's local XY is mapped to world XZ; its depth runs from +Y toward -Y.
    return v4.extrude(name, outline, depth, loc=(0, yc + depth / 2, 0),
                      rot=(math.pi / 2, 0, 0), bevel=bevel, material=material, body=body)


def prism_yz(name, outline, x0, depth, material, body, bevel=0.006):
    # local x,y,z map to world y,z,x: a forged jaw profile extruded along the log axis.
    return v4.extrude(name, outline, depth, loc=(x0, 0, 0),
                      rot=(math.pi / 2, 0, math.pi / 2), bevel=bevel, material=material, body=body)


def quad_slab(name, corners, thickness, material, body):
    """A thin closed panel through four coplanar world-space corners."""
    p = [Vector(c) for c in corners]
    n = (p[1] - p[0]).cross(p[2] - p[0]).normalized()
    verts = [tuple(q) for q in p] + [tuple(q - n * thickness) for q in p]
    faces = [(0, 1, 2, 3), (7, 6, 5, 4), (0, 4, 5, 1), (1, 5, 6, 2),
             (2, 6, 7, 3), (3, 7, 4, 0)]
    mesh = bpy.data.meshes.new(name + "_mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.update()
    obj = bpy.data.objects.new(name, mesh)
    bpy.context.collection.objects.link(obj)
    v4.assign(obj, material)
    v4.part(obj, body)
    return obj


def axis_euler(axis):
    return Vector((0, 0, 1)).rotation_difference(Vector(axis).normalized()).to_euler()


def pin_cap(name, center, radius, depth, axis, material, body):
    return v4.cylinder(name, radius, depth, center, rot=axis_euler(axis), segments=32,
                       bevel=min(depth * 0.15, 0.003), material=material, body=body)


def box_between(name, p0, p1, radius, material, body, square=False):
    return v4.rod(name, p0, p1, radius, material=material, body=body, square=square)


def add_joint_pin(name, point, axis, length, radius, body, cap_material=steel):
    d = Vector(axis).normalized() * length / 2
    v4.rod(name + "_shaft", Vector(point) - d, Vector(point) + d, radius,
           material=steel, body=body)
    # End collars make the pin visibly retain the lug stack.
    for s in (-1, 1):
        c = Vector(point) + Vector(axis).normalized() * (s * (length / 2 - 0.008))
        pin_cap(name + "_collar_" + str(s), c, radius * 1.42, 0.022, axis, dark_steel, body)
        c2 = Vector(point) + Vector(axis).normalized() * (s * (length / 2 + 0.007))
        pin_cap(name + "_cap_" + str(s), c2, radius * 0.86, 0.014, axis, cap_material, body)

# ---- rigid body tree ----------------------------------------------------------------
base = v4.body("undercarriage")
left_track = v4.body("left_track")
right_track = v4.body("right_track")
house = v4.body("upper_house")
boom = v4.body("boom")
stick = v4.body("stick")
head = v4.body("rotator_grapple_head")
load = v4.body("log_bundle")
left_sleeper = v4.body("left_log_sleeper")
right_sleeper = v4.body("right_log_sleeper")
left_tine = v4.body("left_tine")
right_tine = v4.body("right_tine")

# ---- lower carriage and swing ring: fixed to the root --------------------------------
v4.box("lower_torsion_box", (3.35, 1.62, 0.60), (0, 0, 0.94), bevel=0.055,
       material=charcoal, body=base)
v4.box("belly_guard", (2.75, 1.42, 0.085), (-0.10, 0, 0.60), bevel=0.025,
       material=dark_steel, body=base)
# The track frames are part of the fixed undercarriage and visibly reach each axle station.
for side, sy in (("left", -1), ("right", 1)):
    y = sy * 0.91
    v4.box(f"{side}_track_frame", (3.78, 0.27, 0.37), (0, y, 0.56), bevel=0.045,
           material=charcoal, body=base)
    v4.box(f"{side}_frame_top_rail", (3.56, 0.20, 0.085), (0, y, 0.79), bevel=0.025,
           material=dark_steel, body=base)
    # Axle brackets reach from each frame toward the track's central drive spindle.
    for x in (-1.53, 1.53):
        v4.box(f"{side}_axle_cheek_{x}", (0.42, 0.14, 0.29), (x, sy * 1.035, 0.55), bevel=0.035,
               material=dark_steel, body=base)
        pin_cap(f"{side}_frame_boss_{x}", (x, sy * 1.11, 0.55), 0.16, 0.09, (0, 1, 0), steel, base)
# Slewing-ring support and visible bearing race.
v4.cylinder("swing_bearing_base", 0.72, 0.11, (0, 0, 1.28), material=dark_steel, body=base, bevel=0.012)
v4.torus("swing_bearing_race", 0.67, 0.045, (0, 0, 1.35), material=steel, body=base)
v4.torus("slew_gear_lip", 0.76, 0.035, (0, 0, 1.34), material=yellow, body=base)
for i in range(32):
    a = 2 * math.pi * i / 32
    x, y = 0.70 * math.cos(a), 0.70 * math.sin(a)
    v4.cylinder(f"slew_bolt_{i:02d}", 0.026, 0.022, (x, y, 1.355), segments=16,
                material=steel, body=base)
# Grounded crib beams remain fixed to the undercarriage while the grapple lifts the logs.
# Their top heights follow the slight taper of the lower stem so each just supports the load.
for label, x, height, cap_top, body in (
    ("left", 4.53, 0.166, 0.195, left_sleeper),
    ("right", 6.00, 0.172, 0.201, right_sleeper),
):
    v4.box(f"{label}_log_crib_sleeper", (0.24, 1.22, height), (x, 0, height / 2), bevel=0.018,
           material=dark_steel, body=body)
    v4.box(f"{label}_sleeper_wood_cap", (0.21, 1.18, 0.035), (x, 0, cap_top - 0.0175), bevel=0.012,
           material=bark, body=body)
# The carried payload is only the three bark-covered stems.
upper_log_radius = 0.207
upper_log_z = 0.397 + math.sqrt((0.212 + upper_log_radius) ** 2 - upper_log_radius ** 2)
log_specs = [(0.0, 0.397, 0.212, "bottom"), (-upper_log_radius, upper_log_z, upper_log_radius, "upper_left"),
             (upper_log_radius, upper_log_z, upper_log_radius, "upper_right")]
for y, z, radius, label in log_specs:
    start_x, length = 4.12, 2.60
    profile = [(0, 0), (radius * .70, 0), (radius * .89, .05), (radius, .24),
               (radius * .95, .70), (radius * 1.025, 1.10), (radius * .96, 1.52),
               (radius * .91, 2.04), (radius * .78, length - .06), (radius * .62, length), (0, length)]
    log = v4.lathe(f"log_{label}", profile, loc=(start_x, y, z), rot=(0, math.pi / 2, 0),
                   material=bark, body=load)
    # Light end-grain disks are flush with the turned ends.
    v4.cylinder(f"log_{label}_end_a", radius * .62, 0.003, (start_x + .001, y, z),
                rot=(0, math.pi / 2, 0), material=endgrain, body=load)
    v4.cylinder(f"log_{label}_end_b", radius * .62, 0.003, (start_x + length - .001, y, z),
                rot=(0, math.pi / 2, 0), material=endgrain, body=load)
    # A few subtle branch scars, placed on the near side of the bark.
    for k, (xx, dz) in enumerate(((4.72, .12), (5.88, -.12))):
        dy = math.sqrt(max(0.0, (radius + .018) ** 2 - dz ** 2))
        v4.sphere(f"log_{label}_branch_scar_{k}", 0.035, (xx, y - dy, z + dz),
                  segments=20, material=dark_steel, body=load)

# ---- endless shoe-track modules -------------------------------------------------------
TRACK_CZ = 0.54
TRACK_CX = 0.0
TRACK_R = 0.45
TRACK_STRAIGHT = 3.10
TRACK_Y = 1.28

def track_path_sample(distance):
    """Position and tangent around a horizontal stadium in the XZ plane."""
    r, half = TRACK_R, TRACK_STRAIGHT / 2
    lengths = (TRACK_STRAIGHT, math.pi * r, TRACK_STRAIGHT, math.pi * r)
    perimeter = sum(lengths)
    s = distance % perimeter
    # Top run: left to right.
    if s < lengths[0]:
        t = s / lengths[0]
        return (-half + 2 * half * t, TRACK_CZ + r, 1.0, 0.0)
    s -= lengths[0]
    # Right end: top to bottom.
    if s < lengths[1]:
        a = math.pi / 2 - s / r
        return (half + r * math.cos(a), TRACK_CZ + r * math.sin(a), math.sin(a), -math.cos(a))
    s -= lengths[1]
    # Bottom run: right to left.
    if s < lengths[2]:
        t = s / lengths[2]
        return (half - 2 * half * t, TRACK_CZ - r, -1.0, 0.0)
    s -= lengths[2]
    # Left end: bottom to top.
    a = -math.pi / 2 - s / r
    return (-half + r * math.cos(a), TRACK_CZ + r * math.sin(a), math.sin(a), -math.cos(a))


def make_track(side, sy, body):
    yc = sy * TRACK_Y
    perimeter = 2 * TRACK_STRAIGHT + 2 * math.pi * TRACK_R
    shoe_n = 34
    for i in range(shoe_n):
        x, z, dx, dz = track_path_sample(perimeter * (i + 0.5) / shoe_n)
        angle = math.atan2(-dz, dx)
        v4.box(f"{side}_shoe_{i:02d}", (0.247, 0.70, 0.105), (x, yc, z),
               rot=(0, angle, 0), bevel=0.010, material=tread, body=body)
        # A raised transverse grouser on each shoe gives the tread a crisp industrial edge.
        gx, gz = x + math.sin(angle) * 0.073, z + math.cos(angle) * 0.073
        v4.box(f"{side}_grouser_{i:02d}", (0.068, 0.62, 0.048), (gx, yc, gz),
               rot=(0, angle, 0), bevel=0.009, material=tread_edge, body=body)
        if i % 3 == 0:
            outer_y = yc + sy * 0.354
            for j, ofs in enumerate((-0.068, 0.068)):
                bx = x + math.cos(angle) * ofs
                bz = z - math.sin(angle) * ofs
                pin_cap(f"{side}_shoe_pin_{i:02d}_{j}", (bx, outer_y + sy * .003, bz), 0.020, 0.020,
                        (0, 1, 0), steel, body)
    # Full-width chain pins bridge each shoe seam and tie the track loop into the internal rollers.
    for i in range(shoe_n):
        x, z, dx, dz = track_path_sample(perimeter * (i + 1) / shoe_n)
        v4.cylinder(f"{side}_chain_hinge_{i:02d}", .034, .68, (x, yc, z),
                    rot=(math.pi / 2, 0, 0), material=dark_steel, body=body, bevel=.006)
    # Drive sprocket, front idler, and six support rollers; their dark hubs sit inside the shoes.
    for label, x, radius in (("idler", 1.55, .405),):
        v4.cylinder(f"{side}_{label}_wheel", radius, .48, (x, yc, TRACK_CZ),
                    rot=(math.pi / 2, 0, 0), material=dark_steel, body=body, bevel=.018)
        v4.cylinder(f"{side}_{label}_hub", radius * .48, .505, (x, yc, TRACK_CZ),
                    rot=(math.pi / 2, 0, 0), material=steel, body=body, bevel=.012)
        v4.cylinder(f"{side}_{label}_cap", radius * .22, .525, (x, yc, TRACK_CZ),
                    rot=(math.pi / 2, 0, 0), material=charcoal, body=body, bevel=.009)
        for k in range(12):
            a = 2 * math.pi * k / 12
            pin_cap(f"{side}_{label}_bolt_{k:02d}",
                    (x + radius * .34 * math.cos(a), yc + sy * .258, TRACK_CZ + radius * .34 * math.sin(a)),
                    .020, .022, (0, 1, 0), steel, body)
    for i, x in enumerate((-0.85, -0.51, -0.17, 0.17, 0.51, 0.85)):
        radius = .225
        v4.cylinder(f"{side}_road_wheel_{i}", radius, .43, (x, yc, TRACK_CZ),
                    rot=(math.pi / 2, 0, 0), material=charcoal, body=body, bevel=.015)
        v4.cylinder(f"{side}_road_wheel_face_{i}", radius * .60, .447, (x, yc, TRACK_CZ),
                    rot=(math.pi / 2, 0, 0), material=dark_steel, body=body, bevel=.012)
        v4.cylinder(f"{side}_road_wheel_cap_{i}", radius * .18, .464, (x, yc, TRACK_CZ),
                    rot=(math.pi / 2, 0, 0), material=steel, body=body, bevel=.008)
        v4.rod(f"{side}_road_axle_{i}", (x, sy * 1.025, TRACK_CZ),
               (x, sy * 1.065, TRACK_CZ), .065, material=dark_steel, body=base)
        for k in range(8):
            a = 2 * math.pi * k / 8
            pin_cap(f"{side}_road_bolt_{i}_{k}",
                    (x + radius * .39 * math.cos(a), yc + sy * .227,
                     TRACK_CZ + radius * .39 * math.sin(a)), .011, .014, (0, 1, 0), steel, body)

make_track("left", -1, base)
make_track("right", 1, base)


def make_drive_sprocket(side, sy, body):
    x, y, z = -1.55, sy * TRACK_Y, TRACK_CZ
    v4.cylinder(f"{side}_drive_sprocket", .34, .43, (x, y, z),
                rot=(math.pi / 2, 0, 0), material=dark_steel, body=body, bevel=.014)
    v4.cylinder(f"{side}_drive_hub", .205, .50, (x, y, z),
                rot=(math.pi / 2, 0, 0), material=steel, body=body, bevel=.012)
    v4.cylinder(f"{side}_drive_face", .145, .525, (x, y, z),
                rot=(math.pi / 2, 0, 0), material=charcoal, body=body, bevel=.010)
    for k in range(10):
        a = 2 * math.pi * k / 10
        pin_cap(f"{side}_drive_face_bolt_{k:02d}",
                (x + .116 * math.cos(a), y + sy * .260, z + .116 * math.sin(a)),
                .018, .025, (0, 1, 0), steel, body)
    for k in range(12):
        a = 2 * math.pi * k / 12
        bx = x + math.sin(a) * .355
        bz = z + math.cos(a) * .355
        v4.box(f"{side}_sprocket_tooth_{k:02d}", (.10, .37, .046), (bx, y, bz),
               rot=(0, a, 0), bevel=.010, material=steel, body=body)

make_drive_sprocket("left", -1, left_track)
make_drive_sprocket("right", 1, right_track)

# ---- rotating upper house: counterweight, cab, operator controls ------------------------
# Upper deck and swing-motor cover sit against the turntable race.
v4.box("upper_deck_plate", (3.00, 1.62, 0.16), (-0.30, 0, 1.47), bevel=0.045,
       material=charcoal, body=house)
v4.box("upper_floor_pan", (2.66, 1.38, 0.08), (-0.28, 0, 1.59), bevel=0.025,
       material=orange, body=house)
v4.cylinder("slew_motor_cover", .30, .26, (-.15, .27, 1.68), material=charcoal, body=house, bevel=.025)
v4.cylinder("slew_motor_cap", .20, .08, (-.15, .27, 1.85), material=steel, body=house, bevel=.012)
# Counterweight is a sloped, serviceable cast shell over the rear deck.
counterweight = prism_xz("counterweight_shell",
    [(-2.02, 1.56), (-0.55, 1.56), (-0.58, 2.20), (-0.88, 2.43),
     (-1.80, 2.47), (-2.08, 2.23)], 1.50, 0, orange, house, bevel=.075)
# Dark lower rub strip and side access panels are surface-mounted with a small paint seam.
for sy in (-1, 1):
    v4.box(f"counterweight_lower_trim_{sy}", (1.17, .035, .11), (-1.33, sy * .758, 1.68),
           bevel=.022, material=charcoal, body=house)
    v4.box(f"counterweight_access_panel_{sy}", (.69, .025, .39), (-1.34, sy * .742, 1.99),
           bevel=.025, material=yellow, body=house)
    # Panel screws lie around the corners.
    for xx in (-1.63, -1.05):
        for zz in (1.84, 2.14):
            pin_cap(f"counterweight_screw_{sy}_{xx}_{zz}", (xx, sy * .759, zz), .018, .012,
                    (0, 1, 0), steel, house)
# Raised generic forestry label on the camera-facing service panel.
v4.box("counterweight_model_mark", (.32, .014, .045), (-1.34, -.758, 1.99), bevel=.010,
       material=charcoal, body=house)
# Cab pedestal and lower shell.
CAB_Y = -0.88
v4.box("cab_floor", (1.58, 1.28, .14), (-.18, CAB_Y, 1.78), bevel=.035,
       material=charcoal, body=house)
v4.box("cab_lower_shell", (1.47, 1.22, .30), (-.20, CAB_Y, 1.98), bevel=.055,
       material=orange, body=house)
# Side glazing; black gasket rails and orange ROPS posts frame these real window openings.
side_outline = [(-.89, 2.12), (.47, 2.12), (.18, 3.07), (-.76, 3.07)]
for sy, side_name in ((-1, "near"), (1, "far")):
    y = CAB_Y + sy * .626
    pane = prism_xz(f"cab_{side_name}_side_glass", side_outline, .009, y, glass, house, bevel=0)
    # Perimeter and door divider follow the glass edge.
    outline3 = [(x, y - sy * .010, z) for x, z in side_outline]
    for k in range(4):
        a, b = outline3[k], outline3[(k + 1) % 4]
        v4.rod(f"cab_{side_name}_window_gasket_{k}", a, b, .024, material=gasket, body=house)
    v4.rod(f"cab_{side_name}_door_post", (-.10, y - sy * .014, 2.12),
           (-.06, y - sy * .014, 3.07), .028, material=orange, body=house, square=True)
    # Door pull and lower access step on the near side.
    if sy < 0:
        v4.box("cab_door_handle_mount", (.15, .018, .045), (-.46, CAB_Y - .62, 2.27), bevel=.012,
               material=charcoal, body=house)
        v4.rod("cab_door_pull", (-.43, CAB_Y - .641, 2.26), (-.34, CAB_Y - .641, 2.26), .012,
               material=steel, body=house)
        for j, z in enumerate((1.69, 1.48, 1.28)):
            v4.box(f"cab_entry_step_{j}", (.46, .36, .075), (-.56, CAB_Y - .64, z), bevel=.022,
                   material=charcoal, body=house)
# Pair of welded side stringers joins all three access steps to the cab floor.
for sx in (-.73, -.39):
    v4.rod(f"cab_step_stringer_{sx}", (sx, CAB_Y - .64, 1.24),
           (sx, CAB_Y - .64, 1.75), .032, material=yellow, body=house)
# Sloped front windshield joins the two side panes.
quad_slab("cab_front_windshield",
          [(0.47, CAB_Y - .57, 2.12), (0.47, CAB_Y + .57, 2.12),
           (0.17, CAB_Y + .54, 3.07), (0.17, CAB_Y - .54, 3.07)], .010, glass, house)
# Front and roof ROPS rails, roof, and wiper.
for sy in (-1, 1):
    y = CAB_Y + sy * .62
    v4.rod(f"cab_front_roof_pillar_{sy}", (.47, y, 2.10), (.17, y, 3.13), .043,
           material=orange, body=house, square=True)
    v4.rod(f"cab_rear_roof_pillar_{sy}", (-.90, y, 2.10), (-.77, y, 3.13), .043,
           material=orange, body=house, square=True)
    v4.rod(f"cab_roof_side_rail_{sy}", (-.77, y, 3.13), (.17, y, 3.13), .035,
           material=orange, body=house, square=True)
v4.box("cab_roof", (1.14, 1.42, .14), (-.29, CAB_Y, 3.16), bevel=.055,
       material=orange, body=house)
v4.box("cab_windshield_wiper", (.40, .024, .018), (.35, CAB_Y, 2.64), rot=(0, -.30, 0),
       bevel=.008, material=charcoal, body=house)
v4.rod("cab_wiper_arm", (.29, CAB_Y, 2.63), (.40, CAB_Y, 2.72), .008, material=steel, body=house)
# Interior silhouette: sprung operator seat, joysticks, pedals and a readable instrument pod.
v4.box("seat_base", (.43, .42, .14), (-.31, CAB_Y, 2.06), bevel=.035, material=charcoal, body=house)
v4.box("seat_cushion", (.48, .46, .14), (-.31, CAB_Y, 2.16), bevel=.060, material=seat_mat, body=house)
v4.box("seat_back", (.18, .46, .62), (-.54, CAB_Y, 2.46), rot=(0, -.12, 0), bevel=.065,
       material=seat_mat, body=house)
v4.box("seat_headrest", (.17, .30, .16), (-.66, CAB_Y, 2.81), bevel=.055, material=seat_mat, body=house)
v4.box("instrument_console", (.43, .84, .13), (.31, CAB_Y, 2.42), rot=(0, -.16, 0),
       bevel=.035, material=interior, body=house)
v4.box("instrument_display", (.22, .42, .025), (.36, CAB_Y, 2.50), rot=(0, -.16, 0),
       bevel=.014, material=light_lens, body=house)
for sy in (-1, 1):
    v4.rod(f"control_joystick_{sy}", (.16, CAB_Y + sy * .34, 2.18),
           (.18, CAB_Y + sy * .34, 2.39), .018, material=charcoal, body=house)
    v4.sphere(f"control_knob_{sy}", .035, (.18, CAB_Y + sy * .34, 2.39),
              segments=20, material=steel, body=house)
# Mirrors, roof work lamps, handrails, exhaust, and service louvers.
for sy in (-1, 1):
    v4.rod(f"cab_mirror_arm_{sy}", (.26, CAB_Y + sy * .62, 2.65),
           (.42, CAB_Y + sy * .91, 2.68), .017, material=charcoal, body=house)
    v4.box(f"cab_mirror_{sy}", (.19, .045, .14), (.43, CAB_Y + sy * .94, 2.69),
           bevel=.025, material=dark_steel, body=house)
    v4.box(f"cab_roof_worklamp_{sy}", (.18, .17, .13), (.11, CAB_Y + sy * .43, 3.27),
           bevel=.035, material=charcoal, body=house)
    v4.box(f"cab_roof_lens_{sy}", (.12, .015, .075), (.20, CAB_Y + sy * .43, 3.27),
           bevel=.020, material=light_lens, body=house)
    # Safety handrail on the machine deck beside the cab.
    rail_pts = [(-.76, sy * .82, 1.73), (-.76, sy * .95, 2.03),
                (-.05, sy * .95, 2.03), (.16, sy * .82, 1.73)]
    for ri in range(3):
        v4.rod(f"deck_handrail_{sy}_{ri}", rail_pts[ri], rail_pts[ri + 1], .022,
               material=yellow, body=house)
    for ri, x in enumerate((-.76, .16)):
        v4.rod(f"deck_handrail_foot_{sy}_{ri}", (x, sy * .82, 1.53),
               (x, sy * .82, 1.76), .024, material=yellow, body=house)
v4.cylinder("exhaust_stack", .055, .50, (-1.26, .48, 2.65), material=dark_steel, body=house, bevel=.012)
v4.cylinder("exhaust_rain_cap", .085, .035, (-1.26, .48, 2.917), material=steel, body=house, bevel=.010)
for sy in (-1, 1):
    for k in range(5):
        v4.box(f"engine_vent_{sy}_{k}", (.30, .025, .018), (-.78, sy * .742, 1.84 + k * .038),
               bevel=.007, material=dark_steel, body=house)
# Small tail lamps on the counterweight corners.
for sy in (-1, 1):
    v4.box(f"rear_lamp_housing_{sy}", (.18, .08, .16), (-1.94, sy * .60, 2.17), bevel=.022,
           material=charcoal, body=house)
    v4.box(f"rear_lamp_red_{sy}", (.12, .018, .09), (-2.037, sy * .60, 2.17), bevel=.018,
           material=red_lens, body=house)

# Upper-house pedestals and paired clevis cheeks carry the boom heel pin.
for sy in (-1, 1):
    v4.box(f"boom_heel_pedestal_{sy}", (.22, .09, .54), (.58, sy * .31, 1.76), bevel=.035,
           material=charcoal, body=house)
    v4.box(f"boom_heel_house_clevis_{sy}", (.18, .09, .22), (.58, sy * .31, 2.12), bevel=.035,
           material=yellow, body=house)
    pin_cap(f"house_boom_pin_cap_{sy}", (.58, sy * .31, 2.12), .12, .03, (0, 1, 0), steel, house)

# ---- boom and stick welded structures -------------------------------------------------
BOOM_PIVOT = (0.58, 0.0, 2.12)
BOOM_TIP = (3.02, 0.0, 2.66)
boom_outline = [(0.39, 1.98), (0.78, 1.91), (1.17, 2.00), (2.42, 2.35),
                (2.76, 2.46), (3.02, 2.55), (3.02, 2.66), (2.94, 2.78),
                (2.74, 2.77), (1.08, 2.35), (0.60, 2.33)]
boom_shell = prism_xz("boom_main_weldment", boom_outline, .43, 0, orange, boom, bevel=.065)
v4.rod("boom_heel_pin_shaft", (.58, -.38, 2.12), (.58, .38, 2.12), .070, material=steel, body=boom)
# Reinforced lower heel and terminal casting cheeks sit flush against the fabricated section.
for sy in (-1, 1):
    v4.box(f"boom_tip_ear_{sy}", (.16, .07, .28), (2.93, sy * .255, 2.66), bevel=.035,
           material=yellow, body=boom)
    pin_cap(f"boom_heel_cap_{sy}", (BOOM_PIVOT[0], sy * .238, BOOM_PIVOT[2]), .135, .035,
            (0, 1, 0), steel, boom)
    pin_cap(f"boom_tip_cap_{sy}", (BOOM_TIP[0], sy * .25, BOOM_TIP[2]), .11, .03,
            (0, 1, 0), steel, boom)
    # Small grease nipples beside each cap.
    pin_cap(f"boom_heel_grease_{sy}", (.78, sy * .226, 2.16), .022, .022, (0, 1, 0), yellow, boom)
    pin_cap(f"boom_tip_grease_{sy}", (2.86, sy * .25, 2.67), .020, .020, (0, 1, 0), yellow, boom)
# Visible paired hose runs are attached to the boom and turn with it.
for sy in (-1, 1):
    v4.tube(f"boom_hose_bundle_{sy}", [(0.92, sy * .205, 2.31), (1.35, sy * .222, 2.39),
                                        (1.92, sy * .222, 2.55), (2.52, sy * .215, 2.70),
                                        (2.92, sy * .20, 2.76)], .021, material=black, body=boom)
    v4.tube(f"boom_hose_stripe_{sy}", [(1.02, sy * .228, 2.33), (1.48, sy * .24, 2.44),
                                       (2.06, sy * .24, 2.58), (2.63, sy * .23, 2.72)], .008,
            material=yellow, body=boom)
# Stick attaches at boom tip and ends at the rotator spindle.
STICK_END = (5.05, 0.0, 1.50)
stick_outline = [(3.02, 2.55), (3.28, 2.45), (3.57, 2.20), (4.31, 1.76),
                  (4.64, 1.56), (4.84, 1.43), (4.94, 1.47), (4.93, 1.61),
                  (4.70, 1.82), (3.78, 2.46), (3.32, 2.78), (3.02, 2.78)]
stick_shell = prism_xz("stick_main_weldment", stick_outline, .36, 0, orange, stick, bevel=.055)
v4.rod("stick_pin_shaft", (3.02, -.36, 2.66), (3.02, .36, 2.66), .062, material=steel, body=boom)
for sy in (-1, 1):
    v4.box(f"stick_heel_ear_{sy}", (.12, .06, .30), (3.08, sy * .205, 2.66), bevel=.030,
           material=yellow, body=stick)
    pin_cap(f"stick_heel_cap_{sy}", (3.02, sy * .23, 2.66), .095, .025, (0, 1, 0), steel, stick)
    v4.box(f"stick_end_clevis_{sy}", (.22, .05, .20), (4.88, sy * .20, 1.52), bevel=.030,
           material=yellow, body=stick)
    pin_cap(f"stick_end_cap_{sy}", (5.05, sy * .21, 1.50), .085, .025, (0, 1, 0), steel, stick)
    v4.tube(f"stick_hose_{sy}", [(3.38, sy * .178, 2.60), (3.78, sy * .185, 2.49),
                                  (4.20, sy * .17, 2.18), (4.56, sy * .17, 1.91),
                                  (4.77, sy * .16, 1.73)], .018, material=black, body=stick)
# Non-slip service decal lies on the near flat face of the stick.
v4.box("stick_service_mark_panel", (.50, .012, .09), (4.18, -.182, 2.13), bevel=.018,
       material=yellow, body=stick)

# ---- hydraulic hardware mounted to the boom and stick ----------------------------------
for sy in (-1, 1):
    y = sy * .205
    # Two compact ram housings with exposed rod sections sit flush against the beam flanks.
    v4.rod(f"boom_ram_housing_{sy}", (1.16, y, 2.045), (2.00, y, 2.285), .060,
           material=dark_steel, body=boom)
    v4.rod(f"boom_ram_chrome_{sy}", (1.92, y, 2.262), (2.72, y, 2.485), .035,
           material=rod_chrome, body=boom)
    pin_cap(f"boom_ram_gland_{sy}", (1.98, y, 2.279), .074, .055,
            (0.962, 0, 0.275), steel, boom)
    # A double hydraulic ram follows the dipper as a fixed detail on its side plate.
    v4.rod(f"stick_ram_housing_{sy}", (3.54, sy * .17, 2.39), (4.08, sy * .17, 2.12), .052,
           material=dark_steel, body=stick)
    v4.rod(f"stick_ram_chrome_{sy}", (4.02, sy * .17, 2.15), (4.67, sy * .16, 1.76), .032,
           material=rod_chrome, body=stick)
    pin_cap(f"stick_ram_gland_{sy}", (4.05, sy * .17, 2.135), .064, .048,
            (0.815, 0, -0.580), steel, stick)

# ---- suspended hydraulic rotator and fixed crosshead ----------------------------------
# Arm end: a large vertical rotator, lower output flange, hose swivel and jaw crosshead.
v4.cylinder("rotator_motor_can", .18, .29, (5.05, 0, 1.335), material=charcoal, body=head, bevel=.025)
v4.cylinder("rotator_top_cap", .205, .075, (5.05, 0, 1.50), material=steel, body=head, bevel=.018)
v4.cylinder("rotator_neck", .115, .18, (5.05, 0, 1.18), material=dark_steel, body=head, bevel=.016)
v4.cylinder("rotator_output_flange", .29, .10, (5.05, 0, 1.10), material=orange, body=head, bevel=.018)
v4.cylinder("rotator_flange_lip", .245, .035, (5.05, 0, 1.035), material=steel, body=head, bevel=.008)
for i in range(12):
    a = 2 * math.pi * i / 12
    pin_cap(f"rotator_flange_bolt_{i:02d}", (5.05 + .258 * math.cos(a), .258 * math.sin(a), 1.10),
            .022, .018, (0, 0, 1), steel, head)
# Compact hydraulic hose loops at the rotating swivel.
for sy in (-1, 1):
    v4.tube(f"rotator_hose_{sy}", [(4.93, sy * .17, 1.25), (4.79, sy * .26, 1.17),
                                   (4.79, sy * .28, 1.08), (4.92, sy * .22, 1.00)],
            .021, material=black, body=head)
# Broad crosshead and jaw lugs.
v4.box("grapple_crosshead", (.26, .84, .12), (5.05, 0, 1.12), bevel=.055,
       material=orange, body=head)
v4.box("grapple_top_bridge", (.30, .60, .12), (5.05, 0, 1.24), bevel=.035,
       material=yellow, body=head)
for sy in (-1, 1):
    v4.cylinder(f"jaw_hinge_boss_{sy}", .145, .31, (5.05, sy * .55, 1.18),
                rot=(0, math.pi / 2, 0), material=dark_steel, body=head, bevel=.015)
    pin_cap(f"jaw_bearing_cap_{sy}", (5.208, sy * .55, 1.18), .095, .022,
            (1, 0, 0), steel, head)
    # Pin sockets and grease nibs on the exposed cheek.
    pin_cap(f"jaw_grease_{sy}", (5.228, sy * .55, 1.26), .018, .015,
            (1, 0, 0), yellow, head)

# Two opposing forged tines are in the gripping pose around the timber bundle.
left_profile = [(-.54, 1.18), (-.70, 1.02), (-.76, .72), (-.69, .49),
                (-.52, .29), (-.30, .18), (-.17, .18), (-.24, .28),
                (-.45, .43), (-.57, .62), (-.44, .72), (-.43, .90)]
right_profile = [(-y, z) for y, z in reversed(left_profile)]
for body, side, profile, sy, limits in ((left_tine, "left", left_profile, -1, (-math.radians(52), 0)),
                                        (right_tine, "right", right_profile, 1, (0, math.radians(52)))):
    jaw = prism_yz(f"{side}_forged_grapple_tine", profile, 4.90, .30, orange, body, bevel=.035)
    # Thick heel block around the hinge, and dark replaceable wear bars along the inward hook.
    v4.box(f"{side}_jaw_heel", (.38, .19, .22), (5.05, sy * .54, 1.11), bevel=.055,
           material=yellow, body=body)
    v4.tube(f"{side}_jaw_wear_edge", [(5.205, profile[i][0], profile[i][1])
                                       for i in (2, 3, 4, 5, 6)], .037,
            material=dark_steel, body=body)
    v4.tube(f"{side}_jaw_outer_rib", [(5.205, profile[i][0], profile[i][1])
                                       for i in (0, 1, 2, 3, 4)], .025,
            material=yellow, body=body)
    # One pin axle belongs to each moving tine and is captured by the fixed head boss.
    v4.cylinder(f"{side}_jaw_pin", .058, .35, (5.05, sy * .55, 1.18),
                rot=(0, math.pi / 2, 0), material=steel, body=body, bevel=.009)
    pin_cap(f"{side}_jaw_pin_end", (4.89, sy * .55, 1.18), .078, .025,
            (1, 0, 0), dark_steel, body)

# ---- joints: one physical tree; the simulated hydraulic rams follow their host arms --------
v4.joint("left_track_drive", "continuous", base, left_track, origin=(-1.55, -TRACK_Y, TRACK_CZ),
         axis=(0, 1, 0))
v4.joint("right_track_drive", "continuous", base, right_track, origin=(-1.55, TRACK_Y, TRACK_CZ),
         axis=(0, 1, 0))
v4.joint("left_log_sleeper_mount", "fixed", base, left_sleeper, origin=(4.53, 0, 0.083), axis=(0, 0, 1))
v4.joint("right_log_sleeper_mount", "fixed", base, right_sleeper, origin=(6.00, 0, 0.086), axis=(0, 0, 1))
v4.joint("house_slew", "revolute", base, house, origin=(0, 0, 1.34), axis=(0, 0, 1),
         limits=(-math.pi, math.pi))
v4.joint("boom_heel", "revolute", house, boom, origin=BOOM_PIVOT, axis=(0, 1, 0),
         limits=(-math.radians(38), 0.0))
v4.joint("stick_pin", "revolute", boom, stick, origin=BOOM_TIP, axis=(0, 1, 0),
         limits=(-math.radians(35), 0.0))
v4.joint("rotator_spin", "continuous", stick, head, origin=STICK_END, axis=(0, 0, 1))
v4.joint("log_bundle_mount", "fixed", head, load, origin=(5.05, 0, .18), axis=(0, 0, 1))
v4.joint("left_jaw_pin", "revolute", head, left_tine, origin=(5.05, -.55, 1.18),
         axis=(1, 0, 0), limits=(-math.radians(52), 0))
v4.joint("right_jaw_pin", "revolute", head, right_tine, origin=(5.05, .55, 1.18),
         axis=(1, 0, 0), limits=(0, math.radians(52)))

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