"""Detailed articulated tabletop film splicer. Run with the supplied Blender executable."""
import math
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4

v4.reset()

# Finishes
shell = v4.painted("charcoal_cast_aluminum", (0.105, 0.12, 0.13), roughness=0.32, coat=0.28)
deckmat = v4.metal("satin_machined_deck", (0.62, 0.64, 0.62), roughness=0.27)
steel = v4.metal("stainless_steel", (0.78, 0.80, 0.82), roughness=0.23)
darksteel = v4.metal("darkened_steel", (0.29, 0.32, 0.33), roughness=0.34)
poly = v4.plastic("black_clamp_polymer", (0.035, 0.045, 0.047), roughness=0.48, texture=0.2)
grip = v4.rubber("rubber_grip", (0.018, 0.021, 0.022))
amber = v4.plastic("amber_tape", (0.72, 0.31, 0.07), roughness=0.28, texture=0.05)
ivory = v4.mat("warm_white_print", (0.88, 0.84, 0.72), roughness=0.5)
red = v4.painted("safety_red", (0.7, 0.045, 0.025), roughness=0.32, coat=0.15)
film = v4.plastic("warm_clear_film", (0.72, 0.53, 0.30), roughness=0.26, texture=0.02)
loaded_film = v4.plastic("loaded_translucent_amber_film", (0.62, 0.39, 0.20),
                         roughness=0.22, texture=0.015)
brass = v4.metal("warm_latch_brass", (0.86, 0.52, 0.16), roughness=0.26, brushed=False)

# Coordinates use film travel along Y and the cut at Y=0. Z=0 is the tabletop.
base = v4.body("base")
v4.box("cast_chassis", (0.220, 0.108, 0.027), (0, 0, 0.015), bevel=0.006, material=shell, body=base)
work_deck = v4.box("machined_work_deck", (0.176, 0.090, 0.004), (0, 0, 0.0305), bevel=0.0014, material=deckmat, body=base)
# The blade finishes 1.2 mm into this narrow cut slot at the film butt line.
deck_slot_tool = v4.box("tmp_deck_blade_slot", (0.042, 0.0024, 0.010), (0, 0, 0.0305), bevel=0)
v4.boolean(work_deck, deck_slot_tool)
# Lower side skirts and four grippy feet touch the underside of the chassis.
for sx in (-1, 1):
    v4.box(f"side_skirt_{sx}", (0.006, 0.086, 0.012), (sx * 0.107, 0, 0.011), bevel=0.002, material=darksteel, body=base)
for sx in (-1, 1):
    for sy in (-1, 1):
        x, y = sx * 0.084, sy * 0.037
        v4.cylinder(f"rubber_foot_{sx}_{sy}", 0.010, 0.006, (x, y, 0.003), bevel=0.001, material=grip, body=base)

# Film registration track, shallow rails, and two pin blocks (six tapered pins per side).
for sx in (-1, 1):
    x = sx * 0.025
    # A rounded raised rail follows each edge of the perforated film path.
    v4.cylinder(f"raised_film_rail_{sx}", 0.0020, 0.082, (x, 0, 0.0345),
                rot=(math.pi / 2, 0, 0), material=steel, body=base)
    v4.box(f"film_guide_rail_{sx}", (0.002, 0.080, 0.0015), (x, 0, 0.0333), bevel=0.0004, material=darksteel, body=base)
    # A fine pale film leader is visible between the rails and beneath the clamp windows.
    v4.box(f"film_leader_{sx}", (0.034, 0.041, 0.0005), (0, sx * 0.024, 0.0330), bevel=0.0002, material=film, body=base)
    v4.box(f"pin_block_{sx}", (0.047, 0.043, 0.003), (0, sx * 0.025, 0.0347), bevel=0.001, material=darksteel, body=base)
    for xx in (-0.014, 0.014):
        for k in (-1, 0, 1):
            yy = sx * 0.025 + k * 0.012
            v4.cylinder(f"sprocket_pin_{sx}_{xx}_{k}", 0.00135, 0.010, (xx, yy, 0.0412), segments=24,
                        radius_top=0.00105, bevel=0.00012, material=steel, body=base)

# Central butt-cut opening and anvil insert, with the matching blade clearance notch.
anvil = v4.box("cutting_anvil", (0.048, 0.008, 0.0015), (0, 0, 0.0332), bevel=0.0005, material=darksteel, body=base)
anvil_slot_tool = v4.box("tmp_anvil_blade_slot", (0.042, 0.0024, 0.008), (0, 0, 0.0332), bevel=0)
v4.boolean(anvil, anvil_slot_tool)
for xx in (-0.040, 0.040):
    for k in range(5):
        yy = -0.030 + k * 0.015
        v4.box(f"registration_tick_{xx}_{k}", (0.0035, 0.00065, 0.00035), (xx, yy, 0.03275), bevel=0.0001,
               material=ivory, body=base)

# End plates receive a simple engraved scale and raised fasteners so the empty deck reads
# as a usable precision tool rather than a blank sheet of metal.
for sx in (-1, 1):
    v4.box(f"deck_scale_backing_{sx}", (0.020, 0.066, 0.0008), (sx * 0.069, 0, 0.0330),
           bevel=0.0012, material=darksteel, body=base)
    for k in range(9):
        yy = -0.030 + k * 0.0075
        length = 0.006 if k % 2 == 0 else 0.0035
        v4.box(f"deck_scale_tick_{sx}_{k}", (length, 0.0007, 0.0005),
               (sx * 0.069, yy, 0.03365), bevel=0.00015, material=ivory, body=base)
    for yy in (-0.038, 0.038):
        v4.cylinder(f"deck_panel_screw_{sx}_{yy}", 0.0021, 0.0008,
                    (sx * 0.089, yy, 0.0330), segments=20, bevel=0.00015, material=steel, body=base)

# A visible amber splicing-tape leader runs from the tape roll onto the working deck.
# The cut slot itself stays clear for the descending blade. The serrated bar tears tape.
v4.box("tape_leader_to_barrel", (0.055, 0.0055, 0.00065), (0.0285, -0.028, 0.0340),
       bevel=0.00025, material=amber, body=base)
v4.box("tape_tear_bar", (0.0028, 0.012, 0.0022), (0.052, -0.028, 0.0350),
       bevel=0.0004, material=steel, body=base)
for k in range(7):
    yy = -0.033 + k * 0.0017
    v4.box(f"tape_tear_tooth_{k}", (0.0030, 0.0011, 0.0020), (0.0492, yy, 0.0350),
           bevel=0.00025, material=steel, body=base)
v4.cylinder("tape_edge_guide_roller", 0.0025, 0.008, (0.0555, -0.028, 0.0368),
            rot=(math.pi / 2, 0, 0), material=steel, body=base)
for sy in (-1, 1):
    v4.box(f"tape_roller_fork_{sy}", (0.003, 0.002, 0.004),
           (0.0555, -0.028 + sy * 0.0042, 0.0370), bevel=0.0007, material=darksteel, body=base)

# Raised hinge barrel runs across X behind each independent clamp leaf.
for sx in (-1, 1):
    yy = sx * 0.049
    for j, xx in enumerate((-0.026, 0.026)):
        v4.cylinder(f"clamp_hinge_barrel_{sx}_{j}", 0.0032, 0.008, (xx, yy, 0.041),
                    rot=(0, math.pi / 2, 0), material=darksteel, body=base)
    for xx in (-0.0305, 0.0305):
        v4.cylinder(f"clamp_hinge_pin_head_{sx}_{xx}", 0.0041, 0.0015,
                    (xx, yy, 0.041), rot=(0, math.pi / 2, 0), material=steel, body=base)
    # Two cast hinge cheeks descend from the barrel to the deck and make a rigid yoke.
    for xx in (-0.024, 0.024):
        v4.box(f"clamp_hinge_cheek_{sx}_{xx}", (0.006, 0.006, 0.008),
               (xx, yy, 0.037), bevel=0.001, material=shell, body=base)

# Paired hinged clamp plates. Boolean perforation clearances let the fixed pins project
# through the real working surfaces instead of colliding with a solid plate.
clamps = {}
for sx, label in ((-1, "left"), (1, "right")):
    clamp = v4.body(f"clamp_{label}")
    clamps[label] = clamp
    cy = sx * 0.025
    plate = v4.box(f"clamp_plate_{label}", (0.055, 0.048, 0.0032), (0, cy, 0.0396), bevel=0.0015,
                   material=poly, body=clamp)
    # Six holes follow the two perforation rows in this clamp's film end.
    for xx in (-0.014, 0.014):
        for k in (-1, 0, 1):
            yy = cy + k * 0.012
            cutter = v4.cylinder(f"tmp_hole_{label}_{xx}_{k}", 0.00205, 0.010, (xx, yy, 0.0396),
                                 segments=20, bevel=0)
            v4.boolean(plate, cutter)
    film_strip = v4.box(f"loaded_film_{label}", (0.034, 0.047, 0.00055),
                        (0, cy, 0.041475), bevel=0.00018, material=loaded_film, body=clamp)
    for xx in (-0.014, 0.014):
        for k in (-1, 0, 1):
            yy = cy + k * 0.012
            film_hole = v4.cylinder(f"tmp_film_perforation_{label}_{xx}_{k}", 0.0022, 0.004,
                                    (xx, yy, 0.0415), segments=24, bevel=0)
            v4.boolean(film_strip, film_hole)
    film_catch_hole = v4.cylinder(f"tmp_film_catch_clearance_{label}", 0.0037, 0.004,
                                  (sx * 0.022, sx * 0.018, 0.0415), segments=24, bevel=0)
    v4.boolean(film_strip, film_catch_hole)
    # Clearance for the fixed base catch pin at this plate's free edge.
    catch_x = sx * 0.022
    catch_y = sx * 0.018
    catch_cut = v4.cylinder(f"tmp_catch_clearance_{label}", 0.0035, 0.010,
                            (catch_x, catch_y, 0.0396), segments=24, bevel=0)
    v4.boolean(plate, catch_cut)
    # Raised transverse grip ribs and a subtly colored latch index mark.
    for k in range(4):
        yy = cy + (k - 1.5) * 0.008
        v4.box(f"clamp_grip_rib_{label}_{k}", (0.044, 0.0011, 0.0010), (0, yy, 0.0417), bevel=0.0004,
               material=grip, body=clamp)
    v4.box(f"latch_index_{label}", (0.006, 0.003, 0.0007), (0, -sx * 0.001, 0.0417), bevel=0.0005,
           material=red, body=clamp)
    # Small formed hinge ears join the leaf directly to its barrel.
    for xx in (-0.025, 0.025):
        v4.box(f"clamp_hinge_ear_{label}_{xx}", (0.008, 0.007, 0.004), (xx, sx * 0.047, 0.040),
               bevel=0.001, material=poly, body=clamp)
    for xx in (-0.016, 0.016):
        v4.cylinder(f"clamp_hinge_knuckle_{label}_{xx}", 0.0037, 0.008,
                    (xx, sx * 0.049, 0.041), rot=(0, math.pi / 2, 0), material=poly, body=clamp)
    v4.joint(f"clamp_{label}_hinge", "revolute", base, clamp, origin=(0, sx * 0.049, 0.041),
             axis=(1, 0, 0), limits=(0, 1.25) if sx < 0 else (-1.25, 0))

# Each clamp has its own catch pin fixed to the base at its free edge. The pin rises
# through the leaf's clearance hole so its own latch hook can close around the shaft.
for sx, label in ((-1, "left"), (1, "right")):
    catch_x, catch_y = sx * 0.022, sx * 0.018
    v4.cylinder(f"latch_catch_foot_{label}", 0.0032, 0.002, (catch_x, catch_y, 0.0335),
                segments=24, bevel=0.0002, material=darksteel, body=base)
    v4.box(f"latch_keeper_pad_{label}", (0.009, 0.011, 0.0010),
           (catch_x, catch_y, 0.0329), bevel=0.0012, material=brass, body=base)
    v4.cylinder(f"latch_catch_pin_{label}", 0.0017, 0.009, (catch_x, catch_y, 0.0390),
                segments=24, bevel=0.00015, material=steel, body=base)
    v4.cylinder(f"latch_catch_cap_{label}", 0.0025, 0.0015, (catch_x, catch_y, 0.04425),
                segments=24, bevel=0.0002, material=brass, body=base)

# Pivoting over-center latch levers sit at the inner end of each clamp plate.
latches = {}
for sx, label in ((-1, "left"), (1, "right")):
    latch = v4.body(f"latch_{label}")
    latches[label] = latch
    py = sx * 0.003
    hx = sx * 0.022
    handle_x = hx - sx * 0.008
    pin_y = sx * 0.018
    tab_y = pin_y + sx * 0.0095
    v4.cylinder(f"latch_pivot_boss_{label}", 0.0030, 0.008, (0, py, 0.0432), rot=(0, math.pi / 2, 0),
                material=steel, body=latch)
    v4.rod(f"latch_crossbar_{label}", (0, py, 0.0432), (handle_x, py, 0.0432), 0.0024,
           material=darksteel, body=latch)
    v4.rod(f"latch_handle_{label}", (handle_x, py, 0.0432), (handle_x, tab_y, 0.0455), 0.0028,
           material=darksteel, body=latch)
    v4.rod(f"latch_handle_to_hook_{label}", (handle_x, tab_y, 0.0455), (hx, tab_y, 0.0455), 0.0025,
           material=darksteel, body=latch)
    # Red U-hook surrounds the pin shaft; its open end faces the hinge, with a thumb tab
    # at the outer end. All of this geometry stays on its own side of the seam.
    for dx in (-0.004, 0.004):
        v4.box(f"latch_hook_finger_{label}_{dx}", (0.002, 0.009, 0.003),
               (hx + dx, pin_y + sx * 0.004, 0.045), bevel=0.0008, material=red, body=latch)
    v4.box(f"latch_hook_crosspiece_{label}", (0.010, 0.0015, 0.003),
           (hx, pin_y + sx * 0.0035, 0.045), bevel=0.0005, material=red, body=latch)
    v4.box(f"latch_thumb_tab_{label}", (0.014, 0.009, 0.004), (hx, tab_y, 0.046),
           bevel=0.0022, material=red, body=latch)
    v4.joint(f"latch_{label}_pivot", "revolute", clamps[label], latch, origin=(0, py, 0.0432), axis=(1, 0, 0),
             limits=(0, 0.75) if sx < 0 else (-0.75, 0))

# Swing-down cutter: the rest blade is raised and angled back. At 45 degrees its cutting
# edge rotates to y=0 and reaches 1.2 mm below the deck through the matching slot.
blade = v4.body("blade_arm")
hinge = (0, 0.057, 0.091)
v4.cylinder("blade_pivot_hub", 0.009, 0.050, hinge, rot=(0, math.pi / 2, 0), material=darksteel, body=blade)
v4.cylinder("blade_pivot_cap", 0.006, 0.002, (0.026, hinge[1], hinge[2]), rot=(0, math.pi / 2, 0),
            material=steel, body=blade)
# Fixed forked bearing pedestal on the chassis physically carries the cutter pivot.
for xx in (-0.027, 0.027):
    v4.box(f"blade_bearing_upright_{xx}", (0.006, 0.008, 0.0585), (xx, hinge[1], 0.06175),
           bevel=0.0015, material=shell, body=base)
    v4.cylinder(f"blade_bearing_boss_{xx}", 0.010, 0.006, (math.copysign(0.0285, xx), hinge[1], hinge[2]),
                rot=(0, math.pi / 2, 0), material=darksteel, body=base)
v4.rod("cutter_arm_spine", hinge, (0, -0.0345, 0.0980), 0.0045,
       material=shell, body=blade)
arm_angle = math.atan2(-0.02325, 0.05825)
v4.box("cutter_arm_cover", (0.016, 0.020, 0.012), (0, 0.047, 0.095),
       rot=(arm_angle, 0, 0), bevel=0.003, material=deckmat, body=blade)
v4.box("cutter_handle_grip", (0.019, 0.015, 0.014), (0, 0.0518, 0.1071),
       rot=(arm_angle, 0, 0), bevel=0.004, material=grip, body=blade)
# The blade profile is swept back and upward in the raised pose (45-degree local frame).
# Its sharpened lower edge aligns with the seam when the joint reaches +45 degrees.
knife_root = (0, -0.026, 0.0895)
knife_height = 0.012
knife_top = (0, knife_root[1] - knife_height * math.sin(math.pi / 4),
             knife_root[2] + knife_height * math.cos(math.pi / 4))
v4.extrude("tapered_cutting_blade",
           [(-0.019, knife_height), (0.019, knife_height), (0.019, 0.004),
            (0.012, 0.0), (-0.016, 0.0025), (-0.019, 0.005)],
           0.0012, loc=knife_root, rot=(math.pi / 4, 0, 0), bevel=0.00018,
           material=steel, body=blade)
# Clamp shoe sits across the top edge in the same angled frame and is riveted to the arm.
v4.box("knife_mounting_shoe", (0.046, 0.006, 0.004), knife_top,
       rot=(math.pi / 4, 0, 0), bevel=0.0015, material=darksteel, body=blade)
for xx in (-0.015, 0.015):
    v4.cylinder(f"knife_mount_rivet_{xx}", 0.0015, 0.0015,
                (xx, knife_top[1] - 0.0025, knife_top[2] + 0.0025),
                rot=(math.pi / 4, 0, 0), segments=20, bevel=0.0001, material=steel, body=blade)
v4.rod("polished_cutting_bevel", (-0.018, knife_root[1] - 0.0011, knife_root[2] + 0.0011),
       (0.018, knife_root[1] - 0.0011, knife_root[2] + 0.0011), 0.00038,
       material=steel, body=blade)
# Molded grip ribs and rubber stop bumpers on the bearing cheeks.
for k in (-1, 0, 1):
    off = k * 0.004
    v4.box(f"handle_grip_rib_{k}", (0.020, 0.0012, 0.0145),
           (0, 0.0518 + off * math.cos(arm_angle), 0.1071 + off * math.sin(arm_angle)),
           rot=(arm_angle, 0, 0), bevel=0.00045, material=darksteel, body=blade)
for sx in (-1, 1):
    v4.cylinder(f"blade_stop_bumper_{sx}", 0.0020, 0.0015,
                (sx * 0.03225, hinge[1], hinge[2]), rot=(0, math.pi / 2, 0),
                material=grip, body=base)
v4.joint("blade_hinge", "revolute", base, blade, origin=hinge, axis=(1, 0, 0), limits=(0, math.radians(45)))

# Tape roll on a continuous transverse axle, with two thin flanges and a wound amber core.
reel = v4.body("tape_spool")
rx, ry, rz = 0.078, -0.028, 0.050
v4.cylinder("tape_roll", 0.020, 0.022, (rx, ry, rz), rot=(math.pi / 2, 0, 0), material=amber, body=reel)
for side in (-1, 1):
    y = ry + side * 0.012
    v4.cylinder(f"spool_flange_{side}", 0.025, 0.0022, (rx, y, rz), rot=(math.pi / 2, 0, 0),
                material=darksteel, body=reel)
    v4.torus(f"spool_rim_{side}", 0.0225, 0.0010, (rx, y + side * 0.0012, rz),
             rot=(math.pi / 2, 0, 0), material=steel, body=reel)
v4.cylinder("spool_bushing", 0.006, 0.030, (rx, ry, rz), rot=(math.pi / 2, 0, 0), material=steel, body=reel)
v4.joint("tape_spool_axle", "continuous", base, reel, origin=(rx, ry, rz), axis=(0, 1, 0))
# Axle supports are part of the base and touch the reel flange edges.
for sy in (-1, 1):
    v4.box(f"spool_yoke_cheek_{sy}", (0.014, 0.012, 0.034),
           (rx, ry + sy * 0.020, 0.043), bevel=0.003, material=shell, body=base)

# Save the joint-zero working pose. Checker will solve the articulated motion states.
v4.save(os.path.join(os.getcwd(), "asset.blend"))
print("saved asset.blend")
