Files
2nd/10_Wiki/Topics/Frontend/Threejs WebGPU 파티클 예제.md
T
koriweb d8a80f6272 chore(wiki): dangling 링크 canonical 정규화 (768파일/1200건)
이름만 다른(표기 변형) [[위키링크]]를 대상 문서의 canonical 제목으로 치환해
끊겼던 1,200개 링크를 연결. 제목/파일명 정규화 일치만 적용하고 별칭 매칭은
과병합 위험으로 제외(애매성 가드). 원본은 _link_reconcile_backup/ 에 백업.
도구: Datacollect/scripts/link_reconcile_apply.mjs

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 12:24:15 +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 |