"""Detailed adjustable portable basketball hoop. Run with Blender's bundled Python."""
import math
import os
import sys

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


v4.reset()

# Materials: molded charcoal ballast, graphite coated steel, bright rim enamel,
# nickel hardware, nylon guides and cord, plus a softly tinted clear board.
base_mat = v4.plastic("charcoal_rotomolded_polyethylene", (0.12, 0.14, 0.16), roughness=0.48, texture=0.22)
base_trim = v4.plastic("base_molded_detail", (0.075, 0.085, 0.095), roughness=0.46, texture=0.18)
steel = v4.painted("graphite_powdercoat", (0.105, 0.12, 0.135), roughness=0.30, coat=0.65)
steel_edge = v4.metal("zinc_plated_steel", (0.72, 0.75, 0.77), roughness=0.30, brushed=False)
black_steel = v4.painted("black_powdercoat", (0.045, 0.052, 0.06), roughness=0.35, coat=0.55)
guide_mat = v4.plastic("uhmw_carriage_guides", (0.12, 0.14, 0.15), roughness=0.5, texture=0.08)
orange = v4.painted("safety_orange_enamel", (0.96, 0.22, 0.035), roughness=0.27, coat=0.72)
white = v4.mat("silkscreen_warm_white", (0.94, 0.95, 0.92), roughness=0.45)
ink = v4.mat("height_scale_ink", (0.91, 0.67, 0.12), roughness=0.45)
rubber = v4.rubber("wheel_tire_black", (0.025, 0.029, 0.033), roughness=0.82)
hub_mat = v4.plastic("wheel_hub_charcoal", (0.10, 0.12, 0.135), roughness=0.38, texture=0.10)
net_mat = v4.fabric("white_nylon_net", (0.88, 0.89, 0.85), weave_scale=240)
board_mat = v4.glass("smoke_clear_polycarbonate", (0.72, 0.82, 0.88), roughness=0.12)
board_bsdf = board_mat.node_tree.nodes.get("Principled BSDF")
if board_bsdf:
    board_bsdf.inputs["Transmission Weight"].default_value = 0.16
    board_bsdf.inputs["Roughness"].default_value = 0.20
    board_bsdf.inputs["Metallic"].default_value = 0.03

# Main coordinate layout: the basket faces toward -Y.
MAST_Y = 0.28
BASE_Y = 0.30
BOARD_Y = -0.42
BOARD_Z = 3.28
RIM_Z = 3.05
RIM_Y = -0.78

base_body = v4.body("lower_pole")
pole_body = v4.body("pole")
board_body = v4.body("backboard")


def square_tube(name, cx, cy, z0, z1, width, wall, material, body, bevel=0.0015):
    """Open-ended hollow square steel tube with real inner and outer walls."""
    h = width / 2
    hi = h - wall
    outer = [(-h, -h), (h, -h), (h, h), (-h, h)]
    inner = [(-hi, -hi), (hi, -hi), (hi, hi), (-hi, hi)]
    verts = []
    for ring, z in ((outer, z0), (outer, z1), (inner, z0), (inner, z1)):
        verts.extend((cx + x, cy + y, z) for x, y in ring)
    faces = []
    for i in range(4):
        j = (i + 1) % 4
        # Outside and inside faces, then annular end lips.
        faces.append((i, j, 4 + j, 4 + i))
        faces.append((8 + j, 8 + i, 12 + i, 12 + j))
        faces.append((4 + i, 4 + j, 12 + j, 12 + i))
        faces.append((j, i, 8 + i, 8 + 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.children.get("Asset").objects.link(obj)
    v4.assign(obj, material)
    bevel_mod = obj.modifiers.new("soft_rolled_tube_edges", "BEVEL")
    bevel_mod.width = bevel
    bevel_mod.segments = 2
    bevel_mod.limit_method = "ANGLE"
    bevel_mod.angle_limit = math.radians(30)
    normal_mod = obj.modifiers.new("tube_weighted_normals", "WEIGHTED_NORMAL")
    normal_mod.keep_sharp = True
    v4.part(obj, body)
    return obj


def bolt(name, center, radius=0.007, length=0.006, axis="Y", material=steel_edge, body=board_body):
    rot = (math.pi / 2, 0, 0) if axis == "Y" else (0, math.pi / 2, 0)
    return v4.cylinder(name, radius, length, center, rot=rot, segments=24, bevel=0.0008,
                       material=material, body=body)


def torus_axis(name, major, minor, loc, axis="Z", material=steel_edge, body=base_body, segments=48):
    rot = (0, 0, 0) if axis == "Z" else (0, math.pi / 2, 0)
    return v4.torus(name, major, minor, loc, rot=rot, segments=segments, ring_segments=12,
                    material=material, body=body)


# -----------------------------------------------------------------------------
# Fixed base and lower mast
# -----------------------------------------------------------------------------
# Low, broad one-piece molded ballast base, with a softened perimeter.
v4.box("molded_ballast_base", (1.16, 1.00, 0.24), (0, BASE_Y, 0.12), bevel=0.045,
       material=base_mat, body=base_body)

# Shallow molded ribs on the deck and textured bumper strips at the side walls.
for sx in (-1, 1):
    for idx, yy in enumerate((-0.02, 0.20, 0.42, 0.64)):
        v4.box(f"deck_rib_{sx}_{idx}", (0.018, 0.13, 0.006), (sx * 0.46, yy, 0.243),
               bevel=0.003, material=base_trim, body=base_body)
    v4.box(f"side_bumper_{sx}", (0.008, 0.63, 0.105), (sx * 0.581, BASE_Y + 0.02, 0.12),
           bevel=0.012, material=base_trim, body=base_body)

# Fill port: molded neck, threaded-looking ring, retained cap and grip ribs.
cap_x, cap_y = -0.34, 0.62
v4.cylinder("fill_port_neck", 0.066, 0.012, (cap_x, cap_y, 0.245), segments=48,
            bevel=0.002, material=base_trim, body=base_body)
v4.torus("fill_port_lip", 0.054, 0.006, (cap_x, cap_y, 0.254), material=steel_edge, body=base_body)
v4.cylinder("retained_fill_cap", 0.049, 0.014, (cap_x, cap_y, 0.258), segments=48,
            bevel=0.004, material=base_mat, body=base_body)
for i in range(8):
    a = 2 * math.pi * i / 8
    v4.box(f"fill_cap_grip_{i}", (0.008, 0.020, 0.004),
           (cap_x + 0.037 * math.cos(a), cap_y + 0.037 * math.sin(a), 0.267),
           rot=(0, 0, a), bevel=0.001, material=base_trim, body=base_body)
# Short molded tether resting on the deck and landing on the cap rim.
v4.tube("fill_cap_tether", [(cap_x + 0.04, cap_y, 0.262), (cap_x + 0.09, cap_y - 0.04, 0.252),
                             (cap_x + 0.13, cap_y - 0.11, 0.245)], 0.0035,
        material=base_trim, body=base_body, resolution=16)

# Rear transportation wheels and axle hardware; fixed in this asset's body tree.
for sx in (-1, 1):
    x = sx * 0.635
    wy, wz = 0.70, 0.112
    v4.torus(f"transport_tire_{sx}", 0.080, 0.025, (x, wy, wz), rot=(0, math.pi / 2, 0),
             segments=64, ring_segments=16, material=rubber, body=base_body)
    v4.cylinder(f"wheel_hub_{sx}", 0.055, 0.040, (x, wy, wz), rot=(0, math.pi / 2, 0),
                segments=48, bevel=0.003, material=hub_mat, body=base_body)
    # A small centre cap and six lug heads sit on the hub's outward face.
    v4.cylinder(f"hub_centre_cap_{sx}", 0.023, 0.008, (x + sx * 0.024, wy, wz),
                rot=(0, math.pi / 2, 0), segments=32, bevel=0.002,
                material=steel_edge, body=base_body)
    for k in range(6):
        a = 2 * math.pi * k / 6
        v4.cylinder(f"hub_lug_{sx}_{k}", 0.0045, 0.003,
                    (x + sx * 0.022, wy + 0.040 * math.cos(a), wz + 0.040 * math.sin(a)),
                    rot=(0, math.pi / 2, 0), segments=16, bevel=0.0005,
                    material=steel_edge, body=base_body)
    # Fixed axle stubs meet the base side and the inner face of each wheel hub.
    axle_inner = sx * (0.635 - 0.020)
    axle_outer = sx * 0.580
    v4.rod(f"wheel_axle_{sx}", (axle_outer, wy, wz), (axle_inner, wy, wz), 0.012,
           segments=24, bevel=0.001, material=steel, body=base_body)

# Raised front label plaque and raised product lettering.
base_plaque = v4.box("base_brand_plaque", (0.50, 0.008, 0.105), (0, -0.203, 0.132), bevel=0.012,
                     material=black_steel, body=base_body)
v4.text("base_brand_text", "PORTABLE  /  44", size=0.039, loc=(0, -0.208, 0.132),
        rot=(math.pi / 2, 0, 0), material=white, body=base_body, on=base_plaque, height=0.0012)

# A broad steel foot flange is seated on the molded deck. The hollow lower square
# mast starts on the flange, leaving its upper end open for the moving mast.
v4.box("lower_mast_foot_plate", (0.22, 0.22, 0.014), (0, MAST_Y, 0.247), bevel=0.004,
       material=steel, body=base_body)
lower_mast = square_tube("fixed_lower_square_mast", 0, MAST_Y, 0.254, 1.98, 0.120, 0.007,
                         steel, base_body, bevel=0.0018)
# Welded diagonal base braces make the mast-to-ballast load path legible.
for sx in (-1, 1):
    v4.rod(f"base_mast_gusset_{sx}", (sx * 0.059, MAST_Y, 0.80),
           (sx * 0.43, 0.63, 0.245), 0.018, square=True, bevel=0.002,
           material=steel, body=base_body)
    # Reinforcing cheek plates at the mast end of the braces.
    v4.box(f"mast_gusset_cheek_{sx}", (0.010, 0.095, 0.095),
           (sx * 0.065, MAST_Y, 0.80), bevel=0.004, material=steel, body=base_body)

# Height index marks and an external captive adjustment pin on the fixed mast.
mast_front_y = MAST_Y - 0.060
for k, z in enumerate((0.72, 0.88, 1.04, 1.20, 1.36, 1.52, 1.68, 1.84)):
    length = 0.040 if k % 2 == 0 else 0.024
    v4.box(f"height_scale_tick_{k}", (length, 0.0012, 0.004),
           (0.012, mast_front_y - 0.0005, z), bevel=0.0005, material=ink, body=base_body)
    v4.cylinder(f"lower_mast_index_hole_{k}", 0.006, 0.0014,
                (-0.021, mast_front_y - 0.0007, z), rot=(math.pi / 2, 0, 0), segments=20,
                bevel=0.0003, material=black_steel, body=base_body)
v4.cylinder("captive_pull_pin_boss", 0.014, 0.010, (0.066, MAST_Y, 1.62),
            rot=(0, math.pi / 2, 0), bevel=0.002, material=steel_edge, body=base_body)
v4.cylinder("captive_pull_pin_grip", 0.010, 0.018, (0.078, MAST_Y, 1.62),
            rot=(0, math.pi / 2, 0), bevel=0.002, material=black_steel, body=base_body)
torus_axis("pull_pin_ring", 0.020, 0.0025, (0.091, MAST_Y, 1.630), axis="X", material=steel_edge)
height_label = v4.box("mast_height_label", (0.083, 0.0016, 0.20),
                      (0.010, mast_front_y - 0.0015, 1.34), bevel=0.004,
                      material=black_steel, body=base_body)
v4.text("height_label_text", "7.5  -  10 FT", size=0.022,
        loc=(0.010, mast_front_y - 0.0024, 1.34), rot=(math.pi / 2, 0, 0),
        material=white, body=base_body, on=height_label, height=0.0008)

# -----------------------------------------------------------------------------
# Telescoping upper mast
# -----------------------------------------------------------------------------
POLE_BOTTOM, POLE_TOP, POLE_W, POLE_WALL = 1.26, 3.48, 0.094, 0.006
upper_mast = square_tube("telescoping_upper_square_mast", 0, MAST_Y, POLE_BOTTOM, POLE_TOP,
                         POLE_W, POLE_WALL, steel, pole_body, bevel=0.0015)

# Four close-fit polymer guide shoes at the insertion end retain the mast while
# allowing its entire 180 mm travel inside the open lower tube.
for side in (-1, 1):
    v4.box(f"upper_mast_guide_x_{side}", (0.006, 0.052, 0.15),
           (side * 0.050, MAST_Y, 1.40), bevel=0.002, material=guide_mat, body=pole_body)
    v4.box(f"upper_mast_guide_y_{side}", (0.052, 0.006, 0.15),
           (0, MAST_Y + side * 0.050, 1.40), bevel=0.002, material=guide_mat, body=pole_body)

# The upper mast's top end plug sits directly on its annular tube lip.
v4.box("upper_mast_top_plug", (0.102, 0.102, 0.012), (0, MAST_Y, POLE_TOP + 0.006),
       bevel=0.005, material=base_trim, body=pole_body)
v4.box("upper_mast_top_badge", (0.045, 0.002, 0.018),
       (0, MAST_Y - 0.052, POLE_TOP + 0.006), bevel=0.003, material=steel_edge, body=pole_body)

# A visible run of detent holes on the upper tube aligns with the captive lower pin.
for k, z in enumerate((1.48, 1.64, 1.80, 1.96)):
    v4.cylinder(f"upper_mast_detent_{k}", 0.006, 0.0014,
                (0.018, MAST_Y - 0.0477, z), rot=(math.pi / 2, 0, 0), segments=20,
                bevel=0.0003, material=black_steel, body=pole_body)

# -----------------------------------------------------------------------------
# Moving backboard, carriage and rim assembly
# -----------------------------------------------------------------------------
# Clear 44 x 30 inch board with softened glass corners.
board = v4.box("44x30_polycarbonate_backboard", (1.12, 0.042, 0.76),
               (0, BOARD_Y, BOARD_Z), bevel=0.018, material=board_mat, body=board_body)
front_face_y = BOARD_Y - 0.021

# Silkscreen border, target rectangle and central rim alignment marks.
mark_y = front_face_y - 0.00065
for side in (-1, 1):
    v4.box(f"board_border_side_{side}", (0.014, 0.0013, 0.686),
           (side * 0.514, mark_y, BOARD_Z), bevel=0.001, material=white, body=board_body)
for side in (-1, 1):
    v4.box(f"board_border_rail_{side}", (1.014, 0.0013, 0.014),
           (0, mark_y, BOARD_Z + side * 0.344), bevel=0.001, material=white, body=board_body)
target_z = 3.34
for side in (-1, 1):
    v4.box(f"target_square_side_{side}", (0.012, 0.0015, 0.45),
           (side * 0.300, front_face_y - 0.0011, target_z), bevel=0.001,
           material=white, body=board_body)
for side in (-1, 1):
    v4.box(f"target_square_bar_{side}", (0.60, 0.0015, 0.012),
           (0, front_face_y - 0.0011, target_z + side * 0.219), bevel=0.001,
           material=white, body=board_body)

# Rear frame: horizontal steel rails, outer uprights, centre plate and fasteners.
rear_y = BOARD_Y + 0.021
for idx, z in enumerate((3.045, 3.515)):
    v4.box(f"rear_board_crossrail_{idx}", (0.91, 0.024, 0.036),
           (0, rear_y + 0.012, z), bevel=0.004, material=steel, body=board_body)
for sx in (-1, 1):
    v4.box(f"rear_board_upright_{sx}", (0.035, 0.024, 0.47),
           (sx * 0.42, rear_y + 0.012, 3.28), bevel=0.004, material=steel, body=board_body)
v4.box("rear_board_centre_plate", (0.20, 0.012, 0.27),
       (0, rear_y + 0.006, 3.28), bevel=0.005, material=black_steel, body=board_body)
for sx in (-1, 1):
    for z in (3.045, 3.515):
        bolt(f"rear_frame_bolt_{sx}_{z}", (sx * 0.41, rear_y + 0.026, z),
             radius=0.0065, length=0.004, axis="Y", material=steel_edge)

# Two square carriage yokes surround the moving upper mast. The 6 mm pockets
# around the 94 mm mast are occupied by polymer sliding pads, leaving no loose
# or free-floating parts and retaining the board on the pole throughout travel.
def carriage_yoke(name, zc):
    thick, outer_h, inner_h, zth = 0.010, 0.126, 0.106, 0.062
    # Front and rear bridge plates; side plates meet them edge to edge.
    for sy in (-1, 1):
        v4.box(f"{name}_bridge_{sy}", (inner_h, thick, zth),
               (0, MAST_Y + sy * (inner_h / 2 + thick / 2), zc), bevel=0.002,
               material=black_steel, body=board_body)
        v4.box(f"{name}_guide_pad_y_{sy}", (0.060, 0.006, 0.040),
               (0, MAST_Y + sy * 0.050, zc), bevel=0.002, material=guide_mat, body=board_body)
    for sx in (-1, 1):
        v4.box(f"{name}_side_{sx}", (thick, inner_h, zth),
               (sx * (inner_h / 2 + thick / 2), MAST_Y, zc), bevel=0.002,
               material=black_steel, body=board_body)
        v4.box(f"{name}_guide_pad_x_{sx}", (0.006, 0.060, 0.040),
               (sx * 0.050, MAST_Y, zc), bevel=0.002, material=guide_mat, body=board_body)
    # Exposed clamping ears and their through-bolts on each side.
    for sx in (-1, 1):
        v4.box(f"{name}_clamp_ear_{sx}", (0.022, 0.040, 0.054),
               (sx * 0.074, MAST_Y, zc), bevel=0.003, material=steel, body=board_body)
        bolt(f"{name}_clamp_bolt_{sx}", (sx * 0.088, MAST_Y, zc),
             radius=0.008, length=0.006, axis="X", material=steel_edge)


carriage_yoke("lower_carriage_yoke", 2.82)
carriage_yoke("upper_carriage_yoke", 3.08)

# The pair of welded cantilever braces joins the two yokes to the board's rear
# steel rails. Upper and lower braces make a rigid, triangular retained mount.
for sx in (-1, 1):
    v4.rod(f"upper_backboard_brace_{sx}", (sx * 0.080, MAST_Y, 3.08),
           (sx * 0.34, rear_y + 0.018, 3.515), 0.018, bevel=0.0015,
           material=steel, body=board_body)
    v4.rod(f"lower_backboard_brace_{sx}", (sx * 0.080, MAST_Y, 2.82),
           (sx * 0.34, rear_y + 0.018, 3.045), 0.018, bevel=0.0015,
           material=steel, body=board_body)
# Front rim mounting plate bolts through the board into its rear centre plate.
rim_plate_y = front_face_y - 0.008
v4.box("orange_rim_mounting_plate", (0.19, 0.014, 0.17),
       (0, rim_plate_y, 3.035), bevel=0.008, material=orange, body=board_body)
for sx in (-1, 1):
    for sz in (-1, 1):
        bolt(f"rim_plate_bolt_{sx}_{sz}", (sx * 0.064, rim_plate_y - 0.010, 3.035 + sz * 0.052),
             radius=0.008, length=0.004, axis="Y", material=steel_edge)

# Regulation-size orange steel rim and its radial welded support brackets.
v4.torus("orange_18in_rim", 0.226, 0.010, (0, RIM_Y, RIM_Z), segments=96,
         ring_segments=20, material=orange, body=board_body)
for sx in (-1, 1):
    v4.rod(f"rim_radial_support_{sx}", (sx * 0.047, front_face_y - 0.014, RIM_Z),
           (sx * 0.115, RIM_Y + 0.212, RIM_Z), 0.010, segments=20, bevel=0.001,
           material=orange, body=board_body)
v4.rod("rim_rear_crossbar", (-0.115, RIM_Y + 0.212, RIM_Z),
       (0.115, RIM_Y + 0.212, RIM_Z), 0.010, segments=20, bevel=0.001,
       material=orange, body=board_body)
for sx in (-1, 1):
    v4.box(f"rim_weld_tab_{sx}", (0.045, 0.018, 0.018),
           (sx * 0.090, RIM_Y + 0.205, RIM_Z), bevel=0.004,
           material=orange, body=board_body)

# A white braided, tapered net with a small reinforced lower hoop.
bottom_z = RIM_Z - 0.30
v4.torus("net_lower_gather_ring", 0.118, 0.0027, (0, RIM_Y, bottom_z), segments=64,
         ring_segments=10, material=net_mat, body=board_body)
for i in range(12):
    a0 = 2 * math.pi * i / 12
    a1 = a0 + math.pi / 12
    top = (0.226 * math.cos(a0), RIM_Y + 0.226 * math.sin(a0), RIM_Z - 0.010)
    mid = (0.175 * math.cos(a1), RIM_Y + 0.175 * math.sin(a1), RIM_Z - 0.155)
    bot = (0.118 * math.cos(a1), RIM_Y + 0.118 * math.sin(a1), bottom_z)
    v4.tube(f"net_cord_{i:02d}", [top, mid, bot], 0.0026,
            material=net_mat, body=board_body, resolution=16)

# Small board maker's mark on the rear frame center plate.
rear_brand_y = rear_y + 0.012 - 0.006 - 0.001
v4.text("backboard_brand_text", "ADJUSTABLE 44", size=0.027,
        loc=(0, rear_brand_y, 3.28), rot=(math.pi / 2, 0, 0), material=white,
        body=board_body, on="auto", height=0.0009)

# Two real prismatic relationships. Pole and board joints use their retained
# guide mechanisms as the actual mounting interfaces; zero is the shown pose.
v4.joint("mast_height", "prismatic", base_body, pole_body,
         origin=(0, MAST_Y, 1.10), axis=(0, 0, 1), limits=(0.0, 0.18))
v4.joint("backboard_height", "prismatic", pole_body, board_body,
         origin=(0, MAST_Y, 2.90), axis=(0, 0, 1), limits=(-0.76, 0.0))

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