--- id: wiki-2026-0508-instancedmesh2-library title: InstancedMesh2 library category: 10_Wiki/Topics status: verified canonical_id: self aliases: [InstancedMesh2, three-instanced-mesh2, three.ez InstancedMesh2] duplicate_of: none source_trust_level: A confidence_score: 0.9 verification_status: applied tags: [threejs, webgl, instancing, performance, gpu, batching] raw_sources: [] last_reinforced: 2026-05-10 github_commit: pending tech_stack: language: typescript framework: three.js --- # InstancedMesh2 library ## 매 한 줄 > **"매 instancing 의 진짜 한계는 frustum culling 과 per-instance state 다"**. InstancedMesh2 는 Three.js 의 표준 InstancedMesh 위에 BVH-driven frustum/occlusion culling, per-instance LOD, dynamic capacity, color/uniform 관리를 얹은 라이브러리로, 100k+ 오브젝트 씬에서 표준 InstancedMesh 대비 2-10x FPS 를 끌어낸다. ## 매 핵심 ### 매 표준 InstancedMesh 의 한계 - frustum culling 부재 — 모든 인스턴스를 매 프레임 GPU 로 보냄. - 정적 capacity — `count` 변경은 가능하지만 capacity 확장은 재생성 필요. - per-instance visibility/LOD 가 없음 — 수동 matrix 0 으로 숨겨야 함. - 정렬 (transparency) 지원 없음. ### 매 InstancedMesh2 의 추가 기능 - **BVH culling**: `bvhParams` 로 dynamic BVH 구축, `frustum` + `occlusion` culling. - **per-instance LOD**: `addLOD(geometry, material, distance)` 로 거리 기반 자동 swap. - **dynamic capacity**: `addInstances(n, callback)` 로 동적 추가. - **per-instance color/uniform**: `setColorAt`, `setUniformAt`. - **sorting**: alpha blending 을 위한 distance sort. ### 매 응용 1. 대규모 식생/도시/별 시스템 (100k-1M 인스턴스). 2. RTS / 시뮬레이션 게임의 유닛 렌더링. 3. 파티클을 mesh 로 대체 (mesh particles). 4. WebXR 환경의 dense scene rendering. ## 💻 패턴 ### 1. 기본 설치 및 생성 ```typescript // npm install @three.ez/instanced-mesh import { InstancedMesh2 } from '@three.ez/instanced-mesh'; import * as THREE from 'three'; const geometry = new THREE.BoxGeometry(1, 1, 1); const material = new THREE.MeshStandardMaterial({ color: 0x44aa88 }); const mesh = new InstancedMesh2(geometry, material, { capacity: 100_000, createEntities: true, // per-instance proxy objects }); scene.add(mesh); ``` ### 2. 동적 인스턴스 추가 ```typescript mesh.addInstances(50_000, (obj, idx) => { obj.position.set( (Math.random() - 0.5) * 1000, (Math.random() - 0.5) * 1000, (Math.random() - 0.5) * 1000, ); obj.scale.setScalar(0.5 + Math.random()); obj.color.setHSL(Math.random(), 0.7, 0.5); }); ``` ### 3. BVH frustum culling 활성화 ```typescript mesh.computeBVH({ margin: 0 }); // renderer 가 매 프레임 BVH 로 visible 인스턴스만 GPU 에 업로드. // margin: BVH 노드 padding (모션이 큰 경우 늘림). ``` ### 4. per-instance LOD ```typescript const lodGeoMid = new THREE.BoxGeometry(1, 1, 1, 2, 2, 2); const lodGeoLow = new THREE.BoxGeometry(1, 1, 1); mesh.addLOD(lodGeoMid, material, 50); // 50m 부터 mid mesh.addLOD(lodGeoLow, material, 200); // 200m 부터 low // 200m 이후 자동 cull (default) ``` ### 5. per-instance update (애니메이션) ```typescript function animate(t: number) { mesh.updateInstances((obj, idx) => { obj.position.y = Math.sin(t * 0.001 + idx * 0.01) * 5; // obj.updateMatrix() 자동 호출됨 }); renderer.render(scene, camera); } ``` ### 6. 인스턴스 hide / show ```typescript mesh.instances[42].visible = false; // 단일 // bulk for (const inst of mesh.instances) { if (inst.position.distanceTo(camera.position) > 500) inst.visible = false; } ``` ### 7. raycasting (BVH 가속) ```typescript const raycaster = new THREE.Raycaster(); raycaster.setFromCamera(mouse, camera); const hits = raycaster.intersectObject(mesh); // hits[0].instanceId 로 인스턴스 식별 ``` ### 8. transparent sorting ```typescript const mat = new THREE.MeshStandardMaterial({ transparent: true, opacity: 0.5, }); const mesh = new InstancedMesh2(geom, mat, { capacity: 10_000, allowsEuler: false, }); mesh.sortObjects = true; // distance sort each frame ``` ### 9. GPU instancing + custom shader uniform ```typescript mesh.initUniformsPerInstance({ vertex: { uOffset: 'vec3' } }); mesh.setUniformAt(idx, 'uOffset', new THREE.Vector3(0, 5, 0)); ``` ### 10. Forest 예제 (실전) ```typescript const trunk = new InstancedMesh2(trunkGeo, trunkMat, { capacity: 50_000 }); const leaves = new InstancedMesh2(leavesGeo, leavesMat, { capacity: 50_000 }); for (let i = 0; i < 50_000; i++) { const x = (Math.random() - 0.5) * 2000; const z = (Math.random() - 0.5) * 2000; trunk.addInstances(1, (o) => o.position.set(x, 0, z)); leaves.addInstances(1, (o) => o.position.set(x, 5, z)); } trunk.computeBVH(); leaves.computeBVH(); ``` ## 매 결정 기준 | 상황 | Approach | |---|---| | < 1k 동일 mesh | 일반 Mesh + Group 도 OK | | 1k-100k 동일 mesh, 정적 | THREE.InstancedMesh | | 100k+ 또는 동적 cull/LOD 필요 | InstancedMesh2 | | 1M+ + GPU compute | WebGPU + indirect draw + InstancedMesh2 | | transparent + 다수 | InstancedMesh2 sorting | **기본값**: 인스턴스 수가 1만 이상이거나 frustum 외부가 많은 씬은 InstancedMesh2 사용. ## 🔗 Graph - 부모: [[Three.js]] - 변형: [[BatchedMesh]] · [[GPU-Instancing]] - 응용: [[Particle-System]] - Adjacent: [[BVH]] · [[Frustum-Culling]] ## 🤖 LLM 활용 **언제**: Three.js 씬 인스턴스 수가 폭증할 때 코드 마이그레이션 가이드, BVH 파라미터 튜닝, LOD 거리 결정에 활용. **언제 X**: Babylon.js / Unity / WebGPU-only 환경에는 직접 적용 불가 (개념만 차용). ## ❌ 안티패턴 - **무조건 capacity 1M**: 빈 슬롯도 BVH 비용 발생 — 실제 수요의 1.2-1.5x 정도. - **매 프레임 computeBVH()**: 정적 인스턴스는 1회만, 동적은 incremental update 사용. - **per-instance Material**: instancing 의 의미가 없어짐 — uniform-per-instance 로 대체. - **`mesh.instances[i].position.x = v` 후 update 누락**: `updateInstances` 또는 `updateMatrix()` 필수. ## 🧪 검증 / 중복 - Verified (@three.ez/instanced-mesh GitHub README, 2026 docs). - 신뢰도 A. ## 🕓 Changelog | 날짜 | 변경 | |---|---| | 2026-05-08 | Phase 1 | | 2026-05-10 | Manual cleanup — InstancedMesh2 API + BVH/LOD 패턴 정리 |