02사면 미끄짐 — 좌우 대각선 규칙으로 자연스러운 안식각
아래가 막힌 칸은 왼쪽-아래·오른쪽-아래 대각선을 차례로 시도해 비어 있으면 그리로 옮기면, 모래가 한 줄로 곧게 쌓이지 않고 실제처럼 옆으로 퍼지며 안식각을 이룹니다.
쓰임모래시계 로딩 인디케이터, 물감 낙하 아트의 뿔 모양
fillRectrequestAnimationFrame

<main class="stage">
<div class="cd is-demo" id="cdRoot">
<p class="cd__hint">
<span>대각선 시도가 모래를 옆으로 퍼지게 해 안식각을 만듭니다</span>
</p>
<div class="cd__field" id="cdField" role="application" aria-label="모래 사면 미끄짐 셀 오토마타 데모" tabindex="0">
<canvas class="cd__cv" id="cdCv"></canvas>
</div>
<div class="cd__bar">
<span class="cd__meta"><b class="cd__val" id="cdN">100</b>% 대각 시도 100%</span>
<span class="cd__meta cd__meta--dim">canvas · fillRect · requestAnimationFrame</span>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 사면 미끄짐(02). @keyframes 를 아예 두지 않는다 —
// 움직임은 전부 캔버스 rAF 루프(낙하+대각 스캔)가 만든다.
// 무대는 모래밤. 파스텔 고정 팔레트를 --sand-* 로 편 공통 규격(01~09 동일).
$duration: $dur-loop;
$easing: $ease-spring;
$color: $subject-lilac;
@include stage($stage-ink);
// ── 편 공통 파스텔 팔레트(BD26 vivid 0 실측 통과값 — 다른 색 금지) ──
$sand-night: #201c17;
$sand-mist: #d8d2c6;
$sand-glow: #f2e2c4;
$sand-grain: #d9b98a;
$sand-gold: #ecd9b0;
$sand-water: #a9c8dd;
$sand-ice: #cfe3ee;
$sand-fire: #ffc9ad;
$sand-flame: #ffe0c4;
$sand-ash: #b9b2a6;
$sand-smoke: #8e8879;
$sand-plant: #9fd6ad;
$sand-leaf: #c4e6c9;
$sand-acid: #c7dd8f;
$sand-stone: #8a8578;
$sand-wood: #b98a63;
.cd {
// 렌더러가 읽는 색 — JS 는 getComputedStyle 로 --sand-* 를 받아 쓴다
--sand-night: #{$sand-night};
--sand-mist: #{$sand-mist};
--sand-glow: #{$sand-glow};
--sand-grain: #{$sand-grain};
--sand-gold: #{$sand-gold};
--sand-water: #{$sand-water};
--sand-ice: #{$sand-ice};
--sand-fire: #{$sand-fire};
--sand-flame: #{$sand-flame};
--sand-ash: #{$sand-ash};
--sand-smoke: #{$sand-smoke};
--sand-plant: #{$sand-plant};
--sand-leaf: #{$sand-leaf};
--sand-acid: #{$sand-acid};
--sand-stone: #{$sand-stone};
--sand-wood: #{$sand-wood};
display: flex; flex-direction: column; gap: $sp-2;
width: 100%; max-width: 424px;
}
.cd__hint { color: $sand-mist; font-weight: 700; font-size: clamp(10px, 2.8vw, 12px); margin: 0; }
.cd__field {
position: relative; height: 200px;
border-radius: $r-card; overflow: hidden;
background: $sand-night;
box-shadow: inset 0 0 0 1px rgba($sand-mist, .18);
}
.cd__field:focus-visible { outline: 2px solid $subject-lilac; outline-offset: 2px; }
.cd__cv { display: block; width: 100%; height: 100%; }
.cd__bar { display: flex; align-items: baseline; justify-content: space-between; gap: $sp-2; }
.cd__meta { font-size: 10px; font-weight: 500; color: rgba($sand-mist, .72); }
.cd__val { color: $subject-lilac; font-weight: 700; }
.cd__meta--dim { font-size: 10px; }
@media (max-width: 340px) {
.cd { gap: $sp-1; }
.cd__field { height: 110px; }
.cd__meta--dim { display: none; }
}
// reduce — rAF 를 돌리지 않고 규칙 몇 틱의 한 장만 남는다.
@media (prefers-reduced-motion: reduce) {
.cd.is-still .cd__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: #17141a;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.cd {
--sand-night: #201c17;
--sand-mist: #d8d2c6;
--sand-glow: #f2e2c4;
--sand-grain: #d9b98a;
--sand-gold: #ecd9b0;
--sand-water: #a9c8dd;
--sand-ice: #cfe3ee;
--sand-fire: #ffc9ad;
--sand-flame: #ffe0c4;
--sand-ash: #b9b2a6;
--sand-smoke: #8e8879;
--sand-plant: #9fd6ad;
--sand-leaf: #c4e6c9;
--sand-acid: #c7dd8f;
--sand-stone: #8a8578;
--sand-wood: #b98a63;
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
max-width: 424px;
}
.cd__hint {
color: #d8d2c6;
font-weight: 700;
font-size: clamp(10px, 2.8vw, 12px);
margin: 0;
}
.cd__field {
position: relative;
height: 200px;
border-radius: 16px;
overflow: hidden;
background: #201c17;
box-shadow: inset 0 0 0 1px rgba(216, 210, 198, 0.18);
}
.cd__field:focus-visible {
outline: 2px solid #b9a0ff;
outline-offset: 2px;
}
.cd__cv {
display: block;
width: 100%;
height: 100%;
}
.cd__bar {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
}
.cd__meta {
font-size: 10px;
font-weight: 500;
color: rgba(216, 210, 198, 0.72);
}
.cd__val {
color: #b9a0ff;
font-weight: 700;
}
.cd__meta--dim {
font-size: 10px;
}
@media (max-width: 340px) {
.cd {
gap: 4px;
}
.cd__field {
height: 110px;
}
.cd__meta--dim {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
.cd.is-still .cd__field {
cursor: default !important;
}
}// 사면 미끄짐(02). 01 의 낙하 규칙에 대각선 규칙을 얹는다 —
// 아래칸이 막혀 있으면 좌하 → 우하 순서로 SLIDE_P 확률로 시도.
// 중앙 단일 스포너(4칸 폭)에서 쏟아지는 모래가 원뿔 무더기(안식각)를 이룬다.
(function () {
// ── 변형 상수 블록 — 아래 값 하나만 바꿔 변형을 만든다 ──
var SLIDE_P = 1.0; // 대각 시도 확률 — 1.0 은 항상 미끄짐(완만), 낮추면 뾰족
var SPAWN_P = 0.75; // 스포너 칸별 매 틱 생성 확률
var ZONE_W = 56; // 스포너 폭(칸) — 원뿔이 화면 폭을 넉넉히 쓰도록 확대(면적 보정)
// ────────────────────────────────────────────────────
var root = document.getElementById('cdRoot');
var field = document.getElementById('cdField');
var cv = document.getElementById('cdCv');
var ctx = cv.getContext('2d');
var nOut = document.getElementById('cdN');
function makeRand(seed) {
var st = seed >>> 0;
return function () {
st = (st + 0x6D2B79F5) >>> 0;
var t = st;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
var rand = makeRand(0x318A02);
// 색은 CSS 커스텀 프로퍼티(--sand-*)에서 getComputedStyle 로 읽는다 — 파스텔 토큰이 scss 한 곳에
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_NIGHT = tokRGB('--sand-night');
var C_GLOW = tokRGB('--sand-glow');
var C_GRAIN = tokRGB('--sand-grain');
var C_GOLD = tokRGB('--sand-gold');
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var CELL = 4;
var W = 0, H = 0, cols = 0, rows = 0;
var grid = null, shade = null;
var zoneX = 0;
var raf = 0, t0 = -1, acc = 0;
var STEP = 1 / 60;
function idx(x, y) { return y * cols + x; }
function fit() {
var r = field.getBoundingClientRect();
W = r.width; H = r.height;
cv.width = Math.round(W); cv.height = Math.round(H);
cols = Math.max(1, Math.floor(W / CELL));
rows = Math.max(1, Math.floor(H / CELL));
grid = new Uint8Array(cols * rows);
shade = new Uint8Array(cols * rows);
zoneX = Math.max(0, Math.round(cols / 2 - ZONE_W / 2));
}
function spawnStep() {
for (var k = 0; k < ZONE_W; k++) {
var x = zoneX + k;
if (x < 0 || x >= cols) continue;
if (rand() < SPAWN_P) {
var i = idx(x, 0);
if (grid[i] === 0) { grid[i] = 1; shade[i] = rand() < 0.5 ? 0 : 1; }
}
}
}
function update() {
for (var y = rows - 2; y >= 0; y--) {
for (var x = 0; x < cols; x++) {
var i = idx(x, y);
if (grid[i] !== 1) continue;
// 1) 아래로
var bi = idx(x, y + 1);
if (grid[bi] === 0) {
grid[bi] = 1; shade[bi] = shade[i]; grid[i] = 0;
continue;
}
// 2) 대각선 — 좌하 → 우하 순서, SLIDE_P 확률
if (rand() < SLIDE_P) {
var dir = rand() < 0.5 ? -1 : 1;
var try1 = (x + dir >= 0 && x + dir < cols && grid[idx(x + dir, y + 1)] === 0 && grid[idx(x + dir, y)] === 0);
var try2 = false;
if (!try1) {
var d2 = -dir;
try2 = (x + d2 >= 0 && x + d2 < cols && grid[idx(x + d2, y + 1)] === 0 && grid[idx(x + d2, y)] === 0);
}
if (try1 || try2) {
var dx = try1 ? dir : -dir;
var di = idx(x + dx, y + 1);
grid[di] = 1; shade[di] = shade[i]; grid[i] = 0;
}
}
}
}
}
function draw(t) {
ctx.fillStyle = 'rgb(' + C_NIGHT.join(',') + ')';
ctx.fillRect(0, 0, W, H);
// 느린 잔광 — 중심이 sin/cos 로 천천히 도는 radial gradient(안개, 알파 0.06 내외)
var gx = W * (0.5 + 0.36 * Math.sin(t * 0.17));
var gy = H * (0.5 + 0.30 * Math.cos(t * 0.13));
var gr = Math.max(W, H) * 0.7;
var g = ctx.createRadialGradient(gx, gy, 0, gx, gy, gr);
g.addColorStop(0, 'rgba(' + C_GLOW.join(',') + ',0.07)');
g.addColorStop(1, 'rgba(' + C_GLOW.join(',') + ',0)');
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
for (var y = 0; y < rows; y++) {
for (var x = 0; x < cols; x++) {
var i = idx(x, y);
if (grid[i] !== 1) continue;
ctx.fillStyle = shade[i] ? 'rgb(' + C_GOLD.join(',') + ')' : 'rgb(' + C_GRAIN.join(',') + ')';
ctx.fillRect(x * CELL, y * CELL, CELL, CELL);
}
}
}
function stillFrame() {
for (var k = 0; k < 40; k++) { spawnStep(); update(); }
draw(0.6);
}
function frame(now) {
if (t0 < 0) t0 = now;
var dt = Math.min(0.05, (now - (frame.prev || now)) / 1000);
frame.prev = now;
acc += dt;
while (acc >= STEP) { spawnStep(); update(); acc -= STEP; }
draw((now - t0) / 1000);
raf = requestAnimationFrame(frame);
}
window.addEventListener('resize', function () {
fit();
if (reduce) stillFrame();
});
fit();
nOut.textContent = String(Math.round(SLIDE_P * 100));
if (reduce) {
stillFrame();
root.classList.add('is-still');
} else {
raf = requestAnimationFrame(frame);
}
})();// DiagonalSlideSlope — vanilla 판(run/318/demo/02-sand-diagonal-slide-slope/index.html) 의 React 포트.
// 사면 미끄짐 — 낙하 규칙에 좌하→우하 대각선 시도(SLIDE_P 확률)를 얹어 안식각 원뿔을 만든다.
import { useEffect, useRef, useState } from "react";
import type { CSSProperties } from "react";
import styles from "./DiagonalSlideSlope.module.scss";
export type DiagonalSlideSlopeProps = {
duration?: string;
easing?: string;
color?: string;
slideP?: number; // 대각 시도 확률 — 변형 "대각 시도" 축(1.0 완만 · 0.4 뾰족)
spawnP?: number; // 스포너 칸별 매 틱 생성 확률
};
type Vars = CSSProperties & { "--duration"?: string; "--easing"?: string; "--color"?: string };
type Box<T> = { current: T };
type RGB = [number, number, number];
const FIELD_LABEL = "모래 사면 미끄짐 셀 오토마타 데모";
const CELL = 4;
const STEP = 1 / 60;
const ZONE_W = 4;
// 시드 고정 PRNG — mulberry32
function makePRNG(seed: number): () => number {
let s = seed >>> 0;
return function () {
s = (s + 0x6d2b79f5) >>> 0;
let t = s;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
export default function DiagonalSlideSlope({
duration = "2s",
easing = "cubic-bezier(.2, .8, .2, 1)",
color = "#b9a0ff",
slideP = 1.0,
spawnP = 0.42,
}: DiagonalSlideSlopeProps) {
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 sizeRef = useRef({ w: 0, h: 0, cols: 0, rows: 0 }) as Box<{ w: number; h: number; cols: number; rows: number }>;
const gridRef = useRef<Uint8Array | null>(null) as Box<Uint8Array | null>;
const shadeRef = useRef<Uint8Array | null>(null) as Box<Uint8Array | null>;
const zoneRef = useRef(0) as Box<number>;
const colRef = useRef<{ night: RGB; glow: RGB; grain: RGB; gold: RGB } | null>(null);
const slideRef = useRef(slideP) as Box<number>;
const spawnRef = useRef(spawnP) as Box<number>;
const randRef = useRef(makePRNG(0x318a02)) as Box<() => number>;
const rafRef = useRef(0) as Box<number>;
const [n, setN] = useState(String(Math.round(slideP * 100)));
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 idx(x: number, y: number): number { return y * sizeRef.current.cols + x; }
function fit(): void {
const field = fieldRef.current;
const cv = cvRef.current;
if (!field || !cv) return;
const ctx = cv.getContext("2d");
if (!ctx) return;
const r = field.getBoundingClientRect();
const cols = Math.max(1, Math.floor(r.width / CELL));
const rows = Math.max(1, Math.floor(r.height / CELL));
sizeRef.current = { w: r.width, h: r.height, cols, rows };
cv.width = Math.round(r.width);
cv.height = Math.round(r.height);
gridRef.current = new Uint8Array(cols * rows);
shadeRef.current = new Uint8Array(cols * rows);
zoneRef.current = Math.max(0, Math.round(cols / 2 - ZONE_W / 2));
ctxRef.current = ctx;
}
function spawnStep(): void {
const { cols } = sizeRef.current;
const grid = gridRef.current;
const shade = shadeRef.current;
if (!grid || !shade) return;
const rand = randRef.current;
for (let k = 0; k < ZONE_W; k++) {
const x = zoneRef.current + k;
if (x < 0 || x >= cols) continue;
if (rand() < spawnRef.current) {
const i = idx(x, 0);
if (grid[i] === 0) { grid[i] = 1; shade[i] = rand() < 0.5 ? 0 : 1; }
}
}
}
function update(): void {
const { cols, rows } = sizeRef.current;
const grid = gridRef.current;
const shade = shadeRef.current;
if (!grid || !shade) return;
const rand = randRef.current;
for (let y = rows - 2; y >= 0; y--) {
for (let x = 0; x < cols; x++) {
const i = idx(x, y);
if (grid[i] !== 1) continue;
// 1) 아래로
const bi = idx(x, y + 1);
if (grid[bi] === 0) {
grid[bi] = 1; shade[bi] = shade[i]; grid[i] = 0;
continue;
}
// 2) 대각선 — 좌하 → 우하 순서, SLIDE_P 확률
if (rand() < slideRef.current) {
const dir = rand() < 0.5 ? -1 : 1;
let ok1 = false, ok2 = false;
let nx = x + dir;
if (nx >= 0 && nx < cols && grid[idx(nx, y + 1)] === 0 && grid[idx(nx, y)] === 0) ok1 = true;
if (!ok1) {
nx = x - dir;
if (nx >= 0 && nx < cols && grid[idx(nx, y + 1)] === 0 && grid[idx(nx, y)] === 0) ok2 = true;
}
if (ok1 || ok2) {
const dx = ok1 ? dir : -dir;
const di = idx(x + dx, y + 1);
grid[di] = 1; shade[di] = shade[i]; grid[i] = 0;
}
}
}
}
}
function draw(t: number): void {
const ctx = ctxRef.current;
const col = colRef.current;
if (!ctx || !col) return;
const { w: W, h: H, cols, rows } = sizeRef.current;
const grid = gridRef.current;
const shade = shadeRef.current;
if (!grid || !shade) return;
ctx.fillStyle = `rgb(${col.night.join(",")})`;
ctx.fillRect(0, 0, W, H);
const gx = W * (0.5 + 0.36 * Math.sin(t * 0.17));
const gy = H * (0.5 + 0.3 * Math.cos(t * 0.13));
const gr = Math.max(W, H) * 0.7;
const g = ctx.createRadialGradient(gx, gy, 0, gx, gy, gr);
g.addColorStop(0, `rgba(${col.glow.join(",")},0.07)`);
g.addColorStop(1, `rgba(${col.glow.join(",")},0)`);
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
const i = idx(x, y);
if (grid[i] !== 1) continue;
ctx.fillStyle = shade[i] ? `rgb(${col.gold.join(",")})` : `rgb(${col.grain.join(",")})`;
ctx.fillRect(x * CELL, y * CELL, CELL, CELL);
}
}
}
function stillFrame(): void {
for (let k = 0; k < 40; k++) { spawnStep(); update(); }
draw(0.6);
}
let t0 = -1;
let prev = 0;
let acc = 0;
function frame(now: number): void {
if (t0 < 0) t0 = now;
const dt = Math.min(0.05, (now - (prev || now)) / 1000);
prev = now;
acc += dt;
while (acc >= STEP) { spawnStep(); update(); acc -= STEP; }
draw((now - t0) / 1000);
rafRef.current = requestAnimationFrame(frame);
}
useEffect(() => {
const root = rootRef.current;
if (!root) return;
slideRef.current = slideP;
spawnRef.current = spawnP;
colRef.current = {
night: tokRGB(root, "--sand-night"),
glow: tokRGB(root, "--sand-glow"),
grain: tokRGB(root, "--sand-grain"),
gold: tokRGB(root, "--sand-gold"),
};
randRef.current = makePRNG(0x318a02);
fit();
setN(String(Math.round(slideP * 100)));
function onResize(): void {
fit();
if (reduced()) stillFrame();
}
window.addEventListener("resize", onResize);
if (reduced()) {
stillFrame();
setStill(true);
} else {
rafRef.current = requestAnimationFrame(frame);
}
return () => {
window.removeEventListener("resize", onResize);
cancelAnimationFrame(rafRef.current);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [slideP, spawnP]);
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}><b className={styles.val}>{n}</b>% 대각 시도 100%</span>
<span className={styles.metaDim}>canvas · fillRect · requestAnimationFrame</span>
</div>
</div>
</main>
);
}02 사면 미끄짐 — 좌우 대각선 규칙으로 자연스러운 안식각 — 측정 누적면적 33.878% · 움직인 프레임 23/23GODRICH 원작 · zip 에 SCSS·React 포함 · 폴링 샌드(falling sand simulator) 9종 — 모래·물·불 셀 오토마타
이 데모가 속한 글
폴링 샌드(falling sand simulator) 9종 — 모래·물·불 셀 오토마타라이브러리·WebGL 없이 칸 하나의 규칙 네 개(아래·좌아래·우아래·옆)로 모래가 쌓이고 물이 흐르고 불이 번집니다 — 이 폴링 샌드(falling sand simulator) 9종은 그 계산을 캔버스와 바닐라 자 이 글의 데모 전부 보기


