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.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
import { DynamicDrawUsage, StaticDrawUsage, NormalBlending, InstancedMesh, Matrix4, Vector3 } from 'three/webgpu';
import type { BufferGeometry, Mesh, Material, Object3D, Scene } from 'three/webgpu';
export interface InstanceOwner {id:string;object:Object3D;dynamic:boolean;assetId:string}
export interface BatchPolicy {cellSize:number;cellOffset:number;excludeAssets:ReadonlySet<string>}
export interface BatchSet {batches:{mesh:InstancedMesh;sources:{o:Mesh;dynamic:boolean}[];dynamic:boolean}[];stats:{groups:number;sourceMeshes:number;dynamicGroups:number};update():void;restore():void}
function normalMapped(material:Material|Material[]):boolean{return(Array.isArray(material)?material:[material]).some(m=>!!(m as Material&{normalMap?:unknown}).normalMap);}
/**
* FARM-006 (M4 WebGL2 hitch work): write a dynamic batch's instance matrices only when a source moved. Values are compared
* as the Float32 the instance buffer stores, so an unchanged batch keeps its version: no matrix rewrite and no bounding-sphere
* pass that frame, and no upload where the matrices are an instanced vertex attribute with static usage (three 0.186 uploads
* an instanced mesh's per-object uniform buffer every frame it draws, and a DynamicDrawUsage attribute every frame, whatever
* the version; the Farm takes the attribute path with static usage, packages/farm/src/world/instance-attributes.ts).
*/
function writeDynamicBatch(b:{mesh:InstancedMesh;sources:{o:Mesh}[]}):boolean{
const array=b.mesh.instanceMatrix.array as Float32Array;let changed=false;
for(let i=0;i<b.sources.length;i++){const e=b.sources[i]!.o.matrixWorld.elements,at=i*16;for(let k=0;k<16;k++)if(array[at+k]!==Math.fround(e[k]!)){array.set(e,at);changed=true;break;}}
if(changed){b.mesh.instanceMatrix.needsUpdate=true;b.mesh.computeBoundingSphere();}
return changed;
}
export function deriveInstancingSafeGeometry(mesh:Mesh,cache:Map<BufferGeometry,BufferGeometry>):BufferGeometry{if(!normalMapped(mesh.material)||!mesh.geometry.hasAttribute('tangent'))return mesh.geometry;let g=cache.get(mesh.geometry);if(!g){g=mesh.geometry.clone();g.deleteAttribute('tangent');cache.set(mesh.geometry,g);}return g;}
export function assertInstancingSafe(root:Object3D):string[]{const offenders:string[]=[];root.traverse(o=>{const m=o as InstancedMesh;if(m.isInstancedMesh&&normalMapped(m.material)&&m.geometry.hasAttribute('tangent'))offenders.push(m.name||m.uuid);});return offenders;}
/** Generic port of the sealed pilot batching rules; originals remain available for collision and animation. */
export function batchStaticMeshes(scene:Scene,owners:InstanceOwner[],policy:BatchPolicy):BatchSet{
if(!(policy.cellSize>0))throw new Error('Batch cellSize must be positive');scene.updateMatrixWorld(true);const groups=new Map<string,{o:Mesh;dynamic:boolean}[]>(),batches:BatchSet['batches']=[],derived=new Map<BufferGeometry,BufferGeometry>(),pos=new Vector3();let restored=false;
for(const owner of owners){if(policy.excludeAssets.has(owner.assetId))continue;owner.object.traverseVisible(object=>{const o=object as Mesh&{isSkinnedMesh?:boolean};if(!o.isMesh||o.isSkinnedMesh||Array.isArray(o.material)||o.material.transparent||o.morphTargetInfluences?.length||o.matrixWorld.determinant()<=0)return;pos.setFromMatrixPosition(o.matrixWorld);const key=[o.geometry.uuid,o.material.uuid,o.castShadow,o.receiveShadow,Math.floor((pos.x+policy.cellOffset)/policy.cellSize),Math.floor((pos.z+policy.cellOffset)/policy.cellSize)].join('|');let group=groups.get(key);if(!group){group=[];groups.set(key,group);}group.push({o,dynamic:owner.dynamic});});}
for(const sources of groups.values()){if(sources.length<2)continue;const first=sources[0]!.o,mesh=new InstancedMesh(deriveInstancingSafeGeometry(first,derived),first.material,sources.length),dynamic=sources.some(s=>s.dynamic);mesh.name='Repeated '+first.name;mesh.castShadow=first.castShadow;mesh.receiveShadow=first.receiveShadow;mesh.instanceMatrix.setUsage(dynamic?DynamicDrawUsage:StaticDrawUsage);for(let i=0;i<sources.length;i++){mesh.setMatrixAt(i,sources[i]!.o.matrixWorld);sources[i]!.o.visible=false;}mesh.computeBoundingSphere();scene.add(mesh);batches.push({mesh,sources,dynamic});}
return{batches,stats:{groups:batches.length,sourceMeshes:batches.reduce((n,b)=>n+b.sources.length,0),dynamicGroups:batches.filter(b=>b.dynamic).length},update(){if(restored)throw new Error('Batch set has been restored');for(const b of batches)if(b.dynamic){for(const {o}of b.sources)o.updateWorldMatrix(true,false);writeDynamicBatch(b);}},restore(){if(restored)return;restored=true;for(const b of batches){for(const {o}of b.sources)o.visible=true;b.mesh.removeFromParent();b.mesh.dispose();}for(const g of derived.values())g.dispose();derived.clear();}};
}
/** Coarsens culling: streaming scenes must retain cells instead of packing. */
export function packInstancedMeshes(root:Scene,sources:InstancedMesh[]):{groups:number;instances:number;meshes:InstancedMesh[];restore():void}{
root.updateMatrixWorld(true);if(!root.matrixWorld.equals(new Matrix4()))throw new Error('Packing requires an identity scene');const groups=new Map<string,InstancedMesh[]>(),meshes:InstancedMesh[]=[],derived=new Map<BufferGeometry,BufferGeometry>();
for(const source of sources){if(!source.isInstancedMesh||source.parent!==root||!source.visible||source.instanceMatrix.usage!==StaticDrawUsage)throw new Error('Packing requires visible static direct children');if(source.instanceColor||source.morphTexture)throw new Error('Packing does not support instance colour or morph data');if(Array.isArray(source.material)||source.material.transparent||!source.material.depthWrite||source.material.blending!==NormalBlending)throw new Error('Packing requires opaque materials');if((source.geometry as any).isInstancedBufferGeometry||source.matrixWorld.determinant()<=0)throw new Error('Unsupported packing geometry or transform');const key=[source.geometry.uuid,source.material.uuid,source.castShadow,source.receiveShadow,source.layers.mask,source.renderOrder].join('|');let group=groups.get(key);if(!group){group=[];groups.set(key,group);}group.push(source);}
const local=new Matrix4(),world=new Matrix4();for(const group of groups.values()){const first=group[0]!,count=group.reduce((n,m)=>n+m.count,0),mesh=new InstancedMesh(deriveInstancingSafeGeometry(first,derived),first.material,count);mesh.name='Packed '+first.name;mesh.castShadow=first.castShadow;mesh.receiveShadow=first.receiveShadow;mesh.layers.mask=first.layers.mask;mesh.renderOrder=first.renderOrder;let offset=0;for(const source of group)for(let i=0;i<source.count;i++){source.getMatrixAt(i,local);world.multiplyMatrices(source.matrixWorld,local);mesh.setMatrixAt(offset++,world);}mesh.computeBoundingSphere();mesh.computeBoundingBox();mesh.updateMatrixWorld(true);meshes.push(mesh);}
for(const source of sources)source.visible=false;for(const mesh of meshes)root.add(mesh);let restored=false;return{groups:meshes.length,instances:meshes.reduce((n,m)=>n+m.count,0),meshes,restore(){if(restored)return;restored=true;for(const source of sources)source.visible=true;for(const mesh of meshes){mesh.removeFromParent();mesh.dispose();}for(const g of derived.values())g.dispose();}};
}
export function freezeTransforms(owners:InstanceOwner[],isFixed:(o:InstanceOwner)=>boolean):{placements:number;nodes:number;restore():void}{const saved:{o:Object3D;local:boolean;world:boolean}[]=[];let placements=0,restored=false;for(const owner of owners){if(!isFixed(owner)||owner.dynamic)continue;const nodes:Object3D[]=[];owner.object.traverse(o=>nodes.push(o));if(nodes.some(o=>(o as any).isSkinnedMesh||(o as any).isBone||(o as Mesh).morphTargetInfluences?.length||o.animations?.length))continue;owner.object.updateWorldMatrix(true,true);placements++;for(const o of nodes){saved.push({o,local:o.matrixAutoUpdate,world:o.matrixWorldAutoUpdate});o.matrixAutoUpdate=false;o.matrixWorldAutoUpdate=false;}}return{placements,nodes:saved.length,restore(){if(restored)return;restored=true;for(const {o,local,world}of saved){o.matrixAutoUpdate=local;o.matrixWorldAutoUpdate=world;}}};}
export interface FrameGraph {update():void;restore():void;addDynamic(o:Object3D):void;stats:{hiddenRoots:number;dynamicRoots:number}}
/** worldRoot and Scene stay identity; all scene-owned movement is explicitly registered. */
export function createFrameGraph(o:{scene:Scene;worldRoot:Object3D;owners:InstanceOwner[];batches:BatchSet|null;isFixed:(o:InstanceOwner)=>boolean;validateStatic?:boolean}):FrameGraph{
const{scene,worldRoot,owners,batches,isFixed}=o,identity=new Matrix4();scene.updateMatrix();worldRoot.updateMatrix();if(scene.parent||!scene.matrix.equals(identity)||worldRoot.parent!==scene||!worldRoot.matrix.equals(identity))throw new Error('Frame graph requires an identity Scene and direct worldRoot');scene.updateMatrixWorld(true);const auto=scene.matrixWorldAutoUpdate,hidden=new Map<Object3D,boolean>(),dynamic=new Set<Object3D>(),sources=new Set<Mesh>();for(const batch of batches?.batches??[])for(const source of batch.sources)sources.add(source.o);
for(const owner of owners){const root=owner.object;if(root.parent!==worldRoot)throw new Error(`Owner ${owner.id} must be a direct worldRoot child`);let immutable=isFixed(owner)&&!owner.dynamic,hasBatch=false,visibleRender=false;root.traverse(n=>{if(n.matrixAutoUpdate||n.matrixWorldAutoUpdate)immutable=false;if(sources.has(n as Mesh))hasBatch=true;});root.traverseVisible(n=>{const v=n as any;if(v.isMesh||v.isLine||v.isPoints||v.isSprite||v.isLight)visibleRender=true;});if(!immutable)dynamic.add(root);if(root.visible&&hasBatch&&!visibleRender){hidden.set(root,true);root.visible=false;}}
const checkStatic=o.validateStatic??!!import.meta.env?.KILN_DEV;
const snapshots:{node:Object3D;position:Vector3;quaternion:Object3D['quaternion'];scale:Vector3;matrix:Matrix4}[]=[];
if(checkStatic)scene.traverse(node=>snapshots.push({node,position:node.position.clone(),quaternion:node.quaternion.clone(),scale:node.scale.clone(),matrix:node.matrix.clone()}));
const isDynamic=(node:Object3D)=>{let n:Object3D|null=node;while(n){if(dynamic.has(n))return true;n=n.parent;}return false;};
scene.matrixWorldAutoUpdate=false;let restored=false;const stats={hiddenRoots:hidden.size,dynamicRoots:dynamic.size};return{stats,addDynamic(root){if(restored)throw new Error('Frame graph has been restored');dynamic.add(root);stats.dynamicRoots=dynamic.size;},update(){if(restored)throw new Error('Frame graph has been restored');scene.updateMatrix();worldRoot.updateMatrix();if(scene.parent||!scene.matrix.equals(identity)||!worldRoot.matrix.equals(identity))throw new Error('Rebuild frame graph after root transform changes');if(checkStatic)for(const s of snapshots)if(!isDynamic(s.node)&&(!s.position.equals(s.node.position)||!s.quaternion.equals(s.node.quaternion)||!s.scale.equals(s.node.scale)||!s.matrix.equals(s.node.matrix)))throw new Error(`Unregistered moving object: ${s.node.name||s.node.uuid}`);scene.matrixWorldNeedsUpdate=false;for(const root of dynamic)root.updateWorldMatrix(true,true);for(const batch of batches?.batches??[])if(batch.dynamic)writeDynamicBatch(batch);},restore(){if(restored)return;restored=true;scene.matrixWorldAutoUpdate=auto;for(const[root,visible]of hidden)root.visible=visible;dynamic.clear();snapshots.length=0;}};
}