"""Build a production-style articulated vehicle sun visor with v4lib.

Run with the supplied Blender executable from this directory:
    $BLENDER -b --python build.py
"""
import math
import os
import sys

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


def rounded_loop(cx, cy, width, height, radius, z, tube_radius, material, body, name, steps=8):
    """A fine closed seam following a rounded rectangle in the visor face."""
    x0, x1 = cx - width / 2, cx + width / 2
    y0, y1 = cy - height / 2, cy + height / 2
    corners = [
        (x0 + radius, y0 + radius, 180, 270),
        (x1 - radius, y0 + radius, 270, 360),
        (x1 - radius, y1 - radius, 0, 90),
        (x0 + radius, y1 - radius, 90, 180),
    ]
    pts = []
    for x, y, start, end in corners:
        for i in range(steps + 1):
            a = math.radians(start + (end - start) * i / steps)
            pts.append((x + radius * math.cos(a), y + radius * math.sin(a), z))
    return v4.tube(name, pts, tube_radius, material=material, body=body, cyclic=True)


def rounded_prism(name, width, height, depth, radius, loc, bevel, material, body,
                  corner_steps=10, bevel_segments=8):
    """Extruded rounded-rectangle panel with a softly rounded thickness edge."""
    x0, x1 = -width / 2, width / 2
    y0, y1 = -height / 2, height / 2
    corners = [
        (x0 + radius, y0 + radius, 180, 270),
        (x1 - radius, y0 + radius, 270, 360),
        (x1 - radius, y1 - radius, 0, 90),
        (x0 + radius, y1 - radius, 90, 180),
    ]
    outline = []
    for x, y, start, end in corners:
        for i in range(corner_steps + 1):
            a = math.radians(start + (end - start) * i / corner_steps)
            outline.append((x + radius * math.cos(a), y + radius * math.sin(a)))
    obj = v4.extrude(name, outline, depth, loc=loc, bevel=bevel,
                     material=material, body=body)
    for mod in obj.modifiers:
        if mod.type == "BEVEL":
            mod.segments = bevel_segments
    return obj


v4.reset()

# ---- Materials ----------------------------------------------------------------------
headliner = v4.plastic("warm_grey_headliner", (0.73, 0.71, 0.66), roughness=0.62, texture=0.12)
headliner_trim = v4.plastic("satin_headliner_trim", (0.66, 0.64, 0.59), roughness=0.48, texture=0.08)
isolation_rubber = v4.rubber("pivot_isolator", (0.13, 0.13, 0.12), roughness=0.82)
clip_polymer = v4.plastic("clip_charcoal_polymer", (0.19, 0.20, 0.20), roughness=0.38, texture=0.08)
steel = v4.metal("satin_zinc_steel", color=(0.43, 0.46, 0.48), roughness=0.31, brushed=False)
rod_steel = v4.metal("brushed_support_rod", color=(0.77, 0.78, 0.78), roughness=0.25, brushed=True)
fastener_steel = v4.metal("fastener_zinc", color=(0.70, 0.71, 0.70), roughness=0.34, brushed=False)
board_core = v4.plastic("visor_core_sand", (0.69, 0.65, 0.57), roughness=0.7, texture=0.10)
visor_fabric = v4.fabric("visor_woven_taupe", (0.62, 0.57, 0.49), weave_scale=240.0)
seam_thread = v4.fabric("warm_stitch_thread", (0.78, 0.72, 0.62), weave_scale=190.0)
mirror_bezel = v4.plastic("mirror_bezel_black", (0.055, 0.060, 0.061), roughness=0.28, texture=0.06)
mirror_glass = v4.metal("vanity_mirror_silver", color=(0.74, 0.79, 0.82), roughness=0.19, brushed=False)
visor_welting = v4.fabric("visor_edge_welting", (0.55, 0.51, 0.44), weave_scale=220.0)
internal_roof = v4.mat("covered_roof_reinforcement", (0.30, 0.32, 0.33), roughness=0.8)
internal_roof.node_tree.nodes["Principled BSDF"].inputs["Alpha"].default_value = 0.0
internal_roof.surface_render_method = "DITHERED"
strap_fabric = v4.fabric("ticket_strap_elastic", (0.22, 0.23, 0.22), weave_scale=300.0)
label_stock = v4.mat("warning_label_ivory", (0.92, 0.88, 0.77), roughness=0.72)
label_ink = v4.mat("warning_label_ink", (0.16, 0.12, 0.08), roughness=0.75)

# ---- Dimensions (metres) -------------------------------------------------------------
# The board is a typical 365 x 170 x 18 mm moulded sun visor.  X follows its width,
# +Y runs from its pivot edge into the padded board, and +Z points away from the roof.
PANEL_W = 0.365
PANEL_D = 0.170
PANEL_T = 0.018
PANEL_CX = 0.0025
PANEL_CY = 0.014
PANEL_CZ = 0.009
PANEL_X_EDGE = PANEL_CX + PANEL_W / 2
PANEL_Y_HINGE = PANEL_CY - PANEL_D / 2
ASSEMBLY_LIFT = 0.220

# ---- Roof-mounted base: one fixed root body ------------------------------------------
roof = v4.body("roof_anchor")

# A concealed, narrow roof reinforcement ties the compact pivot base to the distinct
# outboard spring clip. The broad headliner surface is deliberately left out of frame.
roof_reinforcement = v4.box("concealed_roof_reinforcement", (0.413, 0.008, 0.004),
                             (0.0, -0.125, 0.047), bevel=0.0015,
                             material=internal_roof, body=roof)
# The reinforcement is an internal roof stiffener that keeps the fixed root assembly
# continuous; it is covered by the headliner in the finished product.
pivot_x, pivot_y = -0.190, -0.115
pivot_mount = v4.box("compact_pivot_mount_base", (0.042, 0.034, 0.010),
                     (pivot_x, pivot_y, 0.050), bevel=0.006, material=headliner_trim, body=roof)

# Bore the mount for the rotating shoulder pin. A visible fixed bushing defines the
# bearing; the rotating cap and shaft pass through its centre with clearance.
pivot_bore = v4.cylinder("pivot_mount_bore_tool", 0.0072, 0.018,
                          (pivot_x, pivot_y, 0.050), segments=48, bevel=0.0)
v4.boolean(pivot_mount, pivot_bore)
v4.torus("fixed_pivot_bushing", 0.0090, 0.0015, (pivot_x, pivot_y, 0.0555),
         material=isolation_rubber, body=roof)

# Fixed lower bearing and a thin washer under the rotating bracket flange.
v4.cylinder("fixed_pivot_bearing_washer", 0.011, 0.001, (pivot_x, pivot_y, 0.0445),
            segments=48, bevel=0.0002, material=steel, body=roof)

# Two flush zinc fasteners secure the compact pivot base.
for i, x in enumerate((pivot_x - 0.014, pivot_x + 0.014)):
    v4.cylinder(f"pivot_mount_fastener_{i}", 0.0024, 0.0014,
                (x, pivot_y - 0.010, 0.0557), segments=24, bevel=0.0002,
                material=fastener_steel, body=roof)

# The spring clip is fixed to the free end of the roof rail. Its open fingers sit just
# outside the visor edge at rest; the opening clears the visor's down and slide sweeps.
clip_x = PANEL_X_EDGE + 0.003
v4.box("clip_mount_foot", (0.028, 0.022, 0.004), (clip_x, -0.125, 0.043), bevel=0.002,
       material=clip_polymer, body=roof)
v4.cylinder("clip_foot_screw_a", 0.0022, 0.0015, (clip_x - 0.008, -0.125, 0.04025),
            segments=20, bevel=0.0002, material=fastener_steel, body=roof)
v4.cylinder("clip_foot_screw_b", 0.0022, 0.0015, (clip_x + 0.008, -0.125, 0.04025),
            segments=20, bevel=0.0002, material=fastener_steel, body=roof)
# A broad molded web rises from the roof foot and tapers down to the spring jaw.
v4.extrude("formed_clip_web", [
    (0.000, 0.000), (0.011, 0.000), (0.026, -0.014),
    (0.047, -0.035), (0.051, -0.039), (0.047, -0.043),
    (0.043, -0.039), (0.022, -0.019), (0.008, -0.005),
    (0.000, -0.005),
], 0.010, loc=(clip_x - 0.005, -0.125, 0.041),
    rot=(math.pi / 2, 0.0, math.pi / 2), bevel=0.0012,
    material=clip_polymer, body=roof)
clip_profile = [
    (clip_x, -0.075, 0.002),
    (clip_x, -0.064, 0.002),
    (clip_x, -0.060, 0.005),
    (clip_x, -0.060, 0.013),
    (clip_x, -0.064, 0.016),
    (clip_x, -0.075, 0.016),
]
v4.tube("spring_retainer_fingers", clip_profile, 0.00125, material=clip_polymer,
        body=roof, resolution=8)
v4.box("clip_outer_cap", (0.004, 0.012, 0.016), (clip_x + 0.0025, -0.0685, 0.009),
       bevel=0.0005, material=headliner_trim, body=roof)

# ---- Hinged support bracket and steel slide rod --------------------------------------
bracket = v4.body("swivel_bracket")
v4.cylinder("rotating_pivot_flange", 0.012, 0.006, (pivot_x, pivot_y, 0.041),
            segments=48, bevel=0.001, material=steel, body=bracket)
v4.cylinder("rotating_pivot_shoulder", 0.0024, 0.016, (pivot_x, pivot_y, 0.047),
            segments=32, bevel=0.0003, material=fastener_steel, body=bracket)
v4.cylinder("pivot_cap_head", 0.0060, 0.0018, (pivot_x, pivot_y, 0.0559),
            segments=32, bevel=0.0003, material=fastener_steel, body=bracket)

# A stamped, tapered steel web joins the pivot housing to the horizontal slide rod.
# Its shaped section replaces the exposed round neck while retaining the same pivots.
v4.extrude("formed_support_web", [
    (0.000, -0.001), (0.006, -0.003), (0.033, -0.019),
    (0.037, -0.024), (0.034, -0.028), (0.028, -0.026),
    (0.004, -0.011), (0.000, -0.008),
], 0.014, loc=(pivot_x - 0.007, pivot_y, 0.038),
    rot=(math.pi / 2, 0.0, math.pi / 2), bevel=0.001,
    material=steel, body=bracket)
# A short formed saddle captures the rod at the web end and stiffens the sheet transition.
v4.box("rod_saddle", (0.020, 0.012, 0.004),
       (pivot_x, -0.079, 0.015), bevel=0.0015, material=steel, body=bracket)
v4.rod("visor_support_rod", (-0.190, -0.079, 0.015), (0.190, -0.079, 0.015),
       0.003, segments=32, bevel=0.0004, material=rod_steel, body=bracket)
v4.cylinder("rod_end_stop", 0.0044, 0.004, (0.187, -0.079, 0.015),
            rot=(0, math.pi / 2, 0), segments=32, bevel=0.0004, material=steel, body=bracket)
v4.torus("rod_saddle_gusset", 0.0044, 0.0013, (-0.190, -0.079, 0.015),
         rot=(0, math.pi / 2, 0), material=steel, body=bracket)

# ---- Sliding hinge carriage -----------------------------------------------------------
carriage = v4.body("hinge_carriage")
rod_y, rod_z = -0.079, 0.015
collar_xs = (-0.155, -0.130)
for i, x in enumerate(collar_xs):
    v4.torus(f"rod_slide_collar_{i}", 0.005, 0.002, (x, rod_y, rod_z),
             rot=(0, math.pi / 2, 0), material=steel, body=carriage)

# Lower bridge joins the two rod collars. A short drop links the bridge to the hinge pin.
v4.box("carriage_lower_bridge", (0.025, 0.004, 0.003), (-0.1425, rod_y, 0.0065),
       bevel=0.0008, material=steel, body=carriage)
v4.box("carriage_drop_link", (0.012, 0.004, 0.006), (-0.1425, -0.076, 0.011),
       bevel=0.001, material=steel, body=carriage)
v4.cylinder("visor_hinge_barrel", 0.004, 0.036, (-0.1425, -0.075, PANEL_CZ),
            rot=(0, math.pi / 2, 0), segments=40, bevel=0.0005, material=steel, body=carriage)
v4.cylinder("hinge_pin_head", 0.0048, 0.002, (-0.1615, -0.075, PANEL_CZ),
            rot=(0, math.pi / 2, 0), segments=32, bevel=0.0004, material=fastener_steel, body=carriage)

# ---- Padded visor board and integrated details ---------------------------------------
visor = v4.body("visor")
visor_core = rounded_prism("moulded_visor_core", PANEL_W, PANEL_D, PANEL_T, 0.022,
                           (PANEL_CX, PANEL_CY, PANEL_CZ - PANEL_T / 2),
                           bevel=0.0045, material=board_core, body=visor,
                           corner_steps=12, bevel_segments=10)

# Face cloth is inset from the rounded edge and bonded flush to the core on both sides.
face_w, face_d = PANEL_W - 0.010, PANEL_D - 0.010
top_face_z = PANEL_CZ + PANEL_T / 2 + 0.0005
bottom_face_z = PANEL_CZ - PANEL_T / 2 - 0.0005
upper_face = rounded_prism("upper_woven_face", face_w, face_d, 0.001, 0.018,
                           (PANEL_CX, PANEL_CY, top_face_z - 0.0005),
                           bevel=0.0002, material=visor_fabric, body=visor,
                           corner_steps=12, bevel_segments=4)
rounded_prism("lower_woven_face", face_w, face_d, 0.001, 0.018,
              (PANEL_CX, PANEL_CY, bottom_face_z - 0.0005),
              bevel=0.0002, material=visor_fabric, body=visor,
              corner_steps=12, bevel_segments=4)

# Double needle stitch follows each broad face, set back from the perimeter piping.
seam_w, seam_d = PANEL_W - 0.025, PANEL_D - 0.025
rounded_loop(PANEL_CX, PANEL_CY, seam_w, seam_d, 0.014, top_face_z + 0.0010,
             0.00045, seam_thread, visor, "upper_double_stitch_outer")
rounded_loop(PANEL_CX, PANEL_CY, seam_w - 0.004, seam_d - 0.004, 0.012,
             top_face_z + 0.0010, 0.00035, seam_thread, visor, "upper_double_stitch_inner")
rounded_loop(PANEL_CX, PANEL_CY, seam_w, seam_d, 0.014, bottom_face_z - 0.0010,
             0.00045, seam_thread, visor, "lower_double_stitch_outer")
rounded_loop(PANEL_CX, PANEL_CY, seam_w - 0.004, seam_d - 0.004, 0.012,
             bottom_face_z - 0.0010, 0.00035, seam_thread, visor, "lower_double_stitch_inner")

# A fine upholstered welt follows the padded perimeter and visually softens the shell edge.
rounded_loop(PANEL_CX, PANEL_CY, face_w - 0.002, face_d - 0.002, 0.017,
             top_face_z + 0.00065, 0.0008, visor_welting, visor, "upper_edge_welt")
rounded_loop(PANEL_CX, PANEL_CY, face_w - 0.002, face_d - 0.002, 0.017,
             bottom_face_z - 0.00065, 0.0008, visor_welting, visor, "lower_edge_welt")

# Cabin-facing vanity mirror: a shallow molded pocket is cut into the core and face cloth,
# and the cassette, bezel and silver glass sit within that recess. The opposite face carries
# the elastic strap and warning label.
mirror_x, mirror_y = 0.058, 0.036
pocket_cutter = v4.box("mirror_pocket_tool", (0.116, 0.076, 0.007),
                       (mirror_x, mirror_y, 0.0185), bevel=0.0025)
v4.boolean(visor_core, pocket_cutter)
pocket_cutter = v4.box("mirror_face_tool", (0.116, 0.076, 0.007),
                       (mirror_x, mirror_y, 0.0185), bevel=0.0025)
v4.boolean(upper_face, pocket_cutter)

rounded_prism("mirror_pocket_cassette", 0.114, 0.074, 0.001, 0.009,
              (mirror_x, mirror_y, 0.015), bevel=0.0002,
              material=mirror_bezel, body=visor, corner_steps=8, bevel_segments=4)
# One continuous rounded rectangular trim ring keeps the bezel width even on all sides.
mirror_frame = rounded_prism("vanity_mirror_bezel", 0.112, 0.072, 0.003, 0.008,
                             (mirror_x, mirror_y, 0.016), bevel=0.0005,
                             material=mirror_bezel, body=visor,
                             corner_steps=8, bevel_segments=5)
aperture_tool = rounded_prism("mirror_bezel_aperture_tool", 0.100, 0.060, 0.006, 0.004,
                              (mirror_x, mirror_y, 0.014), bevel=0.0,
                              material=None, body=None, corner_steps=8, bevel_segments=1)
v4.boolean(mirror_frame, aperture_tool)
rounded_prism("mirror_window_gasket", 0.100, 0.060, 0.001, 0.004,
              (mirror_x, mirror_y, 0.016), bevel=0.0002,
              material=isolation_rubber, body=visor, corner_steps=8, bevel_segments=4)
rounded_prism("vanity_mirror_glass", 0.098, 0.058, 0.001, 0.003,
              (mirror_x, mirror_y, 0.017), bevel=0.0002,
              material=mirror_glass, body=visor, corner_steps=8, bevel_segments=4)

# A narrow elastic ticket band sits at the opposite lower corner of the underside.
strap_x, strap_y = -0.112, 0.006
v4.box("ticket_strap", (0.100, 0.026, 0.0015),
       (strap_x, strap_y, PANEL_CZ - PANEL_T / 2 - 0.00175), bevel=0.0015,
       material=strap_fabric, body=visor)
for i, x in enumerate((strap_x - 0.040, strap_x + 0.040)):
    v4.tube(f"ticket_strap_stitch_{i}", [(x, strap_y - 0.009, PANEL_CZ - PANEL_T / 2 - 0.0025),
                                         (x, strap_y + 0.009, PANEL_CZ - PANEL_T / 2 - 0.0025)],
            0.00035, material=seam_thread, body=visor)

# Small OEM warning label on the underside, with ink embossed onto its face.
warning = v4.box("airbag_warning_label", (0.060, 0.018, 0.001),
                 (-0.105, 0.073, PANEL_CZ - PANEL_T / 2 - 0.0015), bevel=0.001,
                 material=label_stock, body=visor)
v4.text("airbag_warning_text", "WARNING", size=0.0045,
        loc=(-0.105, 0.073, PANEL_CZ - PANEL_T / 2 - 0.002),
        rot=(math.pi, 0, 0), extrude_depth=0.0002, material=label_ink,
        body=visor, on=warning, height=0.00025)

# ---- Joints: two real hinges and an independent rod slide -----------------------------
v4.joint("bracket_swivel", "revolute", roof, bracket,
         origin=(pivot_x, pivot_y, 0.041 + ASSEMBLY_LIFT), axis=(0, 0, 1),
         limits=(0.0, math.radians(96)))
v4.joint("visor_slide", "prismatic", bracket, carriage,
         origin=(-0.155, rod_y, rod_z + ASSEMBLY_LIFT), axis=(1, 0, 0), limits=(-0.035, 0.0))
v4.joint("visor_hinge", "revolute", carriage, visor,
         origin=(-0.1425, -0.075, PANEL_CZ + ASSEMBLY_LIFT), axis=(1, 0, 0),
         limits=(-math.radians(91), 0.0))

# Place every rigid part in the raised assembly frame. Applying this to the part
# meshes keeps the root mount, support clip, and articulated bodies at the same
# height in both the saved asset and Articraft's normalized-root motion renders.
for body_obj in v4.bodies():
    for obj in body_obj.children:
        obj.location.z += ASSEMBLY_LIFT

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