"""Articulated overhead swing-section trolley rail. Run with Blender's Python."""
import math
import os
import sys
import bpy
import bmesh

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

v4.reset()

# Powder-coated structure, finished steelwork, bearing metal and forged parts.
blue = v4.painted("safety_blue_enamel", (0.055, 0.22, 0.48), roughness=0.28, coat=0.55)
navy = v4.painted("carriage_navy", (0.035, 0.075, 0.12), roughness=0.3, coat=0.4)
yellow = v4.painted("safety_yellow", (0.98, 0.54, 0.035), roughness=0.32, coat=0.45)
steel = v4.metal("zinc_plated_steel", (0.72, 0.76, 0.78), roughness=0.25, brushed=True)
darksteel = v4.metal("dark_roller_steel", (0.19, 0.22, 0.25), roughness=0.31, brushed=True)
bronze = v4.metal("bronze_bushings", (0.55, 0.31, 0.12), roughness=0.29, brushed=False)
rubber = v4.rubber("hook_grip", (0.10, 0.12, 0.14))
white = v4.mat("capacity_marking", (0.92, 0.91, 0.82), roughness=0.55)
orange = v4.plastic("latch_pull", (0.95, 0.20, 0.025), roughness=0.35)
red = v4.plastic("latch_red_grip", (0.72, 0.025, 0.018), roughness=0.28)
trim_blue = v4.painted("edge_highlight_blue", (0.18, 0.38, 0.67), roughness=0.38, coat=0.18)

# Working dimensions (metres). Rail top flange is at z=.93 and lower running
# flange at z=.71; all track sections have a 120 x 16 mm I section.
Z = 0.82
FIX_END = 0.0
SWING_END = 0.57
RAIL_START = -1.18
HINGE_Y = .085  # 5 mm beyond the +Y edge of the running flange (half-width .080 m)

fixed = v4.body("fixed_rail")
swing = v4.body("swing_section")
latch = v4.body("latch_bolt")
carriage = v4.body("carriage")
roller_bodies = []
hook = v4.body("load_hook")

def rail_section(body, x0, x1, prefix, color, moving=False):
    """Welded I-beam section, centered in Y, with flange seams and weld toes."""
    L = x1 - x0
    cx = (x0 + x1) / 2
    # Web and two flanges meet at their faces (no coincident stacked solids).
    v4.box(prefix+"_web", (L, .016, .190), (cx, 0, Z), bevel=.0015, material=color, body=body)
    v4.box(prefix+"_top_flange", (L, .132, .022), (cx, 0, Z+.104), bevel=.002, material=color, body=body)
    v4.box(prefix+"_running_flange", (L, .160, .022), (cx, 0, Z-.104), bevel=.002, material=color, body=body)
    for sy in (-1, 1):
        v4.box(prefix+f"_top_edge_highlight_{sy}", (L-.016, .002, .002),
               (cx, sy*.064, Z+.114), bevel=.0007, material=trim_blue, body=body)
    # Top mounting saddles, with four bolts each, are part of the fixed structure.
    if not moving:
        for i, x in enumerate((-1.02, -.61, -.20)):
            v4.box(f"mount_saddle_{i}", (.105, .19, .012), (x, 0, Z+.117), bevel=.004, material=steel, body=body)
            for sx in (-1, 1):
                for sy in (-1, 1):
                    v4.cylinder(f"mount_bolt_{i}_{sx}_{sy}", .007, .008,
                                (x+sx*.031, sy*.064, Z+.127), segments=24, material=darksteel, body=body)
                    v4.cylinder(f"mount_washer_{i}_{sx}_{sy}", .011, .002,
                                (x+sx*.031, sy*.064, Z+.123), segments=32, bevel=0, material=steel, body=body)
    # Machined end caps and small yellow identification bands on the swing tip.
    if moving:
        v4.box("swing_tip_cap", (.012, .161, .023), (x1-.006, 0, Z-.104), bevel=.003, material=yellow, body=body)
        v4.box("swing_tip_web_band", (.012, .018, .18), (x1-.006, 0, Z), bevel=.002, material=yellow, body=body)

def hollow_cylinder(name, radius, bore, depth, loc, rot, material, body, segments=56):
    """A true annular wheel section, leaving clearance for its stationary axle."""
    verts = []
    for zc, r in ((-depth/2, radius), (depth/2, radius),
                  (-depth/2, bore), (depth/2, bore)):
        for i in range(segments):
            a = 2*math.pi*i/segments
            verts.append((r*math.cos(a), r*math.sin(a), zc))
    faces = []
    ob, ot, ib, it = 0, segments, 2*segments, 3*segments
    for i in range(segments):
        j = (i+1) % segments
        faces.append((ob+i, ob+j, ot+j, ot+i))
        faces.append((ib+j, ib+i, it+i, it+j))
        faces.append((ot+i, ot+j, it+j, it+i))
        faces.append((ob+j, ob+i, ib+i, ib+j))
    mesh = bpy.data.meshes.new(name+"_mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.update()
    bm = bmesh.new()
    bm.from_mesh(mesh)
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    bm.to_mesh(mesh)
    bm.free()
    obj = bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.objects.link(obj)
    obj.location = loc
    obj.rotation_euler = rot
    mesh.materials.append(material)
    for poly in mesh.polygons:
        poly.use_smooth = True
    v4.part(obj, body)
    return obj

def triangular_gusset(name, points_xz, y0, y1, material, body):
    """Extruded triangular steel plate tying a bracket into the beam web."""
    verts = [(x, y, z) for y in (y0, y1) for x, z in points_xz]
    mesh = bpy.data.meshes.new(name+"_mesh")
    mesh.from_pydata(verts, [], [(0, 1, 2), (5, 4, 3), (0, 3, 4, 1),
                                 (1, 4, 5, 2), (2, 5, 3, 0)])
    mesh.update()
    bm = bmesh.new()
    bm.from_mesh(mesh)
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    bm.to_mesh(mesh)
    bm.free()
    obj = bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.objects.link(obj)
    mesh.materials.append(material)
    v4.part(obj, body)
    return obj

def web_gusset(name, points_yz, x0, x1, material, body):
    """Extruded plate bridging the fixed beam web to the hinge hanger."""
    verts = [(x, y, z) for x in (x0, x1) for y, z in points_yz]
    mesh = bpy.data.meshes.new(name+"_mesh")
    mesh.from_pydata(verts, [], [(0, 1, 2), (5, 4, 3), (0, 3, 4, 1),
                                 (1, 4, 5, 2), (2, 5, 3, 0)])
    mesh.update()
    bm = bmesh.new()
    bm.from_mesh(mesh)
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    bm.to_mesh(mesh)
    bm.free()
    obj = bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.objects.link(obj)
    mesh.materials.append(material)
    v4.part(obj, body)
    return obj

rail_section(fixed, RAIL_START, FIX_END, "fixed_beam", blue)
rail_section(swing, FIX_END, SWING_END, "swing_beam", blue, moving=True)

# A compact overhead support channel and paired threaded hangers make the
# fixed rail read as an installed suspended monorail rather than a loose beam.
v4.box("overhead_support_channel", (1.12, .105, .040), (-.61, 0, 1.310),
       bevel=.006, material=darksteel, body=fixed)
for i, x in enumerate((-1.02, -.61, -.20)):
    for sy in (-1, 1):
        y = sy*.064
        v4.rod(f"suspension_rod_{i}_{sy}", (x, y, Z+.126), (x, y, 1.296), .0065,
               material=steel, body=fixed)
        v4.cylinder(f"suspension_lower_nut_{i}_{sy}", .010, .007, (x, y, Z+.132),
                    segments=6, material=darksteel, body=fixed)
        v4.cylinder(f"suspension_upper_nut_{i}_{sy}", .010, .007, (x, y, 1.285),
                    segments=6, material=darksteel, body=fixed)
        v4.cylinder(f"suspension_washer_{i}_{sy}", .014, .003, (x, y, Z+.126),
                    segments=32, material=steel, body=fixed)
    v4.box(f"hanger_clamp_saddle_{i}", (.090, .160, .010), (x, 0, 1.287),
           bevel=.002, material=steel, body=fixed)

# Visible top-mounted hinge clevis. Each mounting shoe sits on its own rail end;
# the pin is just outside the +Y flange edge. Fixed outer knuckles alternate
# with one moving centre knuckle on a 30 mm vertical pin.
v4.box("hinge_fixed_mount_shoe", (.14, .050, .012), (-.070, .060, Z+.121),
       bevel=.002, material=steel, body=fixed)
v4.box("hinge_swing_mount_shoe", (.14, .050, .012), (.070, .060, Z+.121),
       bevel=.002, material=steel, body=swing)
v4.box("hinge_fixed_hanger_web", (.060, .016, .084), (-.038, .085, Z+.169),
       bevel=.002, material=steel, body=fixed)
v4.box("hinge_swing_hanger_web", (.060, .016, .057), (.038, .085, Z+.1525),
       bevel=0, material=blue, body=swing)
triangular_gusset("hinge_fixed_gusset", [(-.13, Z+.126), (-.010, Z+.126), (-.038, Z+.205)],
                   .077, .085, steel, fixed)
web_gusset("hinge_web_gusset", [(.006, Z+.050), (.079, Z+.129), (.006, Z+.129)],
           -.052, -.034, steel, fixed)
# Two fixed knuckles and one central moving knuckle, all coaxial at HINGE_Y.
v4.cylinder("hinge_fixed_lower_knuckle", .018, .030, (0, HINGE_Y, Z+.142),
            segments=48, material=steel, body=fixed)
v4.cylinder("hinge_swing_centre_knuckle", .018, .024, (0, HINGE_Y, Z+.169),
            segments=48, material=blue, body=swing)
v4.cylinder("hinge_fixed_upper_knuckle", .018, .030, (0, HINGE_Y, Z+.196),
            segments=48, material=steel, body=fixed)
for knuckle_name, knuckle_z, knuckle_body, finish in (
        ("lower", Z+.142, fixed, darksteel), ("centre", Z+.169, swing, steel),
        ("upper", Z+.196, fixed, darksteel)):
    v4.torus(f"hinge_barrel_band_{knuckle_name}", .0175, .002, (0, HINGE_Y, knuckle_z),
             material=finish, body=knuckle_body)
v4.cylinder("hinge_pin", .006, .126, (0, HINGE_Y, Z+.169),
            segments=32, material=darksteel, body=fixed)
v4.cylinder("hinge_pin_head", .010, .008, (0, HINGE_Y, Z+.236),
            segments=32, material=steel, body=fixed)
v4.cylinder("hinge_pin_cap_washer", .013, .004, (0, HINGE_Y, Z+.242),
            segments=40, material=darksteel, body=fixed)
v4.cylinder("hinge_retainer", .003, .034, (0, HINGE_Y, Z+.236), rot=(math.pi/2, 0, 0),
            segments=24, material=darksteel, body=fixed)
# Four visible shoe bolts on each side of the moving joint.
for side, body, xs in (("fixed", fixed, (-.112, -.038)), ("swing", swing, (.038, .112))):
    for x in xs:
        for y in (.044, .076):
            v4.cylinder(f"hinge_shoe_bolt_{side}_{x}_{y}", .0045, .010,
                        (x, y, Z+.128), segments=24, material=darksteel, body=body)

# Thin bolted end shoes make the cut between the two beam sections legible.
for name, body, x in (("fixed", fixed, -.0025), ("swing", swing, .0025)):
    v4.box(f"{name}_cut_end_plate", (.006, .126, .176), (x, 0, Z),
           bevel=.0015, material=steel, body=body)
    for sy in (-1, 1):
        for zoff in (-.052, .052):
            v4.cylinder(f"{name}_end_plate_bolt_{sy}_{zoff}", .004, .003,
                        (x, sy*.064, Z+zoff), rot=(math.pi/2, 0, 0),
                        segments=24, material=darksteel, body=body)

# Stops at both sides of the break retain a trolley if the rail is opened.
v4.box("fixed_break_stop_plate", (.012, .140, .090), (-.035, 0, Z-.055),
       bevel=.003, material=steel, body=fixed)
v4.box("fixed_break_stop_bumper", (.010, .092, .045), (-.024, 0, Z-.050),
       bevel=.004, material=yellow, body=fixed)
v4.box("swing_tip_stop_plate", (.012, .142, .090), (.575, 0, Z-.055),
       bevel=.003, material=steel, body=swing)
v4.box("swing_tip_stop_bumper", (.010, .094, .046), (.585, 0, Z-.050),
       bevel=.004, material=yellow, body=swing)

# Small exposed coating chips on the web add restrained evidence of service.
for i, (x, zoff, length) in enumerate(((-.96, .025, .027), (-.74, -.018, .016),
                                        (-.48, .041, .020), (-.29, -.034, .024),
                                        (.19, .028, .018), (.43, -.026, .021))):
    owner = fixed if x < 0 else swing
    v4.box(f"web_wear_mark_{i}", (length, .002, .0018), (x, -.0088, Z+zoff),
           rot=(0, 0, (i % 2)*.05), bevel=.0004, material=darksteel, body=owner)

# Far-side receiver bracket is bolted to the fixed rail end; it accepts the
# sliding cross-bolt when the extension is aligned.
v4.box("latch_receiver_base", (.082, .120, .050), (-.041, .050, Z+.012), bevel=.003, material=steel, body=fixed)
v4.box("latch_receiver_upper_ear", (.100, .025, .030), (.005, .096, Z+.032), bevel=.004, material=blue, body=fixed)
v4.box("latch_receiver_lower_ear", (.100, .025, .030), (.005, .096, Z-.016), bevel=.004, material=blue, body=fixed)
# One side cheek plus the upper and lower ears forms a visible U-shaped keeper
# slot around the 16 mm cross-bolt, with clearance as the rail swings away.
for side, x in (("left", -.039),):
    v4.box(f"latch_keeper_{side}_cheek", (.012, .025, .048), (x, .096, Z+.008),
           bevel=.002, material=darksteel, body=fixed)
for zbolt in (Z-.016, Z+.032):
    v4.cylinder("receiver_fastener", .005, .006, (-.041, .098, zbolt), rot=(math.pi/2, 0, 0),
                segments=20, material=darksteel, body=fixed)

# Swing-side guide blocks and cross-bolt body. At zero the steel pin reaches
# into the receiver; positive +Y travel pulls it clear.
for zoff in (-.018, .018):
    v4.box(f"latch_guide_{zoff}", (.035, .020, .028), (.040, .051, Z+zoff+.008),
           bevel=.001, material=blue, body=swing)
# A slim side strap joins both guide blocks while leaving the pin's path clear.
v4.box("latch_guide_mount", (.025, .065, .050), (.018, .025, Z+.008),
       bevel=0, material=blue, body=swing)
v4.rod("latch_cross_pin", (.040, .015, Z+.008), (.040, .106, Z+.008), .008,
       material=steel, body=latch)
v4.cylinder("latch_pull_handle", .014, .035, (.040, .121, Z+.008), rot=(math.pi/2, 0, 0),
            segments=32, material=red, body=latch)
for grip_y in (.111, .117, .125, .131):
    v4.torus(f"latch_grip_rib_{grip_y}", .0125, .0015, (.040, grip_y, Z+.008),
             rot=(math.pi/2, 0, 0), material=darksteel, body=latch)
v4.cylinder("latch_pin_collar", .011, .006, (.040, .080, Z+.008), rot=(math.pi/2, 0, 0),
            segments=32, material=darksteel, body=latch)

# Carriage plates sit outside the running flange. Four flanged wheels capture
# the flange; each wheel runs on a short stub axle bolted to its side plate.
cx = .315
plate_z = Z-.075
for sy, nm in ((-1, "near"), (1, "far")):
    py = sy*.101
    v4.box(f"side_plate_{nm}", (.318, .012, .132), (cx, py, plate_z), bevel=.006, material=navy, body=carriage)
    # Reinforcing ribs around axle bosses.
    for ax in (-1, 1):
        v4.cylinder(f"axle_boss_{nm}_{ax}", .026, .006, (cx+ax*.108, sy*.108, Z-.057),
                    rot=(math.pi/2, 0, 0), segments=40, material=steel, body=carriage)

# Two cross ties above the hook shank, each physically joining both plates.
for i, x in enumerate((cx-.12, cx+.12)):
    v4.rod(f"carriage_cross_tie_{i}", (x, -.095, Z-.140), (x, .095, Z-.140), .009,
           material=steel, body=carriage)

# Four independent grooved wheels, with a shallow raised flange and bearing cap.
wheel_centres = []
for xi, x in enumerate((cx-.12, cx+.12)):
    for si, sy in enumerate((-1, 1)):
        nm = ("front" if xi == 0 else "rear") + ("_near" if sy < 0 else "_far")
        rb = v4.body("roller_"+nm)
        roller_bodies.append(rb)
        y = sy*.066
        z = Z-.057
        v4.rod(f"axle_stub_{nm}", (x, sy*.125, z), (x, sy*.049, z), .008,
               material=darksteel, body=carriage)
        tread = hollow_cylinder("wheel_tread_"+nm, .034, .009, .027, (x, y, z),
                                (math.pi/2, 0, 0), darksteel, rb)
        # The wider flange is on the inboard face; it prevents the wheel walking off.
        flange = hollow_cylinder("wheel_flange_"+nm, .035, .009, .006, (x, y-sy*.011, z),
                                 (math.pi/2, 0, 0), darksteel, rb)
        hub = hollow_cylinder("wheel_hub_"+nm, .016, .009, .031, (x, y, z),
                              (math.pi/2, 0, 0), steel, rb, segments=40)
        cap = hollow_cylinder("wheel_cap_"+nm, .011, .009, .003, (x, y+sy*.017, z),
                              (math.pi/2, 0, 0), darksteel, rb, segments=32)
        v4.torus("wheel_rim_highlight_"+nm, .0305, .002, (x, sy*.080, z),
                 rot=(math.pi/2, 0, 0), material=steel, body=rb)
        v4.torus("wheel_hub_ring_"+nm, .012, .0014, (x, y+sy*.019, z), rot=(math.pi/2, 0, 0), material=steel, body=rb)
        v4.cylinder("axle_nut_washer_"+nm, .014, .003, (x, sy*.112, z),
                    rot=(math.pi/2, 0, 0), segments=32, material=steel, body=carriage)
        v4.cylinder("axle_nut_"+nm, .011, .009, (x, sy*.118, z),
                    rot=(math.pi/2, 0, 0), segments=6, material=darksteel, body=carriage)
        # Axle is part of the fixed carriage, aligned with this rotating wheel.
        v4.joint("roller_axle_"+nm, "continuous", carriage, rb, origin=(x, y, z), axis=(0, 1, 0))

# Brand/capacity plate and stamped details on the camera-facing carriage plate.
v4.box("capacity_plate", (.118, .002, .039), (cx, -.108, Z-.078), bevel=.002, material=steel, body=carriage)
v4.text("capacity_text", "SWL  1.0 t", .014, (cx, -.1095, Z-.075), rot=(math.pi/2, 0, 0),
        extrude_depth=.0003, material=navy, body=carriage)
v4.text("track_arrow", ">", .022, (cx+.122, -.108, Z-.079), rot=(math.pi/2, 0, 0), material=white, body=carriage)
for dx in (-.052, .052):
    for dz in (-.012, .012):
        v4.cylinder("plate_rivet", .003, .002, (cx+dx, -.110, Z-.078+dz),
                    rot=(math.pi/2, 0, 0), segments=20, material=darksteel, body=carriage)

# Hook swivel yoke and cross shaft are carried by the trolley. The actual forged
# hook pivots about Y and has a separately modeled sprung safety gate.
v4.cylinder("hook_cross_shaft", .010, .190, (cx, 0, Z-.136), rot=(math.pi/2, 0, 0),
            segments=40, material=steel, body=carriage)
for sy in (-1, 1):
    v4.cylinder("hook_shaft_washer", .016, .008, (cx, sy*.096, Z-.136), rot=(math.pi/2, 0, 0),
                segments=32, material=darksteel, body=carriage)
for sy in (-1, 1):
    v4.box(f"load_clevis_cheek_{sy}", (.066, .012, .062), (cx, sy*.042, Z-.205),
           bevel=.006, material=steel, body=hook)
v4.box("load_clevis_bridge", (.066, .080, .014), (cx, 0, Z-.200),
       bevel=.004, material=darksteel, body=hook)
v4.cylinder("load_bar", .012, .102, (cx, 0, Z-.205), rot=(math.pi/2, 0, 0),
            segments=40, material=steel, body=hook)
for sy in (-1, 1):
    v4.cylinder(f"load_bar_end_collar_{sy}", .018, .008, (cx, sy*.052, Z-.205),
                rot=(math.pi/2, 0, 0), segments=40, material=darksteel, body=hook)
v4.rod("hook_neck", (cx, 0, Z-.145), (cx, 0, Z-.239), .018, material=steel, body=hook)
v4.tube("forged_hook", [(cx, 0, Z-.229), (cx-.006, 0, Z-.2995), (cx-.0375, 0, Z-.346),
                         (cx-.090, 0, Z-.3535), (cx-.126, 0, Z-.322), (cx-.129, 0, Z-.277)],
        .016, material=steel, body=hook, resolution=20)
v4.torus("hook_throat_reinforcement", .019, .0025, (cx-.123, 0, Z-.280), rot=(0, math.pi/2, 0), material=steel, body=hook)
# Safety latch spans from the hook tip to the bowl, with a visible spring pivot.
v4.rod("hook_safety_gate", (cx-.129, 0, Z-.277), (cx-.0405, 0, Z-.331), .0045, material=darksteel, body=hook)
v4.cylinder("hook_gate_pivot", .008, .032, (cx-.129, 0, Z-.277), rot=(math.pi/2, 0, 0),
            segments=24, material=bronze, body=hook)

# Displayed joint tree. Each wheel is a real independent rotating body.
v4.joint("swing_hinge", "revolute", fixed, swing, origin=(0, HINGE_Y, Z), axis=(0, 0, 1),
         limits=(0, math.radians(75)))
v4.joint("latch_slide", "prismatic", swing, latch, origin=(.040, .015, Z+.008), axis=(0, 1, 0), limits=(0, .045))
v4.joint("carriage_travel", "prismatic", swing, carriage, origin=(cx, 0, Z-.064), axis=(1, 0, 0),
         limits=(-.07, .08))
v4.joint("hook_swivel", "revolute", carriage, hook, origin=(cx, 0, Z-.136), axis=(0, 1, 0),
         limits=(-math.radians(35), math.radians(35)))

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