[G1-Sync] Manual knowledge update
This commit is contained in:
+198
-70
@@ -2,99 +2,227 @@
|
||||
id: wiki-2026-0508-bitecs와-sharedarraybuffer를-결합한-멀
|
||||
title: bitECS와 SharedArrayBuffer를 결합한 멀티스레드 고성능 아키텍처
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-33DDD3]
|
||||
aliases: [bitECS multithreaded, SAB ECS, ECS parallel, bitECS SharedArrayBuffer]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [ecs, bitecs, sharedarraybuffer, parallel, gamedev, browser]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - bitECS와 SharedArrayBuffer를 결합한 멀티스레드 고성능 아키텍처"
|
||||
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: TypeScript
|
||||
framework: bitECS + Web Worker
|
||||
---
|
||||
|
||||
# [[bitECS와 SharedArrayBuffer를 결합한 멀티스레드 고성능 아키텍처]]
|
||||
# bitECS와 SharedArrayBuffer를 결합한 멀티스레드 고성능 아키텍처
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> `bitECS`의 데이터 지향 설계(SoA) 구조와 `SharedArrayBuffer`의 무복사(Zero-Copy) 메모리 공유 기능을 결합하여, 메인 스레드의 렌더링 블로킹 없이 웹 워커에서 수만 개의 엔티티를 병렬 연산하고 실시간으로 동기화하는 초고성능 웹 게임 엔진 아키텍처입니다.
|
||||
## 매 한 줄
|
||||
> **"매 bitECS Component = TypedArray on SAB"**. bitECS의 매 SoA layout 은 매 SharedArrayBuffer 와 매 자연스럽게 결합 — 매 component data 가 매 worker 에서 매 zero-copy 공유. 매 system 분산 + 매 stripe partition 으로 매 100k+ entity 를 매 60fps 에서 매 simulate 가능.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
**1. bitECS의 데이터 지향 설계 (Structure of Arrays, SoA)** `bitECS`는 기존의 객체 지향(AoS) 방식 대신, 컴포넌트 데이터를 `Float32Array`와 같은 `[[TypedArray]]` 기반의 연속된 배열 구조(SoA)로 저장하는 ECS(Entity Component[[ system]]) 라이브러리입니다. 이 구조는 CPU 캐시 적중률을 극대화하여 수천, 수만 개의 엔티티 상태(예: 위치, 속도)를 밀리초 단위로 연산할 수 있게 합니다.
|
||||
## 매 핵심
|
||||
|
||||
**2. SharedArrayBuffer를 통한 Zero-Copy 메모리 공유** `bitECS`가 내부적으로 사용하는 `TypedArray`의 기반 메모리를 `SharedArrayBuffer`로 할당할 수 있습니다. 생성된 버퍼를 웹 워커(Web Worker)로 전달하면 메인 스레드와 워커 스레드가 완전히 동일한 메모리 주소를 공유하게 됩니다. 이를 통해 매 프레임마다 직렬화 및 역직렬화(`postMessage`) 오버헤드 없이 스레드 간 데이터 통신이 가능해집니다.
|
||||
### 매 bitECS 구조
|
||||
- **Entity**: 32-bit integer ID.
|
||||
- **Component**: 매 TypedArray (Float32Array, Int32Array 등) per field, 매 indexed by entity ID.
|
||||
- **System**: query → process loop.
|
||||
- 매 SoA (Struct of Arrays) → 매 cache-friendly + SIMD-friendly.
|
||||
|
||||
**3. 스레드 역할의 엄격한 분리 (단방향 데이터 흐름)** 동시성 문제(Data Race)를 해결하기 위해 스레드 간의 읽기/쓰기 역할을 아키텍처 수준에서 분리합니다.
|
||||
### 매 SAB 통합 핵심
|
||||
- bitECS 의 매 component 매 backing TypedArray 의 매 buffer 를 매 SAB 로 교체.
|
||||
- 매 worker 에서 매 동일 component 에 매 동시 접근 가능.
|
||||
- 매 system 별로 매 worker 분배 — 또는 매 entity range 별 분배.
|
||||
|
||||
- **워커 스레드 (Write 전담):** 물리 엔진 연산, 충돌 처리, AI 이동 로직 등의 `bitECS` 시스템(System)이 독립적인 백그라운드 루프(예: 60Hz)에서 실행되며, 공유 버퍼의 데이터를 업데이트합니다.
|
||||
- **메인 스레드 (Read 전담):** `React Three Fiber(R3F)`의 `useFrame` 렌더링 루프 내에서, 공유 메모리의 `bitECS` 컴포넌트 값(예: `Position.x[eid]`)을 그대로 읽어와 Three.js 메시(Mesh) 인스턴스 참조(ref)에 반영하여 화면에 렌더링합니다.
|
||||
### 매 partition strategy
|
||||
1. **System-level**: physics worker, AI worker, render worker 매 별도.
|
||||
2. **Entity-level**: entity ID 매 mod N → worker N 개에 분산.
|
||||
3. **Stripe-level**: contiguous range, cache-friendly.
|
||||
4. **Hybrid**: 매 read-heavy system 매 모든 worker, write 매 owner worker 만.
|
||||
|
||||
**4. 렌더링과 시뮬레이션의 디커플링 이점** 이 아키텍처를 적용하면 무거운 물리 연산이 React의 가상 DOM 재조정([[Reconciliation]])이나 메인 스레드를 블로킹하지 않습니다. 또한 매 프레임 객체를 새로 생성하지 않고 배열의 값만 변경하므로, 가비지 컬렉션(GC) 스파이크로 인한 프레임 드랍을 원천적으로 방지할 수 있습니다.
|
||||
### 매 응용
|
||||
1. **Boid/flocking**: 100k boids 매 4 worker 에서 stripe.
|
||||
2. **Particle system**: SAB Float32 의 매 position/velocity, 매 worker 별 batch.
|
||||
3. **Pathfinding**: A* 매 worker pool, 매 result 매 SAB 에 적재.
|
||||
4. **Voxel chunk update**: 매 chunk 별 worker, 매 mesh build 매 OffscreenCanvas worker.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
## 💻 패턴
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** Data-Oriented Design (DOD), Structure of Arrays (SoA), Web Worker 멀티스레딩, [[React Three Fiber (R3F)]] 최적화, 메모리 파편화 방지 및 객체 풀링
|
||||
- **Projects/Contexts:** 브라우저 기반 AAA급 멀티스레드 3D 게임, 수만 개의 엔티티가 존재하는 실시간 물리 시뮬레이션
|
||||
- **Contradictions/Notes:** 원시 이진 데이터인 `SharedArrayBuffer`를 직접 다루는 것은 로우 레벨 개발 지식이 필요해 매우 까다롭습니다. 하지만 `bitECS`를 프록시 구조로 활용하면, 개발자는 익숙한 자바스크립트 배열이나 객체를 다루는 듯한 편의성을 누리면서도 내부적으로는 C++ 엔진에 필적하는 메모리 공유 성능을 얻을 수 있다는 강력한 장점이 있습니다.
|
||||
### Pattern 1: bitECS component → SAB-backed
|
||||
```typescript
|
||||
// main.ts
|
||||
import { createWorld, defineComponent, Types } from "bitecs";
|
||||
|
||||
---
|
||||
const MAX_ENTITIES = 100_000;
|
||||
const sab = new SharedArrayBuffer(MAX_ENTITIES * 3 * 4 * 2); // pos+vel, f32
|
||||
|
||||
_Last updated: 2026-04-14_
|
||||
// SAB 위에 매 직접 component 정의 (bitECS 0.4+ allows custom buffer)
|
||||
const Position = {
|
||||
x: new Float32Array(sab, 0, MAX_ENTITIES),
|
||||
y: new Float32Array(sab, MAX_ENTITIES * 4, MAX_ENTITIES),
|
||||
};
|
||||
const Velocity = {
|
||||
x: new Float32Array(sab, MAX_ENTITIES * 8, MAX_ENTITIES),
|
||||
y: new Float32Array(sab, MAX_ENTITIES * 12, MAX_ENTITIES),
|
||||
};
|
||||
|
||||
---
|
||||
|
||||
## 🤖 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
|
||||
const world = createWorld();
|
||||
// ... addEntity, addComponent (writes go into SAB views)
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Pattern 2: worker spawn + SAB share
|
||||
```typescript
|
||||
const N_WORKERS = 4;
|
||||
const workers = Array.from({ length: N_WORKERS }, (_, id) => {
|
||||
const w = new Worker("./physics-worker.ts", { type: "module" });
|
||||
w.postMessage({ sab, workerId: id, n: N_WORKERS, maxEntities: MAX_ENTITIES });
|
||||
return w;
|
||||
});
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Pattern 3: physics system in worker
|
||||
```typescript
|
||||
// physics-worker.ts
|
||||
self.onmessage = ({ data: { sab, workerId, n, maxEntities } }) => {
|
||||
const px = new Float32Array(sab, 0, maxEntities);
|
||||
const py = new Float32Array(sab, maxEntities * 4, maxEntities);
|
||||
const vx = new Float32Array(sab, maxEntities * 8, maxEntities);
|
||||
const vy = new Float32Array(sab, maxEntities * 12, maxEntities);
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const stripe = Math.ceil(maxEntities / n);
|
||||
const start = workerId * stripe;
|
||||
const end = Math.min(start + stripe, maxEntities);
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
setInterval(() => {
|
||||
const dt = 0.016;
|
||||
for (let i = start; i < end; i++) {
|
||||
px[i] += vx[i] * dt;
|
||||
py[i] += vy[i] * dt;
|
||||
}
|
||||
}, 16);
|
||||
};
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Pattern 4: barrier-synchronized frame
|
||||
```typescript
|
||||
// shared int32 frame counter
|
||||
const sync = new Int32Array(sab, syncOffset, 4);
|
||||
// sync[0] = workersReady, sync[1] = generation
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
function workerStep() {
|
||||
// do work
|
||||
doStripe();
|
||||
// barrier
|
||||
if (Atomics.add(sync, 0, 1) + 1 === N_WORKERS) {
|
||||
Atomics.store(sync, 0, 0);
|
||||
Atomics.add(sync, 1, 1);
|
||||
Atomics.notify(sync, 1, N_WORKERS - 1);
|
||||
} else {
|
||||
const gen = Atomics.load(sync, 1);
|
||||
Atomics.wait(sync, 1, gen);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 5: read-only system on all workers
|
||||
```typescript
|
||||
// AI system: read pos/vel of others, write own intent → no contention
|
||||
function aiSystem(workerId: number) {
|
||||
for (let i = start; i < end; i++) {
|
||||
let nearestX = 0, nearestY = 0, nearestDist = Infinity;
|
||||
for (let j = 0; j < maxEntities; j++) {
|
||||
if (j === i) continue;
|
||||
const dx = px[j] - px[i], dy = py[j] - py[i];
|
||||
const d = dx * dx + dy * dy;
|
||||
if (d < nearestDist) { nearestDist = d; nearestX = px[j]; nearestY = py[j]; }
|
||||
}
|
||||
// write only own intent slot
|
||||
intent[i] = computeIntent(px[i], py[i], nearestX, nearestY);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 6: render thread on main, worker writes only
|
||||
```typescript
|
||||
// main thread: requestAnimationFrame → read SAB, render
|
||||
function frame() {
|
||||
for (let i = 0; i < activeCount; i++) {
|
||||
ctx.fillRect(px[i], py[i], 2, 2);
|
||||
}
|
||||
requestAnimationFrame(frame);
|
||||
}
|
||||
// 매 race: workers writing while main reads — visual tearing 가능, 대부분 게임에서 허용.
|
||||
// strict 의 매 double buffer (front/back) → flip on barrier.
|
||||
```
|
||||
|
||||
### Pattern 7: double-buffered position
|
||||
```typescript
|
||||
const pxA = new Float32Array(sab, offA, max);
|
||||
const pxB = new Float32Array(sab, offB, max);
|
||||
let frontIdx = 0;
|
||||
|
||||
function workerStep() {
|
||||
const front = frontIdx === 0 ? pxA : pxB;
|
||||
const back = frontIdx === 0 ? pxB : pxA;
|
||||
// read front, write back
|
||||
for (let i = start; i < end; i++) back[i] = front[i] + vx[i] * dt;
|
||||
// barrier → main flips frontIdx
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 8: SoA SIMD (WASM SIMD or manual unroll)
|
||||
```typescript
|
||||
// 매 4-wide unroll — JIT가 종종 SIMD화
|
||||
for (let i = start; i < end; i += 4) {
|
||||
px[i] += vx[i] * dt;
|
||||
px[i + 1] += vx[i + 1] * dt;
|
||||
px[i + 2] += vx[i + 2] * dt;
|
||||
px[i + 3] += vx[i + 3] * dt;
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 9: spawn/kill queue (lock-free SPSC)
|
||||
```typescript
|
||||
// 매 main 만 spawn, worker 만 kill — single-producer queue
|
||||
// 매 ring buffer of entity IDs, Atomics-driven head/tail
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| <1k entities | Single thread, 매 충분 |
|
||||
| 1k–10k, simple physics | bitECS single-thread |
|
||||
| 10k+, heavy AI/physics | bitECS + SAB + worker pool |
|
||||
| Render heavy | OffscreenCanvas worker |
|
||||
| Voxel/chunk world | Per-chunk worker assignment |
|
||||
|
||||
**기본값**: 매 single thread first. 매 measure → SAB 매 4 worker 부터 의미 있을 때만.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[ECS]] · [[bitECS]] · [[Web Worker]] · [[SharedArrayBuffer]]
|
||||
- 변형: [[Bevy ECS]] · [[Flecs]] · [[Unity DOTS]]
|
||||
- 응용: [[Browser Game Engine]] · [[Particle System]] · [[Boid Simulation]]
|
||||
- Adjacent: [[Web Worker와 SharedArrayBuffer를 이용한 실제 고부하 병렬 처리 구현체 (실패_성공 포함)]] · [[OffscreenCanvas]] · [[가변적 LOD(Level of Detail) 시스템]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 large-scale entity simulation in browser. 매 60fps 매 100k+ entity.
|
||||
**언제 X**: 매 small game, 매 single-thread bitECS 충분 — 매 SAB 의 debug 비용 매 큼.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Anti1: 매 component write 매 worker 동시**: race. 매 ownership 명확히.
|
||||
- **Anti2: 매 frame SAB 재생성**: GC 폭발. startup 1번.
|
||||
- **Anti3: 매 worker 마다 component query**: query overhead 누적. 매 main 에서 ID list 한번 + worker 에 stripe.
|
||||
- **Anti4: false sharing — 매 worker 가 인접 entity write**: 매 stripe 대신 매 mod 분산은 false sharing 위험. stripe 사용.
|
||||
- **Anti5: render race 무시**: visual artifact. 매 double buffer or 매 tolerate.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (bitECS GitHub, 2025–2026 Web Worker SAB ecosystem).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — bitECS+SAB architecture + canonical merge |
|
||||
|
||||
Reference in New Issue
Block a user