"""Detailed articulated acetate eyeglasses, authored with v4lib."""
import math
import os
import sys
import bpy
import bmesh
from mathutils import Vector

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

v4.reset()

# Realistic product materials: warm polished acetate, clear optical lenses,
# stainless hinge hardware, and soft silicone nose pieces.
acetate = v4.plastic("deep_tortoise_acetate", (0.17, 0.075, 0.032), roughness=0.22)
acetate_dark = v4.plastic("temple_dark_tortoise", (0.10, 0.042, 0.022), roughness=0.24)
amber = v4.plastic("amber_tortoise_accents", (0.30, 0.13, 0.045), roughness=0.24)
steel = v4.metal("satin_stainless", color=(0.72, 0.75, 0.78), roughness=0.28, brushed=True)
black = v4.metal("dark_hinge_steel", color=(0.16, 0.18, 0.20), roughness=0.32, brushed=False)
silicone = v4.rubber("nose_pad_silicone", (0.24, 0.27, 0.29))
lensmat = v4.glass("clear_lens", color=(0.91, 0.97, 1.0), roughness=0.08)
groove_mat = v4.plastic("eyewire_inner_groove", (0.07, 0.03, 0.016), roughness=0.3)

front = v4.body("front")
left = v4.body("temple_left")
right = v4.body("temple_right")

YF = -0.012
CZ = 0.025
LX = 0.032

def rounded_rect(cx, cz, width, height, radius, y, n=8):
    """Rounded rectangle in the front XZ plane, ordered around its perimeter."""
    pts = []
    corners = [
        (cx + width/2-radius, cz + height/2-radius, 0),
        (cx - width/2+radius, cz + height/2-radius, 90),
        (cx - width/2+radius, cz - height/2+radius, 180),
        (cx + width/2-radius, cz - height/2+radius, 270),
    ]
    # Angles traverse top-right -> top-left -> bottom-left -> bottom-right.
    for x, z, start in corners:
        for i in range(n):
            a = math.radians(start + 90*i/(n-1))
            pts.append((x + radius*math.cos(a), y, z + radius*math.sin(a)))
    return pts

def lens_outline(width, height, radius):
    pts=[]
    corners=[(width/2-radius,height/2-radius,0),(-width/2+radius,height/2-radius,90),
             (-width/2+radius,-height/2+radius,180),(width/2-radius,-height/2+radius,270)]
    for x,z,start in corners:
        for i in range(10):
            a=math.radians(start+90*i/9)
            pts.append((x+radius*math.cos(a), z+radius*math.sin(a)))
    return pts

def flat_eyewire(name, path, radial=0.00235, depth=0.00105):
    """Closed acetate eyewire with a shallow, gently tapered front section."""
    sides = 16
    verts, faces = [], []
    count = len(path)
    for i, p in enumerate(path):
        prev, nxt = Vector(path[(i-1) % count]), Vector(path[(i+1) % count])
        tangent = (nxt - prev).normalized()
        outward = Vector((tangent.z, 0.0, -tangent.x)).normalized()
        center = Vector(p)
        # Fuller brow, slimming gently down the lower half of each eye.
        h = max(-1.0, min(1.0, (p[2] - CZ) / 0.020))
        section = radial * (1.0 + 0.16*h)
        for j in range(sides):
            a = 2*math.pi*j/sides
            q = center + outward*(section*math.cos(a)) + Vector((0, depth*math.sin(a), 0))
            verts.append(tuple(q))
    for i in range(count):
        ni = (i+1) % count
        for j in range(sides):
            nj = (j+1) % sides
            faces.append((i*sides+j, ni*sides+j, ni*sides+nj, i*sides+nj))
    mesh = bpy.data.meshes.new(name+"_mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.update()
    obj = bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.children["Asset"].objects.link(obj)
    for poly in mesh.polygons:
        poly.use_smooth = True
    v4.assign(obj, acetate)
    v4.part(obj, front)
    return obj

def tapered_tube(name, points, radii, material, body_ref, sides=16, subdivisions=5,
                 width_scale=1.45, height_scale=0.72):
    """Smooth swept mesh with a softly flattened, tapered acetate section."""
    controls = [Vector(p) for p in points]
    samples, rs = [], []
    for i in range(len(controls)-1):
        p0 = controls[max(0, i-1)]
        p1, p2 = controls[i], controls[i+1]
        p3 = controls[min(len(controls)-1, i+2)]
        for k in range(subdivisions):
            t = k/subdivisions
            t2, t3 = t*t, t*t*t
            point = 0.5*((2*p1) + (-p0+p2)*t + (2*p0-5*p1+4*p2-p3)*t2
                         + (-p0+3*p1-3*p2+p3)*t3)
            samples.append(point)
            rs.append(radii[i]*(1-t)+radii[i+1]*t)
    samples.append(controls[-1])
    rs.append(radii[-1])
    verts, faces = [], []
    for i, p in enumerate(samples):
        tangent = (samples[min(i+1,len(samples)-1)] - samples[max(i-1,0)]).normalized()
        ref = Vector((1,0,0)) if abs(tangent.x) < 0.85 else Vector((0,0,1))
        u = (ref - ref.dot(tangent)*tangent).normalized()
        v = tangent.cross(u).normalized()
        for j in range(sides):
            a = 2*math.pi*j/sides
            q = p + rs[i]*(width_scale*math.cos(a)*u + height_scale*math.sin(a)*v)
            verts.append(tuple(q))
    for i in range(len(samples)-1):
        for j in range(sides):
            nj=(j+1)%sides
            faces.append((i*sides+j, i*sides+nj, (i+1)*sides+nj, (i+1)*sides+j))
    faces.append(tuple(reversed(tuple(range(sides)))))
    end=(len(samples)-1)*sides
    faces.append(tuple(end+j for j in range(sides)))
    mesh=bpy.data.meshes.new(name+"_mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.update()
    obj=bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.children["Asset"].objects.link(obj)
    for poly in mesh.polygons:
        poly.use_smooth=True
    v4.assign(obj, material)
    v4.part(obj, body_ref)
    return obj

def curved_lens(name, outline, center_x, center_z, base_y, thickness=0.0015, sag=0.0007):
    """Thin lens shell with a subtle convex bow and rounded optical edge."""
    count, rings = len(outline), 10
    verts, faces = [], []

    def add_surface(edge_y):
        center = len(verts)
        verts.append((center_x, edge_y-sag, center_z))
        ring_ids=[]
        for r in range(1, rings+1):
            scale=r/rings
            ids=[]
            y=edge_y-sag*(1.0-scale*scale)
            for x,z in outline:
                ids.append(len(verts))
                verts.append((center_x+x*scale, y, center_z+z*scale))
            ring_ids.append(ids)
        first=ring_ids[0]
        for j in range(count):
            faces.append((center, first[j], first[(j+1)%count]))
        for r in range(1, rings):
            inner, outer=ring_ids[r-1], ring_ids[r]
            for j in range(count):
                nj=(j+1)%count
                faces.append((inner[j], outer[j], outer[nj], inner[nj]))
        return ring_ids[-1]

    front_edge=add_surface(base_y-thickness)
    back_edge=add_surface(base_y)
    for j in range(count):
        nj=(j+1)%count
        faces.append((front_edge[j], back_edge[j], back_edge[nj], front_edge[nj]))
    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["Asset"].objects.link(obj)
    for poly in mesh.polygons:
        poly.use_smooth = True
    v4.assign(obj, lensmat)
    v4.part(obj, front)
    return obj

def teardrop_pad(name, side, loc):
    """Soft oval silicone pad, wider at its lower end and tapered at the top."""
    rings, segments = 9, 24
    verts, faces = [], []
    for i in range(rings):
        q = -0.94 + 1.88*i/(rings-1)
        taper = math.sqrt(max(0.0, 1.0-q*q)) * (1.0-0.22*q)
        for j in range(segments):
            a = 2*math.pi*j/segments
            verts.append((0.0031*taper*math.cos(a),
                          0.00145*taper*math.sin(a),
                          0.0040*q))
    for i in range(rings-1):
        for j in range(segments):
            nj=(j+1)%segments
            faces.append((i*segments+j, i*segments+nj,
                          (i+1)*segments+nj, (i+1)*segments+j))
    faces.append(tuple(reversed(range(segments))))
    end=(rings-1)*segments
    faces.append(tuple(end+j for j in range(segments)))
    mesh=bpy.data.meshes.new(name+"_mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.update()
    obj=bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.children["Asset"].objects.link(obj)
    obj.location=loc
    obj.rotation_euler[1] = side*math.radians(13)
    for poly in mesh.polygons:
        poly.use_smooth=True
    v4.assign(obj, silicone)
    v4.part(obj, front)
    return obj

# Both full-rim eyewires and their shaped clear lens blanks.
for side, cx in (("L", -LX), ("R", LX)):
    path = rounded_rect(cx, CZ, 0.052, 0.040, 0.016, YF, n=12)
    flat_eyewire(f"{side}_acetate_eyewire", path)
    groove = rounded_rect(cx, CZ, 0.048, 0.036, 0.014, YF-0.00125, n=12)
    v4.tube(f"{side}_inner_groove", groove, 0.00018, material=groove_mat, body=front, cyclic=True)
    curved_lens(f"{side}_optical_lens", lens_outline(0.047, 0.035, 0.013),
                cx, CZ, YF+0.0005)

# Sculpted central bridge, joined to the inner eyewire corners.
bridge_pts = [(-0.007, YF, 0.038), (-0.0055, YF-0.0003, 0.042),
              (-0.003, YF-0.0005, 0.045), (0, YF-0.0006, 0.046),
              (0.003, YF-0.0005, 0.045), (0.0055, YF-0.0003, 0.042),
              (0.007, YF, 0.038)]
tapered_tube("sculpted_arched_bridge", bridge_pts,
             [0.0020,0.0021,0.0023,0.0025,0.0023,0.0021,0.0020],
             acetate, front, width_scale=1.25, height_scale=0.82)

# End pieces and two stationary knuckles per hinge lug.
HINGE_Z = {-1: 0.023, 1: 0.023}
for s, x in ((-1, -0.0725), (1, 0.0725)):
    hz = HINGE_Z[s]
    v4.rod(f"endpiece_{s}", (s*0.057, YF, 0.034), (s*0.0725, 0.0, hz),
           0.0034, material=acetate, body=front)
    # Upper/lower knuckles are separated to receive the temple's center knuckle.
    for k, dz in enumerate((-0.002, 0.002)):
        v4.cylinder(f"front_hinge_knuckle_{s}_{k}", 0.0025, 0.0028,
                    (x, 0.0, hz+dz), segments=32, bevel=0.00025,
                    material=steel, body=front)

# Nose pads and bent stainless pad arms, mounted rigidly to the front.
for s in (-1, 1):
    v4.tube(f"nose_arm_{s}", [(s*0.007, -0.0105, 0.038), (s*0.008, -0.002, 0.037),
                              (s*0.010, 0.010, 0.032), (s*0.013, 0.012, 0.019)],
            0.0008, material=steel, body=front)
    teardrop_pad(f"nose_pad_{s}", s, (s*0.013, 0.012, 0.020))

def build_temple(body, s, label):
    """Temple with a three-knuckle hinge, tapered arm and ergonomic ear hook."""
    hx = s*0.0725
    hz = HINGE_Z[s]
    # Identical pivot heights; the arms occupy separate vertical lanes when
    # folded, with the left arm below the right by 9.5 mm.
    zoff = -0.006 if s < 0 else 0.006
    arm_z = hz + zoff
    # About 25 degrees of down-bend across the last 28 mm of each temple.
    zcurve = (arm_z, arm_z, arm_z, arm_z-0.0065, arm_z-0.0127, arm_z-0.013)
    # Inboard hinge leaf reaches across the frame lug. Its center knuckle
    # interleaves with the two stationary knuckles on the lug.
    leaf_x = hx-s*0.0025
    v4.box(f"{label}_hinge_leaf", (0.010, 0.006, 0.007),
           (leaf_x, -0.001, hz), bevel=0.0022, material=acetate_dark, body=body)
    v4.cylinder(f"{label}_hinge_knuckle", 0.0025, 0.0048,
                (hx, 0.0, hz), segments=32, bevel=0.00025,
                material=steel, body=body)
    # Nearly flush screw on the outboard block face.
    screw_x = leaf_x + s*0.0047
    v4.cylinder(f"{label}_hinge_screw", 0.00072, 0.00035,
                (screw_x, -0.001, hz), rot=(0, math.pi/2, 0),
                segments=24, bevel=0.00008, material=black, body=body)
    # Straight rearward temples with a small hinge offset and a sculpted
    # downward ear bend. The radii taper continuously toward the sleeve.
    temple_pts = [
        (hx, -0.002, hz),
        (hx+s*0.0015, 0.012, (hz+arm_z)/2),
        (hx, 0.024, arm_z), (hx, 0.060, arm_z),
        (hx, 0.095, zcurve[0]), (hx+s*0.004, 0.114, zcurve[1]),
        (hx+s*0.009, 0.128, zcurve[3]),
    ]
    tapered_tube(f"{label}_temple_shaft", temple_pts,
                 [0.0027,0.00255,0.0024,0.0023,0.0021,0.0019,0.00165],
                 acetate, body)
    # Soft, slightly longer sleeve follows a clear 25-degree downturned ear hook.
    v4.tube(f"{label}_rubber_tip", [(hx+s*0.009, 0.128, zcurve[3]),
                                    (hx+s*0.011, 0.137, arm_z-0.0107),
                                    (hx+s*0.013, 0.146, arm_z-0.015)],
            0.0022, material=silicone, body=body)

build_temple(left, -1, "left")
build_temple(right, 1, "right")

# Temple hinge axes coincide with the knuckle/pin line. Right-hand-rule limits
# fold each arm inward from its open, rearward rest position.
v4.joint("left_temple_hinge", "revolute", front, left,
         origin=(-0.0725, 0.0, HINGE_Z[-1]), axis=(0, 0, 1),
         limits=(-math.radians(90), 0))
v4.joint("right_temple_hinge", "revolute", front, right,
         origin=(0.0725, 0.0, HINGE_Z[1]), axis=(0, 0, 1),
         limits=(0, math.radians(90)))

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