[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,99 +2,156 @@
|
||||
id: wiki-2026-0508-instancedmesh2
|
||||
title: InstancedMesh2
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-0E2591]
|
||||
aliases: [three-instanced-mesh2, three.js-instancedmesh2]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [three.js, webgl, performance, instancing, rendering]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - [[InstancedMesh|InstancedMesh]]2"
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: TypeScript
|
||||
framework: three.js
|
||||
---
|
||||
|
||||
# [[InstancedMesh2|InstancedMesh2]]
|
||||
# InstancedMesh2
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> InstancedMesh2는 Three.js의 기본 `InstancedMesh`를 확장하여 성능과 기능을 대폭 강화한 오픈 소스 라이브러리이다 [1-3]. 이 라이브러리는 개별 인스턴스에 대한 절두체 컬링([[Frustum Culling|Frustum Culling]]), 공간 인덱스(BVH)를 이용한 빠른 레이캐스팅, 정렬([[Sorting|Sorting]]), 개별 가시성 관리 및 LOD 기능을 제공한다 [2-5]. 특히 기존 인스턴싱 기술로 처리하기 까다로웠던 개별 애니메이션 상태를 가진 스킨드 메쉬(Skinned Mesh)의 인스턴싱을 지원하여 대규모 3D 환경을 효율적으로 렌더링하는 데 활용된다 [1, 3, 6].
|
||||
## 매 한 줄
|
||||
> **"매 InstancedMesh의 진화형 — frustum culling, LOD, BVH, per-instance uniforms를 그대로 지원하는 instancing 솔루션"**. 매 three.js의 stock InstancedMesh가 모든 instance를 ALWAYS draw 하는 한계를 극복하기 위해 등장한 community library — agargaro/instanced-mesh가 매 2024-2026 사실상 표준으로 자리잡음.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **핵심 기능 및 최적화 기법**
|
||||
* **인스턴스별 절두체 컬링 및 가시성 제어:** 개별 인스턴스 단위로 가시성을 관리하고 절두체 컬링을 수행한다 [2, 3, 5]. 이를 통해 카메라 뷰 내부에 존재하는 인스턴스의 뼈대(Bone) 계산만 수행하는 등 연산을 극도로 최적화할 수 있으며, `onFrustumEnter`를 사용해 인스턴스 렌더링 여부를 정밀하게 제어할 수 있다 [1, 7].
|
||||
* **BVH 기반 빠른 레이캐스팅:** `[[three-mesh-bvh|three-mesh-bvh]]` 라이브러리 설계에 착안한 공간 인덱스(Spatial index)를 포함하여, 수많은 인스턴스가 배치된 환경에서도 빠른 레이캐스팅과 컬링을 지원한다 [3-5, 8].
|
||||
* **LOD 및 애니메이션(Skinning) 최적화:** 객체의 거리(LOD)에 따라 기하학적 구조(Geometry)뿐 아니라 뼈대(Bones) 연산까지 축소하고, 거리에 비례하여 애니메이션 FPS를 0에서 60까지 조절할 수 있다 [1, 6, 9, 10]. 이를 통해 모바일 기기에서도 2만 개 이상의 스킨드 인스턴스를 무리 없이 구동할 수 있다 [1].
|
||||
* **정렬(Sorting):** 렌더링 시 투명도 문제를 방지하기 위해, 내부적으로 BatchedMesh에 기반한 기수 정렬([[Radix Sort|Radix Sort]]) 기능을 제공한다 [11, 12].
|
||||
## 매 핵심
|
||||
|
||||
* **내부 아키텍처 및 데이터 구조**
|
||||
* **간접 참조(Indirection) 기반 인덱싱:** 라이브러리 초기 버전과 달리, `Instanced[[BufferAttribute|BufferAttribute]]`를 활용하여 렌더링될 인스턴스 인덱스를 간접적으로 관리한다 [12]. 이는 GPU로 데이터를 보내기 전 컬링, 선택적 렌더링, 정렬 작업을 배열의 물리적 재정렬 없이 빠르게 수행할 수 있게 한다 [12].
|
||||
* **SquareDataTexture의 활용:** 인스턴스의 행렬(Matrix) 및 주요 데이터를 저장하는 데 `DataTexture`의 확장 버전인 `SquareDataTexture`를 사용한다 [12]. 이 방식은 부분 업데이트(Partial Updates)를 지원하여 전체 데이터를 갱신할 필요 없이 변경된 일부 인스턴스의 정보만 갱신하도록 돕는다 [8, 12].
|
||||
### 매 stock InstancedMesh의 한계
|
||||
- 매 frustum culling 부재 → off-screen instance도 GPU에 commit
|
||||
- 매 per-instance visibility toggle 부재
|
||||
- 매 LOD 미지원 — 매 distance 무관 동일 mesh draw
|
||||
- 매 raycasting brute-force — 매 매 instance 매 triangle scan
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
|
||||
### 매 InstancedMesh2 추가 기능
|
||||
- **Per-instance frustum culling**: 매 BVH 기반 fast cull
|
||||
- **LOD groups**: 매 distance threshold 별 다른 geometry
|
||||
- **BVH acceleration**: 매 raycast O(log n)
|
||||
- **Per-instance uniforms**: 매 색상/sprite frame/animation time 등
|
||||
- **Shadow culling**: 매 shadow camera frustum 별도 cull
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[InstancedMesh|InstancedMesh]], Frustum culling, BVH, [[LOD|LOD]], [[SkinnedMesh|SkinnedMesh]], BatchedMesh
|
||||
- **Projects/Contexts:** [[agargaro의 오픈 소스 라이브러리|agargaro의 오픈 소스 라이브러리]], [[20k skinned instances demo|20k skinned instances demo]]
|
||||
- **Contradictions/Notes:**
|
||||
- `SquareDataTexture`를 활용한 부분 업데이트 기능이 연속되지 않은 메모리 접근과 부가적인 함수 호출로 인해 CPU 오버헤드를 유발할 수 있다는 우려가 제기되었으나, 소수의 인스턴스만 변하는 상황에서는 상당한 대역폭 절약 효과가 있다고 라이브러리 개발자(@agargaro)가 반론했습니다 [8, 13, 14].
|
||||
- 이러한 고급 기능들이 유용함에도 불구하고, Three.js의 메인 코어에 병합하기에는 내부 셰이더 변경과 기존 코드 호환성 파괴(Breaking changes) 등 유지보수 복잡성이 너무 커서 외부 라이브러리로 분리 개발되고 있습니다 [15, 16].
|
||||
### 매 응용
|
||||
1. 매 RTS/시뮬레이션 — 매 1k+ unit 매 60fps.
|
||||
2. 매 archviz — 매 forest/도시 scenery instance.
|
||||
3. 매 particle alternative — 매 mesh-particle hybrid.
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-19*
|
||||
## 💻 패턴
|
||||
|
||||
---
|
||||
### 매 기본 setup
|
||||
```typescript
|
||||
import { InstancedMesh2 } from '@three.ez/instanced-mesh';
|
||||
import * as THREE from 'three';
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
const geo = new THREE.BoxGeometry(1, 1, 1);
|
||||
const mat = new THREE.MeshStandardMaterial();
|
||||
const count = 10_000;
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
const mesh = new InstancedMesh2(geo, mat, { capacity: count });
|
||||
mesh.addInstances(count, (obj, idx) => {
|
||||
obj.position.set(
|
||||
(Math.random() - 0.5) * 200,
|
||||
0,
|
||||
(Math.random() - 0.5) * 200,
|
||||
);
|
||||
obj.color = new THREE.Color(Math.random(), Math.random(), Math.random());
|
||||
});
|
||||
mesh.computeBVH();
|
||||
scene.add(mesh);
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### 매 LOD groups
|
||||
```typescript
|
||||
const lod = new InstancedMesh2(geoHigh, mat, { capacity: 5000 });
|
||||
lod.addLOD(geoMid, mat, 30); // 30 units 부터 mid mesh
|
||||
lod.addLOD(geoLow, mat, 100); // 100 units 부터 low mesh
|
||||
lod.addShadowLOD(geoShadow, 50); // shadow 용 별도 LOD
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### 매 per-instance update
|
||||
```typescript
|
||||
mesh.updateInstances((obj, idx) => {
|
||||
obj.position.y = Math.sin(time + idx * 0.1);
|
||||
obj.rotation.y += 0.01;
|
||||
});
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### 매 frustum culling toggle
|
||||
```typescript
|
||||
mesh.perObjectFrustumCulled = true; // default
|
||||
mesh.sortObjects = true; // 매 transparent 매 back-to-front
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### 매 raycasting BVH
|
||||
```typescript
|
||||
mesh.computeBVH({ margin: 0 });
|
||||
const ray = new THREE.Raycaster();
|
||||
ray.setFromCamera(mouse, camera);
|
||||
const hits = ray.intersectObject(mesh);
|
||||
// hits[0].instanceId 매 정확한 instance
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### 매 instance 제거
|
||||
```typescript
|
||||
mesh.removeInstances([0, 5, 10]); // 매 batch 매 1 frame
|
||||
mesh.computeBVH(); // 매 dirty 면 rebuild
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### 매 color attribute
|
||||
```typescript
|
||||
mesh.setColorAt(idx, new THREE.Color('red'));
|
||||
mesh.instanceColor.needsUpdate = true;
|
||||
```
|
||||
|
||||
### 매 shader integration
|
||||
```typescript
|
||||
mat.onBeforeCompile = (shader) => {
|
||||
shader.vertexShader = shader.vertexShader.replace(
|
||||
'#include <begin_vertex>',
|
||||
`#include <begin_vertex>
|
||||
transformed += instanceMatrix[3].xyz * 0.01;`
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| <500 instance | 매 stock InstancedMesh |
|
||||
| 1k-100k 매 same geometry | InstancedMesh2 |
|
||||
| 매 different geometries | BatchedMesh |
|
||||
| 매 GPU-driven 매 indirect | 매 custom WebGPU |
|
||||
|
||||
**기본값**: 매 1k 이상 instance — InstancedMesh2.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[InstancedMesh]] · [[three.js]]
|
||||
- 변형: [[BatchedMesh]] · [[three-mesh-bvh]]
|
||||
- 응용: [[Frustum Culling]] · [[Draw Call]]
|
||||
- Adjacent: [[BVH]] · [[Raycaster]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 large-scale 동일 mesh scene — vegetation, crowd, debris.
|
||||
**언제 X**: 매 instance 별 geometry 다름 — BatchedMesh 사용.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **BVH 매 update 안 함**: 매 instance 이동 후 raycast 부정확.
|
||||
- **capacity 매 너무 크게**: 매 GPU memory 매 낭비.
|
||||
- **per-frame full update**: 매 dirty flag 만 flush.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (@three.ez/instanced-mesh v0.4+, three.js r170+).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — InstancedMesh2 라이브러리 사용법 + LOD/BVH 패턴 정리 |
|
||||
|
||||
Reference in New Issue
Block a user