# SPDX-License-Identifier: MIT
# Copyright (c) 2026 HexaArchi
"""Original Open Terrace collection. Blender 5.1, no external assets required.
Run: blender --background --python generate.py -- [slug|all]
Models use metres, Z up in Blender; GLB exporter converts to glTF Y up.
Generated models, textures and renders are released under CC0-1.0.
"""
import bpy, math, sys, json, shutil
from pathlib import Path
from mathutils import Vector
import numpy as np

ROOT = Path(__file__).resolve().parent.parent
TAU = math.tau
ASSET = []
M = {}

def texture(name, fabric=False):
    n = 512
    rng = np.random.default_rng(24 if fabric else 17)
    yy, xx = np.mgrid[0:n, 0:n] / n
    if fabric:
        f = .94 + .012 * np.sin(xx * TAU * 100) + .012 * np.sin(yy * TAU * 100) + rng.random((n,n))*.025
        base = np.array([.81,.78,.69])
    else:
        grain = np.sin((xx*35 + .20*np.sin(yy*TAU*3) + .14*np.sin(xx*TAU*5))*TAU)
        f = .88 + .035*grain + .025*rng.random((n,n))
        base = np.array([.48,.31,.17])
    rgba = np.ones((n,n,4),dtype=np.float32)
    rgba[:,:,:3] = np.clip(base[None,None,:]*f[:,:,None],0,1)
    im = bpy.data.images.new(name,width=n,height=n)
    im.pixels.foreach_set(rgba.ravel()); im.filepath_raw=str(ROOT/'textures'/f'{name}.png'); im.file_format='PNG'; im.save(); im.pack()
    return im

def mat(name, color, rough=.6, metallic=0, tex=None):
    m=bpy.data.materials.new(name); m.diffuse_color=(*color,1); m.use_nodes=True
    p=m.node_tree.nodes.get('Principled BSDF'); p.inputs['Base Color'].default_value=(*color,1); p.inputs['Roughness'].default_value=rough; p.inputs['Metallic'].default_value=metallic
    if tex:
        node=m.node_tree.nodes.new('ShaderNodeTexImage'); node.image=tex
        m.node_tree.links.new(node.outputs['Color'],p.inputs['Base Color'])
        bump=m.node_tree.nodes.new('ShaderNodeBump'); bump.inputs['Strength'].default_value=.16; bump.inputs['Distance'].default_value=.001
        m.node_tree.links.new(node.outputs['Color'],bump.inputs['Height']); m.node_tree.links.new(bump.outputs['Normal'],p.inputs['Normal'])
    M[name]=m
    return m

def finish(o,name,material):
    o.name=name; o.data.materials.append(M[material]); ASSET.append(o)
    return o

def box(name, loc, size, material='Teak', bevel=.012, rot=None):
    bpy.ops.mesh.primitive_cube_add(size=1,location=loc); o=bpy.context.object; o.dimensions=size
    bpy.ops.object.transform_apply(location=False,rotation=False,scale=True)
    if bevel:
        mod=o.modifiers.new('Soft crafted edges','BEVEL'); mod.width=min(bevel,min(size)*.48); mod.segments=4
        o.modifiers.new('Face normals','WEIGHTED_NORMAL')
    if rot:o.rotation_euler=rot
    return finish(o,name,material)

def rod(name,a,b,r,material='Teak',r2=None,verts=24):
    delta=Vector(b)-Vector(a)
    bpy.ops.mesh.primitive_cone_add(vertices=verts,radius1=r,radius2=r if r2 is None else r2,depth=delta.length,location=(Vector(a)+Vector(b))/2)
    o=bpy.context.object; o.rotation_euler=delta.to_track_quat('Z','Y').to_euler()
    mod=o.modifiers.new('Edge radius','BEVEL');mod.width=min(.004,r*.2);mod.segments=2
    for p in o.data.polygons:p.use_smooth=len(p.vertices)==4
    return finish(o,name,material)

def curve(name,pts,r,material='Rope'):
    c=bpy.data.curves.new(name,'CURVE');c.dimensions='3D';c.resolution_u=2;c.bevel_depth=r;c.bevel_resolution=2;c.use_fill_caps=True
    s=c.splines.new('POLY');s.points.add(len(pts)-1)
    for p,co in zip(s.points,pts):p.co=(*co,1)
    o=bpy.data.objects.new(name,c);bpy.context.collection.objects.link(o)
    return finish(o,name,material)

def seam(name,w,d,z,center=(0,0,0),radius=.045,material='Piping'):
    points=[]
    for cx,cy,start in [(w/2-radius,d/2-radius,0),(-w/2+radius,d/2-radius,90),(-w/2+radius,-d/2+radius,180),(w/2-radius,-d/2+radius,270)]:
        for i in range(10):
            a=math.radians(start+i*10);points.append((center[0]+cx+radius*math.cos(a),center[1]+cy+radius*math.sin(a),center[2]+z))
    return curve(name,points+[points[0]],.0025,material)

def cushion(name,loc,size,material='Linen',tilt=0):
    o=box(name,loc,size,material,.065)
    # Seam follows the actual rounded cushion perimeter.
    s=seam(name+' / sewn piping',size[0]-.006,size[1]-.006,size[2]*.28,loc)
    if tilt:
        for obj in [o,s]:
            old=obj.matrix_world.copy();obj.rotation_euler.x=tilt
            if obj==s:
                from mathutils import Matrix
                obj.matrix_world=Matrix.Translation(Vector(loc))@Matrix.Rotation(tilt,4,'X')@Matrix.Translation(-Vector(loc))@old
    return o

def screw(a,b):return rod('Recessed brass connector',a,b,.006,'Brass',verts=16)

def seating(width=.76, depth=.78, dining=False, sofa=False):
    seat=.44 if dining else .35; top=.84 if dining else .79; r=.022 if dining else .032
    frame='Graphite' if dining else 'Teak'; half=width/2-.045; front=-depth/2+.075; back=depth/2-.085
    for x in [-half,half]:
        for y in [front,back]:
            rod('Splayed leg', (x*1.04,y*1.1,.015),(x,y,seat),r*.74,frame,r2=r)
            rod('Floor glide',(x*1.04,y*1.1,.006),(x*1.04,y*1.1,.018),r*.77,'Graphite')
        rod('Side seat rail',(x,front,seat),(x,back,seat),r,frame)
        rod('Back upright',(x,back,seat),(x,back+.035,top),r*.83,frame)
        # Gently swept arm rails, separate from the woven infill.
        pts=[(x,front+.01+(back-front)*i/30,seat+.20+.045*math.sin(math.pi*i/30)) for i in range(31)]
        curve('Swept arm rail',pts,r*.85,frame)
        rod('Front arm support',(x,front+.01,seat),(x,front+.01,seat+.20),r*.72,frame)
        for j in range(18):
            y=front+.035+(back-front-.07)*j/17
            curve('Side rope / vertical',[(x+.003*math.sin(i*math.pi/2),y,seat+.03+i*.019) for i in range(11)],.004,'Rope')
        for j in range(6):
            z=seat+.035+j*.026
            curve('Side rope / cross weave',[(x+.005*math.cos(i*math.pi),front+.03+(back-front-.06)*i/36,z) for i in range(37)],.0033,'Rope')
    for y in [front,back]:rod('Seat cross rail',(-half,y,seat),(half,y,seat),r,frame)
    rod('Upper back rail',(-half,back+.035,top),(half,back+.035,top),r*.9,frame)
    count=round(width/.024)
    for j in range(count):
        x=-half+.027+(2*half-.054)*j/(count-1)
        curve('Back rope / warp',[(x,back+.035*i/20+.004*math.sin(i*math.pi/2),seat+.035+(top-seat-.05)*i/20) for i in range(21)],.0045,'Rope')
    for j in range(10):
        z=seat+.04+(top-seat-.07)*j/9
        curve('Back rope / weft',[( -half+.015+(2*half-.03)*i/(count*2),back+.035*(z-seat)/(top-seat)+.005*math.cos(i*math.pi),z) for i in range(count*2+1)],.0035,'Rope')
    for j in range(7):box('Support slat', (0,front+(back-front)*j/6,seat+.005),(width-.08,.032,.024),frame,.007)
    n=3 if sofa else 1; cw=(width-.13)/n
    for i in range(n):
        x=(i-(n-1)/2)*cw
        cushion('Seat cushion',(x,-.02,seat+.077),(cw-.012,depth-.14,.12))
        cushion('Back cushion',(x,back-.012,seat+.275),(cw-.025,.12,.32),'Sage' if sofa else 'Linen',math.radians(10))
    for x in [-half,half]:
        for y in [front,back]:screw((x-r,y,seat),(x+r,y,seat))

def dining_table():
    # Rounded racetrack top made of individually softened teak planks.
    for j in range(11):
        y=(j-5)*.087; width=1.68+math.sqrt(max(0,1-(y/.51)**2))*.36
        box('Individual tabletop slat',(0,y,.748),(width,.080,.045),'Teak',.02)
    for x in [-.72,.72]:
        for y in [-.30,.30]:rod('Tapered table leg',(x*1.07,y*1.13,.01),(x,y,.71),.034,'Teak',r2=.052)
        box('Undertop cross beam',(x,0,.695),(.08,.79,.075))
    for y in [-.31,.31]:box('Long apron',(0,y,.68),(1.53,.045,.10))
    rod('Brass stretcher',(-.72,0,.22),(.72,0,.22),.017,'Brass')

def coffee_table():
    # Double pedestal, fluted timber bases, soft oval stone top.
    o=rod('Travertine oval top',(0,0,.335),(0,0,.395),1,'Stone',verts=96);o.scale=(.65,.37,1)
    for x in [-.33,.33]:
        rod('Pedestal core',(x,0,.025),(x,0,.335),.15,'Teak',verts=64)
        for j in range(36):
            a=j*TAU/36
            rod('Carved pedestal flute',(x+.148*math.cos(a),.148*math.sin(a),.035),(x+.148*math.cos(a),.148*math.sin(a),.33),.012,'Teak',verts=12)
        rod('Recessed pedestal foot',(x,0,.006),(x,0,.026),.13,'Graphite',verts=48)

def side_table():
    rod('Ceramic platter',(0,0,.45),(0,0,.48),.235,'Clay',verts=80)
    seam('Raised rim',.40,.40,.485,radius=.20,material='Clay')
    rod('Fluted tapered body',(0,0,.045),(0,0,.446),.13,'Clay',r2=.18,verts=64)
    for j in range(44):
        a=j*TAU/44
        rod('Ceramic flute',(.128*math.cos(a),.128*math.sin(a),.06),(.175*math.cos(a),.175*math.sin(a),.442),.0075,'Clay',verts=12)
    rod('Inset foot',(0,0,.005),(0,0,.046),.117,'Graphite',verts=48)

def bench():
    for x in [-.63,.63]:
        for y in [-.19,.19]:rod('Tapered bench leg',(x*1.03,y*1.15,.01),(x,y,.43),.023,'Teak',r2=.034)
        rod('End seat rail',(x,-.23,.43),(x,.23,.43),.031)
        rod('Low side stretcher',(x,-.20,.20),(x,.20,.20),.02)
    for y in [-.23,.23]:rod('Long seat rail',(-.66,y,.43),(.66,y,.43),.031)
    for j in range(65):
        x=-.625+j*1.25/64
        curve('Woven seat warp',[(x,-.22+i*.44/28,.438+.005*math.cos(i*math.pi)) for i in range(29)],.006,'Rope')
    for j in range(23):
        y=-.21+j*.42/22
        curve('Woven seat weft',[(-.63+i*1.26/80,y,.438-.005*math.cos(i*math.pi)) for i in range(81)],.005,'Rope')
    rod('Lower long stretcher',(-.63,0,.18),(.63,0,.18),.022)

def lounger():
    for x in [-.33,.33]:
        box('Long chassis rail',(x,0,.275),(.05,1.99,.07))
        for y in [-.76,.67]:rod('Low angled support',(x,y,.02),(x,y*.9,.275),.027,'Teak',r2=.033)
    for j in range(17):box('Deck slat',(0,-.89+j*.067,.30),(.64,.059,.026),'Teak',.009)
    for j in range(12):
        y=.24+j*.06;z=.31+j*.031
        box('Reclined back slat',(0,y,z),(.64,.058,.025),'Teak',.008,(math.atan(.031/.06),0,0))
    for x in [-.28,.28]:
        rod('Back support stay',(x,.28,.27),(x,.82,.62),.016,'Graphite')
        screw((x-.012,.24,.31),(x+.012,.24,.31))
        rod('Transport wheel',(x-.022,.78,.07),(x+.022,.78,.07),.065,'Graphite',verts=48)
        rod('Wheel hub',(x-.024,.78,.07),(x+.024,.78,.07),.018,'Brass')
    cushion('Long reclining pad',(0,-.33,.356),(.60,1.12,.075))
    cushion('Backrest pad',(0,.58,.535),(.60,.78,.075),'Linen',math.atan(.031/.06))
    cushion('Headrest pillow',(0,.835,.72),(.45,.17,.105),'Sage',math.atan(.031/.06))

MODELS={
 'sela-lounge':('Sela Lounge',lambda:seating()),
 'rona-sofa':('Rona Sofa',lambda:seating(2.06,.86,sofa=True)),
 'luma-dining-chair':('Luma Dining Chair',lambda:seating(.58,.60,dining=True)),
 'tala-dining-table':('Tala Dining Table',dining_table),
 'arka-coffee-table':('Arka Coffee Table',coffee_table),
 'tera-side-table':('Tera Side Table',side_table),
 'anyam-bench':('Anyam Bench',bench),
 'nusa-sunlounger':('Nusa Sunlounger',lounger),
}

def aim(o,p):o.rotation_euler=(Vector(p)-o.location).to_track_quat('-Z','Y').to_euler()

def build(slug):
    bpy.ops.wm.read_factory_settings(use_empty=True); ASSET.clear();M.clear()
    (ROOT/'textures').mkdir(parents=True,exist_ok=True);out=ROOT/slug;out.mkdir(parents=True,exist_ok=True)
    mat('Teak',(.50,.30,.13),.46,tex=texture('teak-grain'))
    mat('Linen',(.79,.75,.66),.89,tex=texture('linen-weave',True))
    mat('Sage',(.25,.32,.24),.9);mat('Rope',(.36,.30,.20),.88);mat('Piping',(.54,.50,.40),.86)
    mat('Graphite',(.07,.085,.075),.37,.65);mat('Brass',(.45,.29,.10),.32,.75)
    mat('Stone',(.70,.66,.55),.62);mat('Clay',(.42,.17,.095),.75)
    MODELS[slug][1]()
    bpy.ops.object.select_all(action='DESELECT')
    for o in ASSET:
        if o.type=='CURVE':
            bpy.context.view_layer.objects.active=o;o.select_set(True);bpy.ops.object.convert(target='MESH');o.select_set(False)
    # Bake evaluated meshes into the downloadable asset; keep named components.
    for o in ASSET:
        bpy.context.view_layer.objects.active=o
        for mod in list(o.modifiers):bpy.ops.object.modifier_apply(modifier=mod.name)
    coords=[o.matrix_world@Vector(c) for o in ASSET for c in o.bound_box]
    lo=Vector(tuple(min(v[i] for v in coords) for i in range(3)));hi=Vector(tuple(max(v[i] for v in coords) for i in range(3)))
    dims=hi-lo;center=(lo+hi)/2
    meta={'slug':slug,'name':MODELS[slug][0],'units':'metres','dimensions':[round(v,3) for v in dims], 'objects':len(ASSET),'triangles':sum(sum(len(p.vertices)-2 for p in o.data.polygons) for o in ASSET),'license':'CC0-1.0','version':'1.0.0'}
    for o in bpy.context.scene.objects:o.select_set(False)
    for o in ASSET:o.select_set(True)
    bpy.ops.export_scene.gltf(filepath=str(out/(slug+'.glb')),export_format='GLB',use_selection=True,export_yup=True,export_apply=True)
    bpy.ops.wm.obj_export(filepath=str(out/(slug+'.obj')),export_selected_objects=True,apply_modifiers=True,path_mode='COPY',forward_axis='NEGATIVE_Z',up_axis='Y')
    # Packed textures may lose their absolute path during glTF export.
    # The OBJ material file uses basenames, so always ship these beside it.
    for name in ['teak-grain.png','linen-weave.png']:
        shutil.copy2(ROOT/'textures'/name,out/name)
    (out/'metadata.json').write_text(json.dumps(meta,indent=2))
    scene=bpy.context.scene;scene.unit_settings.system='METRIC';scene.unit_settings.scale_length=1
    scene.world=bpy.data.worlds.new('Warm studio');scene.world.use_nodes=True;scene.world.node_tree.nodes['Background'].inputs[0].default_value=(.78,.80,.76,1);scene.world.node_tree.nodes['Background'].inputs[1].default_value=.4
    mat('Backdrop',(.82,.80,.74),.85)
    bpy.ops.mesh.primitive_plane_add(size=200);floor=bpy.context.object;floor.name='STUDIO / backdrop (not exported)';floor.data.materials.append(M['Backdrop'])
    size=max(dims)
    for name,loc,power,scale in [('Key',(-3,-4,5),750,4),('Fill',(4,-1,3),450,3),('Rim',(0,4,4),600,3)]:
        bpy.ops.object.light_add(type='AREA',location=loc);o=bpy.context.object;o.name='STUDIO / '+name;o.data.energy=power;o.data.shape='DISK';o.data.size=scale;aim(o,center)
    bpy.ops.object.camera_add();camera=bpy.context.object;scene.camera=camera;camera.name='STUDIO / camera';camera.data.type='ORTHO';camera.data.ortho_scale=size*1.95
    scene.render.engine='CYCLES';scene.cycles.samples=24;scene.cycles.use_denoising=True
    try:
        prefs=bpy.context.preferences.addons['cycles'].preferences
        prefs.compute_device_type='CUDA';prefs.get_devices()
        if any(d.type=='CUDA' for d in prefs.devices):
            for device in prefs.devices:device.use=device.type=='CUDA'
            scene.cycles.device='GPU'
    except Exception:
        pass  # CPU rendering remains a supported portable fallback.
    scene.render.resolution_x=1080;scene.render.resolution_y=900;scene.render.resolution_percentage=100
    scene.render.image_settings.file_format='PNG';scene.view_settings.view_transform='AgX'
    scene.render.film_transparent=False
    for view,pos in [('cover',(1.45,-1.8,1.12)),('back',(-1.5,1.8,1.18))]:
        camera.location=center+Vector(pos)*size;aim(camera,center-Vector((0,0,.04)))
        bpy.context.view_layer.update()
        projected=[camera.matrix_world.inverted()@v for v in coords]
        span_x=max(v.x for v in projected)-min(v.x for v in projected)
        span_y=max(v.y for v in projected)-min(v.y for v in projected)
        camera.data.ortho_scale=max(span_x,span_y*1.2)*1.2
        scene.render.filepath=str(out/(view+'.png'));bpy.ops.render.render(write_still=True)
    camera.location=center+Vector((1.45,-1.8,1.12))*size;aim(camera,center-Vector((0,0,.04)))
    bpy.ops.object.select_all(action='DESELECT')
    for o in ASSET:o.select_set(True)
    bpy.ops.wm.save_as_mainfile(filepath=str(out/(slug+'.blend')),compress=True)
    print('HEXA_FURNITURE_DONE',json.dumps(meta),flush=True)

if __name__=='__main__':
    arg=sys.argv[sys.argv.index('--')+1] if '--' in sys.argv else 'all'
    for slug in MODELS if arg=='all' else [arg]:build(slug)
