7.7 KiB
7.7 KiB
텀블링 몽키 3D 물리 간이 실험 (2026-10-11)
docs/games/tumblin-monkeys.md 8.1절 수치의 근거. 대충 만든 모양(기둥 20면, 막대 24개, 원숭이 30마리 = 캡슐 몸통 + 캡슐 팔 4개)으로 한 간이 실험이라, 실제 게임 모양으로 바꾸면 다시 잰다.
- 엔진:
@dimforge/rapier3d-deterministic-compat@0.21.0, Bun 1.3.13, 이 서버(8코어). - 저장소 의존성에는 넣지 않았다. 재현: 빈 폴더(
$HOME/.tmp/...)에서bun init -y && bun add @dimforge/rapier3d-deterministic-compat@0.21.0뒤 아래 두 파일을bun spike.ts,bun snap.ts로 실행.
결과
- 결정성: 같은 시드(1)로 두 번 → 최종 원숭이 위치·회전 해시
dcc3de9cd4d3f318동일, 막대별 떨어진 수도 동일. 스냅숏 저장 → 복원 후 300걸음 계산도 계속 계산한 것과 해시 동일. - 속도: 한 걸음 약 0.20
0.21ms. 막대 24개를 차례로 뽑는 데 11931634걸음, 255342ms(막대 하나 평균 약 1114ms, 한 번 상한 600걸음 ≈ 120ms). - 스냅숏 크기: 134,076바이트(base64 178,768) → 상태에는 넣지 않고 멈춘 위치만 저장하기로 함.
- 모양 문제: 붓고 나서 시드 1은 30마리 중 21마리, 시드 2는 27마리가 바로 떨어짐. 모양 조정이 필요.
출력
1 {
initialFallen: 21,
pourSettleMs: "512",
steps: 723,
pullSteps: 1634,
pullMs: "342",
msPerStep: "0.209",
pullLog: "0,0,0,0,0,0,1,0,0,0,0,0,0,3,1,3,0,0,0,0,1,0,0,0",
hash: "dcc3de9cd4d3f318",
}
1 {
initialFallen: 21,
pourSettleMs: "395",
steps: 723,
pullSteps: 1634,
pullMs: "330",
msPerStep: "0.202",
pullLog: "0,0,0,0,0,0,1,0,0,0,0,0,0,3,1,3,0,0,0,0,1,0,0,0",
hash: "dcc3de9cd4d3f318",
}
2 {
initialFallen: 27,
pourSettleMs: "300",
steps: 563,
pullSteps: 1193,
pullMs: "255",
msPerStep: "0.214",
pullLog: "0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0",
hash: "9ff54a49db397749",
}
snapshot bytes 134076 base64 178768
continuous 3b5d355264528620 restored 3b5d355264528620
spike.ts
import RAPIER from '@dimforge/rapier3d-deterministic-compat';
await RAPIER.init();
function lcg(seed: number) { let s = seed >>> 0; return () => ((s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 2 ** 32); }
const TRUNK_R = 1.0, TRUNK_H = 4.0, STICK_Y0 = 1.6, STICK_Y1 = 3.6;
type Pose = { p: [number,number,number]; q: [number,number,number,number] };
function buildWorld(rand: () => number, nSticks: number) {
const world = new RAPIER.World({ x: 0, y: -9.81, z: 0 });
// floor tray
world.createCollider(RAPIER.ColliderDesc.cuboid(3, 0.05, 3).setTranslation(0, -0.05, 0));
// trunk walls: 20 boxes forming tube from y=1.2 to TRUNK_H
const seg = 20;
for (let i = 0; i < seg; i++) {
const a = (i / seg) * Math.PI * 2;
const half = Math.sin(Math.PI / seg) * TRUNK_R + 0.02;
const d = RAPIER.ColliderDesc.cuboid(0.04, (TRUNK_H - 1.2) / 2, half)
.setTranslation(Math.cos(a) * TRUNK_R, 1.2 + (TRUNK_H - 1.2) / 2, Math.sin(a) * TRUNK_R)
.setRotation(quatY(-a));
world.createCollider(d);
}
const sticks: RAPIER.Collider[] = [];
for (let i = 0; i < nSticks; i++) {
const y = STICK_Y0 + (i / nSticks) * (STICK_Y1 - STICK_Y0);
const a = rand() * Math.PI;
// cylinder along x axis -> rotate. Rapier cylinder along Y; rotate 90 deg about Z then around Y
const q = mul(quatY(a), quatZ(Math.PI / 2));
const c = world.createCollider(RAPIER.ColliderDesc.cylinder(TRUNK_R * 1.05, 0.035).setTranslation(0, y, 0).setRotation(q));
sticks.push(c);
}
return { world, sticks };
}
function quatY(a: number) { return { x: 0, y: Math.sin(a / 2), z: 0, w: Math.cos(a / 2) }; }
function quatZ(a: number) { return { x: 0, y: 0, z: Math.sin(a / 2), w: Math.cos(a / 2) }; }
function mul(a: any, b: any) { return { w: a.w*b.w - a.x*b.x - a.y*b.y - a.z*b.z, x: a.w*b.x + a.x*b.w + a.y*b.z - a.z*b.y, y: a.w*b.y - a.x*b.z + a.y*b.w + a.z*b.x, z: a.w*b.z + a.x*b.y - a.y*b.x + a.z*b.w }; }
function addMonkey(world: RAPIER.World, x: number, y: number, z: number, rot: any) {
const rb = world.createRigidBody(RAPIER.RigidBodyDesc.dynamic().setTranslation(x, y, z).setRotation(rot).setCcdEnabled(true).setLinearDamping(0.3).setAngularDamping(0.5));
world.createCollider(RAPIER.ColliderDesc.capsule(0.06, 0.06).setDensity(1).setFriction(0.8), rb); // body
// arms: hooks raised, curved -> two capsules each at 45deg
for (const s of [-1, 1]) {
world.createCollider(RAPIER.ColliderDesc.capsule(0.07, 0.022).setTranslation(s * 0.1, 0.12, 0).setRotation(quatZ(s * -0.7)).setFriction(0.9), rb);
world.createCollider(RAPIER.ColliderDesc.capsule(0.04, 0.022).setTranslation(s * 0.12, 0.24, 0).setRotation(quatZ(s * 0.6)).setFriction(0.9), rb);
}
return rb;
}
function run(seed: number, nMonkeys: number, nSticks: number) {
const rand = lcg(seed);
const { world, sticks } = buildWorld(rand, nSticks);
const monkeys: RAPIER.RigidBody[] = [];
const t0 = performance.now();
let steps = 0;
for (let i = 0; i < nMonkeys; i++) {
const r = rand() * 0.6, a = rand() * Math.PI * 2;
const q = mul(quatY(rand() * 6.28), quatZ((rand() - 0.5) * 1.5));
monkeys.push(addMonkey(world, Math.cos(a) * r, TRUNK_H + 0.3 + (i % 3) * 0.25, Math.sin(a) * r, q));
if (i % 3 === 2) for (let k = 0; k < 30; k++) { world.step(); steps++; }
}
// settle
let settleSteps = 0;
while (settleSteps < 1200) { world.step(); steps++; settleSteps++; if (monkeys.every(m => m.isSleeping() || m.linvel().y ** 2 + m.linvel().x ** 2 + m.linvel().z ** 2 < 1e-4)) break; }
const t1 = performance.now();
const fallen = () => monkeys.filter(m => m.translation().y < 1.2).length;
const initialFallen = fallen();
const pullLog: number[] = [];
let pullSteps = 0;
// pull sticks one by one
for (let s = 0; s < sticks.length; s++) {
world.removeCollider(sticks[s], true);
for (const m of monkeys) m.wakeUp();
const before = fallen();
let k = 0;
for (; k < 600; k++) { world.step(); pullSteps++; if (k > 30 && monkeys.every(m => m.isSleeping() || (m.linvel().x**2 + m.linvel().y**2 + m.linvel().z**2) < 1e-4)) break; }
pullLog.push(fallen() - before);
}
const t2 = performance.now();
const hashArr = new Float64Array(monkeys.flatMap(m => { const t = m.translation(), r = m.rotation(); return [t.x, t.y, t.z, r.x, r.y, r.z, r.w]; }));
const h = Bun.hash(new Uint8Array(hashArr.buffer)).toString(16);
return { initialFallen, pourSettleMs: (t1 - t0).toFixed(0), steps, pullSteps, pullMs: (t2 - t1).toFixed(0), msPerStep: ((t2 - t1) / pullSteps).toFixed(3), pullLog: pullLog.join(','), hash: h };
}
for (const seed of [1, 1, 2]) console.log(seed, run(seed, 30, 24));
snap.ts
import RAPIER from '@dimforge/rapier3d-deterministic-compat';
await RAPIER.init();
const w = new RAPIER.World({x:0,y:-9.81,z:0});
w.createCollider(RAPIER.ColliderDesc.cuboid(3,0.05,3));
const bs = [] as RAPIER.RigidBody[];
for (let i=0;i<30;i++){ const rb=w.createRigidBody(RAPIER.RigidBodyDesc.dynamic().setTranslation((i%5)*0.3-0.6, 0.5+i*0.2, Math.floor(i/5)*0.05)); w.createCollider(RAPIER.ColliderDesc.capsule(0.06,0.06),rb); for(const s of [-1,1]) w.createCollider(RAPIER.ColliderDesc.capsule(0.07,0.02).setTranslation(s*0.1,0.12,0),rb); bs.push(rb);}
for(let i=0;i<60;i++) w.step();
const snap = w.takeSnapshot();
console.log('snapshot bytes', snap.length, 'base64', Buffer.from(snap).toString('base64').length);
const h = (world: RAPIER.World) => { const a:number[]=[]; world.forEachRigidBody(b=>{const t=b.translation(),r=b.rotation(); a.push(t.x,t.y,t.z,r.x,r.y,r.z,r.w)}); return Bun.hash(new Uint8Array(new Float64Array(a).buffer)).toString(16); };
for(let i=0;i<300;i++) w.step();
const w2 = RAPIER.World.restoreSnapshot(snap)!;
for(let i=0;i<300;i++) w2.step();
console.log('continuous', h(w), 'restored', h(w2));