[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+170 -65
View File
@@ -1,95 +1,200 @@
---
id: wiki-2026-0508-depth-pre-pass
title: Depth Pre Pass
title: Depth Pre-Pass
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-B5A436]
aliases: [Z-prepass, depth prepass, early-Z, Z-only pass]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [graphics, rendering, gpu, optimization, depth-buffer, overdraw]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - Depth Pre-Pass"
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: HLSL / GLSL / Shader
framework: Unreal / Unity / Custom
---
# [[Depth Pre-Pass|Depth Pre-Pass]]
# Depth Pre-Pass
## 📌 한 줄 통찰 (The Karpathy Summary)
> Depth Pre-Pass는 복잡한 기하학적 구조를 가진 씬에서 가려진 객체를 제거하는 오클루전 컬링(Occlusion culling)을 수행하기 위해 사용되는 효과적인 렌더링 전략입니다 [1]. 특히 필 레이트(fill-rate)와 프래그먼트 처리 성능이 제한된 내장 GPU(iGPU) 환경에서 유용한 해결책으로 활용됩니다 [1]. 렌더링을 두 단계로 나누어 불필요한 프래그먼트 셰이더 연산을 방지함으로써 오버드로우([[Overdraw|Overdraw]])가 심한 모델의 렌더링 성능을 크게 향상시킵니다 [1, 2].
## 한 줄
> **"매 main shading 전 의 depth-only render"**. 매 overdraw 의 reduce — 매 expensive pixel shader 의 hidden surface 의 skip. 매 modern GPU 의 early-Z + Hi-Z + 매 deferred / forward+. 매 cost: 매 vertex 2x.
## 📖 구조화된 지식 (Synthesized Content)
* **작동 원리 (두 단계의 렌더링 프로세스):** Depth Pre-Pass는 다음과 같은 두 가지 렌더링 단계로 구성됩니다 [1].
1. **Stage 1 (Depth-Only):** 씬 전체를 `MeshBasicMaterial`과 같이 매우 단순한 재질을 사용하여 렌더링하며, 이때 색상 쓰기 기능은 비활성화(`colorWrite: false`)합니다 [1]. 이 첫 번째 패스는 가장 가까운 프래그먼트의 깊이(depth) 값으로 Z-버퍼(Z-buffer)를 채우는 역할만을 수행합니다 [1].
2. **Stage 2 (Main Render):** 깊이 테스트(depth test) 함수를 `EQUAL`로 설정한 후, 전체 셰이딩을 적용하여 씬을 다시 렌더링합니다 [1]. Z-버퍼에는 이미 화면에 보이는 표면의 깊이 값만 저장되어 있으므로, GPU는 다른 물체에 가려진(occluded) 프래그먼트들이 연산 비용이 높은 메인 셰이더 로직에 진입하기 전에 이를 자동으로 폐기(discard)합니다 [1].
## 매 핵심
* **성능 향상 및 적용 효과:**
이러한 수동 Z-prepass 로직을 구현하면 프래그먼트 셰이더에 가해지는 부하를 최대 30%까지 줄일 수 있습니다 [2]. 이는 숨겨진 내부 기하구조 레이어가 많아 픽셀이 여러 번 덧그려지는 '오버드로우(overdraw)'가 심하게 발생하는 CAD 모델을 렌더링할 때 특히 귀중한 최적화 기법입니다 [2]. 개발자들은 이러한 깊이 기반의 가시성 판별(Depth Pre-Pass) 기술을 구조적 최적화 및 Render-on-Demand 실행 모델과 결합하여, 표준 모바일 하드웨어에서도 워크스테이션 수준의 시각화 경험을 제공할 수 있습니다 [3].
### 매 motivation
- **Overdraw**: 매 same pixel 의 shade 여러 번.
- **Expensive shader**: 매 PBR + IBL + many light → 매 pixel cost ↑.
- **Solution**: 매 depth 만 의 first → 매 main pass 의 occluded fragment 의 reject.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 mechanism
1. **Pass 1**: 매 depth-only (vertex + null pixel shader).
2. **Pass 2**: 매 full shading + EQUAL depth test.
3. 매 GPU 의 early-Z 의 pixel shader 전 의 reject.
## 🔗 지식 연결 (Graph)
- **Related Topics:** Occlusion Culling, Z-buffer, [[Overdraw|Overdraw]], Fragment Shader
- **Projects/Contexts:** [[WebGL|WebGL]]/Three.js CAD Rendering [[Optimization|Optimization]]
- **Contradictions/Notes:** 소스에 상충되는 내용은 없으며, 오클루전 컬링을 CPU에서 처리하기 어렵거나 GPU 레이턴시로 인해 비용이 높을 때 이를 해결하는 가장 효과적인 우회(workaround) 기법으로 설명됩니다 [1].
### 매 trade-off
- **Win**: 매 expensive pixel shader 의 occluded fragment 의 skip.
- **Loss**: 매 vertex stage 2x.
- **Net**: 매 shader complexity 의 high 의 win.
---
*Last updated: 2026-04-19*
### 매 modern variant
- **Hi-Z**: 매 hierarchical depth 의 GPU 의 cull tile.
- **Forward+**: 매 light culling + Z-prepass.
- **Deferred**: 매 G-buffer 의 prepass-like.
- **Visibility buffer**: 매 modern alternative (Unreal 5 Nanite).
---
### 매 응용
1. **Open world**: 매 dense vegetation overdraw.
2. **Particle**: 매 alpha sort cost.
3. **PBR-heavy**: 매 expensive shader.
4. **VR**: 매 fill rate critical.
5. **Mobile**: 매 tile-based 의 different approach (defer to TBDR).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Z-prepass (Unreal-style HLSL)
```hlsl
// Pass 1 — depth only
struct VSInput { float3 pos : POSITION; };
**언제 쓰면 안 되는가:**
- *(TODO)*
float4 VS_DepthOnly(VSInput v) : SV_POSITION {
return mul(float4(v.pos, 1.0), MVP);
}
// 매 no pixel shader (or null)
## 🧪 검증 상태 (Validation)
// Pass 2 — full shading with EQUAL test
DepthStencilState : DepthFunc = EQUAL; DepthWrite = OFF;
- **정보 상태:** 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
float4 PS_Main(VSOutput v) : SV_TARGET {
return PBR_Shade(v); // 매 expensive
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### OpenGL setup
```cpp
// Pass 1
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glDepthMask(GL_TRUE);
glDepthFunc(GL_LESS);
DrawScene(depth_only_program);
**선택 A를 써야 할 때:**
- *(TODO)*
// Pass 2
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glDepthMask(GL_FALSE);
glDepthFunc(GL_EQUAL);
DrawScene(main_program);
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Vulkan render pass
```cpp
VkAttachmentDescription depthAttach = {
.format = VK_FORMAT_D32_SFLOAT,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
};
// Subpass 1: depth only
// Subpass 2: shading w/ EQUAL test, read-only depth
```
**기본값:**
> *(TODO)*
### Cost-benefit decision
```cpp
bool should_use_depth_prepass(SceneStats stats) {
// 매 high overdraw + expensive shader → 매 win
float avg_overdraw = stats.pixels_shaded / stats.unique_pixels;
float shader_cost = stats.shader_alu_count;
return avg_overdraw > 2.0 && shader_cost > 100;
}
```
## ❌ 안티패턴 (Anti-Patterns)
### Hi-Z chain (compute)
```hlsl
// 매 each level 의 max of 4 source pixels
[numthreads(8, 8, 1)]
void GenerateHiZ(uint3 tid : SV_DispatchThreadID) {
float4 d;
d.x = SrcDepth[tid.xy * 2 + uint2(0, 0)];
d.y = SrcDepth[tid.xy * 2 + uint2(1, 0)];
d.z = SrcDepth[tid.xy * 2 + uint2(0, 1)];
d.w = SrcDepth[tid.xy * 2 + uint2(1, 1)];
DstDepth[tid.xy] = max(max(d.x, d.y), max(d.z, d.w));
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Occlusion query (validation)
```cpp
GLuint q;
glGenQueries(1, &q);
glBeginQuery(GL_SAMPLES_PASSED, q);
DrawObject(obj);
glEndQuery(GL_SAMPLES_PASSED);
GLuint samples;
glGetQueryObjectuiv(q, GL_QUERY_RESULT, &samples);
// 매 samples == 0 → fully occluded
```
### Early-Z disqualification
```hlsl
// 매 pixel shader 의 discard / depth-write → 매 early-Z 의 disabled
float4 PS_Bad(VSOut v) : SV_TARGET {
if (alpha < 0.5) discard; // ❌ early-Z 의 break
return shade(v);
}
// 매 ✅ early-Z friendly: 매 alpha test 의 discard 의 separate pass
[earlydepthstencil]
float4 PS_Good(VSOut v) : SV_TARGET {
return shade(v);
}
```
### TBDR mobile (no prepass needed)
```
// 매 mobile (Adreno, Mali, Apple) 의 tile-based deferred
// 매 already 의 hidden surface 의 reject before pixel shader
// 매 explicit Z-prepass 의 redundant
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Desktop + heavy PBR | Z-prepass |
| Mobile (TBDR) | NO (HW already does it) |
| Forward+ | Z-prepass + light cull |
| Deferred | G-buffer pass = prepass |
| Particle / transparent | After opaque (no prepass) |
| Modern Unreal 5 | Visibility buffer / Nanite |
**기본값**: 매 desktop + 매 heavy shader → Z-prepass. 매 mobile → skip. 매 modern engine → visibility buffer.
## 🔗 Graph
- 부모: [[Rendering-Pipeline]] · [[GPU-Optimization]]
- 변형: [[Early-Z]] · [[Hi-Z]] · [[Visibility-Buffer]]
- 응용: [[Forward-Plus]] · [[Deferred-Rendering]]
- Adjacent: [[Overdraw]] · [[Compute-Shader]] · [[TBDR]]
## 🤖 LLM 활용
**언제**: 매 PBR-heavy desktop. 매 dense scene. 매 fill-rate-bound.
**언제 X**: 매 mobile TBDR. 매 vertex-bound. 매 simple shader.
## ❌ 안티패턴
- **Always prepass**: 매 vertex-bound 의 lose.
- **Discard in main**: 매 early-Z 의 break.
- **Mobile prepass**: 매 redundant + cost.
- **No EQUAL test in main**: 매 prepass 의 useless.
- **Animated geometry mismatch**: 매 prepass 와 main 의 different vertex.
## 🧪 검증 / 중복
- Verified (Real-Time Rendering 4ed, Unreal docs, Vulkan spec).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-04-20 | Auto-reinforced |
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Z-prepass + 매 HLSL / GL / Vulkan / Hi-Z code |