Files
2nd/10_Wiki/Topic_Programming/Architecture/InstancedMesh.md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

6.1 KiB
Raw Blame History

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-instancedmesh InstancedMesh 10_Wiki/Topics verified self
InstancedMesh
GPU Instancing
three.js InstancedMesh
none A 0.95 applied
threejs
webgl
gpu-instancing
rendering
performance
2026-05-10 pending
language framework
JavaScript/TypeScript three.js

InstancedMesh

매 한 줄

"매 thousands of meshes 매 single draw call". THREE.InstancedMesh 매 same-geometry+material 매 N copies 매 GPU instancing 매 single draw — 매 forest, crowd, particle, voxel 의 standard pattern. 2026 매 r170+ 매 BatchedMesh (multi-geometry instancing) 매 추가됨.

매 핵심

매 InstancedMesh vs alternatives

  • Mesh × N: 매 N draw calls. 매 simple, 매 slow at >100.
  • InstancedMesh: 매 1 draw call, 매 same geom/material, 매 per-instance matrix + color.
  • BatchedMesh (r150+): 매 1 draw call, 매 different geom 가능, 매 same material.
  • Custom shader InstancedBufferGeometry: 매 full control, 매 boilerplate.

매 Per-instance attributes

  • setMatrixAt(i, matrix) — 매 position/rotation/scale.
  • setColorAt(i, color) — 매 per-instance tint (requires instanceColor).
  • Custom InstancedBufferAttribute — 매 임의 per-instance data (HP, age, type).

매 응용

  1. Forest/foliage: 10k 매 trees 매 60fps.
  2. Crowd simulation: 매 NPCs 매 unique pose 매 transform.
  3. Voxel terrain: 매 cube instance 매 chunk.
  4. Particle system: 매 GPU-driven particle.
  5. Bullet patterns: 매 bullet hell 매 thousands of bullets.

💻 패턴

Basic InstancedMesh

import * as THREE from 'three';

const count = 10000;
const geom = new THREE.BoxGeometry(1, 1, 1);
const mat  = new THREE.MeshStandardMaterial({ color: 0x44aa88 });
const mesh = new THREE.InstancedMesh(geom, mat, count);

const m = new THREE.Matrix4();
for (let i = 0; i < count; i++) {
  m.setPosition(
    (Math.random() - 0.5) * 100,
    (Math.random() - 0.5) * 100,
    (Math.random() - 0.5) * 100
  );
  mesh.setMatrixAt(i, m);
}
mesh.instanceMatrix.needsUpdate = true;
scene.add(mesh);

Per-instance color

mesh.instanceColor = new THREE.InstancedBufferAttribute(
  new Float32Array(count * 3), 3
);
const c = new THREE.Color();
for (let i = 0; i < count; i++) {
  c.setHSL(i / count, 0.7, 0.5);
  mesh.setColorAt(i, c);
}
mesh.instanceColor.needsUpdate = true;

Dynamic update (animated swarm)

const dummy = new THREE.Object3D();
function tick(time) {
  for (let i = 0; i < count; i++) {
    dummy.position.set(
      Math.sin(time + i) * 10,
      Math.cos(time * 0.5 + i * 0.3) * 5,
      Math.sin(time * 0.3 + i) * 10
    );
    dummy.rotation.y = time + i;
    dummy.updateMatrix();
    mesh.setMatrixAt(i, dummy.matrix);
  }
  mesh.instanceMatrix.needsUpdate = true;
}

Custom per-instance attribute (shader)

const hpAttr = new THREE.InstancedBufferAttribute(new Float32Array(count), 1);
geom.setAttribute('aHp', hpAttr);

mat.onBeforeCompile = (shader) => {
  shader.vertexShader = shader.vertexShader
    .replace('#include <common>', `
      #include <common>
      attribute float aHp;
      varying float vHp;
    `)
    .replace('#include <begin_vertex>', `
      #include <begin_vertex>
      vHp = aHp;
    `);
  shader.fragmentShader = shader.fragmentShader
    .replace('#include <common>', `
      #include <common>
      varying float vHp;
    `)
    .replace('#include <dithering_fragment>', `
      gl_FragColor.rgb = mix(vec3(1,0,0), gl_FragColor.rgb, vHp);
      #include <dithering_fragment>
    `);
};

Frustum culling per instance (CPU side)

const frustum = new THREE.Frustum().setFromProjectionMatrix(
  new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)
);
let visible = 0;
for (let i = 0; i < total; i++) {
  if (frustum.containsPoint(positions[i])) {
    visibleMesh.setMatrixAt(visible++, matrices[i]);
  }
}
visibleMesh.count = visible;
visibleMesh.instanceMatrix.needsUpdate = true;

BatchedMesh (r150+, multi-geometry)

const batch = new THREE.BatchedMesh(maxInstances, maxVerts, maxIndices, mat);
const treeId  = batch.addGeometry(treeGeom);
const rockId  = batch.addGeometry(rockGeom);
for (let i = 0; i < 5000; i++) batch.addInstance(i % 2 === 0 ? treeId : rockId);

Raycasting against InstancedMesh

const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
const hits = raycaster.intersectObject(mesh);
if (hits.length) {
  const i = hits[0].instanceId;
  console.log('Hit instance', i);
}

매 결정 기준

상황 Approach
매 same geom/material × N (>100) InstancedMesh
매 different geom × N BatchedMesh (r150+)
매 fully GPU-driven (compute-style) InstancedBufferGeometry + WebGPU
매 N < 50 regular Mesh OK
매 LOD per instance InstancedMesh × LOD level + custom culling

기본값: 매 N ≥ 100 → InstancedMesh.

🔗 Graph

🤖 LLM 활용

언제: 매 three.js 매 thousands of repeated objects; 매 WebGL 매 draw call optimization. 언제 X: 매 단일 unique mesh; 매 Unity (different API); 매 native C++ engine (use API-specific instancing).

안티패턴

  • Per-frame full rebuild: 매 모든 matrix 매 update — 매 변하지 않는 instance 매 skip.
  • Forgetting needsUpdate: 매 setMatrixAt 후 매 GPU 매 stale.
  • InstancedMesh × different materials: 매 불가능 — BatchedMesh or 분리.
  • Raycast against 100k instances every frame: 매 BVH (three-mesh-bvh) 사용.

🧪 검증 / 중복

  • Verified (three.js docs r170, official examples webgl_instancing_*, BatchedMesh PR #25556).
  • 신뢰도 A.

🕓 Changelog

날짜 변경
2026-05-08 Phase 1
2026-05-10 Manual cleanup — full content (instancing patterns + BatchedMesh)