"""Build on a dedicated Blender scene. Supply STUDY_ROOT or run this saved script."""
import bpy, bmesh, math, json, csv, os
from pathlib import Path
from mathutils import Vector
import numpy as np
R=Path(os.environ.get('STUDY_ROOT') or globals().get('STUDY_ROOT') or Path(__file__).resolve().parents[1]); A=R/'scene/assets'
# Use a new scene, then link the dedicated model objects there.
sc=bpy.data.scenes.new('Proof verification | Seminar room');bpy.context.window.scene=sc
coll=sc.collection
def lin(k):
    v=int(k,16)/255
    return v/12.92 if v<.04045 else ((v+.055)/1.055)**2.4
def mat(name,h,metal=0,rough=.55,tex=None,emission=0):
    m=bpy.data.materials.new(name);m.diffuse_color=(*[lin(h[i:i+2]) for i in (0,2,4)],1);m.use_nodes=True
    bs=m.node_tree.nodes.get('Principled BSDF');bs.inputs['Base Color'].default_value=m.diffuse_color;bs.inputs['Roughness'].default_value=rough;bs.inputs['Metallic'].default_value=metal
    if tex:
        im=m.node_tree.nodes.new('ShaderNodeTexImage');im.image=bpy.data.images.load(str(A/tex),check_existing=True);m.node_tree.links.new(im.outputs['Color'],bs.inputs['Base Color'])
    if emission:bs.inputs['Emission Color'].default_value=m.diffuse_color;bs.inputs['Emission Strength'].default_value=emission
    return m
oak=mat('Quarter-sawn oak','a17b51',tex='wood_photo.jpg');trim=mat('Oiled walnut edge','63452e');plaster=mat('Limewash','e9e3d2',rough=.92)
stone=mat('Honed terrazzo','bbaf99',tex='floor_photo.jpg');brass=mat('Brushed bronze','9e8257',.57,.36);steel=mat('Gunmetal structure','4b5657',.48,.42)
dark=mat('Board backing','293e38');seat=mat('Olive upholstery','677260',rough=.95);glass=mat('Daylight glazing','d6e4df',rough=.33,emission=.45)
white=mat('Paper','f2e9c8');lamp=mat('Diffuser','fff1d6',emission=1.4);teal=mat('Verdigris','37776d',.25)
ochre=mat('Clay red','b76140');meshmat=mat('Glazed function model','69ae99',.32,.29)
for material,image in [(oak,'wood_normal.jpg'),(stone,'floor_normal.jpg')]:
    tree=material.node_tree;node=tree.nodes.new('ShaderNodeTexImage');node.image=bpy.data.images.load(str(A/image));node.image.colorspace_settings.name='Non-Color'
    normal=tree.nodes.new('ShaderNodeNormalMap');normal.inputs['Strength'].default_value=.28;tree.links.new(node.outputs['Color'],normal.inputs['Color']);tree.links.new(normal.outputs['Normal'],tree.nodes.get('Principled BSDF').inputs['Normal'])
window=mat('Western sky','deebed',rough=1,tex='window.jpg');paperchart=mat('Printed reduction diagram','efecd9',tex='handout.jpg')
verts0=[(-1,-1,-1),(1,-1,-1),(1,1,-1),(-1,1,-1),(-1,-1,1),(1,-1,1),(1,1,1),(-1,1,1)]
faces0=[(0,3,2,1),(4,5,6,7),(0,1,5,4),(1,2,6,5),(2,3,7,6),(3,0,4,7)]
cache={}
def mesh(n,verts,faces,m):
    me=bpy.data.meshes.new(n);me.from_pydata(verts,[],faces);me.materials.append(m);me.update();return me
def obj(n,me,xyz):
    o=bpy.data.objects.new(n,me);coll.objects.link(o);o.location=xyz;return o
def box(n,xyz,size,m):
    k=tuple(size)+(m.name,)
    if k not in cache:
        me=mesh(n,[(a*size[0]/2,b*size[1]/2,c*size[2]/2) for a,b,c in verts0],faces0,m)
        uv=me.uv_layers.new()
        for poly in me.polygons:
            sx,sy=1,1
            if m in (oak,stone):
                dims=[(size[1],size[0]),(size[0],size[1]),(size[0],size[2]),(size[1],size[2]),(size[0],size[2]),(size[1],size[2])][poly.index]
                scale=1.7 if m==oak else 1.5;sx,sy=[max(.18,d/scale) for d in dims]
            for idx,pair in zip(poly.loop_indices,[(0,0),(sx,0),(sx,sy),(0,sy)]):uv.data[idx].uv=pair
        if m in (oak,trim,steel,seat,brass,dark) and min(size)>.028:
            bm=bmesh.new();bm.from_mesh(me);bmesh.ops.bevel(bm,geom=list(bm.edges),offset=min(.012,min(size)*.11),segments=2,profile=.5,affect='EDGES');bm.to_mesh(me);bm.free();me.update()
        cache[k]=me
    return obj(n,cache[k],xyz)
def panel(n,x,y,z,w,h,m):
    me=mesh(n,[(-w/2,0,-h/2),(w/2,0,-h/2),(w/2,0,h/2),(-w/2,0,h/2)],[(0,1,2,3)],m)
    uv=me.uv_layers.new()
    for i,p in enumerate([(0,0),(1,0),(1,1),(0,1)]):uv.data[i].uv=p
    return obj(n,me,(x,y,z))
def lamp_at(n,xyz,at,energy,diameter,color):
    light=bpy.data.lights.new(n,'AREA');light.energy=energy;light.shape='DISK';light.size=diameter;light.color=color
    o=obj(n,light,xyz);o.rotation_euler=(Vector(at)-o.location).to_track_quat('-Z','Y').to_euler()
box('Terrazzo floor',(0,-5.8,-.11),(15.6,13.7,.22),stone)
box('Chalk wall',(0,.62,2.85),(15.5,.24,5.7),plaster)
box('Eastern wall',(7.65,-5.8,2.84),(.22,13,5.7),plaster)
box('Rear wall',(0,-12.47,2.84),(15.5,.20,5.7),plaster)
box('Acoustic ceiling',(0,-5.8,5.68),(15.5,13.6,.16),plaster)
for x in [-6.2,-3.1,0,3.1,6.2]:box('Ceiling joist',(x,-5.75,5.53),(.14,13,.20),oak)
for y in [-1.4,-4.7,-8.0]:
    for x in [-4,0,4]:
        box('Pendant housing',(x,y,5.25),(2.1,.21,.09),steel);box('Warm diffuser',(x,y,5.19),(2.04,.17,.035),lamp)
        for dx in [-.82,.82]:box('Pendant rod',(x+dx,y,5.42),(.016,.016,.31),steel)
for i in range(36):
    x=-7.25+i*.414
    box('Oak wall lining',(x,.41,.65),(.399,.12,1.30),oak)
box('Oak cap',(0,.32,1.31),(15.2,.19,.085),trim)
box('Dais',(0,-1.04,.08),(15.25,2.95,.16),oak);box('Dais nosing',(0,-2.50,.09),(15.28,.08,.19),trim)
for r,z in enumerate((3.88,2.39)):
    for c,x in enumerate((-4.30,0,4.30)):
        i=r*3+c+1
        box('Sliding slate housing',(x,.29,z),(4.23,.22,1.55),steel)
        box('Dark recessed backing',(x,.163,z),(4.13,.05,1.46),dark)
        m=mat('Slate and chalk '+str(i),'73857a',rough=.91,tex=f'board{i}.jpg')
        o=panel('Board_'+str(i),x,.128,z,4.08,1.397,m);o['station']=i-1
        for dx in (-2.105,2.105):box('Anodized slide rail',(x+dx,.112,z),(.045,.095,1.54),brass)
        box('Chalk tray',(x,.08,z-.753),(4.20,.28,.062),steel)
        for dx in [-1.41,-1.28]:box('Chalk sticks',(x+dx,-.025,z-.702),(.091,.019,.019),white)
        box('Felt eraser',(x+1.63,.035,z-.68),(.225,.12,.077),trim)
# Window bays, deep reveals, frames and sill on the west wall.
for k in range(5):
    y=-.88-k*2.56
    box('Window apron',(-7.63,y,.76),(.22,2.58,1.52),plaster);box('Window header',(-7.64,y,5.03),(.22,2.58,1.24),plaster)
    sky=panel('Window light',-7.71,y,2.98,2.55,2.92,window);sky.rotation_euler.z=math.pi/2
    uv=sky.data.uv_layers.active
    for i,(u,v) in enumerate([(0,0),(1,0),(1,1),(0,1)]):uv.data[i].uv=((4-k+u)/5,v)
    box('Sill',(-7.49,y,1.53),(.46,2.62,.105),oak)
    for dy in [-1.25,0,1.25]:box('Window mullion',(-7.55,y+dy,2.98),(.12,.075,2.98),steel)
    box('Window transom',(-7.55,y,3.72),(.12,2.52,.065),steel)
# Tiered desks. Separate central aisle gives a continuous sight line to the boards.
for row,y in enumerate([-4.55,-6.5,-8.45,-10.40]):
    h=.085*row
    box('Audience tier',(0,y-.58,h/2),(15.1,1.91,max(.025,h)),stone)
    for x in [-4.37,4.37]:
        box('Bench writing surface',(x,y,.82+h),(5.65,.69,.085),oak)
        box('Edge band',(x,y+.34,.79+h),(5.66,.048,.10),trim)
        for dx in [-2.0,2.0]:
            box('Desk standard',(x+dx,y,.43+h),(.115,.41,.78),steel)
        for dx in [-2.10,-.7,.7,2.10]:
            cx=x+dx
            box('Seat shell',(cx,y-.77,.47+h),(.88,.57,.085),oak)
            box('Seat cushion',(cx,y-.77,.53+h),(.82,.51,.08),seat)
            b=box('Bent backrest',(cx,y-1.04,.81+h),(.87,.09,.46),oak);b.rotation_euler.x=-.10
            for leg in [-.31,.31]:box('Chair frame',(cx+leg,y-.80,.25+h),(.059,.48,.44),steel)
# Three distinct lectern exhibits are indexed by their corresponding board.
for x in [-3.42,.10,3.65]:
    box('Bench top',(x,-1.47,1.13),(2.86,.92,.115),oak)
    box('Bench apron',(x,-1.07,.90),(2.59,.10,.40),trim)
    for dx in [-1.10,1.10]:
        box('Lectern end',(x+dx,-1.45,.64),(.13,.75,.94),oak)
# A 3D numerical magnitude model, same shape and samples as the figure atlas.
g=np.load(R/'results/field.npz');amp=np.log1p(np.hypot(g['real'],g['imag']))[::3,::2]
rows,cols=amp.shape
verts=[((i/(rows-1)-.5)*1.79,(.5-j/(cols-1))*.67,.52*amp[i,j]) for i in range(rows) for j in range(cols)]
faces=[(i*cols+j,i*cols+j+1,(i+1)*cols+j+1,(i+1)*cols+j) for i in range(rows-1) for j in range(cols-1)]
o=obj('Exhibit_Surface',mesh('Measured ζ relief',verts,faces,meshmat),(0,-1.47,1.26))
for p in o.data.polygons:p.use_smooth=True
box('Exhibit_SurfaceBase',(0,-1.47,1.215),(1.91,.80,.08),dark)
# Indexed bead ruler, scaled to the measured heights.
zeros=list(csv.DictReader((R/'results/zeros.csv').open()))
box('Exhibit_RulerBase',(-3.42,-1.48,1.22),(2.43,.43,.10),trim)
box('Exhibit_Ruler',(-3.42,-1.48,1.42),(2.34,.036,.036),brass)
for x in [-4.55,-2.29]:box('Ruler post',(x,-1.48,1.34),(.045,.075,.26),brass)
for row in zeros[:16]:
    pos=-4.52+(float(row['height'])-14)/54*2.19
    bpy.ops.mesh.primitive_uv_sphere_add(segments=12,ring_count=8,radius=.066,location=(pos,-1.48,1.42))
    bead=bpy.context.object;bead.name='Exhibit_Zero_'+row['index'];bead.scale=(.67,1,1);bead.data.materials.append(meshmat)
    for poly in bead.data.polygons:poly.use_smooth=True
# Verification monitor carries locally parsed axiom data; nearby bound files hold the primary references.
box('Exhibit_TerminalBase',(3.58,-1.46,1.23),(.61,.37,.055),steel)
box('Monitor stem',(3.58,-1.47,1.42),(.105,.08,.36),steel)
box('Exhibit_Terminal',(3.58,-1.48,1.70),(1.02,.085,.61),steel)
panel('Exhibit_TerminalFace',3.58,-1.53,1.70,.945,.526,mat('Audit display','84998c',tex='board6.jpg'))
for i in range(3):
    x=4.46-.03*i
    box('Exhibit_Sources_'+str(i),(x,-1.44,1.22+i*.072),(.40,.51,.065),[teal,white,trim][i])
for j,(px,py) in enumerate([(-2.37,-1.48),(2.72,-1.6),(4.57,-1.68)]):
    sheet=panel('Exhibit_Sources_Plate'+str(j),px,py,1.214,.43,.26,paperchart);sheet.rotation_euler=( -math.pi/2,.0,.16*(j-1))
for y in [-3,-6.8,-10.4]:
    box('East pilaster',(7.45,y,2.67),(.24,.23,5.34),oak)
world=bpy.data.worlds.new('Daylight');world.use_nodes=True;world.node_tree.nodes['Background'].inputs[0].default_value=(.63,.69,.71,1);world.node_tree.nodes['Background'].inputs[1].default_value=.55;sc.world=world
lamp_at('West daylight',(-6,-4,4.3),(0,.1,2.3),1650,5,(1,.91,.78))
lamp_at('Diffuse room light',(4,-4.5,4.8),(0,0,2),1050,5,(.87,.94,1))
cam=bpy.data.cameras.new('Seminar view');co=obj('Seminar camera',cam,(-.78,-8.4,2.47));co.rotation_euler=(Vector((0,0,2.50))-co.location).to_track_quat('-Z','Y').to_euler();cam.lens=22;sc.camera=co
sc.render.resolution_x=1440;sc.render.resolution_y=900;sc.render.resolution_percentage=100
for im in bpy.data.images:
    if im.filepath and im.name!='Render Result' and im.source=='FILE':
        if not im.packed_file:im.pack()
        im.filepath='//assets/'+Path(im.filepath).name
bpy.context.preferences.filepaths.save_version=0
bpy.ops.wm.save_as_mainfile(filepath=str(R/'scene/classroom.blend'))
bpy.ops.export_scene.gltf(filepath=str(R/'scene/classroom.glb'),export_format='GLB',use_active_scene=True,export_cameras=False,export_lights=False,export_extras=True)
print('Recorded seminar room:',len(sc.objects),'objects in scene')

