[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,96 +2,179 @@
|
||||
id: wiki-2026-0508-indirect-draw
|
||||
title: Indirect Draw
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-8EEC8D]
|
||||
aliases: [Indirect Drawing, GPU-Driven Rendering, drawIndirect]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [graphics, gpu, webgpu, vulkan, rendering, performance]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - Indirect Draw"
|
||||
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: wgsl
|
||||
framework: webgpu
|
||||
---
|
||||
|
||||
# [[Indirect Draw|Indirect Draw]]
|
||||
# Indirect Draw
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> Indirect Draw(간접 그리기)는 렌더링할 객체의 수와 정보를 CPU가 아닌 GPU가 컴퓨트 셰이더([[Compute Shader|Compute Shader]])의 연산 결과를 바탕으로 직접 결정하여 화면에 그리는 GPU 주도 렌더링(GPU-driven Rendering) 기법이다 [1, 2]. 이 방식을 사용하면 시야 절두체 컬링([[Frustum Culling|Frustum Culling]])이나 오클루전(Occlusion) 컬링의 결과를 GPU 내부 버퍼에 저장하고 `drawIndirect` 명령으로 바로 출력하므로, CPU와 GPU 간의 데이터 전송량 및 동기화 지연을 거의 0으로 줄일 수 있다 [2, 3]. 매 프레임 수백만 개의 인스턴스를 GPU에서 직접 컬링하고 렌더링해야 하는 대규모 3D 환경에서 필수적인 성능 최적화 기술로 활용된다 [1, 2].
|
||||
## 매 한 줄
|
||||
> **"매 indirect draw 는 draw call args 의 GPU buffer 의 read — CPU roundtrip 없이 GPU 의 self-dispatch"**. 2026 의 GPU-driven rendering pipeline 의 foundation: Vulkan/D3D12/Metal/WebGPU 의 support. 매 culling, LOD, instancing 의 GPU 에서 결정 → CPU draw-call overhead 의 elimination.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **작동 원리 및 GPU 주도 렌더링 (GPU-Driven Rendering):**
|
||||
전통적인 렌더링 파이프라인과 달리, Indirect Draw는 컴퓨트 셰이더를 통해 GPU가 객체의 가시성을 직접 판별하도록 설계되었다 [2, 4]. 컬링 테스트(Cull test)를 통과하여 화면에 보여야 할 객체가 발견되면, 간접 그리기 명령(draw indirect command)의 인스턴스 카운트(instanceCount) 매개변수를 증가시키고 가시성이 확인된 객체에 대해서만 렌더링 명령을 버퍼에 추가(append)하는 방식으로 작동한다 [4, 5].
|
||||
|
||||
* **성능 최적화 및 CPU 병목 해소:**
|
||||
렌더링을 위한 데이터와 명령 버퍼가 GPU 내부에서 생성되고 직접 참조되므로(`drawIndexedIndirect` 등), CPU와 GPU 간의 무거운 메모리 전송 및 동기화 지연이 제거된다 [2, 3]. 이는 구조적으로 "CPU가 GPU에게 무엇을 할지 지시하는 방식"에서 벗어나 "GPU가 스스로 무엇을 렌더링할지 지시하는 시스템"으로의 그래픽스 패러다임 전환을 의미한다 [3].
|
||||
## 매 핵심
|
||||
|
||||
* **지원 환경 및 한계 극복:**
|
||||
[[WebGPU|WebGPU]], Vulkan 등 최신 그래픽스 API 환경에서 주로 활용되며, Three.js에서도 WebGPU 도입과 함께 적극 활용되고 있다 [2, 6, 7]. 매우 복잡하고 방대한 객체를 다룰 때, 기존의 [[InstancedMesh|InstancedMesh]]나 BatchedMesh가 CPU 기반 데이터 업데이트 및 버퍼 패킹으로 인해 겪게 되는 성능 저하 한계를 근본적으로 극복할 수 있는 기술로 평가받는다 [2, 8, 9].
|
||||
### 매 vs Direct Draw
|
||||
- **Direct**: `draw(vertexCount, instanceCount, firstVertex, firstInstance)` — args from CPU.
|
||||
- **Indirect**: `drawIndirect(buffer, offset)` — args read from GPU buffer.
|
||||
- **Multi-draw indirect (MDI)**: thousands of draws from one CPU command.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Graphics & Performance 분야의 자동 자산화 수행.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[GPU-driven Rendering|GPU-Driven Rendering]], Compute Shader, Frustum Culling, [[WebGPU|WebGPU]]
|
||||
- **Projects/Contexts:** Three.js WebGPURenderer, BatchedMesh, [[Vulkan|Vulkan]]
|
||||
- **Contradictions/Notes:** 대규모 지오메트리를 처리할 때 BatchedMesh만으로는 CPU의 버퍼 업로드 병목이 발생할 수 있어 근본적인 성능 문제를 피하기 어려우며, 이를 해결하기 위해서는 WebGPU 환경의 Indirect Draw 지원이 필수적이라는 점이 소스에서 한계점(pushing the limits)으로 지적된다 [9].
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-19*
|
||||
|
||||
---
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(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
|
||||
### 매 Args Layout (WebGPU)
|
||||
```
|
||||
struct DrawIndirectArgs {
|
||||
vertexCount: u32,
|
||||
instanceCount: u32,
|
||||
firstVertex: u32,
|
||||
firstInstance: u32,
|
||||
}
|
||||
struct DrawIndexedIndirectArgs {
|
||||
indexCount: u32,
|
||||
instanceCount: u32,
|
||||
firstIndex: u32,
|
||||
baseVertex: i32,
|
||||
firstInstance: u32,
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### 매 Pipeline (GPU-driven)
|
||||
1. Compute shader: per-object frustum/occlusion cull → write visible list.
|
||||
2. Compute shader: write indirect args buffer (instanceCount=0 for culled).
|
||||
3. `drawIndexedIndirect` (or MDI) reads buffer → renders only visible.
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### 매 응용
|
||||
1. Massive instanced scenes (foliage, crowds, particles).
|
||||
2. GPU-driven culling (frustum, occlusion via Hi-Z).
|
||||
3. LOD selection on GPU.
|
||||
4. Variable-rate / batched rendering (cluster culling, Nanite-style).
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### WebGPU Indirect Draw Setup
|
||||
```ts
|
||||
// Args buffer (visible after compute)
|
||||
const indirectBuffer = device.createBuffer({
|
||||
size: 16, // 4 u32
|
||||
usage: GPUBufferUsage.INDIRECT | GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
|
||||
});
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
// Initialize: 36 verts, 1000 instances, offset 0/0
|
||||
device.queue.writeBuffer(indirectBuffer, 0,
|
||||
new Uint32Array([36, 1000, 0, 0]));
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
// In render pass
|
||||
pass.setPipeline(pipeline);
|
||||
pass.setVertexBuffer(0, vertices);
|
||||
pass.drawIndirect(indirectBuffer, 0);
|
||||
```
|
||||
|
||||
### Culling Compute Shader (WGSL)
|
||||
```wgsl
|
||||
struct DrawArgs { vertexCount: u32, instanceCount: u32,
|
||||
firstVertex: u32, firstInstance: u32 }
|
||||
|
||||
@group(0) @binding(0) var<storage, read> objects: array<Object>;
|
||||
@group(0) @binding(1) var<storage, read_write> drawArgs: DrawArgs;
|
||||
@group(0) @binding(2) var<storage, read_write> visibleInstances: array<u32>;
|
||||
@group(0) @binding(3) var<uniform> camera: Camera;
|
||||
|
||||
@compute @workgroup_size(64)
|
||||
fn cullCS(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
let i = gid.x;
|
||||
if (i >= arrayLength(&objects)) { return; }
|
||||
let obj = objects[i];
|
||||
if (frustumTest(obj.bounds, camera.frustum)) {
|
||||
let slot = atomicAdd(&drawArgs.instanceCount, 1u);
|
||||
visibleInstances[slot] = i;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Reset Pass (clear instanceCount)
|
||||
```ts
|
||||
// Each frame, before culling, zero out instanceCount
|
||||
device.queue.writeBuffer(indirectBuffer, 4, new Uint32Array([0]));
|
||||
```
|
||||
|
||||
### Multi-Draw Indirect (Vulkan)
|
||||
```cpp
|
||||
// Draw N different meshes from one buffer
|
||||
vkCmdDrawIndexedIndirect(cmd, indirectBuf, 0,
|
||||
/*drawCount*/ N,
|
||||
/*stride*/ sizeof(VkDrawIndexedIndirectCommand));
|
||||
|
||||
// Or with count buffer (drawCount is itself on GPU)
|
||||
vkCmdDrawIndexedIndirectCount(cmd, indirectBuf, 0,
|
||||
countBuf, 0, /*maxDraws*/ N,
|
||||
sizeof(VkDrawIndexedIndirectCommand));
|
||||
```
|
||||
|
||||
### Three.js (R175+ has WebGPU)
|
||||
```js
|
||||
import { WebGPURenderer, BatchedMesh } from 'three';
|
||||
const renderer = new WebGPURenderer();
|
||||
// BatchedMesh internally uses indirect draw + instancing
|
||||
const batched = new BatchedMesh(maxInstances, maxVerts, maxIndices);
|
||||
batched.addGeometry(geom1);
|
||||
batched.addGeometry(geom2);
|
||||
// One draw call, GPU handles per-instance state
|
||||
```
|
||||
|
||||
### Hi-Z Occlusion Culling (sketch)
|
||||
```wgsl
|
||||
// Sample Hi-Z mip — fastest mip where bounding sphere covers >1 texel
|
||||
fn occluded(bsphere: vec4<f32>) -> bool {
|
||||
let screenRect = projectToScreen(bsphere);
|
||||
let mip = computeMip(screenRect);
|
||||
let depth = textureSampleLevel(hiZ, samp, screenRect.center, mip).r;
|
||||
return bsphereMinDepth(bsphere) > depth;
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| <100 unique objects | Direct draw / instancing — overhead 의 not worth |
|
||||
| 1k-1M instances | Indirect draw + GPU cull |
|
||||
| Many distinct meshes | Multi-draw indirect (Vulkan/D3D12); WebGPU 의 batched |
|
||||
| Foliage/crowd | Indirect + GPU LOD selection |
|
||||
| Mobile / low-end | Direct draw (compute overhead 의 watch) |
|
||||
|
||||
**기본값**: large dynamic scene 의 GPU-driven indirect pipeline. Small scene 의 direct draw.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[GPU Rendering]] · [[Graphics Pipeline]]
|
||||
- 변형: [[Multi-Draw Indirect]] · [[GPU-Driven Rendering]]
|
||||
- 응용: [[Frustum Culling]] · [[Occlusion Culling]] · [[Nanite]]
|
||||
- Adjacent: [[WebGPU]] · [[Vulkan]] · [[Compute Shader]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: GPU-driven pipeline 의 design, culling 의 implement, draw-call overhead 의 reduce.
|
||||
**언제 X**: simple scene 의 indirect draw 의 over-engineering — direct 의 fine.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **CPU readback of indirect buffer**: 매 stall. GPU 의 self-contained 의 keep.
|
||||
- **Per-frame full buffer rewrite**: defeats purpose. 매 GPU compute 의 update.
|
||||
- **No Hi-Z for occlusion**: false positives — Hi-Z 또는 conservative AABB 의 사용.
|
||||
- **Indirect for tiny scenes**: compute dispatch overhead > savings.
|
||||
- **WebGL fallback assumed**: WebGL 의 no indirect draw — WebGPU required.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (WebGPU spec, Vulkan spec, GPU Gems / Activision Nanite paper).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — indirect draw / GPU-driven rendering full content |
|
||||
|
||||
Reference in New Issue
Block a user