"""Parametric articulated electric toothbrush.

Run from this directory with the task Blender binary:
    blender -b --python build.py
"""
import math
import os
import sys

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


v4.reset()

# ---- materials ----------------------------------------------------------------------
shell = v4.plastic("pearl_white_ABS", (0.90, 0.93, 0.92), roughness=0.28, texture=0.07)
rubber = v4.rubber("deep_teal_elastomer", (0.025, 0.16, 0.18), roughness=0.78)
panel = v4.plastic("switch_panel_teal", (0.018, 0.10, 0.12), roughness=0.48, texture=0.12)
base_trim = v4.plastic("base_graphite", (0.12, 0.15, 0.15), roughness=0.43, texture=0.08)
chrome = v4.metal("satin_stainless", color=(0.70, 0.73, 0.73), roughness=0.26, brushed=True)
bright_chrome = v4.metal("polished_pivot_steel", color=(0.84, 0.87, 0.87), roughness=0.19, brushed=False)
blue = v4.plastic("aqua_accent", (0.06, 0.48, 0.58), roughness=0.27, texture=0.04)
button_mat = v4.plastic("soft_aqua_switch", (0.24, 0.72, 0.73), roughness=0.3, texture=0.05)
button_ink = v4.mat("button_symbol_white", (0.94, 0.98, 0.96), roughness=0.33)
plate_mat = v4.plastic("bristle_plate_ceramic", (0.84, 0.90, 0.89), roughness=0.4, texture=0.06)
bristle_white = v4.plastic("nylon_ivory", (0.96, 0.97, 0.93), roughness=0.38, texture=0.035)
bristle_blue = v4.plastic("nylon_blue", (0.13, 0.48, 0.65), roughness=0.39, texture=0.035)
led_mat = v4.emissive("blue_status_light", (0.16, 0.68, 0.95), strength=1.3)
dark_ink = v4.mat("marking_dark_teal", (0.04, 0.20, 0.23), roughness=0.5)

# ---- helpers for smooth, variable-section molded shells -------------------------------
def _expanded_profile(profile, steps=3):
    """Linearly insert profile rings so the loft has a smooth silhouette."""
    out = []
    for i in range(len(profile) - 1):
        a, b = profile[i], profile[i + 1]
        for j in range(steps):
            t = j / steps
            out.append(tuple(a[k] * (1.0 - t) + b[k] * t for k in range(3)))
    out.append(tuple(profile[-1]))
    return out


def _front_material_for_handle(z, theta):
    a = abs(theta)
    # Soft-touch oval panel on the forward gripping surface; its narrow ends are rounded.
    dz = abs(z - 0.049)
    max_a = 0.64
    if dz > 0.021:
        cap = max(0.0, min(1.0, (0.031 - dz) / 0.010))
        max_a *= math.sqrt(cap)
    if 0.018 < z < 0.080 and a < max_a:
        # The elastomer grip is a separate conforming mesh overlay so its outline
        # can have smooth molded radii rather than a faceted material boundary.
        return 0
    # Dark molded switch island follows the compact bezel perimeter with a clean seam.
    panel_z = 0.0099
    dz = abs(z - 0.1140)
    if dz < panel_z:
        exponent = 1.0 / 0.62
        outline = max(0.0, 1.0 - (dz / panel_z) ** exponent)
        panel_x = 0.0077 * outline ** (1.0 / exponent)
        rx, _ = _section_at(handle_profile, z)
        panel_a = math.asin(min(0.999, panel_x / max(rx, 1e-6)))
        if a < panel_a:
            return 2
    if 0.0055 < z < 0.0085:
        return 3
    # Relief collar surface is given its own metal finish.
    if 0.1435 < z < 0.1482:
        return 4
    if 0.1490 < z < 0.1512:
        return 5
    return 0


def _make_loft(name, profile, material_list, body, material_rule=None,
               center_y=0.0, segments=112, steps=3):
    """Closed elliptic loft around Z. Profile entries are (z, radius_x, radius_y)."""
    p = _expanded_profile(profile, steps)
    verts = []
    for z, rx, ry in p:
        for k in range(segments):
            th = 2.0 * math.pi * k / segments
            verts.append((rx * math.sin(th), center_y - ry * math.cos(th), z))
    faces, face_mats = [], []
    for r in range(len(p) - 1):
        zm = (p[r][0] + p[r + 1][0]) * 0.5
        for k in range(segments):
            kn = (k + 1) % segments
            # theta first, then Z: outward normals point away from the loft axis.
            faces.append((r * segments + k,
                          r * segments + kn,
                          (r + 1) * segments + kn,
                          (r + 1) * segments + k))
            th = 2.0 * math.pi * (k + 0.5) / segments
            face_mats.append(material_rule(zm, th) if material_rule else 0)
    bottom_center = len(verts)
    verts.append((0.0, center_y, p[0][0]))
    top_center = len(verts)
    verts.append((0.0, center_y, p[-1][0]))
    for k in range(segments):
        kn = (k + 1) % segments
        faces.append((bottom_center, kn, k))
        face_mats.append(0)
        off = (len(p) - 1) * segments
        faces.append((top_center, off + k, off + kn))
        face_mats.append(0)

    mesh = bpy.data.meshes.new(name + "_mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.materials.clear()
    for m in material_list:
        mesh.materials.append(m)
    mesh.update()
    for poly, mi in zip(mesh.polygons, face_mats):
        poly.material_index = mi
        poly.use_smooth = len(poly.vertices) == 4
    ob = bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.objects.link(ob)
    # The face loops are consistently wound; keep the loft smooth but retain flat end caps.
    wn = ob.modifiers.new("Weighted corner normals", "WEIGHTED_NORMAL")
    wn.keep_sharp = True
    wn.weight = 35
    v4.part(ob, body)
    return ob, p


def _section_at(profile, z):
    if z <= profile[0][0]:
        return profile[0][1], profile[0][2]
    if z >= profile[-1][0]:
        return profile[-1][1], profile[-1][2]
    for a, b in zip(profile, profile[1:]):
        if a[0] <= z <= b[0]:
            t = (z - a[0]) / (b[0] - a[0])
            return a[1] * (1 - t) + b[1] * t, a[2] * (1 - t) + b[2] * t
    return profile[-1][1], profile[-1][2]


def _surface_front(profile, x, z):
    rx, ry = _section_at(profile, z)
    q = max(0.04, 1.0 - (x / max(rx, 1e-6)) ** 2)
    return -ry * math.sqrt(q)


def _make_domed_switch(name, body, profile, center_x, center_z, half_x, half_z,
                       surface_gap=0.00018, dome=0.0016, segments=48, radial=9):
    """A thin domed switch cap whose rim follows the handle's curved face."""
    verts = []
    rings_front, rings_back = [], []
    rs = [0.0] + [i / radial for i in range(1, radial + 1)]
    # Slightly elliptical round-corner outline.
    for r in rs:
        fr, br = [], []
        for k in range(segments):
            th = 2.0 * math.pi * k / segments
            # A mild superellipse keeps the button broad and pill-shaped, not spherical.
            c = math.copysign(abs(math.cos(th)) ** 0.88, math.cos(th))
            s = math.copysign(abs(math.sin(th)) ** 0.88, math.sin(th))
            x = center_x + half_x * r * c
            z = center_z + half_z * r * s
            sy = _surface_front(profile, x, z)
            back_y = sy - surface_gap
            front_y = back_y - dome * math.sqrt(max(0.0, 1.0 - r * r))
            fr.append(len(verts))
            verts.append((x, front_y, z))
            br.append(len(verts))
            verts.append((x, back_y, z))
        rings_front.append(fr)
        rings_back.append(br)

    faces = []
    # Front dome and conforming back skin. The back skin stays a fraction of a mm clear of the grip.
    for r in range(len(rs) - 1):
        for k in range(segments):
            kn = (k + 1) % segments
            faces.append((rings_front[r][k], rings_front[r][kn],
                          rings_front[r + 1][kn], rings_front[r + 1][k]))
            faces.append((rings_back[r][kn], rings_back[r][k],
                          rings_back[r + 1][k], rings_back[r + 1][kn]))
    # The innermost front/back rings meet; close the perimeter edge.
    for k in range(segments):
        kn = (k + 1) % segments
        faces.append((rings_front[-1][k], rings_front[-1][kn],
                      rings_back[-1][kn], rings_back[-1][k]))
    # Close the centre of each skin with a tiny polygon fan.
    for skin in (rings_front[0], rings_back[0]):
        cx = sum(verts[i][0] for i in skin) / segments
        cy = sum(verts[i][1] for i in skin) / segments
        cz = sum(verts[i][2] for i in skin) / segments
        ci = len(verts)
        verts.append((cx, cy, cz))
        for k in range(segments):
            kn = (k + 1) % segments
            if skin is rings_front[0]:
                faces.append((ci, skin[k], skin[kn]))
            else:
                faces.append((ci, skin[kn], skin[k]))
    mesh = bpy.data.meshes.new(name + "_mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.materials.append(button_mat)
    mesh.update()
    for poly in mesh.polygons:
        poly.use_smooth = True
    ob = bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.objects.link(ob)
    v4.part(ob, body)
    return ob


def _make_switch_bezel(name, body, profile, center_x, center_z,
                       outer_x=0.0079, outer_z=0.0101,
                       inner_x=0.00685, inner_z=0.0087,
                       segments=72, relief=0.00030, thickness=0.00075):
    """Rounded annular bezel seated on the curved shell around the rocker pocket."""
    verts, loops = [], []
    # A soft superellipse gives a molded capsule-like frame rather than sharp corners.
    for hx, hz, offset in ((outer_x, outer_z, -relief),
                           (inner_x, inner_z, -relief),
                           (outer_x, outer_z, thickness),
                           (inner_x, inner_z, thickness)):
        ring = []
        for k in range(segments):
            th = 2.0 * math.pi * k / segments
            c = math.copysign(abs(math.cos(th)) ** 0.62, math.cos(th))
            s = math.copysign(abs(math.sin(th)) ** 0.62, math.sin(th))
            x, z = center_x + hx * c, center_z + hz * s
            y = _surface_front(profile, x, z) + offset
            ring.append(len(verts))
            verts.append((x, y, z))
        loops.append(ring)
    outer_front, inner_front, outer_back, inner_back = loops
    faces = []
    for k in range(segments):
        kn = (k + 1) % segments
        faces.append((outer_front[k], inner_front[k], inner_front[kn], outer_front[kn]))
        faces.append((outer_back[kn], inner_back[kn], inner_back[k], outer_back[k]))
        faces.append((outer_front[kn], outer_back[kn], outer_back[k], outer_front[k]))
        faces.append((inner_front[k], inner_back[k], inner_back[kn], inner_front[kn]))
    mesh = bpy.data.meshes.new(name + "_mesh")
    mesh.from_pydata(verts, [], faces)
    bm = bmesh.new()
    bm.from_mesh(mesh)
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    bm.to_mesh(mesh)
    bm.free()
    mesh.materials.append(panel)
    mesh.update()
    for poly in mesh.polygons:
        poly.use_smooth = True
    ob = bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.objects.link(ob)
    bevel = ob.modifiers.new("soft molded bezel edge", "BEVEL")
    bevel.width = 0.00018
    bevel.segments = 3
    bevel.limit_method = "ANGLE"
    v4.part(ob, body)
    return ob


def _make_rounded_grip_panel(name, body, profile, center_z,
                             half_x=0.0086, half_z=0.0310,
                             segments=96, radial=12,
                             relief=0.00035, embed=0.00022):
    """Solid soft-touch pad following the front curvature of the handle."""
    verts, front_rings, back_rings = [], [], []
    cy = center_z
    center_surface = _surface_front(profile, 0.0, cy)
    front_center = len(verts)
    verts.append((0.0, center_surface - relief, cy))
    back_center = len(verts)
    verts.append((0.0, center_surface + embed, cy))
    for ri in range(1, radial + 1):
        r = ri / radial
        front, back = [], []
        for k in range(segments):
            th = 2.0 * math.pi * k / segments
            c = math.copysign(abs(math.cos(th)) ** 0.55, math.cos(th))
            s = math.copysign(abs(math.sin(th)) ** 0.55, math.sin(th))
            x = half_x * r * c
            z = center_z + half_z * r * s
            surface = _surface_front(profile, x, z)
            front.append(len(verts))
            verts.append((x, surface - relief, z))
            back.append(len(verts))
            verts.append((x, surface + embed, z))
        front_rings.append(front)
        back_rings.append(back)

    faces = []
    first_f, first_b = front_rings[0], back_rings[0]
    for k in range(segments):
        kn = (k + 1) % segments
        faces.append((front_center, first_f[k], first_f[kn]))
        faces.append((back_center, first_b[kn], first_b[k]))
    for ri in range(radial - 1):
        f0, f1 = front_rings[ri], front_rings[ri + 1]
        b0, b1 = back_rings[ri], back_rings[ri + 1]
        for k in range(segments):
            kn = (k + 1) % segments
            faces.append((f0[k], f1[k], f1[kn], f0[kn]))
            faces.append((b0[kn], b1[kn], b1[k], b0[k]))
    outer_f, outer_b = front_rings[-1], back_rings[-1]
    for k in range(segments):
        kn = (k + 1) % segments
        faces.append((outer_f[k], outer_f[kn], outer_b[kn], outer_b[k]))

    mesh = bpy.data.meshes.new(name + "_mesh")
    mesh.from_pydata(verts, [], faces)
    bm = bmesh.new()
    bm.from_mesh(mesh)
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    bm.to_mesh(mesh)
    bm.free()
    mesh.materials.append(rubber)
    mesh.update()
    for poly in mesh.polygons:
        poly.use_smooth = True
    ob = bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.objects.link(ob)
    bevel = ob.modifiers.new("soft elastomer perimeter", "BEVEL")
    bevel.width = 0.00013
    bevel.segments = 2
    bevel.limit_method = "ANGLE"
    v4.part(ob, body)
    return ob


def _tube_on_front(name, points, radius, material, body):
    return v4.tube(name, points, radius, material=material, body=body, resolution=16)


# ---- fixed handle, neck, drive shaft and charging base --------------------------------
handle = v4.body("handle")
handle_profile = [
    (0.0042, 0.0085, 0.0080),
    (0.0052, 0.0115, 0.0108),
    (0.0070, 0.0135, 0.0128),
    (0.0100, 0.0146, 0.0138),
    (0.0160, 0.0150, 0.0143),
    (0.0250, 0.0149, 0.0140),
    (0.0360, 0.0144, 0.0134),
    (0.0500, 0.0136, 0.0125),
    (0.0650, 0.0132, 0.0121),
    (0.0790, 0.0134, 0.0122),
    (0.0920, 0.0138, 0.0127),
    (0.1030, 0.0143, 0.0131),
    (0.1140, 0.0147, 0.0135),
    (0.1190, 0.0146, 0.0134),
    (0.1240, 0.0142, 0.0130),
    (0.1280, 0.0133, 0.0122),
    (0.1320, 0.0118, 0.0109),
    (0.1360, 0.0097, 0.0090),
    (0.1390, 0.0075, 0.0072),
    (0.1415, 0.0063, 0.0061),
    (0.1434, 0.0064, 0.0062),
    (0.1443, 0.0069, 0.0067),
    (0.1474, 0.0069, 0.0067),
    (0.1484, 0.0063, 0.0061),
    (0.1491, 0.0061, 0.0059),
    (0.1500, 0.0065, 0.0062),
    (0.1512, 0.0065, 0.0062),
    (0.1520, 0.0059, 0.0057),
    (0.1580, 0.0057, 0.0055),
    (0.1650, 0.0052, 0.0051),
    (0.1700, 0.0047, 0.0047),
    (0.1728, 0.0038, 0.0039),
    (0.1740, 0.0025, 0.0026),
]
handle_shell, _ = _make_loft(
    "ergonomic_handle_neck_and_drive_shaft", handle_profile,
    [shell, rubber, panel, base_trim, chrome, blue], handle,
    material_rule=_front_material_for_handle, segments=192, steps=8)

# Cut a rounded, shallow rocker pocket so the button can actually press into the grip.
switch_cutter = v4.box("temporary_switch_recess_cutter", (0.0200, 0.0105, 0.0260),
                       (0.0, -0.0140, 0.1140), bevel=0.0035)
v4.boolean(handle_shell, switch_cutter)
_make_switch_bezel("rounded_rocker_bezel", handle, handle_profile,
                   center_x=0.0, center_z=0.1140)
_make_rounded_grip_panel("soft_touch_front_grip_pad", handle, handle_profile,
                         center_z=0.0490)

# A shallow underside charging well with a pair of flush metal charging contacts.
v4.cylinder("charging_contact_left", 0.00155, 0.0014,
            (-0.0044, 0.0, 0.00355), segments=32, bevel=0.00015,
            material=bright_chrome, body=handle)
v4.cylinder("charging_contact_right", 0.00155, 0.0014,
            (0.0044, 0.0, 0.00355), segments=32, bevel=0.00015,
            material=bright_chrome, body=handle)

# Six low grip ribs follow the handle's molded front contour.
for i, z in enumerate((0.032, 0.040, 0.048, 0.056, 0.064, 0.072)):
    pts = []
    for j in range(9):
        x = -0.0058 + j * (0.0116 / 8)
        pts.append((x, _surface_front(handle_profile, x, z) - 0.00048, z))
    _tube_on_front(f"grip_micro_rib_{i:02d}", pts, 0.00022, panel, handle)

# Tiny status lenses below the switch; each sits directly on the molded face.
for i, z in enumerate((0.0935, 0.0970, 0.1005)):
    y = _surface_front(handle_profile, 0.0, z) - 0.00020
    v4.sphere(f"charge_led_{i+1}", 0.00073,
              (0.0, y, z), segments=24, material=led_mat, body=handle)

# Product marking on the curved front shell and a reverse-face care instruction.
v4.text("handle_brand", "NOVA", 0.0048, (0.0, -0.01245, 0.0860),
        rot=(math.pi / 2, 0, 0), material=dark_ink, body=handle,
        on=handle_shell, height=0.00016)

# ---- hinged power button on the grip ---------------------------------------------------
button = v4.body("button")
button_pivot = (0.0, -0.0092, 0.1065)
_make_domed_switch("hinged_aqua_power_button", button, handle_profile,
                   center_x=0.0, center_z=0.1140,
                   half_x=0.00635, half_z=0.0081,
                   surface_gap=0.00018, dome=0.00115)

# Raised power glyph follows the front of the domed cap.
button_face_y = _surface_front(handle_profile, 0.0, 0.1140) - 0.00182
v4.torus("power_symbol_ring", 0.00250, 0.00027,
         (0.0, button_face_y, 0.1132), rot=(math.pi / 2, 0, 0),
         segments=40, ring_segments=10, material=button_ink, body=button)
v4.rod("power_symbol_stem", (0.0, button_face_y - 0.00003, 0.1130),
       (0.0, button_face_y - 0.00003, 0.1178), 0.00027,
       segments=16, bevel=0.00008, material=button_ink, body=button)

# A compact steel trunnion stays inside the rocker pocket and is joined to the
# button through the central neck, avoiding exposed tabs beyond the bezel.
v4.rod("button_hinge_axle", (-0.0032, button_pivot[1], button_pivot[2]),
       (0.0032, button_pivot[1], button_pivot[2]), 0.00062,
       segments=24, bevel=0.00010, material=bright_chrome, body=button)
v4.rod("button_hinge_neck", (0.0, -0.01325, button_pivot[2]),
       (0.0, button_pivot[1], button_pivot[2]), 0.0010,
       segments=24, bevel=0.00010, material=bright_chrome, body=button)

v4.joint("button_hinge", "revolute", handle, button,
         origin=button_pivot, axis=(1, 0, 0),
         limits=(-0.28, 0.16))

# ---- replaceable brush head, bristle plate, and real tuft field ------------------------
head = v4.body("head")
head_profile = [
    (0.1740, 0.0065, 0.0038),
    (0.1750, 0.0072, 0.0044),
    (0.1770, 0.0082, 0.0049),
    (0.1800, 0.0087, 0.0051),
    (0.1850, 0.0090, 0.0052),
    (0.1920, 0.0089, 0.0052),
    (0.1970, 0.0086, 0.0050),
    (0.1995, 0.0077, 0.0046),
    (0.2015, 0.0058, 0.0038),
    (0.2025, 0.0032, 0.0024),
    (0.2030, 0.0007, 0.0007),
]

def _material_for_head(z, theta):
    a = abs(theta)
    # Slim molded turquoise parting seam at the replaceable-head socket.
    if 0.1745 < z < 0.1765:
        return 1
    # The front-facing bristle plate is integrated into the shell topology.
    if 0.1782 < z < 0.1985 and a < 0.89:
        return 2
    if 0.1775 < z < 0.1990 and 0.91 <= a < 0.97:
        return 3
    # A fine rear accent stripe gives the replaceable head a molded ID band.
    if 0.184 < z < 0.194 and a > 2.75:
        return 1
    return 0


head_shell, _ = _make_loft(
    "oval_brush_head_housing_and_integral_bristle_plate", head_profile,
    [shell, blue, plate_mat, chrome], head,
    material_rule=_material_for_head, segments=192, steps=8)

# Stainless pivot caps on each side of the transverse head hinge.
for side in (-1, 1):
    side_name = "left" if side < 0 else "right"
    v4.cylinder(f"head_hinge_pivot_cap_{side_name}", 0.00135, 0.0010,
                (side * 0.00735, 0.0, 0.1749),
                rot=(0, math.pi / 2, 0), segments=48, bevel=0.00012,
                material=bright_chrome, body=head)
    # A shallow dark centre dot suggests a pin head rather than a blank disk.
    v4.cylinder(f"head_hinge_pin_recess_{side_name}", 0.00034, 0.00016,
                (side * 0.00795, 0.0, 0.1749),
                rot=(0, math.pi / 2, 0), segments=24, bevel=0.00004,
                material=dark_ink, body=head)

# Each compact tuft contains 37 individual, tapered nylon filaments. The strands are
# fine (0.22 mm diameter), slightly varied in length, and rooted into the curved plate.
def _make_nylon_tuft(name, body, profile, cx, cz, material, row, col):
    verts, faces, smooth_faces = [], [], []
    # A close-packed hexagonal lattice gives the tuft a circular, bristle-dense footprint.
    # Neighboring root rings meet at shared vertices, joining the fibers into one checked part.
    pitch = 0.00028
    offsets = []
    for q in range(-3, 4):
        for r in range(-3, 4):
            if max(abs(q), abs(r), abs(q + r)) <= 3:
                offsets.append((pitch * (q + 0.5 * r),
                                pitch * (math.sqrt(3.0) * 0.5 * r)))

    sides = 6
    common_root_y = -0.0025  # roots start just inside the molded bristle plate
    for strand, (dx, dz) in enumerate(offsets):
        root_x = cx + dx
        root_z = cz + dz
        root_y = common_root_y
        plate_y = _surface_front(profile, root_x, root_z)
        length = (0.0084 + 0.00024 * ((row * 11 + col * 7 + strand * 5) % 8)
                  + root_y - plate_y)
        # Small per-fiber splay and independent endpoint variation give the tuft
        # a soft cut profile instead of one uniform, flat-ended strip.
        phase = row * 7.1 + col * 13.3 + strand * 2.399
        tip_x = cx + dx * 1.14 + 0.00018 * math.sin(phase)
        tip_z = cz + dz * 1.14 + 0.00018 * math.cos(phase * 1.13)
        # The anchor roots touch inside the plate; exposed shafts taper to fine,
        # separated filaments and flare gently at their rounded tips.
        ring_specs = ((0.0, 0.000140), (0.06, 0.000110),
                      (0.91, 0.000110), (0.986, 0.000050))
        strand_rings = []
        for t, radius in ring_specs:
            ring = []
            for k in range(sides):
                a = 2.0 * math.pi * k / sides
                x = root_x * (1.0 - t) + tip_x * t + radius * math.cos(a)
                z = root_z * (1.0 - t) + tip_z * t + radius * math.sin(a)
                y = root_y - length * t
                ring.append(len(verts))
                verts.append((x, y, z))
            strand_rings.append(ring)
        first = len(verts)
        verts.append((tip_x, root_y - length, tip_z))
        for r in range(len(strand_rings) - 1):
            lower, upper = strand_rings[r], strand_rings[r + 1]
            for k in range(sides):
                kn = (k + 1) % sides
                faces.append((lower[k], lower[kn], upper[kn], upper[k]))
                smooth_faces.append(True)
        root_center = len(verts)
        verts.append((root_x, root_y, root_z))
        for k in range(sides):
            kn = (k + 1) % sides
            faces.append((root_center, strand_rings[0][kn], strand_rings[0][k]))
            smooth_faces.append(False)
            faces.append((strand_rings[-1][k], strand_rings[-1][kn], first))
            smooth_faces.append(False)

    mesh = bpy.data.meshes.new(name + "_mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.materials.append(material)
    mesh.update()
    bm = bmesh.new()
    bm.from_mesh(mesh)
    bmesh.ops.remove_doubles(bm, verts=list(bm.verts), dist=1e-7)
    bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))
    bm.to_mesh(mesh)
    bm.free()
    mesh.update()
    for poly, smooth in zip(mesh.polygons, smooth_faces):
        poly.use_smooth = smooth
    ob = bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.objects.link(ob)
    v4.part(ob, body)
    return ob


tuft_x = (-0.0048, -0.0024, 0.0, 0.0024, 0.0048)
# Keep the 5-by-8 field inside the molded plate. Odd columns sit halfway
# between the even-column rows so the edge-on silhouette reads as a tuft field,
# not eight continuous brush-like bars.
tuft_z = (0.1796, 0.1818, 0.1840, 0.1862,
          0.1884, 0.1906, 0.1928, 0.1950)
for row, z in enumerate(tuft_z):
    for col, x in enumerate(tuft_x):
        # Aqua indicator bundles are clustered through the middle, as on many retail heads.
        material = bristle_blue if (col in (1, 3) and row in (2, 4, 6)) else bristle_white
        # Stagger neighboring tufts in both directions to break up long row lines.
        x += 0.00050 if row % 2 else -0.00050
        z += (0.00110 if col % 2 else 0.0)
        z += 0.00010 * math.sin(row * 1.13 + col * 1.71)
        _make_nylon_tuft(f"fine_nylon_tuft_{row:02d}_{col:02d}", head,
                         head_profile, x, z, material, row, col)

# Small raised brand on the rear of the brush neck. The local text-up axis maps
# to world +Z and its face normal to world +Y, so NOVA reads upright from behind.
v4.text("head_brand", "NOVA", 0.0032, (0.0, 0.0049, 0.1880),
        rot=(math.pi / 2, 0, math.pi), material=dark_ink, body=head,
        on=head_shell, height=0.00010)

v4.joint("head_hinge", "revolute", handle, head,
         origin=(0.0, 0.0, 0.1740), axis=(1, 0, 0),
         limits=(-0.20, 0.20))

# v4.save always resets to the neutral pose before writing asset.blend.
v4.save(os.path.join(os.getcwd(), "asset.blend"))
print("saved asset.blend")
