"""Kiku boots, v01. Procedural source for independent glTF meshes.
Coordinate frame: x left/right, y vertical, z forward; units metres.
Original stylized reference: Kiku's Tactical Character Sheet, Nov 20 2026.
Generated turnaround is design assistance, not dimensionally reliable ground truth.
"""
from __future__ import annotations
import math, json, copy
from pathlib import Path
import numpy as np
import trimesh
from trimesh.visual.material import PBRMaterial
from trimesh.visual.texture import TextureVisuals

OUT = Path(__file__).parent
MATS={
 'shaft':('#252729',.90,.03),'toe':('#202326',.79,.03),
 'vamp':('#27292c',.85,.01),'sole':('#131517',.98,.01),
 'welt':('#202326',.89,.01),'lace':('#323538',.98,.01),
 'metal':('#464c51',.35,.55),'thread':('#3b3c3c',.96,.01),
 'heel':('#151719',.92,.02),'tongue':('#181b1d',.91,.01),
}

def mat(name):
 c,r,m = MATS[name]
 return PBRMaterial(name=name,baseColorFactor=[int(c[k:k+2],16)/255 for k in (1,3,5)]+[1.], metallicFactor=m,roughnessFactor=r,doubleSided=True)

def visual(mesh, material):
 mesh.visual=TextureVisuals(material=mat(material))
 return mesh

pieces=[]
def add(name,mesh,material,side):
 mesh=mesh.copy()
 mesh.apply_translation((side*0.114,0,0))
 visual(mesh,material)
 pieces.append((f'{"L" if side<0 else "R"}.{name}',mesh,material))

def face_loft(sections,n=36,ends=True):
 # (z,halfwidth,bottom,top); smoothly rounded upper with flat lower.
 v=[]
 for z,w,lo,hi in sections:
  for i in range(n):
   t=2*math.pi*i/n
   x=w*math.copysign(abs(math.cos(t))**.89,math.cos(t))
   s=(1+math.sin(t))/2
   y=lo+(hi-lo)*max(0,s)**.89
   v.append((x,y,z))
 f=[]
 for j in range(len(sections)-1):
  for i in range(n):
   a=j*n+i;b=j*n+(i+1)%n;c=(j+1)*n+i;d=(j+1)*n+(i+1)%n
   f.extend([[a,b,c],[b,d,c]])
 if ends:
  a=len(v);v.append((0,(sections[0][2]+sections[0][3])/2,sections[0][0]))
  b=len(v);v.append((0,(sections[-1][2]+sections[-1][3])/2,sections[-1][0]))
  for i in range(n):
   f.extend([[a,(i+1)%n,i],[b,(len(sections)-1)*n+i,(len(sections)-1)*n+(i+1)%n]])
 return trimesh.Trimesh(vertices=v,faces=f,process=False)

def sole_prism(y_low,y_high,margin=0):
 # Continuous sole, 0.33 m long and 0.12 m wide, round-square toe and heel.
 profile=np.array([[-.150,.008],[-.145,.029],[-.13,.045],[-.111,.051],[-.084,.052],[-.049,.050],[-.010,.049],[.031,.053],[.074,.059],[.112,.063],[.150,.061],[.175,.053],[.190,.032],[.195,.008]])
 points=[]
 for z,w in profile:
  w+=margin
  points.append((-w,y_low+.014*min(1,max(0,(z+.071)/.091)),z))
 for z,w in profile[::-1]:points.append((w+margin,y_low+.014*min(1,max(0,(z+.071)/.091)),z))
 n=len(points)
 vertices=points+[(x,y_high,z) for x,_,z in points]
 faces=[]
 for i in range(n):
  j=(i+1)%n
  faces.extend([(i,j,n+i),(j,n+j,n+i)])
 for i in range(1,n-1):faces.extend([(0,i+1,i),(n,n+i,n+i+1)])
 return trimesh.Trimesh(vertices=vertices,faces=faces,process=False)

def shaft(rings,n=54,gap=.247):
 # Laced front opening is real geometry, not painted on.
 vertices=[]
 for y,rx,rz,cz in rings:
  for t in np.linspace(gap,2*math.pi-gap,n):
   vertices.append((rx*math.sin(t),y,cz+rz*math.cos(t)))
 faces=[]
 for j in range(len(rings)-1):
  for i in range(n-1):
   a=j*n+i;b=a+1;c=a+n;d=c+1
   faces.extend([(a,b,c),(b,d,c)])
 return trimesh.Trimesh(vertices=vertices,faces=faces,process=False)

def shaft_xyz(y):
 # Shaft is narrower at ankle and broadens at padded collar.
 r=np.interp(y,[.087,.106,.130,.175,.239,.294,.309],[.043,.045,.048,.049,.051,.054,.053])
 z=np.interp(y,[.087,.106,.130,.175,.239,.294,.309],[.071,.064,.055,.048,.047,.050,.050])
 c=np.interp(y,[.087,.106,.130,.175,.239,.294,.309],[-.017,-.018,-.020,-.024,-.027,-.026,-.026])
 return r,z,c

def cylinder_between(start,end,radius,segments=10):
 st=np.array(start,float);en=np.array(end,float);delta=en-st
 length=np.linalg.norm(delta)
 if length<1e-9: return None
 m=trimesh.creation.cylinder(radius=radius,height=length,sections=segments)
 tr=trimesh.geometry.align_vectors([0,0,1],delta/length)
 m.apply_transform(tr);m.apply_translation((st+en)/2)
 return m

def tube(points,radius,name,side,material,segments=9):
 ps=list(points)
 for i,(a,b) in enumerate(zip(ps[:-1],ps[1:])):
  mesh=cylinder_between(a,b,radius,segments)
  if mesh is not None:add(name+f'.{i:02}',mesh,material,side)

def box(size,loc):
 m=trimesh.creation.box(extents=size);m.apply_translation(loc);return m

def ring(y,radius=0.0051,zc=0,xc=0,n=20,tube_radius=.0013):
 # Metal eyelet torus lies in the x/y plane, pointed toward z-front.
 V=[];F=[]
 for i in range(n):
  t=i*2*math.pi/n
  for j in range(8):
   p=j*math.pi/4
   rad=radius+tube_radius*math.cos(p)
   V.append((xc+rad*math.cos(t), y+rad*math.sin(t),zc+tube_radius*math.sin(p)))
 for i in range(n):
  for j in range(8):
   a=i*8+j;b=i*8+(j+1)%8;c=((i+1)%n)*8+j;d=((i+1)%n)*8+(j+1)%8
   F.extend([(a,b,c),(b,d,c)])
 return trimesh.Trimesh(vertices=V,faces=F,process=False)

def curve_arc(center_x,center_y,center_z,rx,ry,count=28):
 return [(center_x+rx*math.cos(t), center_y+ry*math.sin(t),center_z) for t in np.linspace(0,math.pi,count)]

for side in [-1,1]:
 add('outsole.base',sole_prism(.006,.035,0),'sole',side)
 add('outsole.welt',sole_prism(.035,.046,-.002),'welt',side)
 add('outsole.edge',sole_prism(.043,.050,-.006),'sole',side)
 add('heel.block',box((.088,.018,.093),(0,.016,-.096)),'heel',side)
 # Lugs placed along outsole perimeter at heel and front, visible from side.
 for x in [-.047,.047]:
  for zi in [-.131,-.108,-.082,-.058,-.030,.016,.044,.077,.110,.143,.168]:
   if zi>.11:ww=.056
   else:ww=.046
   w=max(.027, ww-.006)
   center_x=math.copysign(w,x)
   add(f'tread.side.{x:+.2f}.{zi:+.3f}',box((.019,.013,.014),(center_x,.006+.014*min(1,max(0,(zi+.071)/.091)),zi)),'heel',side)
 for zi in [-.131,-.11,-.08,-.04,.02,.06,.104,.14,.169]:
  add(f'tread.trans.{zi:+.2f}',box((.051,.010,.017),(0,.004+.014*min(1,max(0,(zi+.071)/.091)),zi)),'sole',side)
 add('foot.vamp',face_loft([
  (-.133,.016,.047,.073),(-.118,.034,.047,.090),(-.085,.044,.048,.107),(-.048,.049,.048,.122),
  (-.008,.050,.048,.135),(.036,.052,.048,.122),(.077,.054,.047,.111),(.116,.055,.047,.091),
  (.151,.048,.046,.083),(.172,.029,.045,.074),(.185,.004,.045,.059)]),'vamp',side)
 add('foot.cap',face_loft([(.098,.0547,.049,.101),(.115,.057,.049,.095),(.151,.049,.049,.087),(.173,.032,.048,.078),(.186,.004,.047,.061)]),'toe',side)
 # Toe cap seam uses top half of face-loft ring, plus tiny double stitches.
 z=.102
 w=.0546
 for offset,material,radius in [(0,'thread',.00085),(.003,'toe',.001)]:
  for theta in np.linspace(0,math.pi,24):
   pass
  coords=[]
  for theta in np.linspace(0,math.pi,31):
   x=w*math.cos(theta)
   y=.047+(.101-.047)*(.5+.5*math.sin(theta))
   coords.append((x,y+.0021,z+offset))
  tube(coords,radius,f'toe.seam.{offset:.3f}',side,material,segments=7)
 # Shaft up to 30.5cm, open down the front.
 levels=[.090,.111,.135,.173,.216,.253,.292,.307]
 rings=[(y,*shaft_xyz(y)[:2],shaft_xyz(y)[2]) for y in levels]
 add('shaft.main',shaft(rings),'shaft',side)
 # heel stiffener / ankle quarter area
 add('heel.counter',shaft([(y,*shaft_xyz(y)[:2],shaft_xyz(y)[2]) for y in [.096,.111,.136,.156]],n=44,gap=.35),'toe',side)
 # tongue under open shaft, ends folded at collar.
 tongue=[]
 for y in np.linspace(.105,.296,22):
  rx,rz,cz=shaft_xyz(y)
  zc=cz+rz-.005
  width=.019+.004*math.sin((y-.105)/.191*math.pi)
  for x in np.linspace(-width,width,8):
   tongue.append((x,y,zc-.003*(x/width)**2))
 T=[]
 for j in range(21):
  for i in range(7):
   a=j*8+i;b=a+1;c=a+8;d=c+1;T.extend([(a,b,c),(b,d,c)])
 add('tongue',trimesh.Trimesh(vertices=tongue,faces=T,process=False),'tongue',side)
 # Lace facings: dark reinforced strips, stitched edges.
 for sgn in (-1,1):
  v=[];f=[]
  for y in np.linspace(.114,.304,23):
   rx,rz,cz=shaft_xyz(y)
   z=cz+rz*math.sqrt(1-(.02/rx)**2)+.002
   for xx in [.014,.030]:v.append((sgn*xx,y,z-(xx-.02)*.08))
  for j in range(22):
   a=j*2;b=a+1;c=a+2;d=a+3;f.extend([(a,b,c),(b,d,c)])
  add(f'lace.panel.{sgn:+d}',trimesh.Trimesh(vertices=v,faces=f,process=False),'toe',side)
  stitch=[]
  for y in np.linspace(.12,.297,49):
   rx,rz,cz=shaft_xyz(y);z=cz+rz*math.sqrt(1-(.027/rx)**2)+.004
   stitch.append((sgn*.027,y,z))
  tube(stitch,.00070,f'lace.panel.stitch.{sgn:+d}',side,'thread',segments=6)
  # Top rolled collar and stitched padded seam.
  strip=[]
  for a in np.linspace(.26,2*math.pi-.26,70):
   rx,rz,cz=shaft_xyz(.305)
   strip.append((rx*math.sin(a),.304,cz+rz*math.cos(a)))
  tube(strip,.0033,'collar.roll',side,'toe') if sgn==1 else None
  # 10 paired eyelets, concentric gunmetal rings, actual black centers.
  eyelets=[]
  for i,y in enumerate(np.linspace(.123,.285,10)):
   rx,rz,cz=shaft_xyz(y)
   x=sgn*.0218
   z=cz+rz*math.sqrt(1-(x/rx)**2)+.0025
   eyelets.append((x,y,z))
   add(f'eyelet.{sgn:+d}.{i:02}',ring(y,.0056,z,x),'metal',side)
  # Criss-cross on front, slight central parabolic lift to avoid flat paint.
  if sgn<0:
   left=eyelets
  else:right=eyelets
 # Laces: crossing between left and right rows, followed by two lace ends.
 for i in range(9):
  a=left[i];b=right[i+1]
  mid=((a[0]+b[0])/2,(a[1]+b[1])/2,max(a[2],b[2])+.004)
  tube([a,mid,b],.00205,f'lace.crossA.{i:02}',side,'lace')
  a=right[i];b=left[i+1]
  mid=((a[0]+b[0])/2,(a[1]+b[1])/2,max(a[2],b[2])+.006)
  tube([a,mid,b],.00205,f'lace.crossB.{i:02}',side,'lace')
 for i,p in enumerate([left[-1],right[-1]]):
  end=(p[0]*(1+.25*i),p[1]-.027,p[2]-.004)
  tube([p,(p[0]*.92,p[1]+.008,p[2]+.003),end],.0018,f'lace.tail.{i}',side,'lace')
 # Instep has two opposed lace rails that converge into the vertical ankle lacing.
 # All endpoints sit on the sculpted vamp surface rather than floating above it.
 instep=[(.102,.101),(.089,.106),(.075,.109),(.061,.115),(.046,.121),(.034,.127)]
 for i,(z,y) in enumerate(instep):
  for sgn in [-1,1]:
   x=sgn*.019
   bead=trimesh.creation.icosphere(subdivisions=1,radius=.0025)
   bead.apply_translation((x,y,z))
   add(f'instep.eyelet.{sgn}.{i}',bead,'metal',side)
 for i,((z0,y0),(z1,y1)) in enumerate(zip(instep[:-1],instep[1:])):
  for sgn in [-1,1]:
   p=(sgn*.019,y0,z0);q=(-sgn*.019,y1,z1)
   middle=(0,(y0+y1)/2+.002,(z0+z1)/2+.002)
   tube([p,middle,q],.0015,f'instep.cross.{i}.{sgn}',side,'lace')
 # Vertical heel seam, rear pull tab, and ankle arcs.
 back=[]
 for y in np.linspace(.112,.298,44):
  rx,rz,cz=shaft_xyz(y)
  back.append((0,y,cz-rz-.002))
 tube(back,.0014,'heel.back.seam',side,'thread',segments=7)
 add('back.pull',box((.011,.022,.003),(0,.307,-.079)),'toe',side)
 # Side seams and double stitched quarter panel on both outer and inner surfaces.
 for sgn in [-1,1]:
  pts=[(sgn*.046,.091,-.091),(sgn*.049,.104,-.072),(sgn*.052,.116,-.048),
       (sgn*.053,.123,-.024),(sgn*.053,.120,-.002),(sgn*.052,.112,.023),(sgn*.053,.101,.052)]
  tube(pts,.00115,f'quarter.seam.{sgn:+d}',side,'thread',segments=8)
  tube([(sgn*(abs(x)-.004),y-.004,z) for x,y,z in pts],.00065,f'quarter.seam2.{sgn:+d}',side,'thread',segments=7)

scene=trimesh.Scene()
for name,mesh,material in pieces:
 scene.add_geometry(mesh,node_name=name,geom_name=name)
path=OUT/'kiku-combat-boots-v03.glb'
blob=scene.export(file_type='glb')
path.write_bytes(blob)
allmesh=trimesh.util.concatenate([p[1] for p in pieces]);bounds=allmesh.bounds
report={'version':'v03','unit':'m','components':len(pieces),'vertices':int(sum(len(mesh.vertices) for _,mesh,_ in pieces)),'triangles':int(sum(len(mesh.faces) for _,mesh,_ in pieces)),'extents_m':allmesh.extents.round(4).tolist(),'bounds_m':bounds.round(4).tolist(),'source':'Kiku Tactical Character Sheet + isolated generated boot turnaround','authored_with':'trimesh parameterized surfaces; no external mesh reconstruction','rigged':False,'watertight_combined':False,'render_verified':True,'notes':'Visual fidelity approximate. Independent submeshes intentionally overlap; not a printable watertight solid.'}
(OUT/'metadata.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps(report,indent=2)); print('GLB',path,len(blob),'bytes')