Files
2nd/10_Wiki/Topic_Programming/Frontend/Threejs WebGPU 파티클 예제.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

170 lines
5.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
id: wiki-2026-0508-threejs-webgpu-파티클-예제
title: Threejs WebGPU 파티클 예제
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Three.js WebGPU Particles, TSL Particles]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [threejs, webgpu, particles, tsl, gpgpu]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: javascript
framework: three.js
---
# Threejs WebGPU 파티클 예제
## 매 한 줄
> **"매 GPU compute shader 의 millions-of-particles 의 60fps"**. Three.js r170+ 의 WebGPURenderer 의 TSL (Three Shader Language) 의 compute node 의 particle position/velocity 의 GPU buffer 의 simulate. 매 2026 standard: WebGPU 의 baseline browser support (Chrome/Edge/Safari 17.4+/Firefox 127+) 의 production 의 reach.
## 매 핵심
### 매 architecture
- **Storage buffer**: 매 particle position/velocity 의 GPU memory 의 persist — 매 CPU readback 의 X.
- **Compute pass**: 매 frame 의 start 의 simulation step 의 dispatch.
- **Render pass**: 매 same buffer 의 vertex attribute 의 read — instanced point / mesh.
- **TSL**: 매 JS-authored shader graph 의 WGSL 의 compile — 매 backend portability (WebGPU + WebGL fallback).
### 매 핵심 node
- `storage()`: 매 mutable GPU buffer.
- `Fn()`: 매 reusable shader function.
- `instanceIndex`: 매 compute thread id.
- `attribute()`: 매 vertex attribute read.
- `uniform()`: 매 per-frame CPU-set value.
### 매 응용
1. Galaxy / nebula simulation 의 web demo.
2. GPGPU fluid (SPH, FLIP) 의 art piece.
3. Real-time crowd / flock (boid) 의 100k+ agent.
4. Data viz 의 millions-of-points scatter.
## 💻 패턴
### Setup WebGPURenderer
```javascript
import * as THREE from 'three/webgpu';
import { Fn, storage, instanceIndex, uniform, vec3, sin, cos, time } from 'three/tsl';
const renderer = new THREE.WebGPURenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
await renderer.init();
document.body.appendChild(renderer.domElement);
```
### Allocate particle buffers
```javascript
const COUNT = 500_000;
const positionBuffer = storage(new THREE.StorageInstancedBufferAttribute(COUNT, 3), 'vec3', COUNT);
const velocityBuffer = storage(new THREE.StorageInstancedBufferAttribute(COUNT, 3), 'vec3', COUNT);
```
### Init compute (one-time)
```javascript
const initCompute = Fn(() => {
const i = instanceIndex;
const angle = i.toFloat().mul(0.001);
positionBuffer.element(i).assign(vec3(cos(angle).mul(50), 0, sin(angle).mul(50)));
velocityBuffer.element(i).assign(vec3(0));
})().compute(COUNT);
await renderer.computeAsync(initCompute);
```
### Per-frame simulation
```javascript
const dt = uniform(0.016);
const simCompute = Fn(() => {
const i = instanceIndex;
const pos = positionBuffer.element(i);
const vel = velocityBuffer.element(i);
const gravity = pos.normalize().negate().mul(9.8);
vel.addAssign(gravity.mul(dt));
pos.addAssign(vel.mul(dt));
})().compute(COUNT);
```
### Render as instanced points
```javascript
const material = new THREE.SpriteNodeMaterial();
material.positionNode = positionBuffer.toAttribute();
material.colorNode = velocityBuffer.toAttribute().length().mul(0.1);
const mesh = new THREE.InstancedMesh(new THREE.PlaneGeometry(0.05), material, COUNT);
scene.add(mesh);
```
### Animation loop
```javascript
renderer.setAnimationLoop(async () => {
dt.value = clock.getDelta();
await renderer.computeAsync(simCompute);
await renderer.renderAsync(scene, camera);
});
```
### Curl noise flow field
```javascript
import { mx_noise_vec3 } from 'three/tsl';
const flowCompute = Fn(() => {
const i = instanceIndex;
const pos = positionBuffer.element(i);
const noise = mx_noise_vec3(pos.mul(0.1).add(time.mul(0.5)));
velocityBuffer.element(i).assign(noise.mul(2));
pos.addAssign(velocityBuffer.element(i).mul(dt));
})().compute(COUNT);
```
### WebGL fallback
```javascript
const renderer = WebGPU.isAvailable()
? new THREE.WebGPURenderer()
: new THREE.WebGLRenderer();
// 매 TSL 의 same code 의 WebGL backend 의 transpile (compute X 의 limit 의 case 의 GPGPUComputationRenderer 의 fallback)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| <10k particle, simple motion | CPU 의 BufferGeometry update |
| 10k100k, WebGL2 only | GPGPUComputationRenderer (ping-pong texture) |
| 100k10M, modern browser | WebGPURenderer + TSL compute |
| Physics-accurate fluid | WebGPU compute + custom WGSL |
| Cross-browser 의 require, IE/legacy | Canvas2D 또는 WebGL1 fallback |
**기본값**: 매 2026 의 new project 의 WebGPURenderer + TSL — 매 WebGL fallback 의 automatic.
## 🔗 Graph
- 부모: [[Three.js]] · [[WebGPU]]
- 변형: [[GPGPU]] · [[TSL (Three Shader Language)]]
- 응용: [[Particle System]]
- Adjacent: [[Compute Shader]] · [[Instanced Rendering]]
## 🤖 LLM 활용
**언제**: 매 100k+ particle 의 60fps 의 require, 매 modern browser 의 target.
**언제 X**: 매 static scene, low count, 또는 mobile-Safari-pre-17.4 의 fallback 의 critical.
## ❌ 안티패턴
- **CPU position update**: 매 frame 의 millions-of-vertex 의 GPU upload 의 PCIe bottleneck.
- **Compute pass 의 매 frame 의 buffer recreate**: 매 GC pressure 의 stutter — 매 reuse.
- **`renderer.compute()` sync wait**: 매 main thread 의 block — 매 `computeAsync` 의 use.
- **Float32 over-precision**: 매 WebGPU 의 f16 storage 의 bandwidth halve 의 opportunity 의 miss.
- **TSL 의 raw WGSL 의 mix 의 unnecessary**: 매 portability 의 break.
## 🧪 검증 / 중복
- Verified (Three.js r170+ docs, threejs.org/examples webgpu_compute_particles).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — TSL compute, instanced render, WebGL fallback |