Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

14.0 KB
Raw Blame
import { expect,test } from 'bun:test';
import { BoxGeometry, BufferAttribute, Group, Matrix4, Mesh, MeshStandardMaterial, Scene, Texture, InstancedMesh, SkinnedMesh, Vector3, Box3, Sphere } from 'three/webgpu';
import { deriveInstancingSafeGeometry, assertInstancingSafe, batchStaticMeshes, packInstancedMeshes, freezeTransforms, createFrameGraph } from '../../src/instancing/core';
import { buildInstanceSet, splitInstanceCells, selectCellLod } from '../../src/instancing/instances';
import { createZoneVisibility, createCellStreamer, wantedCells } from '../../src/instancing/streaming';
const matrix=new Matrix4();
test('U-12 only normal-mapped tangent geometry cloned, cached and asserted',()=>{const g=new BoxGeometry();g.setAttribute('tangent',new BufferAttribute(new Float32Array(g.attributes.position!.count*4),4));const m=new MeshStandardMaterial({normalMap:new Texture()}),mesh=new Mesh(g,m),cache=new Map();const derived=deriveInstancingSafeGeometry(mesh,cache);expect(derived).not.toBe(g);expect(derived.getAttribute('tangent')).toBeUndefined();expect(g.hasAttribute('tangent')).toBe(true);expect(derived.getAttribute('position').array).toEqual(g.getAttribute('position').array);expect(deriveInstancingSafeGeometry(mesh,cache)).toBe(derived);const root=new Group(),bad=new InstancedMesh(g,m,1);bad.name='offender';root.add(bad);expect(assertInstancingSafe(root)).toEqual(['offender']);bad.geometry=derived;expect(assertInstancingSafe(root)).toEqual([]);expect(deriveInstancingSafeGeometry(new Mesh(g,new MeshStandardMaterial()),cache)).toBe(g);});
test('U-13 batching keys, exclusions, dynamic update, freeze and graph restore',()=>{
 const scene=new Scene(),worldRoot=new Group();scene.add(worldRoot);const geometry=new BoxGeometry(),material=new MeshStandardMaterial();const owners:any[]=[];
 function owner(id:string,x:number,dynamic=false,g=geometry,m:any=material){const object=new Group(),mesh=new Mesh(g,m);mesh.name=id;object.add(mesh);object.position.x=x;worldRoot.add(object);const o={id,assetId:id.startsWith('excluded')?'excluded':'normal',object,dynamic};owners.push(o);return mesh;}
 const a=owner('a',0),b=owner('b',1,true);owner('far',48);owner('excluded-a',0);owner('excluded-b',1);owner('transparent-a',0,false,geometry,new MeshStandardMaterial({transparent:true}));owner('multi-a',0,false,geometry,[material]);const negative=owner('negative',0);negative.scale.x=-1;const morph=owner('morph',0);morph.morphTargetInfluences=[1];const other=owner('cast',0);other.castShadow=true;
 const batches=batchStaticMeshes(scene,owners,{cellSize:96,cellOffset:48,excludeAssets:new Set(['excluded'])});expect(batches.stats).toEqual({groups:1,sourceMeshes:2,dynamicGroups:1});expect(a.visible).toBe(false);expect(b.visible).toBe(false);b.position.z=3;batches.update();batches.batches[0]!.mesh.getMatrixAt(1,matrix);expect(matrix.elements[14]).toBe(3);
 const frozen=freezeTransforms(owners,o=>!o.dynamic);expect(frozen.placements).toBe(owners.length-2);const graph=createFrameGraph({scene,worldRoot,owners,batches,isFixed:o=>!o.dynamic});expect(graph.stats.hiddenRoots).toBe(2);expect(scene.matrixWorldAutoUpdate).toBe(false);owners[1].object.position.x=2;graph.update();batches.batches[0]!.mesh.getMatrixAt(1,matrix);expect(matrix.elements[12]).toBe(2);graph.restore();frozen.restore();batches.restore();batches.restore();expect(a.visible).toBe(true);expect(scene.matrixWorldAutoUpdate).toBe(true);
});
test('packing combines transformed matrices and restores without disposing borrowed resources',()=>{const s=new Scene(),g=new BoxGeometry(),m=new MeshStandardMaterial(),meshes=[];for(let i=0;i<4;i++){const x=new InstancedMesh(g,m,2);x.setMatrixAt(0,new Matrix4().makeTranslation(1,0,0));x.setMatrixAt(1,new Matrix4().makeTranslation(2,0,0));x.position.x=i*10;x.castShadow=i%2===0;s.add(x);meshes.push(x);}const p=packInstancedMeshes(s,meshes);expect(p.groups).toBe(2);expect(p.instances).toBe(8);expect(meshes.every(m=>!m.visible)).toBe(true);p.restore();p.restore();expect(s.children.length).toBe(4);});
test('FARM-006 frame graph writes a dynamic batch only when a source moved',()=>{
 const scene=new Scene(),worldRoot=new Group();scene.add(worldRoot);const geometry=new BoxGeometry(),material=new MeshStandardMaterial(),owners:any[]=[];
 for(const [id,x] of [['a',0],['b',1]] as const){const object=new Group(),mesh=new Mesh(geometry,material);object.add(mesh);object.position.x=x;worldRoot.add(object);owners.push({id,assetId:'normal',object,dynamic:true});}
 const batches=batchStaticMeshes(scene,owners,{cellSize:96,cellOffset:48,excludeAssets:new Set()}),mesh=batches.batches[0]!.mesh;
 const graph=createFrameGraph({scene,worldRoot,owners,batches,isFixed:()=>false}),version=mesh.instanceMatrix.version;
 graph.update();graph.update();expect(mesh.instanceMatrix.version).toBe(version);
 owners[1].object.position.x=5.1;graph.update();expect(mesh.instanceMatrix.version).toBe(version+1);mesh.getMatrixAt(1,matrix);expect(matrix.elements[12]).toBeCloseTo(5.1);expect(mesh.boundingSphere!.center.x).toBeGreaterThan(2);
 graph.update();batches.update();expect(mesh.instanceMatrix.version).toBe(version+1);
 owners[0].object.position.x=-1;batches.update();expect(mesh.instanceMatrix.version).toBe(version+2);mesh.getMatrixAt(0,matrix);expect(matrix.elements[12]).toBe(-1);
 graph.restore();batches.restore();
});
test('frame graph development guard finds unregistered movement',()=>{const scene=new Scene(),worldRoot=new Group(),unregistered=new Mesh(new BoxGeometry(),new MeshStandardMaterial());scene.add(worldRoot,unregistered);const graph=createFrameGraph({scene,worldRoot,owners:[],batches:null,isFixed:()=>true,validateStatic:true});unregistered.position.x=1;expect(()=>graph.update()).toThrow('Unregistered');graph.addDynamic(unregistered);expect(()=>graph.update()).not.toThrow();graph.restore();});
test('U-28 static split, density, LOD and dynamic handle dirty ranges/colors',()=>{
 const matrices=new Float32Array(4*16);[-1,1,9,11].forEach((x,i)=>new Matrix4().makeTranslation(x,0,0).toArray(matrices,i*16));const cells=splitInstanceCells(matrices,10);expect(cells.map(c=>c.key)).toEqual(['-1,0','0,0','1,0']);expect(cells[1]!.indices).toEqual([1,2]);expect(selectCellLod(10.2,[10,30],0)).toBe(0);expect(selectCellLod(10.6,[10,30],0)).toBe(1);expect(selectCellLod(9.8,[10,30],1)).toBe(1);expect(selectCellLod(9.4,[10,30],1)).toBe(0);
 const set={key:'test',geometry:new BoxGeometry(),material:new MeshStandardMaterial(),matrices,castShadow:false,receiveShadow:true,cellSize:10,density:'instance' as const};const built=buildInstanceSet(set);built.setDensity(.5);expect(built.meshes.map(m=>m.count)).toEqual([0,1,0]);built.dispose();
 const dynamic=buildInstanceSet({...set,dynamic:true,cellSize:0,colors:new Float32Array(12).fill(1),bounds:new Sphere(new Vector3(),50)});const h=dynamic.handle!;h.count=3;h.setMatrix(2,new Matrix4().makeTranslation(20,0,0));h.setColor(2,.1,.2,.3);const v=dynamic.meshes[0]!.instanceMatrix.version;h.flush();expect(dynamic.meshes[0]!.instanceMatrix.version).toBe(v+1);h.flush();expect(dynamic.meshes[0]!.instanceMatrix.version).toBe(v+1);expect(dynamic.meshes[0]!.count).toBe(3);expect(dynamic.meshes[0]!.instanceColor!.array[6]).toBeCloseTo(.1);dynamic.dispose();
});
test('U-17b zones BFS, debounce and nearest fallback',()=>{const zones=['a','b','c'].map((id,i)=>({id,bounds:new Box3(new Vector3(i*10,0,0),new Vector3(i*10+9,9,9)),neighbors:i===0?['b']:i===1?['a','c']:['b']})),roots=new Map(zones.map(z=>[z.id,new Group()])),p=new Vector3(1,1,1);let hops=1;const z=createZoneVisibility(zones,roots,()=>p,()=>hops);z.update(0);expect(z.current()).toBe('a');expect(roots.get('c')!.visible).toBe(false);p.x=21;z.update(200);expect(z.current()).toBe('a');z.update(400);z.update(600);expect(z.current()).toBe('c');hops=0;z.update(800);expect(roots.get('b')!.visible).toBe(false);p.x=100;z.update(1000);expect(z.current()).toBe('c');z.dispose();expect([...roots.values()].every(x=>x.visible)).toBe(true);});
test('U-29 streaming nearest order, concurrency, budget, grace, LRU and late abort disposal',async()=>{
 expect(wantedCells(new Vector3(5,5,5),10,10)[0]).toEqual({x:0,y:0,z:0});const point=new Vector3(5,5,5),pending:{cell:any,resolve:(v:number)=>void,signal:AbortSignal}[]=[],attached:number[]=[],detached:number[]=[],disposed:number[]=[];let time=0;
 const s=createCellStreamer({cellSize:10,viewpoint:()=>point,radius:()=>11,hysteresis:.2,concurrent:2,attachBudgetMs:1,maxResident:2,graceMs:500,load:(cell,signal)=>new Promise<number>(resolve=>pending.push({cell,signal,resolve})),attach:(_c,v,r)=>{attached.push(v);r.add(()=>disposed.push(v));time+=2;},detach:(_c,v)=>{detached.push(v);}},()=>time);
 s.update(0);expect(pending.length).toBe(2);pending[0]!.resolve(1);pending[1]!.resolve(2);await Promise.resolve();s.update(1);expect(attached.length).toBe(1);s.update(2);expect(attached.length).toBe(2);expect(s.stats().resident).toBe(2);point.set(100,100,100);s.update(300);expect(detached.length).toBe(0);s.update(900);expect(detached).toEqual([1,2]);expect(disposed).toEqual([1,2]);s.dispose();expect(pending.every(p=>p.signal.aborted)).toBe(true);
});
test('U-29 failure retry uses backoff and child registries dispose on attach failure',async()=>{let attempts=0,disposed=0;const s=createCellStreamer({cellSize:10,viewpoint:()=>new Vector3(5,5,5),radius:()=>0,hysteresis:.1,concurrent:1,attachBudgetMs:1,maxResident:1,graceMs:100,load:async()=>{attempts++;if(attempts===1)throw Error('transient');return 1;},attach:(_c,_v,r)=>{r.add(()=>disposed++);throw Error('bad attach');},detach:()=>{}},()=>0);s.update(0);await Promise.resolve();await Promise.resolve();s.update(500);expect(attempts).toBe(1);s.update(1000);expect(attempts).toBe(2);await Promise.resolve();s.update(1001);expect(disposed).toBe(1);s.dispose();});
test('U-29 content arriving after abort is detached without attaching',async()=>{let resolve!:(x:number)=>void,detached=0,attached=0;const s=createCellStreamer({cellSize:10,viewpoint:()=>new Vector3(),radius:()=>0,hysteresis:0,concurrent:1,attachBudgetMs:1,maxResident:1,graceMs:0,load:()=>new Promise<number>(r=>resolve=r),attach:()=>attached++,detach:()=>detached++},()=>0);s.update(0);s.dispose();resolve(1);await Promise.resolve();expect(detached).toBe(1);expect(attached).toBe(0);});
test('U-13 every supplied exclusion and skinned mesh is skipped; material/geometry/shadow keys remain separate',()=>{
 const scene=new Scene(),geometry=new BoxGeometry(),material=new MeshStandardMaterial(),owners:any[]=[],excludeAssets=new Set(Array.from({length:7},(_,i)=>`excluded-${i}`));
 const add=(assetId:string,mesh:Mesh)=>{scene.add(mesh);owners.push({id:`owner-${owners.length}`,assetId,object:mesh,dynamic:false});};
 for(const id of excludeAssets){add(id,new Mesh(geometry,material));add(id,new Mesh(geometry,material));}
 add('skin',new SkinnedMesh(geometry,material));add('skin',new SkinnedMesh(geometry,material));
 add('regular',new Mesh(geometry,material));add('regular',new Mesh(geometry,material));
 add('other-material',new Mesh(geometry,new MeshStandardMaterial()));add('other-geometry',new Mesh(new BoxGeometry(),material));const receiver=new Mesh(geometry,material);receiver.receiveShadow=true;add('receiver',receiver);
 const batches=batchStaticMeshes(scene,owners,{cellSize:96,cellOffset:48,excludeAssets});expect(batches.stats.sourceMeshes).toBe(2);expect(batches.stats.groups).toBe(1);expect(batches.stats.dynamicGroups).toBe(0);batches.restore();
});
test('U-28 instance build derives tangents and cell update applies LOD and distance hysteresis',()=>{
 const geometry=new BoxGeometry();geometry.computeTangents();const material=new MeshStandardMaterial({normalMap:new Texture()}),matrices=new Float32Array(16);new Matrix4().toArray(matrices);
 const built=buildInstanceSet({key:'lod-test',geometry,material,matrices,cellSize:0,density:'none',castShadow:false,receiveShadow:true,lods:[{geometry,maxDistance:10},{geometry:new BoxGeometry(.5,.5,.5),maxDistance:30}]});
 expect(assertInstancingSafe(built.root)).toEqual([]);expect(built.meshes[0]!.geometry).not.toBe(geometry);expect(geometry.hasAttribute('tangent')).toBe(true);
 built.update(new Vector3(0,0,1),50,1);expect(built.meshes.map(m=>m.visible)).toEqual([true,false]);built.update(new Vector3(0,0,20),50,1);expect(built.meshes.map(m=>m.visible)).toEqual([false,true]);built.update(new Vector3(0,0,60),50,1);expect(built.meshes.every(m=>!m.visible)).toBe(true);built.update(new Vector3(0,0,50),50,1);expect(built.meshes.every(m=>!m.visible)).toBe(true);built.update(new Vector3(0,0,40),50,1);expect(built.meshes[1]!.visible).toBe(true);built.dispose();
});
test('U-29 maxResident uses last-wanted order while hysteresis preserves resident cells',async()=>{
 const p=new Vector3(5,5,5),detached:string[]=[],attached:string[]=[];
 const s=createCellStreamer({cellSize:10,viewpoint:()=>p,radius:()=>11,hysteresis:.3,concurrent:2,attachBudgetMs:1,maxResident:2,graceMs:5000,load:async c=>`${c.x},${c.y},${c.z}`,attach:(_c,value)=>attached.push(value),detach:(_c,value)=>detached.push(value)},()=>0);
 s.update(0);await Promise.resolve();s.update(1);expect(s.stats().resident).toBe(2);p.x=10;s.update(250);await Promise.resolve();s.update(251);expect(s.stats().resident).toBe(2);expect(detached).toEqual(['-1,0,0']);expect(attached.at(-1)).toBe('1,0,0');p.x=12;s.update(500);expect(s.stats().resident).toBe(2);s.dispose();
});
test('U-28 dynamic colour writes allocate no buffer and moved bounds follow flush',()=>{
 const matrices=new Float32Array(16);new Matrix4().toArray(matrices);const built=buildInstanceSet({key:'moving',geometry:new BoxGeometry(),material:new MeshStandardMaterial(),matrices,dynamic:true,cellSize:0,density:'none',castShadow:false,receiveShadow:false}),mesh=built.meshes[0]!,handle=built.handle!;
 expect(mesh.instanceColor).not.toBeNull();const colors=mesh.instanceColor!.array;handle.setColor(0,.1,.2,.3);handle.setMatrix(0,new Matrix4().makeTranslation(100,0,0));handle.flush();const range=mesh.instanceMatrix.updateRanges[0];handle.setMatrix(0,new Matrix4().makeTranslation(101,0,0));handle.flush();expect(mesh.instanceMatrix.updateRanges[0]).toBe(range);expect(mesh.instanceColor!.array).toBe(colors);built.update(new Vector3(101,0,0),5,1);expect(mesh.visible).toBe(true);built.dispose();
});