"""Detailed articulated rechargeable sonic toothbrush. Run with Blender's Python."""
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: warm white gloss shell, teal elastomer, and restrained metal accents.
shell = v4.plastic("Porcelain white polymer", (0.91, 0.93, 0.91), roughness=0.24, texture=0.04)
teal = v4.rubber("Deep teal soft touch", (0.035, 0.22, 0.23))
teal_gloss = v4.plastic("Teal trim", (0.025, 0.28, 0.29), roughness=0.25, texture=0.02)
metal = v4.metal("Satin champagne alloy", color=(0.72, 0.58, 0.36), roughness=0.32, brushed=True)
steel = v4.metal("Shaft stainless steel", color=(0.72, 0.76, 0.77), roughness=0.28, brushed=True)
dark = v4.mat("Graphite inset", (0.055, 0.08, 0.085), roughness=0.45)
wellmat = v4.mat("Deep teal control recess", (0.035, 0.105, 0.112), roughness=0.5)
blue = v4.plastic("Pale blue nylon", (0.52, 0.79, 0.88), roughness=0.4, texture=0)
white = v4.plastic("Soft white nylon", (0.94, 0.96, 0.90), roughness=0.38, texture=0)
mint = v4.plastic("Mint polishing tuft", (0.25, 0.72, 0.59), roughness=0.38, texture=0)
amber = v4.emissive("Amber status LED", (1.0, 0.48, 0.08), strength=1.8)

grip = v4.body("grip")
button = v4.body("button")
head = v4.body("head")

def rounded_loft(name, sections, material, body, n=128, exponent=3.0, subdivisions=6):
    """Build a smoothly sampled superelliptic shell through rounded profile stations."""
    # Catmull-Rom interpolation through the profile dimensions removes hard shoulder
    # changes while preserving the stations as exact silhouette anchors.
    samples=[]
    for i in range(len(sections)-1):
        p0=sections[max(0,i-1)]; p1=sections[i]
        p2=sections[i+1]; p3=sections[min(len(sections)-1,i+2)]
        for step in range(subdivisions):
            t=step/subdivisions; t2=t*t; t3=t2*t
            vals=[p1[0]+(p2[0]-p1[0])*t]
            for d in range(1,len(p1)):
                v=0.5*((2*p1[d])+(-p0[d]+p2[d])*t+(2*p0[d]-5*p1[d]+4*p2[d]-p3[d])*t2+
                       (-p0[d]+3*p1[d]-3*p2[d]+p3[d])*t3)
                vals.append(max(0.0001,v) if d in (1,2) else v)
            samples.append(tuple(vals))
    samples.append(tuple(sections[-1]))
    verts, faces = [], []
    for z, rx, ry, cy in samples:
        for k in range(n):
            a = 2 * math.pi * k / n
            ca, sa = math.cos(a), math.sin(a)
            x = rx * math.copysign(abs(ca) ** (2.0 / exponent), ca)
            y = cy + ry * math.copysign(abs(sa) ** (2.0 / exponent), sa)
            verts.append((x, y, z))
    for j in range(len(samples) - 1):
        for k in range(n):
            a = j*n+k
            b = j*n+(k+1)%n
            faces.append((a,b,b+n,a+n))
    faces.append(tuple(range(n-1,-1,-1)))
    start=(len(samples)-1)*n
    faces.append(tuple(start+k for k in range(n)))
    mesh=bpy.data.meshes.new(name+"Mesh")
    mesh.from_pydata(verts, [], faces); mesh.materials.append(material); mesh.update()
    obj=bpy.data.objects.new(name, mesh); bpy.context.scene.collection.objects.link(obj)
    for p in mesh.polygons: p.use_smooth=True
    v4.part(obj, body)
    return obj

# Main handle, with a narrowed waist and softly flared shoulder. Bottom is above the
# ground plane just enough to retain the rounded heel.
handle = rounded_loft("Moulded_handle_shell", [
    (0.004,0.010,0.009,0.000),(0.006,0.014,0.012,0.000),
    (0.012,0.016,0.013,0.000),(0.025,0.016,0.013,0.000),
    (0.043,0.015,0.0125,0.000),(0.070,0.0155,0.013,0.000),
    (0.094,0.0165,0.0135,0.000),(0.108,0.016,0.013,0.000),
    (0.116,0.013,0.010,0.000),(0.121,0.010,0.008,0.000)], shell, grip)

# A deep, radiused control pocket gives the rocker clear space throughout its full
# travel. Its rear wall sits behind the button's inward-swept back face.
control_cutter = v4.box("Control_pocket_cutter", (0.0205,0.0148,0.0265),
                        (0,-0.0126,0.087), bevel=0.0035)
v4.boolean(handle, control_cutter)

def rear_surface_y(x, z):
    """Evaluate the handle's positive-Y superellipse and offset it 1.5 mm."""
    profile = [(0.004,0.010,0.009),(0.006,0.014,0.012),(0.012,0.016,0.013),
               (0.025,0.016,0.013),(0.043,0.015,0.0125),(0.070,0.0155,0.013),
               (0.094,0.0165,0.0135),(0.108,0.016,0.013),(0.116,0.013,0.010),
               (0.121,0.010,0.008)]
    for a,b in zip(profile,profile[1:]):
        if a[0] <= z <= b[0]:
            t=(z-a[0])/(b[0]-a[0])
            rx=a[1]*(1-t)+b[1]*t; ry=a[2]*(1-t)+b[2]*t
            return ry * max(0.0,1.0-(abs(x)/rx)**3.0)**(1.0/3.0) + 0.0015
    raise ValueError("rear panel sample outside handle")

# A capsule-shaped rear overlay, sampled directly on the curved handle surface. The
# round ends are continuous and the visible face stays 1.5 mm proud of the shell.
pad_verts=[]; pad_faces=[]
pad_rows=40; pad_cols=31
for iz in range(pad_rows):
    z=0.0205+(0.0895-0.0205)*iz/(pad_rows-1)
    if z < 0.033:
        t=(z-0.033)/0.013
    elif z > 0.077:
        t=(z-0.077)/0.013
    else:
        t=0.0
    halfw=0.013*math.sqrt(max(0.002,1.0-t*t))
    for ix in range(pad_cols):
        x=-halfw+2*halfw*ix/(pad_cols-1)
        pad_verts.append((x,rear_surface_y(x,z),z))
for iz in range(pad_rows-1):
    for ix in range(pad_cols-1):
        a=iz*pad_cols+ix
        # Order vertices for outward (+Y) normals.
        pad_faces.append((a,a+pad_cols,a+pad_cols+1,a+1))
pad_mesh=bpy.data.meshes.new("Rear_grip_inlayMesh")
pad_mesh.from_pydata(pad_verts,[],pad_faces); pad_mesh.materials.append(teal); pad_mesh.update()
pad=bpy.data.objects.new("Rear_grip_inlay",pad_mesh); bpy.context.scene.collection.objects.link(pad)
for poly in pad_mesh.polygons: poly.use_smooth=True
solid=pad.modifiers.new("Inlay backing thickness","SOLIDIFY"); solid.thickness=0.0011; solid.offset=-1.0
edge=pad.modifiers.new("Soft inlay edge","BEVEL"); edge.width=0.00045; edge.segments=3
v4.part(pad,grip)
# Fine molded transverse grip ribs on the back panel.
for i,z in enumerate((0.032,0.038,0.044,0.050,0.056,0.062,0.068,0.074,0.080)):
    v4.box("Grip_rib_%02d"%i,(0.020,0.00045,0.0011),(0,0.0148,z),bevel=0.00035,material=teal_gloss,body=grip)

# Lower service cap seam and a tiny inset heel detail.
v4.torus("Battery_cap_seam",0.0121,0.00042,(0,0,0.015),rot=(math.pi/2,0,0),material=metal,body=grip)
v4.box("Heel_cap_flat",(0.018,0.004,0.004),(0,0,0.006),bevel=0.0015,material=teal_gloss,body=grip)
# Charging contacts sit flush on the rear-facing heel, inset from the base.
for i,x in enumerate((-0.0045,0.0045)):
    v4.cylinder("Charging_contact_%d"%i,0.0022,0.0012,(x,0.0108,0.010),rot=(math.pi/2,0,0),segments=32,bevel=0.00025,material=metal,body=grip)

# Neck fairing and metal drive spindle are part of the fixed grip assembly.
rounded_loft("Neck_fairing",[(0.112,0.0090,0.0075,0),(0.119,0.0075,0.0065,0),
    (0.128,0.0062,0.0055,0),(0.151,0.0052,0.0048,0),(0.163,0.0050,0.0046,0)],shell,grip)
v4.cylinder("Exposed_drive_spindle",0.0023,0.038,(0,0,0.148),segments=32,bevel=0.0003,material=steel,body=grip)
# Hinge fork and transverse pin; visible shoulders flank the rotating head hub.
v4.cylinder("Head_hinge_pin",0.0018,0.018,(0,0,0.169),rot=(0,math.pi/2,0),segments=32,bevel=0.00025,material=metal,body=grip)
for sx in (-1,1):
    v4.cylinder("Pin_end_%s"%sx,0.0021,0.0009,(sx*0.0090,0,0.169),rot=(0,math.pi/2,0),segments=32,bevel=0.0002,material=metal,body=grip)
# Narrow champagne collar below the spindle/head connection.
v4.torus("Neck_collar",0.0062,0.00075,(0,0,0.126),material=metal,body=grip)
# A defined ferrule caps the fixed drive shaft just below the articulating head hub.
v4.torus("Drive_shaft_ferrule",0.0048,0.00055,(0,0,0.163),
        material=metal,body=grip)

# Matte recess floor sits 3 mm behind the button's furthest inward swept face.
# It slightly overlaps the pocket's rear edge so it remains integrated with the shell.
# Recessed metal bezel strips sit flush with the pocket lip, clear of the moving cap.
for sx in (-1,1):
    v4.box("Bezel_side_%s"%sx,(0.0014,0.0008,0.0245),(sx*0.0103,-0.0122,0.087),
           bevel=0.00045,material=metal,body=grip)
for sz in (-1,1):
    v4.box("Bezel_end_%s"%sz,(0.0205,0.0008,0.0013),(0,-0.0122,0.087+sz*0.0137),
           bevel=0.0004,material=metal,body=grip)
v4.box("Control_well",(0.0225,0.0012,0.0285),(0,-0.0058,0.087),bevel=0.0045,material=wellmat,body=grip)
# Small battery/status bars below the rocker.
for i,z in enumerate((0.104,0.107,0.110)):
    v4.sphere("Battery_level_led_%d"%i,0.0008,(0,-0.0128,z),segments=16,material=amber if i==2 else teal_gloss,body=grip)
v4.text("Handle_brand", "SONA", 0.0044, loc=(0,-0.0137,0.055), rot=(math.pi/2,0,0),
        extrude_depth=0.00025, material=teal_gloss, body=grip, on=handle, height=0.00035)
v4.text("Handle_model", "SONIC  |  2", 0.0021, loc=(0,-0.0138,0.048), rot=(math.pi/2,0,0),
        extrude_depth=0.00015, material=metal, body=grip, on=handle, height=0.0002)

# Rocker button body: a narrow gold rim under the elastomer cap, both carried on the
# central transverse axle. The fixed backing remains deep in the handle pocket.
v4.box("Rocker_cap",(0.0142,0.00125,0.0188),(0,-0.01315,0.087),bevel=0.0050,material=teal,body=button)
v4.torus("Power_icon_ring",0.0027,0.00027,(0,-0.01410,0.0861),rot=(math.pi/2,0,0),material=white,body=button)
v4.rod("Power_icon_stroke",(0,-0.01418,0.0878),(0,-0.01418,0.0911),0.00031,material=white,body=button)
v4.cylinder("Rocker_hinge_pin",0.0016,0.018,(0,-0.0135,0.078),rot=(0,math.pi/2,0),segments=24,bevel=0.0002,material=metal,body=button)
# Concealed fixed hinge arms bridge the axle ends to the recessed well. The pin remains
# coaxial, so the rocker can rotate without the supports crossing its swept volume.
for sx in (-1,1):
    v4.rod("Rocker_axle_support_%s"%sx,(sx*0.009,-0.0050,0.078),(sx*0.009,-0.0135,0.078),
           0.00065,material=metal,body=grip)

# Hinged head shell with a compact rounded rectangle footprint, approximately 29 x 18 mm.
# The lower bearing hub is concentric with the pin and the oval brush head rises from it.
v4.cylinder("Head_bearing_sleeve",0.0035,0.0155,(0,0,0.169),rot=(0,math.pi/2,0),segments=64,bevel=0.00065,material=shell,body=head)
for sx in (-1,1):
    v4.torus("Hinge_seal_%s"%sx,0.00335,0.00038,(sx*0.0076,0,0.169),rot=(0,math.pi/2,0),
             material=teal_gloss,body=head)
rounded_loft("Brush_head_shell",[(0.173,0.0058,0.0048,0),(0.176,0.0070,0.0055,0),
    (0.179,0.0079,0.0059,0),(0.194,0.0079,0.0059,0),(0.198,0.0070,0.0051,0),
    (0.199,0.0054,0.0043,0)],shell,head,exponent=2.8)
# Dark inset bristle plate on the -Y face, following the outer capsule footprint.
rounded_loft("Inset_bristle_plate",[(0.177,0.0067,0.0004,-0.00625),
    (0.178,0.0070,0.00055,-0.00640),(0.183,0.0071,0.00062,-0.00657),
    (0.189,0.0071,0.00062,-0.00657),(0.194,0.0070,0.00055,-0.00640),
    (0.195,0.0064,0.0004,-0.00620)],dark,head,exponent=2.8)
# Closely spaced tuft clusters made from fine individual nylon filaments. Longer
# center fibers and shorter perimeter fibers give the working face a gentle crown.
for row in range(11):
    z=0.1780+row*0.00148
    for col in range(10):
        x=-0.0060+col*0.00132+(0.00016 if row%2 else 0.0)
        if col==9 and row%2:
            continue
        x += 0.00008*math.sin(row*4.7+col*2.3)
        zc=z+0.00007*math.sin(col*3.1-row*1.9)
        mat=(mint if col in (3,4,5) and row in (3,4,5,6) else
             (blue if (row//2+col//2)%3==0 else white))
        length=0.00550-0.00065*(abs(x)/0.0069)**2-0.00026*(abs(zc-0.1854)/0.0077)**2
        offsets=[(0,0),(0.00021,0),(-0.00021,0),(0,0.00021),(0,-0.00021),
                 (0.00015,0.00015),(-0.00015,-0.00015)]
        # One connected tuft mesh keeps the fine filaments individually visible while
        # avoiding hundreds of separate rigid shapes in downstream articulation checks.
        tuft_verts=[(x,-0.00692,zc)]
        tuft_faces=[]
        sides=6
        for strand,(dx,dz) in enumerate(offsets):
            tx=x+dx; tz=zc+dz
            root=[]; tip=[]
            for radius, yy, ring in ((0.000052,-0.00692,root),(0.000040,-0.00692-length,tip)):
                for k in range(sides):
                    a=2*math.pi*k/sides
                    ring.append(len(tuft_verts))
                    tuft_verts.append((tx+radius*math.cos(a),yy,tz+radius*math.sin(a)))
            for k in range(sides):
                kn=(k+1)%sides
                tuft_faces.append((0,root[k],root[kn]))
                tuft_faces.append((root[k],tip[k],tip[kn],root[kn]))
            tuft_faces.append(tuple(reversed(tip)))
        mesh=bpy.data.meshes.new("Bristle_tuft_%02d_%02dMesh"%(row,col))
        mesh.from_pydata(tuft_verts,[],tuft_faces); mesh.materials.append(mat); mesh.update()
        tuft=bpy.data.objects.new("Bristle_tuft_%02d_%02d"%(row,col),mesh)
        bpy.context.scene.collection.objects.link(tuft)
        for poly in mesh.polygons: poly.use_smooth=True
        v4.part(tuft,head)

# Real revolute joints, both with small travel about transverse X pins.
v4.joint("button_rocker","revolute",grip,button,origin=(0,-0.0135,0.078),axis=(1,0,0),
         limits=(-math.radians(12),math.radians(12)))
v4.joint("head_hinge","revolute",grip,head,origin=(0,0,0.169),axis=(1,0,0),
         limits=(-math.radians(14),math.radians(14)))

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