"""Articulated premium central-pole patio umbrella. Run in Blender with v4lib."""
import math
import os
import sys

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

v4.reset()

# Materials: satin metalwork, powder-coated hardware, and UV-stable woven acrylic.
aluminum = v4.metal("champagne_anodized_aluminum", (0.68, 0.60, 0.43), roughness=0.31)
steel = v4.metal("stainless_and_zinc_hardware", (0.72, 0.75, 0.77), roughness=0.27, brushed=False)
dark_metal = v4.painted("charcoal_powdercoat", (0.12, 0.14, 0.15), roughness=0.34)
fabric_a = v4.fabric("forest_acrylic_canvas", (0.006, 0.20, 0.018), weave_scale=240)
fabric_b = v4.fabric("alternate_forest_canvas", (0.010, 0.30, 0.030), weave_scale=240)
binding = v4.fabric("reinforced_canvas_binding", (0.005, 0.13, 0.016), weave_scale=220)
rubber = v4.rubber("grip_rubber", (0.075, 0.08, 0.075))
mark = v4.metal("warm_silver_marking", (0.83, 0.79, 0.67), roughness=0.3, brushed=False)

# Realistic dimensions: 2.7 m canopy, 2.45 m tall mast, 45 mm pole.
N = 6
R = 1.35
HUB_Z = 2.43
EDGE_Z = 2.20
RIB_PIVOT_R = 0.040
RIB_PICKUP_R = 0.566
def canopy_z(r):
    t = max(0.0, min(1.0, r / R))
    return HUB_Z + 0.042 - 0.26 * (t ** 1.42) - 0.022 * (t ** 1.4)
RIB_PICKUP_Z = canopy_z(RIB_PICKUP_R) - 0.008
RUNNER_Z = 1.90
MAST_R = 0.0225

mast = v4.body("mast")  # lower mast and fixed stand hardware
upper_mast = v4.body("upper_mast")

# Heavy cast umbrella foot with concentric pressed rim and radial traction scallops.
v4.lathe("weighted_cast_base", [(0, 0.018), (0.25, 0.018), (0.31, 0.028), (0.34, 0.055),
                                  (0.33, 0.078), (0.30, 0.087), (0, 0.087)],
         material=dark_metal, body=mast)
v4.torus("base_rolled_rim", 0.312, 0.008, loc=(0, 0, 0.065), material=steel, body=mast)
v4.cylinder("base_mast_socket", 0.044, 0.14, (0, 0, 0.145), material=dark_metal, body=mast)
v4.torus("socket_lock_ring", 0.031, 0.003, loc=(0, 0, 0.209), material=steel, body=mast)
v4.cylinder("socket_tighten_knob",0.012,0.045,(0.040,0,0.178),rot=(0,math.pi/2,0),material=dark_metal,body=mast)
v4.rod("socket_knob_crossbar",(0.062,-0.018,0.178),(0.062,0.018,0.178),0.004,material=steel,body=mast)
for k in range(16):
    a = 2 * math.pi * k / 16
    v4.box(f"base_grip_{k:02d}", (0.012, 0.026, 0.004),
           (0.285 * math.cos(a), 0.285 * math.sin(a), 0.088),
           rot=(0, 0, a), bevel=0.002, material=steel, body=mast)

# Mast split at the tilt knuckle, above the runner's entire stroke.
TILT_Z = 2.18
PIVOT_Z = TILT_Z + 0.0225
# The lower shaft stops beneath the pin; the upper shaft starts above it.
lower_tube=v4.cylinder("lower_mast_tube", MAST_R, TILT_Z - 0.2025, (0, 0, (0.18 + TILT_Z - 0.0225) / 2), material=aluminum, body=mast)
v4.cylinder("upper_mast_tube", MAST_R, 0.47, (0, 0, 2.45), material=aluminum, body=upper_mast)
for z in (0.24, 1.76, 1.84):
    band=v4.torus(f"mast_band_{z:.2f}", MAST_R + 0.001, 0.0018, loc=(0, 0, z), material=steel, body=mast)
    v4.boolean(lower_tube,band,op="UNION")
joiner=v4.cylinder("mast_joiner", 0.027, 0.045, (0, 0, 1.80), material=steel, body=mast)
v4.boolean(lower_tube,joiner,op="UNION")

# Gearbox cast around the crank spindle. The crank and grip form one rotating body.
v4.box("gearbox_mount_bracket", (0.075, 0.17, 0.15), (0.0, -0.055, 0.93), bevel=0.006,
       material=aluminum, body=mast)
v4.box("gearbox_main_shell", (0.12, 0.095, 0.22), (0.066, -0.14, 0.93), bevel=0.018,
       material=dark_metal, body=mast)
v4.box("gearbox_face_plate", (0.099, 0.020, 0.175), (0.066, -0.184, 0.93), bevel=0.003,
       material=aluminum, body=mast)
# Clearance opening in the molded cover aligns with the rotating spindle.
plate_bore=v4.cylinder("cover_bore_tool",0.0125,0.030,(0.066,-0.184,0.93),rot=(math.pi/2,0,0),material=steel,body=mast)
v4.boolean(bpy.data.objects["gearbox_face_plate"],plate_bore)
# Fuse the face cover to the molded shell so it is one connected cast assembly.
v4.boolean(bpy.data.objects["gearbox_main_shell"],bpy.data.objects["gearbox_face_plate"],op="UNION")
for sx in (-1, 1):
    for sz in (-1, 1):
        v4.cylinder(f"gear_cover_screw_{sx}_{sz}", 0.004, 0.003,
                    (0.066 + sx * 0.037, -0.188, 0.93 + sz * 0.071),
                    rot=(math.pi / 2, 0, 0), segments=16, material=steel, body=mast)
v4.cylinder("gearbox_axle_boss", 0.027, 0.018, (0.066, -0.188, 0.93),
            rot=(math.pi / 2, 0, 0), material=steel, body=mast)
# A close clearance bore leaves the rotating spindle free of the boss wall.
axle_bore = v4.cylinder("axle_bore_tool", 0.0125, 0.024, (0.066,-0.188,0.93),
                        rot=(math.pi/2,0,0), material=steel, body=mast)
v4.boolean(bpy.data.objects["gearbox_axle_boss"], axle_bore)
v4.boolean(bpy.data.objects["gearbox_main_shell"],bpy.data.objects["gearbox_axle_boss"],op="UNION")
for sx in (-1, 1):
    for sz in (-1, 1):
        screw=bpy.data.objects.get(f"gear_cover_screw_{sx}_{sz}")
        if screw:
            v4.boolean(bpy.data.objects["gearbox_main_shell"],screw,op="UNION")
v4.boolean(bpy.data.objects["gearbox_main_shell"],bpy.data.objects["gearbox_mount_bracket"],op="UNION")
v4.boolean(lower_tube,bpy.data.objects["gearbox_main_shell"],op="UNION")
# Molded cable outlet sits through the top of the gearbox cover.
# The exit is molded as a raised lip on the housing itself (no loose grommet island).

# 45 mm cast tilt knuckle, pivoting upper mast, and the crown hardware.
lower_tilt_collar=v4.cylinder("tilt_lower_collar", 0.026, 0.045, (0, 0, TILT_Z), material=dark_metal, body=mast)
upper_tilt_collar=v4.cylinder("tilt_upper_collar", 0.026, 0.045, (0, 0, TILT_Z+0.045), material=aluminum, body=upper_mast)
for collar in (lower_tilt_collar,upper_tilt_collar):
    bore=v4.cylinder("tilt_pin_bore_tool",0.0125,0.080,(0,0,PIVOT_Z),rot=(0,math.pi/2,0),material=steel,body=mast)
    v4.boolean(collar,bore)
v4.cylinder("tilt_pivot_pin", 0.012, 0.074, (0, 0, PIVOT_Z), rot=(0,math.pi/2,0), material=steel, body=upper_mast)
for side,x in (("left",-0.037),("right",0.037)):
    v4.cylinder(f"tilt_pin_endcap_{side}",0.014,0.004,(x,0,PIVOT_Z),rot=(0,math.pi/2,0),material=dark_metal,body=upper_mast)
v4.cylinder("crown_hub_body", 0.040, 0.115, (0, 0, HUB_Z - 0.015), material=aluminum, body=upper_mast)
v4.torus("crown_hub_lower_bead", 0.039, 0.004, loc=(0, 0, HUB_Z - 0.067), material=steel, body=upper_mast)
v4.lathe("crown_finial", [(0, 0), (0.028, 0), (0.035, 0.012), (0.026, 0.025), (0.014, 0.042), (0, 0.05)],
         loc=(0, 0, HUB_Z + 0.042), material=aluminum, body=upper_mast)
v4.cylinder("vent_cap", 0.11, 0.035, (0,0,HUB_Z+0.058), material=dark_metal, body=upper_mast)
v4.torus("vent_cap_bead", 0.102, 0.004, loc=(0,0,HUB_Z+0.078), material=steel, body=upper_mast)
# A compact grooved sheave is visible below the vent cap and merges into the hub.
v4.cylinder("crown_hoist_sheave",0.034,0.016,(0,-0.035,HUB_Z-0.075),
            rot=(math.pi/2,0,0),material=dark_metal,body=upper_mast)
v4.torus("crown_sheave_rim",0.027,0.003,loc=(0,-0.045,HUB_Z-0.075),
         rot=(math.pi/2,0,0),material=steel,body=upper_mast)
v4.joint("a_tilt_hinge", "revolute", mast, upper_mast, origin=(0,0,PIVOT_Z), axis=(1,0,0), limits=(0,math.radians(35)))

# Reserve rib bodies so the cloth panels can be attached to the moving frame.
rib_bodies = [v4.body(f"rib_{i}") for i in range(N)]
# One continuous fabric skin is divided into six material gores. A runner-driven
# shape key gathers the cloth down the mast as the frame folds.
can_nr, can_na = 20, 32
canopy_inner_r=0.035
verts=[]
for ir in range(can_nr+1):
    rr=canopy_inner_r+(R-canopy_inner_r)*ir/can_nr; t=rr/R
    for ia in range(can_na+1):
        u=ia/can_na
        aa=2*math.pi*u
        sag=0.018*t*math.sin(N*aa/2)**2
        scallop=0.035*math.sin(N*aa/2)**2 if ir==can_nr else 0.0
        zz=canopy_z(rr)-sag-scallop
        verts.append((rr*math.cos(aa),rr*math.sin(aa),zz))
faces=[]
for ir in range(can_nr):
    inner=ir*(can_na+1); outer=(ir+1)*(can_na+1)
    for ia in range(can_na):
        faces.append((inner+ia,outer+ia,outer+ia+1,inner+ia+1))
can_me=bpy.data.meshes.new("six_gore_continuous_acrylic_canopy_mesh")
can_me.from_pydata(verts,[],faces); can_me.update()
canopy_obj=bpy.data.objects.new("six_gore_continuous_acrylic_canopy",can_me)
bpy.context.scene.collection.objects.link(canopy_obj)
can_me.materials.append(fabric_a);can_me.materials.append(fabric_b);can_me.materials.append(binding)
for ir in range(can_nr):
    for ia in range(can_na):
        p=can_me.polygons[ir*can_na+ia]
        p.use_smooth=True
        sector=(ia*N)//can_na
        sector_u=(ia*N/can_na)-sector
        p.material_index=2 if min(sector_u,1-sector_u)<0.035 else sector%2
# The collapsed state is a slim fabric sleeve whose hem ends alongside folded ribs.
canopy_obj.shape_key_add(name="Basis")
folded=canopy_obj.shape_key_add(name="Runner_down_gathered")
for idx,(x,y,z) in enumerate(verts):
    rr=math.hypot(x,y); t=rr/R; ang=math.atan2(y,x)
    close_r=0.060+0.025*(1-t)
    close_z=HUB_Z-0.07-1.30*t-0.025*math.sin(N*ang/2)**2
    folded.data[idx].co=(close_r*math.cos(ang),close_r*math.sin(ang),close_z)
v4.part(canopy_obj,upper_mast)

# Crank is a single articulated assembly with an offset arm and a comfortable rotating grip.
crank = v4.body("crank")
v4.cylinder("crank_axle", 0.012, 0.045, (0.066, -0.218, 0.93), rot=(math.pi / 2, 0, 0),
            material=steel, body=crank)
v4.rod("crank_throw", (0.066, -0.246, 0.93), (0.066, -0.246, 0.675), 0.009,
       material=aluminum, body=crank)
v4.cylinder("crank_lower_hub", 0.018, 0.033, (0.066, -0.246, 0.675),
            rot=(math.pi / 2, 0, 0), material=steel, body=crank)
v4.cylinder("crank_grip", 0.018, 0.125, (0.066, -0.308, 0.675),
            rot=(math.pi / 2, 0, 0), material=rubber, body=crank)
v4.cylinder("crank_grip_endcap", 0.018, 0.009, (0.066, -0.373, 0.675),
            rot=(math.pi / 2, 0, 0), material=dark_metal, body=crank)
v4.joint("crank_turn", "continuous", mast, crank, origin=(0.066, -0.213, 0.93), axis=(0, 1, 0))

# Runner collar slides on the mast; its eight clevis ears hold the stretcher hinges.
slider = v4.body("slider")
fold_driver=folded.driver_add("value").driver
fold_driver.type='SCRIPTED'; fold_driver.expression="max(0,min(1,-runner_z/0.75))"
fold_var=fold_driver.variables.new(); fold_var.name="runner_z"; fold_var.type='TRANSFORMS'
fold_target=fold_var.targets[0]; fold_target.id=slider
fold_target.transform_type='LOC_Z'; fold_target.transform_space='WORLD_SPACE'
v4.cylinder("runner_collar", 0.042, 0.105, (0, 0, RUNNER_Z), material=aluminum, body=slider)
runner_mast_bore=v4.cylinder("runner_mast_bore_tool",MAST_R+0.002,0.13,(0,0,RUNNER_Z),
                              material=steel,body=slider)
v4.boolean(bpy.data.objects["runner_collar"],runner_mast_bore)
v4.torus("runner_lower_lip", 0.041, 0.005, loc=(0, 0, RUNNER_Z - 0.05), material=steel, body=slider)
v4.torus("runner_upper_lip", 0.041, 0.004, loc=(0, 0, RUNNER_Z + 0.05), material=steel, body=slider)
v4.torus("runner_clevis_carrier_ring",0.046,0.006,loc=(0,0,RUNNER_Z),material=steel,body=slider)
# Cross-drilled locking-pin hole and molded thumb screw.
lock_angle=math.pi/6
lock_radial=Vector((math.cos(lock_angle),math.sin(lock_angle),0))
runner_bore=v4.cylinder("runner_lock_bore_tool",0.0045,0.10,
                        (lock_radial.x*0.041,lock_radial.y*0.041,RUNNER_Z+0.012),
                        rot=(0,math.pi/2,lock_angle),material=steel,body=slider)
v4.boolean(bpy.data.objects["runner_collar"],runner_bore)
v4.cylinder("runner_lock_knob",0.012,0.027,
            (lock_radial.x*0.055,lock_radial.y*0.055,RUNNER_Z+0.012),rot=(0,math.pi/2,lock_angle),
            material=dark_metal,body=slider)
v4.box("runner_cable_clamp",(0.012,0.012,0.020),(0,-0.038,RUNNER_Z+0.010),bevel=0.003,
       material=aluminum,body=slider)
# An enclosed hoist strand runs down the mast to the crank gearbox. It is hidden
# inside the pole wall at rest, but keeps the runner's transmission represented.
v4.rod("hoist_cable_eyelet",(0.038,0.0,RUNNER_Z+0.010),(0.078,0.0,RUNNER_Z+0.010),0.0025,
       material=steel,body=slider)
runner_joint=v4.joint("runner_slide", "prismatic", mast, slider, origin=(0, 0, RUNNER_Z), axis=(0, 0, 1), limits=(-0.75, 0))
runner_joint["v4_coupled_to"]="crank_turn"
runner_joint["v4_ratio_m_per_turn"]=-0.75/15.0
# Keep the prismatic joint free for articulated poses; the crank drives the
# slider body's relative offset, which also lets its fabric gather key respond.
drv=slider.driver_add("location",2).driver
CRANK_LIFT_PER_REV=0.75/15.0
drv.type='SCRIPTED'; drv.expression=f"max(-0.75,min(0, -crank_angle * {CRANK_LIFT_PER_REV} / (2*pi)))"
var=drv.variables.new(); var.name="crank_angle"; var.type='TRANSFORMS'
target=var.targets[0]; target.id=bpy.data.objects["J_crank_turn"]
target.transform_type='ROT_Z'; target.transform_space='LOCAL_SPACE'
# The fabric gores are carried directly by their rib bodies; the crank driver
# lifts the runner and folds the cloth with the articulated frame.

# Each four-bar is tree-rooted at the runner so slider travel drives the full frame;
# the real hub rib pin closes each loop.
for i in range(N):
    a = 2 * math.pi * i / N
    radial = Vector((math.cos(a), math.sin(a), 0))
    tangent = Vector((-math.sin(a), math.cos(a), 0))
    hub = radial * RIB_PIVOT_R + Vector((0, 0, HUB_Z - 0.07))
    pickup = radial * RIB_PICKUP_R + Vector((0, 0, RIB_PICKUP_Z))
    tip = radial * R + Vector((0, 0, EDGE_Z))
    runner_pin = radial * 0.047 + Vector((0, 0, RUNNER_Z))

    rib = rib_bodies[i]
    # Forked crown ears leave a 15 mm slot for the 11 mm rib profile.
    for side in (-1,1):
        v4.box(f"crown_knuckle_tab_{i}_{side}",(0.030,0.008,0.024),
               (radial.x*0.052-tangent.x*side*0.011,radial.y*0.052-tangent.y*side*0.011,HUB_Z-0.07),
               rot=(0,0,a),bevel=0.002,material=aluminum,body=upper_mast)
    v4.rod(f"crown_hinge_pin_{i}",hub-tangent*0.024,hub+tangent*0.024,0.0095,
           material=steel,body=upper_mast)
    rib_pickup = radial * RIB_PICKUP_R + Vector((0,0,RIB_PICKUP_Z))
    strut_pickup = rib_pickup - Vector((0,0,0.035))
    rib_tip = radial * (R-0.008) + Vector((0,0,canopy_z(R)-0.016))
    rib_pickup = radial * RIB_PICKUP_R + Vector((0,0,RIB_PICKUP_Z-0.008))
    v4.rod(f"rib_extrusion_inner_{i}", hub, rib_pickup, 0.0055, square=True, bevel=0.0015,
           material=aluminum, body=rib)
    v4.rod(f"rib_extrusion_outer_{i}", rib_pickup, rib_tip, 0.0055, square=True, bevel=0.0015,
           material=aluminum, body=rib)
    tip = rib_tip
    v4.cylinder(f"rib_tip_cap_{i}", 0.008, 0.018, loc=tip, rot=(0,math.pi/2,a), material=dark_metal, body=rib)
    v4.rod(f"fabric_tip_pocket_{i}",tip-radial*0.095,tip+radial*0.012,0.013,
           material=fabric_a if i%2==0 else fabric_b,body=rib)
    v4.rod(f"rib_pickup_lug_{i}",strut_pickup,rib_pickup,0.006,material=aluminum,body=rib)
    # The strut eye itself carries the through-pin at the lowered pickup; no
    # bulky rib boss intrudes into the moving link's swept envelope.
    strut = v4.body(f"stretcher_{i}")
    # The endpoints are the exact runner pin and the rib pickup at the rest pose.
    strut_dir=(strut_pickup-runner_pin).normalized()
    v4.rod(f"stretcher_bar_{i}", runner_pin+strut_dir*0.048, strut_pickup, 0.0055, square=True, bevel=0.001,
           material=aluminum, body=strut)
    v4.rod(f"stretcher_bar_neck_{i}",runner_pin+strut_dir*0.014,runner_pin+strut_dir*0.052,
           0.003,material=aluminum,body=strut)
    for side in (-1,1):
        v4.box(f"slider_clevis_ear_{i}_{side}",(0.020,0.012,0.020),
               (radial.x*0.044-tangent.x*side*0.015,radial.y*0.044-tangent.y*side*0.015,RUNNER_Z),
               rot=(0,0,a),bevel=0.002,material=aluminum,body=slider)
    v4.rod(f"slider_clevis_pin_{i}",runner_pin-tangent*0.024,runner_pin+tangent*0.024,
           0.0055,material=steel,body=slider)
    v4.torus(f"stretcher_runner_eye_{i}",0.0125,0.004,loc=runner_pin,
             rot=(math.pi/2,0,a),material=steel,body=strut)
    v4.rod(f"stretcher_rib_eye_{i}", strut_pickup - tangent * 0.022,
           strut_pickup + tangent * 0.022, 0.0055, material=steel, body=strut)
    v4.joint(f"stretcher_hinge_{i}", "revolute", slider, strut, origin=runner_pin, axis=tangent,
             limits=(-math.radians(110), math.radians(10)))
    v4.joint(f"rib_stretcher_pin_{i}", "revolute", strut, rib, origin=strut_pickup, axis=tangent,
             limits=(-1.4, 1.4))
    # The hub hinge closes each runner-rooted four-bar; slider motion is the input.
    v4.joint(f"rib_hinge_{i}", "revolute", upper_mast, rib, origin=hub, axis=tangent,
             limits=(0, math.radians(95)))

# Intentionally independent: v4's joint schema has no helical/cable transmission DOF.
v4.save(os.path.join(os.getcwd(), "asset.blend"))
print("saved asset.blend")
