# Copied loader logic from C:/q2/refit.py (not edited there); no side effects.
import json,struct,numpy as np
GLB="C:/q2/r/production/handoffs/quik/2026-10-16/crown-landmark/SHELL-C02/MODEL/PI-BLD-0001-V01_CrownLandmark_SHELL_C02.glb"
def load():
    b=open(GLB,"rb").read();ln=struct.unpack("<I",b[8:12])[0];off=12;js=bn=None
    while off<ln:
        cl,ct=struct.unpack("<II",b[off:off+8]);cd=b[off+8:off+8+cl];off+=8+cl
        if ct==0x4E4F534A: js=json.loads(cd)
        else: bn=cd
    def acc(i):
        a=js["accessors"][i];bv=js["bufferViews"][a["bufferView"]];o=bv.get("byteOffset",0)+a.get("byteOffset",0)
        nc={"SCALAR":1,"VEC3":3}[a["type"]];dt={5126:np.float32,5125:np.uint32,5123:np.uint16}[a["componentType"]]
        return np.frombuffer(bn,dtype=dt,count=a["count"]*nc,offset=o).reshape(-1,nc)
    mesh={}
    for n in js["nodes"]:
        assert not any(k in n for k in("matrix","rotation","translation","scale","children"))
        p=js["meshes"][n["mesh"]]["primitives"][0]
        v=acc(p["attributes"]["POSITION"]).astype(float)
        src=np.c_[v[:,0],-v[:,2],v[:,1]]
        t=acc(p["indices"]).reshape(-1,3).astype(int)
        mesh[n["name"]]=(src,t)
    return mesh
def slice_segments(v,t,z):
    """Plane z slice -> (n,2,2) array of segments (vectorised)."""
    tri=v[t]; zz=tri[:,:,2]-z
    pos=zz>0
    cnt=pos.sum(1); sel=np.where((cnt==1)|(cnt==2))[0]
    segs=[]
    for k in sel:
        pts=[]
        for a,c in((0,1),(1,2),(2,0)):
            if pos[k,a]!=pos[k,c]:
                u=zz[k,a]/(zz[k,a]-zz[k,c]); pts.append(tri[k,a,:2]+u*(tri[k,c,:2]-tri[k,a,:2]))
        if len(pts)==2: segs.append(pts)
    return np.array(segs) if segs else np.zeros((0,2,2))
