"""Head geometry in millimetres converted to Blender metres. Execute once in assembly."""
import math
import bpy
from mathutils import Vector
from math import cos,sin,pi

def build_head():
    col = bpy.data.collections.new("Head")
    bpy.context.scene.collection.children.link(col)
    mats={}
    for name,rgb,metal,rough in [
        ("Satin titanium",(.28,.29,.30),1,.33),("Graphite contact polymer",(.032,.043,.047),0,.28),
        ("Alumina",(.79,.76,.66),0,.32),("Silicone",(.09,.10,.11),0,.55),
        ("Porous ceramic",(.58,.53,.42),0,.77),("Resistance alloy",(.33,.28,.21),1,.37),
        ("Contact gold",(.73,.48,.14),1,.28)]:
        m=bpy.data.materials.new("Head / "+name)
        m.use_nodes=True
        node=m.node_tree.nodes.get("Principled BSDF")
        node.inputs["Base Color"].default_value=(*rgb,1)
        node.inputs["Roughness"].default_value=rough
        node.inputs["Metallic"].default_value=metal
        m.diffuse_color=(*rgb,1)
        mats[name]=m
    def mesh(part,label,v,f,mat,process,contact):
        me=bpy.data.meshes.new(label); me.from_pydata([tuple(a*.001 for a in xyz) for xyz in v],[],f); me.update()
        o=bpy.data.objects.new(part+" "+label,me); col.objects.link(o)
        o.data.materials.append(mats[mat])
        for k,val in dict(part_id=part,material_candidate=mat,process=process,contact=contact,basis="R01 assumed concept geometry; physical qualification outstanding").items(): o[k]=val
        for poly in me.polygons:poly.use_smooth=True
        return o
    def ring(part,label,profile,mat,process,contact,x=0,y=0):
        n=96; v=[]; f=[]
        for r,z in profile:
            v += [(x+r*cos(2*pi*i/n),y+r*sin(2*pi*i/n),z) for i in range(n)]
        for j in range(len(profile)):
            k=(j+1)%len(profile)
            for i in range(n):
                h=(i+1)%n; f.append((j*n+i,j*n+h,k*n+h,k*n+i))
        return mesh(part,label,v,f,mat,process,contact)
    def tube(part,label,points,r,mat,contact):
        points=[Vector(p) for p in points]; v=[]; f=[]; n=12
        for i,p in enumerate(points):
            t=(points[min(i+1,len(points)-1)]-points[max(i-1,0)]).normalized()
            u=(Vector((0,0,1)) if abs(t.z)<.96 else Vector((1,0,0))).cross(t).normalized(); w=t.cross(u)
            v.extend(tuple(p+r*(cos(2*pi*k/n)*u+sin(2*pi*k/n)*w)) for k in range(n))
        for j in range(len(points)-1):
            for k in range(n):
                h=(k+1)%n;f.append((j*n+k,j*n+h,(j+1)*n+h,(j+1)*n+k))
        f.extend([tuple(reversed(range(n))),tuple(range(len(v)-n,len(v)))])
        return mesh(part,label,v,f,mat,"formed wire or pin",contact)
    def cut(o,x,y,z,r,depth,rotation,sides=48):
        bpy.ops.mesh.primitive_cylinder_add(vertices=sides,radius=r*.001,depth=depth*.001,location=(x*.001,y*.001,z*.001),rotation=rotation)
        tool=bpy.context.object; mod=o.modifiers.new("Machined opening","BOOLEAN");mod.object=tool
        bpy.context.view_layer.objects.active=o;bpy.ops.object.modifier_apply(modifier=mod.name)
        bpy.data.objects.remove(tool,do_unlink=True)
    shell=ring("HD01","Air inlet collar",[(10.15,86),(10.42,86.3),(10.42,91.7),(10.25,92),(9.4,92),(9.4,86)],"Satin titanium","turned and cross-drilled","air")
    for z in (88.8,90.0):
        for x in (-2.5,0,2.5):cut(shell,x,0,z,.46,25,(pi/2,0,0))
    floor=ring("HD02","Feedthrough carrier",[(9.4,86),(9.4,87.1),(1.38,87.1),(1.38,86)],"Alumina","formed and finished","air / liquid boundary")
    for x in (-4.6,4.6):
        cut(floor,x,0,86.55,.49,3,(0,0,0))
    for index,y in enumerate((-8.0,8.0)):
        cut(floor,0,y,86.55,.68,3,(0,0,0))
        # Closed solid of revolution with a blind hex recess.
        profile=[(.48,84.55),(.60,84.68),(.60,87.1),(.98,87.1),(1.05,87.17),(1.05,87.72),(.97,87.8)]
        n=72
        vertices=[(r*cos(i*2*pi/n),y+r*sin(i*2*pi/n),z) for r,z in profile for i in range(n)]
        faces=[(j*n+i,j*n+(i+1)%n,(j+1)*n+(i+1)%n,(j+1)*n+i) for j in range(len(profile)-1) for i in range(n)]
        faces.extend([tuple(reversed(range(n))),tuple(range(len(vertices)-n,len(vertices)))])
        bolt=mesh("HD"+str(14+index),"Deck retaining socket screw",vertices,faces,"Satin titanium","turned or cold-formed M1.2 candidate; nominal thread envelope","air / service")
        cut(bolt,0,y,87.85,.46,1,(0,0,0),6)
    ring("HD03","Liquid feed ferrule",[(1.37,86.14),(1.37,87.1),(1.78,87.1),(1.78,88.55),(1.35,88.55),(1.08,87.25),(1.08,86.14)],"Satin titanium","turned","liquid")
    ring("HD04","Capillary wick",[(1.02,87.25),(1.34,88.55),(1.34,93.15),(1.15,93.3),(.34,93.3),(.34,87.25)],"Porous ceramic","sintered porous form","liquid / aerosol")
    pts=[(1.49*cos(i*2*pi/48),1.49*sin(i*2*pi/48),88.85+i*.84/48) for i in range(241)]
    tube("HD05","Wick heater winding",pts,.15,"Resistance alloy","liquid / aerosol")
    for k,x in enumerate([4.6,-4.6]):
        tube("HD0"+str(6+k),"Insulated-deck contact",[(x,0,86),(x,0,87.45)],.48,"Contact gold","electrical / air")
    tube("HD08","Lower heater termination",[(4.6,0,87.45),(4.6,0,88.2),(1.49,0,88.85)],.15,"Resistance alloy","air")
    tube("HD09","Upper heater termination",[(-4.6,0,87.45),(-4.6,0,93.55),(0,2.4,93.55),(1.49,0,93.05)],.15,"Resistance alloy","air")
    ring("HD10","Collection trough and chimney",[(10.24,92),(10.36,92.2),(10.36,94.55),(9.76,95.1),(8.86,95.1),(8.86,94.55),(4.12,94.55),(4.12,97),(3.77,97.2),(3.45,97.2),(3.45,94),(4.55,93.45),(8.9,93.45),(9.25,92)],"Satin titanium","turned annular condensate well","air / condensate")
    ring("HD11","Detachable tapered mouthpiece",[(9.75,95.1),(9.88,95.3),(9.8,96.3),(9.3,97.6),(8.15,99.45),(6.85,102.3),(6.3,105.45),(6.05,105.95),(5.55,106.1),(3.52,106.1),(3.32,105.9),(3.32,98.2),(3.65,97.55),(4.48,97.45),(4.48,95.15),(5.35,95.15),(5.35,97.15),(7.85,96.35),(8.85,95.1)],"Graphite contact polymer","machined or moulded; final resin open","mouth / air / condensate")
    ring("HD12","Chimney retention seal",[(4.12+.23*cos(a*2*pi/24),96.12+.36*sin(a*2*pi/24)) for a in range(24)],"Silicone","moulded elastomer","air / condensate")
    # Expand outer contact lip to bridge the slip fit on the mouthpiece spigot.
    seal=col.objects.get("HD12 Chimney retention seal")
    for vv in seal.data.vertices:
        radius=math.hypot(vv.co.x,vv.co.y)
        scale=(.00430+(radius-.00412)*.92)/radius;vv.co.x*=scale;vv.co.y*=scale
    ring("HD13","Outlet face gasket",[(1.36,86),(1.37,86.14),(1.05,86.14),(.82,86)],"Silicone","moulded face gasket","liquid")
    import bmesh
    for obj in col.objects:
        bm=bmesh.new();bm.from_mesh(obj.data)
        for edge in bm.edges:
            if edge.is_manifold:
                edge.smooth=edge.calc_face_angle() < math.radians(35)
        for face in bm.faces:
            face.smooth=abs(face.normal.z)<.999
        bm.to_mesh(obj.data);bm.free();obj.data.update()
    return col

build_head()
