05합체 잔해 타원 은하 — 나선이 부서져 뭉툭해지는 결말
충돌이 지나고 시간을 계속 흐르게 두면 나선팔이 흩어지고 궤도 방향이 뒤섞여 무난하지만 특징 없는 타원체가 남는데, 나선 은하 두 개의 '마지막 모습'이 적분 결과로 도출되는 장면입니다.
쓰임스토리텔링 씬, 우주 콘텐츠 히어로
CanvasRenderingContext2DellipserequestAnimationFrame

<main class="stage">
<div class="gx is-demo" id="gxRoot">
<p class="gx__hint">
<span>충돌이 지나도 시간을 계속 흐르게 두면 나선팔이 흩어지고 궤도 방향이 뒤섞여 특징 없는 타원체가 남습니다</span>
</p>
<div class="gx__field" id="gxField" role="application" aria-label="합체 잔해 실험판" tabindex="0">
<canvas class="gx__cv" id="gxCv"></canvas>
</div>
<div class="gx__bar">
<span class="gx__meta">두 번째 스침부터 시작 · 별 320개</span>
<span class="gx__meta gx__meta--dim">canvas · virial mix · requestAnimationFrame</span>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 합체 잔해 타원 은하(05). 첫 스침 이후 상태에서 시작해 타원체로 안정되는 장면 —
// 나선 팔 형성(02). @keyframes 를 두지 않는다 —
// 움직임은 전부 캔버스 rAF 루프(중심 질량 + 별 상호 중력 O(N²) 레인포드 적분 → 점 그리기)가 만든다.
// 무대는 편 공통 심우주 팔레트. 파스텔 주색을 --gx-* 로 편 전체(01~09) 공통 규격.
$duration: $dur-loop;
$easing: $ease-spring;
$color: $subject-lilac;
// ── 편 공통 심우주 팔레트(BD9~11 원칙: 편마다 다시 정하지 않는다) ──
$gx-stage: #12101c; // 심우주 자정 — 저채도 짙은 남보라 (파스텔 검사 무관: 저채도·저명도)
@include stage($gx-stage);
$gx-ink: #0b0a13; // 관측창 바닥 — 무대보다 한 톤 어두운 보라검
$gx-glow: #b7c8ff; // 은하 A 별빛 — 파스텔 페리윙클(고명도라 vivid 아님)
$gx-hot: #ffdf9e; // 은하 B 코어 — 파스텔 앰버
$gx-text: #d8d4e6; // 라벨 글자 — 밝은 회보라
.gx {
// 렌더러가 읽는 색 — JS 는 getComputedStyle 로 --gx-* 를 받아 쓴다
--gx-ink: #{$gx-ink};
--gx-glow: #{$gx-glow};
--gx-hot: #{$gx-hot};
--gx-tail: #{$subject-pink};
display: flex; flex-direction: column; gap: $sp-2;
width: 100%; max-width: 424px;
}
.gx__hint {
display: flex; align-items: center; gap: $sp-1; margin: 0;
font-weight: 700; font-size: clamp(10px, 2.8vw, 12px); line-height: 1.35;
color: $gx-text;
}
.gx__field {
position: relative; height: 180px;
border-radius: $r-card; overflow: hidden;
background: $gx-ink;
box-shadow: inset 0 0 0 1px rgba($gx-text, .18);
}
.gx__field:focus-visible { outline: 2px solid $gx-glow; outline-offset: 2px; }
.gx__cv { display: block; width: 100%; height: 100%; }
.gx__bar { display: flex; align-items: baseline; justify-content: space-between; gap: $sp-2; }
.gx__meta { font-size: 10px; font-weight: 500; color: rgba($gx-text, .72); }
.gx__meta--dim { font-size: 10px; }
@media (max-width: 340px) {
.gx { gap: $sp-1; }
.gx__field { height: 100px; }
.gx__meta--dim { display: none; }
}
// reduce — rAF 를 돌리지 않고 궤적이 다 쌓인 한 장만 남는다.
@media (prefers-reduced-motion: reduce) {
.gx.is-still .gx__field { cursor: default !important; }
}html, body {
margin: 0;
overflow: hidden;
}
.stage {
box-sizing: border-box;
min-height: 100vh;
display: grid;
place-items: center;
margin: 0;
background: #12101c;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.gx {
--gx-ink: #0b0a13;
--gx-glow: #b7c8ff;
--gx-hot: #ffdf9e;
--gx-tail: #ff9ebb;
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
max-width: 424px;
}
.gx__hint {
display: flex;
align-items: center;
gap: 4px;
margin: 0;
font-weight: 700;
font-size: clamp(10px, 2.8vw, 12px);
line-height: 1.35;
color: #d8d4e6;
}
.gx__field {
position: relative;
height: 180px;
border-radius: 16px;
overflow: hidden;
background: #0b0a13;
box-shadow: inset 0 0 0 1px rgba(216, 212, 230, 0.18);
}
.gx__field:focus-visible {
outline: 2px solid #b7c8ff;
outline-offset: 2px;
}
.gx__cv {
display: block;
width: 100%;
height: 100%;
}
.gx__bar {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
}
.gx__meta {
font-size: 10px;
font-weight: 500;
color: rgba(216, 212, 230, 0.72);
}
.gx__meta--dim {
font-size: 10px;
}
@media (max-width: 340px) {
.gx {
gap: 4px;
}
.gx__field {
height: 100px;
}
.gx__meta--dim {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
.gx.is-still .gx__field {
cursor: default !important;
}
}// 합체 잔해 타원 은하(05) — 첫 스침을 지난 시점부터 시간을 흐르게 두는 장면.
// 시작은 두 은하가 이미 한 번 스쳐 꼬리가 늘어선 상태(두 번째 스침 직전):
// 시드에서 첫 스침을 미리 적분해 만든다(두 원반을 가깝게 놓고 몇백 스텝 = 첫 스침).
// 이후 화면의 시간이 흐르면 궤도 방향이 뒤섞이고(virial 화) 나선팔 구조가 흍어져
// 특징 없는 타원체가 남는다 — 관측되는 타원 은하가 합체 잔해라는 설명의 재현.
// 계산은 01 과 같은 전 쌍 O(N²) 뉴턴 중력 + leapfrog 적분(근사 아님).
(function () {
// ── 변형 상수 블록 — 아래 값 하나만 바꿔 변형을 만든다 ──
var NSTARS = 320; // 두 은하 합계 별 수
var PREPASS = 420; // 시작 전 미리 흘려 둘 스텝(첫 스침+꼬리 형성) — 변형 "시작 시점"
// ────────────────────────────────────────────────────
var root = document.getElementById('gxRoot');
var field = document.getElementById('gxField');
var cv = document.getElementById('gxCv');
var css = getComputedStyle(root);
function tokRGB(name) {
var s = css.getPropertyValue(name).trim();
var hx = s.length === 4
? s.charAt(1) + s.charAt(1) + s.charAt(2) + s.charAt(2) + s.charAt(3) + s.charAt(3)
: s.slice(1);
return [parseInt(hx.slice(0, 2), 16), parseInt(hx.slice(2, 4), 16), parseInt(hx.slice(4, 6), 16)];
}
var C_INK = tokRGB('--gx-ink');
var C_GLOW = tokRGB('--gx-glow');
var C_HOT = tokRGB('--gx-hot');
var C_TAIL = tokRGB('--gx-tail');
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var raf = 0, t0 = -1;
var W = 0, H = 0, dpr = 1;
var chainCv, chainCtx;
var N = 0, X = [], Y = [], VX = [], VY = [];
function fit() {
var r = field.getBoundingClientRect();
W = Math.round(r.width); H = Math.round(r.height);
dpr = Math.min(2, window.devicePixelRatio || 1);
cv.width = W * dpr; cv.height = H * dpr;
cv.style.width = '100%'; cv100pct();
chainCv = document.createElement('canvas');
chainCv.width = W * dpr; chainCv.height = H * dpr;
chainCtx = chainCv.getContext('2d');
chainCtx.scale(dpr, dpr);
}
function cv100pct() { cv.style.width = '100%'; cv.style.height = '100%'; }
function mulberry32(seed) {
return function () {
seed |= 0; seed = (seed + 0x6D2B79F5) | 0;
var t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// G·질량은 캔버스 픽셀 단위 시뮬레이션 값(물리 상수 아님 — 글에서 설명)
var G = 140.0, SOFT2 = 16;
var DT = 1 / 60;
var AX = [], AY = [];
function accel() {
// 전 쌍 O(N²) 뉴턴 중력 — a_i = Σ G·(x_j - x_i)/(|d|²+ε²)^1.5 (근사 아님)
var i, j, dx, dy, d2, inv, f;
for (i = 0; i < N; i++) { AX[i] = 0; AY[i] = 0; }
for (i = 0; i < N; i++) {
for (j = i + 1; j < N; j++) {
dx = X[j] - X[i]; dy = Y[j] - Y[i];
d2 = dx * dx + dy * dy + SOFT2;
inv = 1 / Math.sqrt(d2);
f = G * inv * inv * inv;
AX[i] += dx * f; AY[i] += dy * f;
AX[j] -= dx * f; AY[j] -= dy * f;
}
}
}
var aReady = false;
function stepLeap() {
// leapfrog — 절반 스텝 대칭 킥으로 에너지를 오래 보존(장면이 몇 초 흐러도 부풀지 않는다)
if (!aReady) { accel(); aReady = true; }
var h = DT * 0.5;
for (var i = 0; i < N; i++) {
VX[i] += AX[i] * h; VY[i] += AY[i] * h;
X[i] += VX[i] * DT; Y[i] += VY[i] * DT;
}
accel();
for (var j = 0; j < N; j++) {
VX[j] += AX[j] * h; VY[j] += AY[j] * h;
}
}
function placeDisk(cx, cy, R, count, phase, dvx, dvy, dir, rnd, sc) {
// 원반 — r² 균등 면밀도, 원궤도 속도(01 과 동일 결정론 시더)
var M = R * R * 0.90;
for (var i = 0; i < count; i++) {
var r = R * Math.sqrt(rnd());
var a = phase + (i / count) * Math.PI * 2 + rnd() * 0.5;
var v = Math.sqrt(M / Math.max(r, 6)) * dir;
X.push(cx + Math.cos(a) * r);
Y.push(cy + Math.sin(a) * r);
VX.push(dvx * sc * 0.30 + -Math.sin(a) * v + (rnd() - 0.5) * 2);
VY.push(dvy * sc * 0.30 + Math.cos(a) * v + (rnd() - 0.5) * 2);
N++;
}
}
function seed() {
// 두 원반을 첫 스침 직전 거리(가깝게)에 놓고 PREPASS 스텝 미리 적분 —
// 화면의 t=0 은 이미 한 번 스치고 꼬리가 늘어선 두 번째 스침 직전 상태다
X = []; Y = []; VX = []; VY = []; N = 0; aReady = false;
var rnd = mulberry32(9);
var half = NSTARS >> 1;
var R = Math.min(W, H) * 0.44;
var sc = R;
placeDisk(W * 0.36, H * 0.34, R, half, 0, 0.62, -0.42, 1.0, rnd, sc);
placeDisk(W * 0.64, H * 0.66, R, NSTARS - half, Math.PI, -0.62, 0.42, 0.85, rnd, sc);
for (var s = 0; s < PREPASS; s++) stepLeap();
}
function rgba(c, a) { return 'rgba(' + c[0] + ',' + c[1] + ',' + c[2] + ',' + a + ')'; }
function decay() {
chainCtx.setTransform(1, 0, 0, 1, 0, 0);
chainCtx.globalCompositeOperation = 'destination-out';
chainCtx.fillStyle = 'rgba(0,0,0,0.012)';
chainCtx.fillRect(0, 0, W * dpr, H * dpr);
chainCtx.globalCompositeOperation = 'source-over';
chainCtx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
var prev = null;
function stamp() {
if (prev) {
for (var i = 0; i < N; i++) {
chainCtx.strokeStyle = rgba(i < (N >> 1) ? C_GLOW : C_TAIL, 0.30);
chainCtx.lineWidth = 1.9;
chainCtx.beginPath();
chainCtx.moveTo(prev[0][i], prev[1][i]);
chainCtx.lineTo(X[i], Y[i]);
chainCtx.stroke();
}
}
if (!prev) { prev = [X.slice(), Y.slice()]; }
else { prev[0] = X.slice(); prev[1] = Y.slice(); }
}
function draw() {
var ctx = cv.getContext('2d'); // CanvasRenderingContext2D — 이 데모의 모든 그리기 문맥
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.fillStyle = rgb(C_INK);
ctx.fillRect(0, 0, W, H);
var rnd = mulberry32(10);
ctx.fillStyle = rgba(C_GLOW, 0.35);
for (var k = 0; k < 40; k++) {
var bx = rnd() * W, by = rnd() * H, br = rnd() * 0.8 + 0.3;
ctx.globalAlpha = 0.12 + rnd() * 0.22;
ctx.beginPath(); ctx.arc(bx, by, br, 0, Math.PI * 2); ctx.fill();
}
ctx.globalAlpha = 1;
ctx.drawImage(chainCv, 0, 0, W, H);
// 별 — 타원체 잔해 중심은 앰버 코어. ellipse 글로우를 겹쳐 은하 전체 윤곽을 암시한다
var cx = 0, cy = 0;
for (i = 0; i < N; i++) { cx += X[i]; cy += Y[i]; }
cx /= N; cy /= N;
var sx = 0, sy = 0;
for (i = 0; i < N; i++) { sx += (X[i] - cx) * (X[i] - cx); sy += (Y[i] - cy) * (Y[i] - cy); }
var rx = Math.sqrt(sx / N) * 1.9, ry = Math.sqrt(sy / N) * 1.9;
ctx.fillStyle = rgba(C_HOT, 0.055);
ctx.beginPath(); ctx.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = rgba(C_HOT, 0.05);
ctx.beginPath(); ctx.ellipse(cx, cy, rx * 0.72, ry * 0.72, 0, 0, Math.PI * 2); ctx.fill();
// 별 점 — 은하 A 페리윙클 · 은하 B 핑크(합쳐지며 섞인다)
for (var i = 0; i < N; i++) {
var col = i < (N >> 1) ? C_GLOW : C_TAIL;
var d = Math.hypot(X[i] - cx, Y[i] - cy);
var near = Math.max(0, 1 - d / (Math.min(W, H) * 0.70));
ctx.fillStyle = rgba(col, 0.10 + near * 0.10);
ctx.beginPath(); ctx.arc(X[i], Y[i], 3.8, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = rgba(col, 0.55 + near * 0.45);
ctx.beginPath(); ctx.arc(X[i], Y[i], 1.7 + near * 1.0, 0, Math.PI * 2); ctx.fill();
}
// 중심부 — 앰버 핵 점(무게중심)
ctx.fillStyle = rgba(C_HOT, 0.95);
ctx.beginPath(); ctx.arc(cx, cy, 2.4, 0, Math.PI * 2); ctx.fill();
}
function rgb(c) { return 'rgb(' + c[0] + ',' + c[1] + ',' + c[2] + ')'; }
var simSteps = 0;
function frame(now) {
if (t0 < 0) t0 = now;
var loop = ((now - t0) / 1000) % 4.0; // 4초 루프 — 두 번째 스침 → 궤도 뒤섞임 → 타원체
var target = Math.floor(loop / DT);
while (simSteps < target) { stepLeap(); simSteps++; stamp(); }
if (target < simSteps - 3) { seed(); simSteps = 0; prev = null; chainCtx.clearRect(0, 0, W, H); }
decay();
draw();
raf = requestAnimationFrame(frame);
}
function stillFrame() {
// reduce — 궤도가 뒤섞여 타원체가 잡히는 장면까지 적분한 뒤 한 장 고정
for (var s = 0; s < 300; s++) { stepLeap(); stamp(); }
draw();
}
window.addEventListener('resize', function () {
fit(); seed(); simSteps = 0; prev = null; aReady = false;
if (reduce) stillFrame();
});
fit();
seed();
if (reduce) {
stillFrame();
root.classList.add('is-still');
} else {
raf = requestAnimationFrame(frame);
}
})();// GalaxyNbodyMergerRemnant — vanilla 판(run/322/demo/05-galaxy-nbody-merger-remnant/index.html) 의 React 포트.
// 합체 잔해 타원 은하 — 첫 스침을 지난 시점부터 시간을 흐르게 두는 장면.
// 시작은 두 은하가 이미 한 번 스쳐 꼬리가 늘어선 상태(두 번째 스침 직전):
// 시드에서 첫 스침을 미리 적분해 만든다(두 원반을 가깝게 놓고 몇백 스텝 = 첫 스침).
// 이후 화면의 시간이 흐르면 궤도 방향이 뒤섞이고(virial 화) 나선팔 구조가 흍어져
// 특징 없는 타원체가 남는다 — 관측되는 타원 은하가 합체 잔해라는 설명의 재현.
// 계산은 01 과 같은 전 쌍 O(N²) 뉴턴 중력 + leapfrog 적분(근사 아님).
import { useEffect, useRef, useState } from "react";
import type { CSSProperties } from "react";
import styles from "./GalaxyNbodyMergerRemnant.module.scss";
export type GalaxyNbodyMergerRemnantProps = {
duration?: string;
easing?: string;
color?: string;
nstars?: number; // 두 은하 합계 별 수
prepass?: number; // 시작 전 미리 흘려 둘 스텝(첫 스침+꼬리 형성) — 변형 "시작 시점"
};
type Vars = CSSProperties & { "--duration"?: string; "--easing"?: string; "--color"?: string };
type Box<T> = { current: T };
type RGB = [number, number, number];
type Sim2D = { N: number; X: number[]; Y: number[]; VX: number[]; VY: number[] };
const FIELD_LABEL = "합체 잔해 실험판";
// G·질량은 캔버스 픽셀 단위 시뮬레이션 값(물리 상수 아님 — 글에서 설명)
const G = 140.0, SOFT2 = 16;
const DT = 1 / 60;
function mulberry32(seed: number): () => number {
let s = seed | 0;
return function (): number {
s = (s + 0x6D2B79F5) | 0;
let t = Math.imul(s ^ (s >>> 15), 1 | s);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
export default function GalaxyNbodyMergerRemnant({
duration = "2s",
easing = "cubic-bezier(.2, .8, .2, 1)",
color = "#b7c8ff",
nstars = 320,
prepass = 420
}: GalaxyNbodyMergerRemnantProps) {
const rootRef = useRef<HTMLDivElement | null>(null);
const fieldRef = useRef<HTMLDivElement | null>(null);
const cvRef = useRef<HTMLCanvasElement | null>(null);
const ctxRef = useRef<CanvasRenderingContext2D | null>(null);
const colRef = useRef<{ ink: RGB; glow: RGB; hot: RGB; tail: RGB } | null>(null);
const chainCvRef = useRef<HTMLCanvasElement | null>(null);
const chainCtxRef = useRef<CanvasRenderingContext2D | null>(null);
const nstarsRef = useRef(nstars) as Box<number>;
const prepassRef = useRef(prepass) as Box<number>;
const wRef = useRef(0) as Box<number>;
const hRef = useRef(0) as Box<number>;
const dprRef = useRef(1) as Box<number>;
const rafRef = useRef(0) as Box<number>;
const [still, setStill] = useState(false);
const vars: Vars = { "--duration": duration, "--easing": easing, "--color": color };
function reduced(): boolean {
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}
function tokRGB(root: HTMLDivElement, name: string): RGB {
const s = getComputedStyle(root).getPropertyValue(name).trim();
const hx = s.length === 4
? s.charAt(1) + s.charAt(1) + s.charAt(2) + s.charAt(2) + s.charAt(3) + s.charAt(3)
: s.slice(1);
return [parseInt(hx.slice(0, 2), 16), parseInt(hx.slice(2, 4), 16), parseInt(hx.slice(4, 6), 16)];
}
function rgba(c: RGB, a: number): string {
return "rgba(" + c[0] + "," + c[1] + "," + c[2] + "," + a + ")";
}
function rgb(c: RGB): string {
return "rgb(" + c[0] + "," + c[1] + "," + c[2] + ")";
}
const simRef = useRef({ N: 0, X: [] as number[], Y: [] as number[], VX: [] as number[], VY: [] as number[] }) as Box<Sim2D>;
const AXRef = useRef<number[]>([]) as Box<number[]>;
const AYRef = useRef<number[]>([]) as Box<number[]>;
const aReadyRef = useRef(false) as Box<boolean>;
const prevRef = useRef<[number[], number[]] | null>(null);
const simStepsRef = useRef(0) as Box<number>;
function fit(): void {
const field = fieldRef.current;
const cv = cvRef.current;
if (!field || !cv) return;
const r = field.getBoundingClientRect();
const W = Math.round(r.width), H = Math.round(r.height);
const dpr = Math.min(2, window.devicePixelRatio || 1);
wRef.current = W; hRef.current = H; dprRef.current = dpr;
cv.width = W * dpr; cv.height = H * dpr;
cv.style.width = "100%"; cv.style.height = "100%";
ctxRef.current = cv.getContext("2d");
const chainCv = document.createElement("canvas");
chainCv.width = W * dpr; chainCv.height = H * dpr;
const chainCtx = chainCv.getContext("2d");
if (chainCtx) chainCtx.scale(dpr, dpr);
chainCvRef.current = chainCv;
chainCtxRef.current = chainCtx;
}
function accel(): void {
// 전 쌍 O(N²) 뉴턴 중력 — a_i = Σ G·(x_j - x_i)/(|d|²+ε²)^1.5 (근사 아님)
const sim = simRef.current;
const AX = AXRef.current, AY = AYRef.current;
const N = sim.N;
let i: number, j: number, dx: number, dy: number, d2: number, inv: number, f: number;
for (i = 0; i < N; i++) { AX[i] = 0; AY[i] = 0; }
for (i = 0; i < N; i++) {
for (j = i + 1; j < N; j++) {
dx = sim.X[j] - sim.X[i]; dy = sim.Y[j] - sim.Y[i];
d2 = dx * dx + dy * dy + SOFT2;
inv = 1 / Math.sqrt(d2);
f = G * inv * inv * inv;
AX[i] += dx * f; AY[i] += dy * f;
AX[j] -= dx * f; AY[j] -= dy * f;
}
}
}
function stepLeap(): void {
// leapfrog — 절반 스텝 대칭 킥으로 에너지를 오래 보존(장면이 몇 초 흐러도 부풀지 않는다)
const sim = simRef.current;
const AX = AXRef.current, AY = AYRef.current;
if (!aReadyRef.current) { accel(); aReadyRef.current = true; }
const h = DT * 0.5;
for (let i = 0; i < sim.N; i++) {
sim.VX[i] += AX[i] * h; sim.VY[i] += AY[i] * h;
sim.X[i] += sim.VX[i] * DT; sim.Y[i] += sim.VY[i] * DT;
}
accel();
for (let j = 0; j < sim.N; j++) {
sim.VX[j] += AX[j] * h; sim.VY[j] += AY[j] * h;
}
}
function placeDisk(cx: number, cy: number, R: number, count: number, phase: number, dvx: number, dvy: number, dir: number, rnd: () => number, sc: number): void {
// 원반 — r² 균등 면밀도, 원궤도 속도(01 과 동일 결정론 시더)
const sim = simRef.current;
const M = R * R * 0.90;
for (let i = 0; i < count; i++) {
const r = R * Math.sqrt(rnd());
const a = phase + (i / count) * Math.PI * 2 + rnd() * 0.5;
const v = Math.sqrt(M / Math.max(r, 6)) * dir;
sim.X.push(cx + Math.cos(a) * r);
sim.Y.push(cy + Math.sin(a) * r);
sim.VX.push(dvx * sc * 0.30 + -Math.sin(a) * v + (rnd() - 0.5) * 2);
sim.VY.push(dvy * sc * 0.30 + Math.cos(a) * v + (rnd() - 0.5) * 2);
sim.N++;
}
}
function seed(): void {
// 두 원반을 첫 스침 직전 거리(가깝게)에 놓고 PREPASS 스텝 미리 적분 —
// 화면의 t=0 은 이미 한 번 스치고 꼬리가 늘어선 두 번째 스침 직전 상태다
const sim = simRef.current;
sim.X = []; sim.Y = []; sim.VX = []; sim.VY = []; sim.N = 0;
aReadyRef.current = false;
const rnd = mulberry32(9);
const half = nstarsRef.current >> 1;
const W = wRef.current, H = hRef.current;
const R = Math.min(W, H) * 0.44;
const sc = R;
placeDisk(W * 0.36, H * 0.34, R, half, 0, 0.62, -0.42, 1.0, rnd, sc);
placeDisk(W * 0.64, H * 0.66, R, nstarsRef.current - half, Math.PI, -0.62, 0.42, 0.85, rnd, sc);
for (let s = 0; s < prepassRef.current; s++) stepLeap();
}
function decay(): void {
const chainCtx = chainCtxRef.current;
const dpr = dprRef.current;
const W = wRef.current, H = hRef.current;
if (!chainCtx) return;
chainCtx.setTransform(1, 0, 0, 1, 0, 0);
chainCtx.globalCompositeOperation = "destination-out";
chainCtx.fillStyle = "rgba(0,0,0,0.012)";
chainCtx.fillRect(0, 0, W * dpr, H * dpr);
chainCtx.globalCompositeOperation = "source-over";
chainCtx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
function stamp(): void {
const chainCtx = chainCtxRef.current;
const col = colRef.current;
const sim = simRef.current;
const prev = prevRef.current;
if (!chainCtx || !col) return;
if (prev) {
for (let i = 0; i < sim.N; i++) {
chainCtx.strokeStyle = rgba(i < (sim.N >> 1) ? col.glow : col.tail, 0.30);
chainCtx.lineWidth = 1.9;
chainCtx.beginPath();
chainCtx.moveTo(prev[0][i], prev[1][i]);
chainCtx.lineTo(sim.X[i], sim.Y[i]);
chainCtx.stroke();
}
}
if (!prev) prevRef.current = [sim.X.slice(), sim.Y.slice()];
else { prev[0] = sim.X.slice(); prev[1] = sim.Y.slice(); }
}
function draw(): void {
const ctx = ctxRef.current;
const chainCv = chainCvRef.current;
const col = colRef.current;
const dpr = dprRef.current;
const sim = simRef.current;
const W = wRef.current, H = hRef.current;
if (!ctx || !chainCv || !col) return;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.fillStyle = rgb(col.ink);
ctx.fillRect(0, 0, W, H);
const rnd = mulberry32(10);
ctx.fillStyle = rgba(col.glow, 0.35);
for (let k = 0; k < 40; k++) {
const bx = rnd() * W, by = rnd() * H, br = rnd() * 0.8 + 0.3;
ctx.globalAlpha = 0.12 + rnd() * 0.22;
ctx.beginPath(); ctx.arc(bx, by, br, 0, Math.PI * 2); ctx.fill();
}
ctx.globalAlpha = 1;
ctx.drawImage(chainCv, 0, 0, W, H);
// 별 — 타원체 잔해 중심은 앰버 코어. ellipse 글로우를 겹쳐 은하 전체 윤곽을 암시한다
let cx = 0, cy = 0;
for (let i = 0; i < sim.N; i++) { cx += sim.X[i]; cy += sim.Y[i]; }
cx /= sim.N; cy /= sim.N;
let sx = 0, sy = 0;
for (let i = 0; i < sim.N; i++) { sx += (sim.X[i] - cx) * (sim.X[i] - cx); sy += (sim.Y[i] - cy) * (sim.Y[i] - cy); }
const rx = Math.sqrt(sx / sim.N) * 1.9, ry = Math.sqrt(sy / sim.N) * 1.9;
ctx.fillStyle = rgba(col.hot, 0.055);
ctx.beginPath(); ctx.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = rgba(col.hot, 0.05);
ctx.beginPath(); ctx.ellipse(cx, cy, rx * 0.72, ry * 0.72, 0, 0, Math.PI * 2); ctx.fill();
// 별 점 — 은하 A 페리윙클 · 은하 B 핑크(합쳐지며 섞인다)
for (let i = 0; i < sim.N; i++) {
const c = i < (sim.N >> 1) ? col.glow : col.tail;
const d = Math.hypot(sim.X[i] - cx, sim.Y[i] - cy);
const near = Math.max(0, 1 - d / (Math.min(W, H) * 0.70));
ctx.fillStyle = rgba(c, 0.10 + near * 0.10);
ctx.beginPath(); ctx.arc(sim.X[i], sim.Y[i], 3.8, 0, Math.PI * 2); ctx.fill();
ctx.fillStyle = rgba(c, 0.55 + near * 0.45);
ctx.beginPath(); ctx.arc(sim.X[i], sim.Y[i], 1.7 + near * 1.0, 0, Math.PI * 2); ctx.fill();
}
// 중심부 — 앰버 핵 점(무게중심)
ctx.fillStyle = rgba(col.hot, 0.95);
ctx.beginPath(); ctx.arc(cx, cy, 2.4, 0, Math.PI * 2); ctx.fill();
}
function stillFrame(): void {
// reduce — 궤도가 뒤섞여 타원체가 잡히는 장면까지 적분한 뒤 한 장 고정
for (let s = 0; s < 300; s++) { stepLeap(); stamp(); }
draw();
}
let t0 = -1;
function frame(now: number): void {
if (t0 < 0) t0 = now;
const loop = ((now - t0) / 1000) % 4.0; // 4초 루프 — 두 번째 스침 → 궤도 뒤섞임 → 타원체
const target = Math.floor(loop / DT);
while (simStepsRef.current < target) { stepLeap(); simStepsRef.current++; stamp(); }
if (target < simStepsRef.current - 3) {
seed(); simStepsRef.current = 0; prevRef.current = null;
const chainCtx = chainCtxRef.current;
if (chainCtx) chainCtx.clearRect(0, 0, wRef.current, hRef.current);
}
decay();
draw();
rafRef.current = requestAnimationFrame(frame);
}
useEffect(() => {
const root = rootRef.current;
if (!root) return;
nstarsRef.current = nstars;
prepassRef.current = prepass;
colRef.current = {
ink: tokRGB(root, "--gx-ink"),
glow: tokRGB(root, "--gx-glow"),
hot: tokRGB(root, "--gx-hot"),
tail: tokRGB(root, "--gx-tail"),
};
fit();
seed();
simStepsRef.current = 0;
prevRef.current = null;
function onResize(): void {
fit(); seed(); simStepsRef.current = 0; prevRef.current = null; aReadyRef.current = false;
if (reduced()) stillFrame();
}
window.addEventListener("resize", onResize);
if (reduced()) {
stillFrame();
setStill(true);
} else {
t0 = -1;
rafRef.current = requestAnimationFrame(frame);
}
return () => {
window.removeEventListener("resize", onResize);
cancelAnimationFrame(rafRef.current);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [nstars, prepass]);
const rootCls = still ? `${styles.root} ${styles.isStill}` : styles.root;
return (
<main className={styles.stage}>
<div className={rootCls} ref={rootRef} style={vars}>
<p className={styles.hint}>
<span>충돌이 지나도 시간을 계속 흐르게 두면 나선팔이 흩어지고 궤도 방향이 뒤섞여 특징 없는 타원체가 남습니다</span>
</p>
<div
className={styles.field}
ref={fieldRef}
role="application"
aria-label={FIELD_LABEL}
tabIndex={0}
>
<canvas className={styles.cv} ref={cvRef}></canvas>
</div>
<div className={styles.bar}>
<span className={styles.meta}>두 번째 스침부터 시작 · 별 320개</span>
<span className={styles.metaDim}>canvas · virial mix · requestAnimationFrame</span>
</div>
</div>
</main>
);
}05 합체 잔해 타원 은하 — 나선이 부서져 뭉툭해지는 결말 — 측정 누적면적 32.382% · 움직인 프레임 23/23GODRICH 원작 · zip 에 SCSS·React 포함 · 은하 충돌 시뮬레이션 9종 — 서로 잡아당기는 별들로 나선팔·조석 꼬리를 만드는 캔버스
이 데모가 속한 글
은하 충돌 시뮬레이션 9종 — 서로 잡아당기는 별들로 나선팔·조석 꼬리를 만드는 캔버스은하 충돌 시뮬레이션은 라이브러리·WebGL 없이 별 하나하나에 뉴턴 중력을 매 프레임 적분하면 두 은하가 스치며 조석 꼬리를 남기고 합쳐지는데, 새로고침 없이 눈앞에서 우주 규모의 인력이 이루어지는 장면을 그대로 이 글의 데모 전부 보기


