"""Detailed articulated tabletop crank marble machine. Run with Blender + v4lib."""
import math
import os
import sys

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

v4.reset()

# Materials
maple = v4.wood("honey_maple", light=(0.72, 0.49, 0.27), dark=(0.36, 0.20, 0.09), grain_scale=5.2)
walnut = v4.wood("walnut_trim", light=(0.43, 0.25, 0.13), dark=(0.21, 0.105, 0.045), grain_scale=7)
steel = v4.metal("satin_nickel", color=(0.72, 0.76, 0.78), roughness=0.27)
brass = v4.metal("warm_brass", color=(0.78, 0.49, 0.18), roughness=0.29, brushed=False)
bronze = v4.metal("dark_bronze_gears", color=(0.40, 0.25, 0.11), roughness=0.31)
red = v4.painted("enamel_red", (0.72, 0.12, 0.045), roughness=0.25)
blue = v4.glass("cobalt_marble", (0.04, 0.28, 0.85), roughness=0.12)
amber = v4.glass("amber_marble", (0.95, 0.39, 0.035), roughness=0.12)
green = v4.glass("jade_marble", (0.025, 0.58, 0.22), roughness=0.12)
black = v4.rubber("dark_rubber", (0.035, 0.035, 0.032))
cream = v4.mat("ivory_legend", (0.94, 0.79, 0.49), roughness=0.4)

# Coordinates: front/operator side is -Y. Plinth is 0.36 x 0.27 x 0.038 m.
frame = v4.body("frame")
crank = v4.body("crank")
wheel = v4.body("elevator_wheel")
idler = v4.body("return_gear")
gate = v4.body("lever_gate")

# Base and feet
v4.box("bevelled_maple_plinth", (0.36, 0.27, 0.038), (0, 0.005, 0.026), bevel=0.006, material=maple, body=frame)
v4.box("dark_walnut_front_inlay", (0.32, 0.006, 0.009), (0, -0.131, 0.028), bevel=0.002, material=walnut, body=frame)
for ix, x in enumerate((-.145, .145)):
    for iy, y in enumerate((-.10, .105)):
        v4.cylinder(f"rubber_foot_{ix}_{iy}", .018, .012, (x, y, .006), bevel=.003, material=black, body=frame)
        v4.cylinder(f"foot_screw_{ix}_{iy}", .004, .004, (x, y, .034), rot=(0,0,0), bevel=.0005, material=brass, body=frame)

# Upright lift-column cheek plates and rear stay. Main wheel center (-.083, -.015, .238).
cx, cy, cz = -.083, -.015, .238
for side, y in (("near", -.074), ("far", .027)):
    v4.box(f"lift_column_{side}", (.018, .018, .365), (cx, y, .215), bevel=.003, material=walnut, body=frame)
    # axle bearing collars at wheel and gear heights
    v4.cylinder(f"wheel_bearing_{side}", .019, .012, (cx, y, cz), rot=(math.pi/2,0,0), bevel=.002, material=brass, body=frame)
    v4.cylinder(f"bearing_boss_{side}", .013, .008, (cx, y, cz), rot=(math.pi/2,0,0), bevel=.001, material=steel, body=frame)
v4.box("rear_column_tie", (.20, .018, .016), (-.02, .036, .30), bevel=.002, material=maple, body=frame)
v4.rod("rear_diagonal_brace", (-.16,.063,.042), (-.14,.063,.315), .008, material=walnut, body=frame)

# Decorative wooden crossbars around the elevator path; wheels and gears remain visible.
v4.box("lift_guard_top", (.194,.012,.012), (-.083,.036,.405), bevel=.003, material=maple, body=frame)
v4.box("lift_guard_bottom", (.194,.012,.012), (-.083,.036,.055), bevel=.003, material=maple, body=frame)

# Wheel: two side discs, rim, six scoop blades, hub, large gear, and representative marbles.
v4.torus("paddle_wheel_outer_rim", .101, .0035, (cx,-.015,cz), rot=(math.pi/2,0,0), material=brass, body=wheel)
v4.cylinder("elevator_hub", .023, .058, (cx,-.015,cz), rot=(math.pi/2,0,0), bevel=.002, material=brass, body=wheel)
v4.cylinder("hub_cap", .012, .071, (cx,-.015,cz), rot=(math.pi/2,0,0), bevel=.002, material=steel, body=wheel)

# Open-spoke cheeks leave the lifting pockets and their marbles visible from either side.
for side, y in (("front",-.022),("back",-.008)):
    for i in range(6):
        a=2*math.pi*i/6
        v4.rod(f"wheel_spoke_{side}_{i}", (cx+.019*math.cos(a),y,cz+.019*math.sin(a)),
               (cx+.097*math.cos(a),y,cz+.097*math.sin(a)), .0035, material=maple, body=wheel)

# Six narrow radial back vanes and tangent shelves make recognizable lifting pockets.
for i in range(6):
    a = 2*math.pi*i/6 + math.radians(8)
    rad = .068
    px, pz = cx + rad*math.cos(a), cz + rad*math.sin(a)
    # radial vane
    v4.box(f"paddle_vane_{i}", (.069,.035,.005), (cx + .070*math.cos(a), -.015, cz + .070*math.sin(a)),
           rot=(0,-a,0), bevel=.001, material=red if i%2==0 else walnut, body=wheel)
    # shelf tangent to the wheel at the ball seat radius
    phi = a + math.pi/2
    v4.box(f"paddle_shelf_{i}", (.043,.035,.006), (px,-.015,pz), rot=(0,-phi,0), bevel=.0015,
           material=brass, body=wheel)
    marble_mat = (blue, amber, green)[i%3]
    # marbles sit at the outer edge of their individual lift pockets
    bx, bz = cx + .078*math.cos(a), cz + .078*math.sin(a)
    v4.sphere(f"lifted_marble_{i}", .009, (bx,-.015,bz), segments=32, material=marble_mat, body=wheel)

# Toothed gear outlines are polygonal involute approximations; count and pitch align at rest.
def gear_outline(teeth, root_r, tip_r, phase=0.0):
    pts=[]
    for i in range(teeth):
        base=phase+2*math.pi*i/teeth
        for frac, r in ((0,root_r),(.20,root_r),(.27,tip_r),(.68,tip_r),(.75,root_r),(1.0,root_r)):
            a=base+frac*2*math.pi/teeth
            pts.append((r*math.cos(a), r*math.sin(a)))
    return pts

# Large 18 tooth gear belongs to the elevator wheel. Place tooth faces on operator side.
v4.extrude("elevator_spur_gear_18t", gear_outline(18,.044,.050, math.radians(5)), .014,
           loc=(cx,-.039,cz), rot=(math.pi/2,0,0), bevel=.0006, material=bronze, body=wheel)

# Intermediate 12 tooth gear, its axle and washer details.
v4.extrude("return_spur_gear_12t", gear_outline(12,.028,.032), .012,
           loc=(-.001,-.039,cz), rot=(math.pi/2,0,0), bevel=.0005, material=bronze, body=idler)
v4.cylinder("return_gear_hub", .012, .016, (-.001,-.058,cz), rot=(math.pi/2,0,0), bevel=.001, material=brass, body=idler)

# Hand crank and 10 tooth pinion: offset arm lies in XZ plane; grip projects toward the user.
gear_x = .057
v4.extrude("crank_pinion_10t", gear_outline(10,.024,.028), .012,
           loc=(gear_x,-.039,cz), rot=(math.pi/2,0,0), bevel=.0005, material=bronze, body=crank)
v4.cylinder("crank_shaft", .008, .080, (gear_x,-.005,cz), rot=(math.pi/2,0,0), bevel=.001, material=steel, body=crank)
v4.cylinder("crank_shaft_collar", .013, .009, (gear_x,-.050,cz), rot=(math.pi/2,0,0), bevel=.001, material=brass, body=crank)
arm_profile = [(-.016,-.010),(.034,-.010),(.042,-.016),(.058,-.016),(.066,-.008),
               (.066,.008),(.058,.016),(.042,.010),(.034,.010),(-.016,.010)]
v4.extrude("offset_crank_arm", arm_profile, .014, loc=(gear_x,-.050,cz), rot=(math.pi/2,0,0),
           bevel=.002, material=steel, body=crank)
v4.cylinder("crank_grip_spindle", .007, .040, (gear_x+.050,-.075,cz), rot=(math.pi/2,0,0), bevel=.001, material=brass, body=crank)
grip_profile = [(0,0),(.008,0),(.010,.004),(.011,.012),(.010,.032),(.008,.037),(.008,.041),(0,.041)]
v4.lathe("turned_maple_crank_grip", grip_profile,
         loc=(gear_x+.050,-.095,cz), rot=(math.pi/2,0,0), material=maple, body=crank)
v4.cylinder("grip_endcap", .009, .006, (gear_x+.050,-.140,cz), rot=(math.pi/2,0,0), bevel=.001, material=brass, body=crank)

# Return track as one fixed body: twin rounded rails, cross ties, end catch and supports.
path = [(-.083,.350),(-.025,.350),(.115,.323),(.132,.302),(.132,.278),(.115,.258),(-.105,.235),
        (-.122,.216),(-.122,.194),(-.105,.175),(.115,.153),(.132,.135),(.132,.115),(.113,.098),(-.083,.082)]
rail_y=(.035,.058)
for side, y in zip(("near","far"),rail_y):
    v4.tube(f"track_rail_{side}", [(x,y,z) for x,z in path], .0042, material=steel, body=frame, resolution=2)
    # turned entry horn guides a marble out of the elevator
    v4.tube(f"entry_guide_{side}", [(-.085,y,.333),(-.065,y,.350),(-.025,y,.350)], .0042,
            material=brass, body=frame, resolution=2)
v4.tube("track_center_roller", [(x,.0465,z-.001) for x,z in path], .0032,
        material=brass, body=frame, resolution=2)

# Wooden transverse ties at every meaningful change in direction.
for i,(x,z) in enumerate(path[1:-1]):
    if math.hypot(x-cx, z-cz) < .115:
        continue
    v4.box(f"track_tie_{i:02d}", (.012,.040,.007), (x,.0465,z-.006), rot=(0,0,0),
           bevel=.0015, material=maple, body=frame)

# Fixed supports underneath the return runs: struts meet the wood cross-ties.
for i in (2,3,5,6,8,9,11,12,13):
    x,z=path[i]
    v4.rod(f"track_support_{i}", (x,.073,.045), (x,.073,z-.008), .0045, material=walnut, body=frame)
    v4.box(f"track_support_foot_{i}", (.025,.025,.006), (x,.073,.043), bevel=.001, material=brass, body=frame)

# Bottom return cup/catch is a shallow wood basin directly over the elevator intake.
v4.box("marble_return_cup_floor", (.075,.040,.008), (-.083,.0465,.048), bevel=.003, material=maple, body=frame)
for sx in (-1,1):
    v4.box(f"return_cup_side_{sx}", (.008,.040,.025), (-.083+sx*.037,.0465,.061), bevel=.002, material=walnut, body=frame)
v4.box("return_cup_back", (.075,.008,.025), (-.083,.0665,.061), bevel=.002, material=walnut, body=frame)

# Decorative fixed screw heads on column and track ties.
for j,y in enumerate((-.074,.027)):
    for z in (.075,.388):
        v4.cylinder(f"column_screw_{j}_{z}", .0032,.002, (cx-.009,y,z), rot=(0,math.pi/2,0),
                    bevel=.0005, material=brass, body=frame)

# Gate hinge and arm. Pivot at near rail edge; arm spans the marble channel when closed.
gx, gy, gz = .070, .023, .351
v4.cylinder("gate_hinge_post", .0045,.034, (gx,gy,.334), bevel=.001, material=brass, body=gate)
v4.cylinder("gate_hinge_barrel", .007,.012, (gx,gy,gz), bevel=.001, material=steel, body=gate)
v4.rod("gate_stop_arm", (gx,gy,gz), (gx,gy+.040,gz), .0035, material=brass, body=gate)
v4.sphere("gate_arm_end", .005, (gx,gy+.040,gz), segments=24, material=red, body=gate)
v4.box("gate_mount_block", (.018,.020,.012), (gx,.024,.321), bevel=.002, material=walnut, body=frame)

# Small maker badge embedded on front plinth face. Raised lettering is projected onto the badge.
badge = v4.box("maker_badge", (.105,.003,.019), (0,-.136,.030), bevel=.003, material=brass, body=frame)
v4.text("maker_badge_letters", "MAPLE MARBLE CO.", .0075, loc=(0,-.138,.030), rot=(math.pi/2,0,0),
        material=cream, body=frame, on=badge, height=.0007)

# Joints: world-space points and axes, with all three independent spinning axes around Y.
v4.joint("crank_rotation", "continuous", frame, crank, origin=(gear_x,-.005,cz), axis=(0,1,0))
v4.joint("elevator_rotation", "continuous", frame, wheel, origin=(cx,-.015,cz), axis=(0,1,0))
v4.joint("return_gear_rotation", "continuous", frame, idler, origin=(-.001,-.015,cz), axis=(0,1,0))
v4.joint("gate_hinge", "revolute", frame, gate, origin=(gx,gy,gz), axis=(0,0,1),
         limits=(-math.radians(60), math.radians(60)))

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