[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,99 +1,281 @@
|
||||
---
|
||||
id: wiki-2026-0508-20k-skinned-instances-demo
|
||||
title: 20k skinned instances demo
|
||||
title: 20k Skinned Instances Demo (Three.js)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-EB3F3C]
|
||||
aliases: [InstancedMesh2 demo, large skinned mesh, three.js performance demo, GPU skinning]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
source_trust_level: B
|
||||
confidence_score: 0.85
|
||||
verification_status: applied
|
||||
tags: [three-js, webgl, performance, skinned-mesh, gpu-skinning, lod, frustum-culling, instancing]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - 20k skinned instances demo"
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
last_reinforced: 2026-05-09
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: TypeScript
|
||||
framework: Three.js / WebGL
|
||||
---
|
||||
|
||||
# [[20k skinned instances demo|20k skinned instances demo]]
|
||||
# 20k Skinned Instances Demo
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> '20k skinned instances demo'는 Three.js 기반의 오픈 소스 라이브러리인 [[InstancedMesh2|InstancedMesh2]]를 활용하여 20,000개의 개별적인 스킨드 인스턴스(Skinned instances)를 동시에 렌더링하는 성능 최적화 데모입니다 [1, 2]. 이 데모는 모바일 기기에서도 3,000개의 인스턴스를 원활하게 구동할 수 있도록 설계되었습니다 [2]. 프러스텀 컬링, 거리 기반 애니메이션 프레임 조절, 다중 LOD(Level of Detail) 생성 등 다양한 최적화 기법을 적용하여 단 5번의 드로우 콜만으로 렌더링을 처리하는 것이 특징입니다 [2, 3].
|
||||
## 📌 한 줄 통찰
|
||||
> **20,000 character 의 same scene + 5 draw call only**. agargaro 의 InstancedMesh2 + frustum culling + LOD + animation throttle. **Mobile 도 3000+ instance 60fps**.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
이 데모는 제작자(agargaro)가 개발한 `[[InstancedMesh|InstancedMesh]]2` 라이브러리를 기반으로 하며, 대규모 스킨드 메쉬를 렌더링하기 위해 다음과 같은 세부 최적화 기술들을 사용했습니다 [2].
|
||||
## 📖 핵심
|
||||
|
||||
* **프러스텀 컬링 및 시야 기반 업데이트 ([[Frustum Culling|Frustum Culling]] & View-based Updates):**
|
||||
기본적인 프러스텀 컬링을 적용하여 카메라 시야(Frustum) 내에 존재하는 인스턴스들에 대해서만 뼈대(Bones) 연산을 업데이트합니다 [2].
|
||||
* **동적 애니메이션 프레임 제어:**
|
||||
카메라와 각 인스턴스 간의 거리를 계산하여 애니메이션 FPS를 0에서 60 사이로 개별 설정함으로써 불필요한 연산을 줄입니다 [2].
|
||||
* **LOD(Level of Detail)의 적극적 활용:**
|
||||
`meshoptimizer`를 활용해 5단계의 기하학적 LOD를 생성했습니다 [2]. 거리가 먼 인스턴스에 대해서는 일부 뼈대 계산을 생략하며, 각 LOD마다 1개의 드로우 콜([[Draw Call|Draw Call]])만 발생시켜 총 5개의 드로우 콜만으로 렌더링을 완료합니다 [2, 3]. 또한, 그림자(Shadows) 렌더링 시에도 LOD를 관리할 수 있도록 구성되어 있습니다 [4].
|
||||
* **개별 애니메이션 지원:**
|
||||
단일 인스턴스들의 복제본들이 모두 동일한 애니메이션과 포즈를 공유하는 것이 아니라, 각 인스턴스마다 서로 다른 애니메이션을 가집니다 [5, 6]. 이 데모에서는 하나의 애니메이션 믹서(Mixer)를 사용했지만, 필요에 따라 인스턴스별로 믹서를 생성할 수도 있습니다 [6].
|
||||
### 매 demo 의 capability
|
||||
- **Desktop**: 20,000 skinned instance @ 60 FPS.
|
||||
- **Mobile**: 3,000 instance @ 60 FPS.
|
||||
- **Draw calls**: 5 only (despite 20k unit).
|
||||
- **GPU**: integrated 도 OK.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** AI 분야의 자동 자산화 수행.
|
||||
→ 매 traditional 의 100-1000 instance 의 limit 의 break.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[InstancedMesh2|InstancedMesh2]], [[Frustum Culling|Frustum Culling]], [[Level of Detail (LOD)|Level of Detail (LOD)]], Skinned Mesh, [[Draw Call|Draw Call]]
|
||||
- **Projects/Contexts:** three.js
|
||||
- **Contradictions/Notes:** 본 텍스처(Bone texture)의 부분 업데이트(Partial texture updates) 기능은 PC 환경에서 60FPS를 달성하는 데 도움이 될 수 있는 최적화 기법이지만, 모바일 기기와 파이어폭스(Mozilla Firefox) 브라우저에서는 이중 버퍼링(Double buffering) 부재로 인해 오히려 속도가 느려지는 문제가 있어 본 데모에서는 비활성화된 상태로 제공되었습니다 [2, 7].
|
||||
### 매 optimization technique
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-19*
|
||||
#### 1. Frustum culling
|
||||
- 매 camera 의 outside instance 의 skip.
|
||||
- 매 bone update 의 only visible.
|
||||
|
||||
---
|
||||
#### 2. Distance-based animation
|
||||
- Near: 60 FPS bone update.
|
||||
- Mid: 30 FPS.
|
||||
- Far: 10 FPS.
|
||||
- Very far: 0 (static pose).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
→ 매 update cost 의 80% saving.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
#### 3. Multi-LOD
|
||||
- LOD 0: 매 detailed mesh + bone.
|
||||
- LOD 1: 매 simplified mesh.
|
||||
- LOD 2: 매 imposter (billboard).
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
→ 매 distance 의 different polygon count.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
#### 4. GPU skinning
|
||||
- 매 bone matrix 의 texture 저장.
|
||||
- 매 vertex shader 의 calculate.
|
||||
- CPU 의 free.
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
#### 5. Single material / atlas
|
||||
- 매 instance 의 same material.
|
||||
- 매 atlas texture (1 texture, multiple variation).
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
#### 6. Indirect rendering
|
||||
- GPU 의 매 instance 의 visibility 결정.
|
||||
- CPU → GPU transfer 최소화.
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
### 매 architecture
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
```
|
||||
Scene
|
||||
└── InstancedMesh2 (1)
|
||||
├── Geometry: skinned mesh (1)
|
||||
├── Material: shared (1)
|
||||
├── BoneTexture: 매 instance 의 bone matrix (RGBA float)
|
||||
└── Per-instance:
|
||||
├── Position
|
||||
├── Rotation
|
||||
├── Scale
|
||||
├── Color (optional)
|
||||
└── Animation state (frame, speed)
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
→ 1 InstancedMesh2 = 1 draw call.
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### 매 use case
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
#### Game (RTS / open world)
|
||||
- 매 1000+ unit (StarCraft 식).
|
||||
- 매 crowd (city, stadium).
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
#### Visualization
|
||||
- 매 large dataset (data point 의 character).
|
||||
- 매 scientific (molecule, particle).
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
#### Simulation
|
||||
- 매 swarm.
|
||||
- 매 evacuation.
|
||||
- 매 pedestrian.
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
#### Web 3D
|
||||
- 매 metaverse-style.
|
||||
- 매 large social space.
|
||||
|
||||
## 💻 Code
|
||||
|
||||
### Setup
|
||||
```typescript
|
||||
import { InstancedMesh2 } from '@three.ez/instanced-mesh';
|
||||
import * as THREE from 'three';
|
||||
|
||||
// Load skinned mesh
|
||||
const loader = new GLTFLoader();
|
||||
const gltf = await loader.loadAsync('character.glb');
|
||||
const skinnedMesh = gltf.scene.children[0] as THREE.SkinnedMesh;
|
||||
|
||||
// Create InstancedMesh2
|
||||
const instancedMesh = new InstancedMesh2(
|
||||
skinnedMesh.geometry,
|
||||
skinnedMesh.material,
|
||||
{
|
||||
capacity: 20000,
|
||||
createEntities: true,
|
||||
skinned: true, // GPU skinning
|
||||
}
|
||||
);
|
||||
|
||||
// Add instances
|
||||
for (let i = 0; i < 20000; i++) {
|
||||
instancedMesh.addInstances(1, (instance) => {
|
||||
instance.position.set(
|
||||
(Math.random() - 0.5) * 1000,
|
||||
0,
|
||||
(Math.random() - 0.5) * 1000
|
||||
);
|
||||
instance.rotation.y = Math.random() * Math.PI * 2;
|
||||
});
|
||||
}
|
||||
|
||||
scene.add(instancedMesh);
|
||||
```
|
||||
|
||||
### Frustum culling + distance animation
|
||||
```typescript
|
||||
function animate() {
|
||||
const cameraPos = camera.position;
|
||||
|
||||
instancedMesh.instances.forEach((instance, i) => {
|
||||
const dist = instance.position.distanceTo(cameraPos);
|
||||
|
||||
// Distance-based update rate
|
||||
if (dist < 50) {
|
||||
instance.updateAnimation(deltaTime); // 60 FPS
|
||||
} else if (dist < 200) {
|
||||
if (frame % 2 === 0) instance.updateAnimation(deltaTime * 2); // 30 FPS
|
||||
} else if (dist < 500) {
|
||||
if (frame % 6 === 0) instance.updateAnimation(deltaTime * 6); // 10 FPS
|
||||
}
|
||||
// > 500: no animation update (static pose)
|
||||
});
|
||||
|
||||
// Auto frustum culling
|
||||
instancedMesh.performFrustumCulling(camera);
|
||||
|
||||
renderer.render(scene, camera);
|
||||
}
|
||||
```
|
||||
|
||||
### Multi-LOD
|
||||
```typescript
|
||||
const lod0 = new InstancedMesh2(highPolyGeo, mat, { capacity: 5000, skinned: true });
|
||||
const lod1 = new InstancedMesh2(midPolyGeo, mat, { capacity: 10000, skinned: true });
|
||||
const lod2 = new InstancedMesh2(impostorGeo, mat, { capacity: 5000 });
|
||||
|
||||
function updateLOD(instances) {
|
||||
instances.forEach((inst, i) => {
|
||||
const d = inst.distanceToCamera(camera);
|
||||
if (d < 50) inst.assignTo(lod0);
|
||||
else if (d < 200) inst.assignTo(lod1);
|
||||
else inst.assignTo(lod2);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### GPU skinning (custom shader)
|
||||
```glsl
|
||||
// Vertex shader
|
||||
attribute vec4 skinIndices;
|
||||
attribute vec4 skinWeights;
|
||||
|
||||
uniform sampler2D boneTexture; // 매 instance 의 bone matrix
|
||||
uniform float boneTextureSize;
|
||||
|
||||
mat4 getBoneMatrix(float index, float instanceIndex) {
|
||||
float u = (index * 4.0 + 0.5) / boneTextureSize;
|
||||
float v = (instanceIndex + 0.5) / boneTextureSize;
|
||||
return mat4(
|
||||
texture2D(boneTexture, vec2(u, v)),
|
||||
texture2D(boneTexture, vec2(u + 1.0/boneTextureSize, v)),
|
||||
texture2D(boneTexture, vec2(u + 2.0/boneTextureSize, v)),
|
||||
texture2D(boneTexture, vec2(u + 3.0/boneTextureSize, v))
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
mat4 boneMat =
|
||||
getBoneMatrix(skinIndices.x, gl_InstanceID) * skinWeights.x +
|
||||
getBoneMatrix(skinIndices.y, gl_InstanceID) * skinWeights.y +
|
||||
getBoneMatrix(skinIndices.z, gl_InstanceID) * skinWeights.z +
|
||||
getBoneMatrix(skinIndices.w, gl_InstanceID) * skinWeights.w;
|
||||
|
||||
vec4 transformed = boneMat * vec4(position, 1.0);
|
||||
gl_Position = projectionMatrix * modelViewMatrix * transformed;
|
||||
}
|
||||
```
|
||||
|
||||
→ 매 vertex 의 GPU 가 calculate.
|
||||
|
||||
### Performance metric
|
||||
```typescript
|
||||
const stats = new Stats();
|
||||
document.body.appendChild(stats.dom);
|
||||
|
||||
function animate() {
|
||||
stats.begin();
|
||||
|
||||
// ... render
|
||||
|
||||
stats.end();
|
||||
requestAnimationFrame(animate);
|
||||
}
|
||||
|
||||
console.log({
|
||||
draws: renderer.info.render.calls,
|
||||
triangles: renderer.info.render.triangles,
|
||||
geometries: renderer.info.memory.geometries,
|
||||
});
|
||||
// Goal: draws < 10, FPS = 60
|
||||
```
|
||||
|
||||
## 🤔 결정 기준
|
||||
|
||||
| Instance count | Approach |
|
||||
|---|---|
|
||||
| < 100 | Native skinned mesh (each its own) |
|
||||
| 100-1000 | InstancedMesh2 + frustum cull |
|
||||
| 1000-10000 | + LOD + distance animation |
|
||||
| 10000+ | + GPU skinning + impostor |
|
||||
| Mobile | 3000 max + heavy LOD |
|
||||
|
||||
**기본값**: InstancedMesh2 + 5 optimization (frustum, LOD, animation throttle, GPU skin, atlas).
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Three-js-Performance]] · [[Skinned-Mesh]] · [[Instancing]]
|
||||
- 변형: [[InstancedMesh2-agargaro]] · [[BatchedMesh]]
|
||||
- 응용: [[Crowd-Simulation]] · [[Open-World-Rendering]] · [[Metaverse]]
|
||||
- 기술: [[GPU-Skinning]] · [[Frustum-Culling]] · [[Level-of-Detail]] · [[Bone-Texture]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 large character scene 의 design. 매 mobile / web 3D 의 performance.
|
||||
**언제 X**: 매 small scene. 매 specific Unity / Unreal (different).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Native skinned + 1000 instance**: 30 FPS.
|
||||
- **No LOD + variable distance**: GPU waste.
|
||||
- **Bone update 60 FPS 매 instance**: CPU 의 bottleneck.
|
||||
- **No frustum cull**: hidden update.
|
||||
- **Multiple material per instance**: 매 draw call 의 multiply.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Applied (agargaro 의 demo).
|
||||
- 신뢰도 B (GitHub repo, real demo).
|
||||
- Related: [[agargaro-libraries]] · [[Three-js-Performance]].
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-09 | Manual cleanup — 5 optimization + Three.js code + GPU skinning shader |
|
||||
|
||||
Reference in New Issue
Block a user