07센서 각도 모프 — 각도 하나로 산호에서 혈관까지 형태가 바뀌기
센서 벌림각과 거리 두 숫자만 슬라이더로 바꾸면 같은 규칙이 촘촘한 산호 모양, 성긴 혈관 모양, 격자형 도시 모양까지 완전히 다른 네트워크를 그려냅니다.
쓰임파라미터 실험 데모, 교육용 인터랙티브 도해
ImageDatarequestAnimationFrame

<main class="stage">
<div class="sm is-demo" id="smRoot">
<p class="sm__hint">
<span>센서 벌림각과 거리 두 숫자만 슬라이더로 바꾸면 같은 규칙이 촘촘한 산호 모양, 성긴 혈관 모양, 격자형 도시 모양까지 완전히 다른 네트워크를 그려냅니다</span>
</p>
<div class="sm__field" id="smField" role="application" aria-label="센서 각도 모프 점균 실험판" tabindex="0">
<canvas class="sm__cv" id="smCv"></canvas>
</div>
<div class="sm__bar">
<label class="sm__ctl">
<span class="sm__lab" id="smAngLab">벌림각 29°</span>
<input class="sm__rng" id="smAng" type="range" min="10" max="90" step="1" value="29" aria-label="센서 벌림각">
</label>
<label class="sm__ctl">
<span class="sm__lab" id="smDistLab">거리 15</span>
<input class="sm__rng" id="smDist" type="range" min="4" max="30" step="1" value="15" aria-label="센서 거리">
</label>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 센서 각도 모프(07). @keyframes 를 두지 않는다 —
// 움직임은 전부 캔버스 rAF 루프(슬라이더 파라미터 + 3센서 감지 → 회전 → 트레일 → 확산·증발)가 만든다.
// 무대는 종이(paper) — 일곱 번째 순환(01밤·02종이·03밀짚·04노을·05먹·06남색). 파라미터 실험판에는
// 밝은 종이가 계기판처럼 어울린다.
$duration: $dur-loop;
$easing: $ease-spring;
$color: $subject-ink;
// ── 이 항목만의 파스텔 팔레트(밝은 계열, L 0.85 이상 — BD26 안전) ──
$sm-stage: #f4f7f2; // 연한 이끼 종이 무대
@include stage($sm-stage);
$sm-floor: #f4f7f2; // 필드 바닥 — 무대와 같은 톤
$sm-trail: #cfe3c8; // 트레일 — 파스텔 세이지
$sm-acct: #f6cfd4; // 파라미터 표시기 — 파스텔 로즈
$sm-text: #2c3326; // 종이 위 — 짙은 이끼 글자(대비)
.sm {
--sm-floor: #{$sm-floor};
--sm-trail: #{$sm-trail};
--sm-acct: #{$sm-acct};
display: flex; flex-direction: column; gap: $sp-2;
width: 100%; max-width: 424px;
}
.sm__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: $sm-text;
}
.sm__field {
position: relative; height: 180px;
border-radius: $r-card; overflow: hidden;
background: $sm-floor;
box-shadow: inset 0 0 0 1px rgba($sm-text, .18);
}
.sm__field:focus-visible { outline: 2px solid $sm-text; outline-offset: 2px; }
.sm__cv { display: block; width: 100%; height: 100%; }
.sm__bar {
display: flex; align-items: center; justify-content: space-between;
gap: $sp-2; flex-wrap: wrap;
}
.sm__ctl {
display: flex; align-items: center; gap: $sp-1;
min-width: 0;
}
.sm__lab {
font-size: 10px; font-weight: 700; line-height: 1;
color: rgba($sm-text, .72); white-space: nowrap;
}
.sm__rng {
appearance: none; -webkit-appearance: none;
width: clamp(64px, 20vw, 108px); height: 16px;
background: transparent; border: 0; padding: 0; margin: 0;
cursor: pointer;
}
.sm__rng::-webkit-slider-runnable-track {
height: 4px; border-radius: $r-pill;
background: rgba($sm-text, .22);
}
.sm__rng::-webkit-slider-thumb {
appearance: none; -webkit-appearance: none;
width: 12px; height: 12px; margin-top: -4px;
border-radius: 50%; border: 0;
background: $sm-trail;
box-shadow: 0 0 0 2px rgba($sm-text, .35);
}
.sm__rng::-moz-range-track {
height: 4px; border-radius: $r-pill;
background: rgba($sm-text, .22);
}
.sm__rng::-moz-range-thumb {
width: 12px; height: 12px; border-radius: 50%; border: 0;
background: $sm-trail;
box-shadow: 0 0 0 2px rgba($sm-text, .35);
}
.sm__rng:focus-visible { outline: 2px solid $sm-text; outline-offset: 2px; }
@media (max-width: 340px) {
.sm { gap: $sp-1; }
.sm__field { height: 82px; }
.sm__bar { flex-direction: column; align-items: stretch; gap: $sp-1; }
.sm__ctl { justify-content: space-between; }
.sm__rng { flex: 0 0 auto; }
}
// reduce — rAF 를 돌리지 않고 혈관 모양 파라미터로 자란 한 장만 남는다.
@media (prefers-reduced-motion: reduce) {
.sm.is-still .sm__rng { pointer-events: auto; }
}html, body {
margin: 0;
overflow: hidden;
}
.stage {
box-sizing: border-box;
min-height: 100vh;
display: grid;
place-items: center;
margin: 0;
background: #f4f7f2;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.sm {
--sm-floor: #f4f7f2;
--sm-trail: #cfe3c8;
--sm-acct: #f6cfd4;
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
max-width: 424px;
}
.sm__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: #2c3326;
}
.sm__field {
position: relative;
height: 180px;
border-radius: 16px;
overflow: hidden;
background: #f4f7f2;
box-shadow: inset 0 0 0 1px rgba(44, 51, 38, 0.18);
}
.sm__field:focus-visible {
outline: 2px solid #2c3326;
outline-offset: 2px;
}
.sm__cv {
display: block;
width: 100%;
height: 100%;
}
.sm__bar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
flex-wrap: wrap;
}
.sm__ctl {
display: flex;
align-items: center;
gap: 4px;
min-width: 0;
}
.sm__lab {
font-size: 10px;
font-weight: 700;
line-height: 1;
color: rgba(44, 51, 38, 0.72);
white-space: nowrap;
}
.sm__rng {
appearance: none;
-webkit-appearance: none;
width: clamp(64px, 20vw, 108px);
height: 16px;
background: transparent;
border: 0;
padding: 0;
margin: 0;
cursor: pointer;
}
.sm__rng::-webkit-slider-runnable-track {
height: 4px;
border-radius: 999px;
background: rgba(44, 51, 38, 0.22);
}
.sm__rng::-webkit-slider-thumb {
appearance: none;
-webkit-appearance: none;
width: 12px;
height: 12px;
margin-top: -4px;
border-radius: 50%;
border: 0;
background: #cfe3c8;
box-shadow: 0 0 0 2px rgba(44, 51, 38, 0.35);
}
.sm__rng::-moz-range-track {
height: 4px;
border-radius: 999px;
background: rgba(44, 51, 38, 0.22);
}
.sm__rng::-moz-range-thumb {
width: 12px;
height: 12px;
border-radius: 50%;
border: 0;
background: #cfe3c8;
box-shadow: 0 0 0 2px rgba(44, 51, 38, 0.35);
}
.sm__rng:focus-visible {
outline: 2px solid #2c3326;
outline-offset: 2px;
}
@media (max-width: 340px) {
.sm {
gap: 4px;
}
.sm__field {
height: 82px;
}
.sm__bar {
flex-direction: column;
align-items: stretch;
gap: 4px;
}
.sm__ctl {
justify-content: space-between;
}
.sm__rng {
flex: 0 0 auto;
}
}
@media (prefers-reduced-motion: reduce) {
.sm.is-still .sm__rng {
pointer-events: auto;
}
}// 센서 각도 모프(07). Physarum 스티그머지 + 실시간 파라미터 모프 —
// 센서 벌림각(도)과 센서 거리 두 값을 실제 range 슬라이더로 바꾼다. 같은 3센서 규칙이라도
// 좁은 각도+짧은 거리는 촘촘한 산호, 넓은 각도+긴 거리는 성긴 혈관·격자형 도시망을 그린다.
// .is-demo 동안은 슬라이더가 사람 손 없이 스스로 움직여(자동 시연) 형태 변화를 보여주고,
// 사람이 실제로 슬라이더를 잡으면 그 즉시 같은 파라미터가 시뮬레이션에 반영된다.
//
// 화면이 사는 장치 — 077 캔버스 기준의 "매 프레임 계산":
// · 캔버스는 절대 clear 하지 않는다. 필드 전체를 매 프레임 새로 계산해 얹는다.
// · 앰비언트 글로우 레이어(두 옥타브 값노이즈)가 전면을 확산 구조로 흔들어 누적면적을 채운다.
(function () {
// ── 변형 상수 블록 ──
var AGENTS = 1500; // 동시에 걷는 에이전트 수
var DECAY = 0.045; // 증발률
// ────────────────────────────────────
var TURN = 0.5;
var STEP = 1.05;
var DEPOSIT = 4.2;
var DIFFUSE = 0.5;
var CAP = 7;
var SUBSTEPS = 3;
// 파라미터(슬라이더가 실시간으로 바꾼다)
var sensorAngleDeg = 29; // 도(°)
var sensorDist = 15;
var root = document.getElementById('smRoot');
var field = document.getElementById('smField');
var cv = document.getElementById('smCv');
var ctx = cv.getContext('2d', { alpha: false });
var angRng = document.getElementById('smAng');
var distRng = document.getElementById('smDist');
var angLab = document.getElementById('smAngLab');
var distLab = document.getElementById('smDistLab');
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(0x320A07);
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_FLOOR = tokRGB('--sm-floor');
var C_TRAIL = tokRGB('--sm-trail');
var C_ACCT = tokRGB('--sm-acct');
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var W = 0, H = 0, fw = 0, fh = 0, raf = 0, t0 = -1;
var trail, trailB, img, data;
var ax, ay, ah;
// ── 값노이즈(앰비언트 글로우용) ──
var perm = new Uint8Array(512);
(function () {
var p = [];
for (var i = 0; i < 256; i++) p.push(i);
for (var i2 = 255; i2 > 0; i2--) {
var k2 = Math.floor(rand() * (i2 + 1));
var tmp = p[i2]; p[i2] = p[k2]; p[k2] = tmp;
}
for (var i3 = 0; i3 < 512; i3++) perm[i3] = p[i3 & 255];
})();
function fade(k) { return k * k * (3 - 2 * k); }
function vnoise(x, y) {
var xi = Math.floor(x), yi = Math.floor(y);
var xf = x - xi, yf = y - yi;
var a2 = perm[(perm[xi & 255] + yi) & 255];
var b2 = perm[(perm[(xi + 1) & 255] + yi) & 255];
var c2 = perm[(perm[xi & 255] + yi + 1) & 255];
var d2 = perm[(perm[(xi + 1) & 255] + yi + 1) & 255];
var u = fade(xf), v = fade(yf);
return (a2 + (b2 - a2) * u + (c2 - a2) * v + (a2 - b2 - c2 + d2) * u * v) / 255;
}
function idx(x, y) {
x = x % fw; if (x < 0) x += fw;
y = y % fh; if (y < 0) y += fh;
return (y * fw + x) | 0;
}
function clampIdx(x, y) {
x = Math.max(0, Math.min(fw - 1, Math.round(x)));
y = Math.max(0, Math.min(fh - 1, Math.round(y)));
return y * fw + x;
}
function sense(x, y) {
return trail[clampIdx(x, y)];
}
function initAgents() {
ax = new Float32Array(AGENTS); ay = new Float32Array(AGENTS); ah = new Float32Array(AGENTS);
var cx = fw / 2, cy = fh / 2, r = Math.min(fw, fh) * 0.15;
for (var i = 0; i < AGENTS; i++) {
var a = rand() * Math.PI * 2, rr = rand() * r;
ax[i] = cx + Math.cos(a) * rr;
ay[i] = cy + Math.sin(a) * rr;
ah[i] = rand() * Math.PI * 2;
}
}
function stepAgents() {
var sa = sensorAngleDeg * Math.PI / 180;
var sd = sensorDist / 3;
for (var i = 0; i < AGENTS; i++) {
var x = ax[i], y = ay[i], h = ah[i];
var sf = sense(x + Math.cos(h) * sd, y + Math.sin(h) * sd);
var sl = sense(x + Math.cos(h + sa) * sd, y + Math.sin(h + sa) * sd);
var sr = sense(x + Math.cos(h - sa) * sd, y + Math.sin(h - sa) * sd);
if (sf >= sl && sf >= sr) {
// 직진
} else if (sl > sr) {
h += TURN;
} else if (sr > sl) {
h -= TURN;
} else {
h += (rand() < 0.5 ? 1 : -1) * TURN;
}
h += (rand() - 0.5) * 0.14;
var nx = x + Math.cos(h) * STEP, ny = y + Math.sin(h) * STEP;
nx = ((nx % fw) + fw) % fw; ny = ((ny % fh) + fh) % fh;
ax[i] = nx; ay[i] = ny; ah[i] = h;
var ii = idx(Math.round(nx), Math.round(ny));
trail[ii] = Math.min(CAP, trail[ii] + DEPOSIT);
}
}
function diffuseEvap() {
for (var y = 0; y < fh; y++) {
var ym = y === 0 ? fh - 1 : y - 1, yp = y === fh - 1 ? 0 : y + 1;
var rowY = y * fw, rowYm = ym * fw, rowYp = yp * fw;
for (var x = 0; x < fw; x++) {
var xm = x === 0 ? fw - 1 : x - 1, xp = x === fw - 1 ? 0 : x + 1;
var i = rowY + x;
var avg = (trail[rowY + xm] + trail[rowY + xp] + trail[rowYm + x] + trail[rowYp + x]) * 0.25;
trailB[i] = (trail[i] * (1 - DIFFUSE) + avg * DIFFUSE) * (1 - DECAY);
}
}
var t = trail; trail = trailB; trailB = t;
}
function render(t) {
for (var y = 0; y < fh; y++) {
for (var x = 0; x < fw; x++) {
var i = y * fw + x;
var j = i * 4;
var v = trail[i] / CAP; if (v > 1) v = 1;
var k = v * v * (3 - 2 * v);
var rr = C_FLOOR[0] + (C_TRAIL[0] - C_FLOOR[0]) * k;
var gg = C_FLOOR[1] + (C_TRAIL[1] - C_FLOOR[1]) * k;
var bb = C_FLOOR[2] + (C_TRAIL[2] - C_FLOOR[2]) * k;
// 파라미터 표시기 — 슬라이더 값이 화면 구석에 옅게 비친다(파라미터 실험 컨셉)
var meterX = x / fw;
var inAng = y < 5 && meterX < sensorAngleDeg / 90;
var inDist = y >= 6 && y < 11 && meterX < (sensorDist - 4) / 26;
if (inAng || inDist) {
rr += (C_ACCT[0] - rr) * 0.5; gg += (C_ACCT[1] - gg) * 0.5; bb += (C_ACCT[2] - bb) * 0.5;
}
var n1 = vnoise(x * 0.09, y * 0.09 + t * 0.9);
var n2 = vnoise(x * 0.03 + 40, y * 0.03 + t * 0.6);
var sh = (n1 - 0.5) * 28 + (n2 - 0.5) * 18;
rr += sh; gg += sh; bb += sh;
data[j] = rr; data[j + 1] = gg; data[j + 2] = bb; data[j + 3] = 255;
}
}
ctx.putImageData(img, 0, 0);
}
function fit() {
var r = field.getBoundingClientRect();
W = Math.round(r.width); H = Math.round(r.height);
fw = Math.max(96, Math.min(200, Math.round(W / 3)));
fh = Math.max(52, Math.min(120, Math.round(H / 3)));
cv.width = fw; cv.height = fh;
cv.style.width = '100%'; cv.style.height = '100%';
ctx = cv.getContext('2d', { alpha: false });
img = ctx.createImageData(fw, fh); data = img.data;
trail = new Float32Array(fw * fh); trailB = new Float32Array(fw * fh);
initAgents();
}
function setLabels() {
if (angLab) angLab.textContent = '벌림각 ' + sensorAngleDeg + '°';
if (distLab) distLab.textContent = '거리 ' + sensorDist;
if (angRng) angRng.value = String(sensorAngleDeg);
if (distRng) distRng.value = String(sensorDist);
}
function stillFrame() {
sensorAngleDeg = 45; sensorDist = 20; setLabels();
for (var k = 0; k < 280; k++) { stepAgents(); diffuseEvap(); }
render(2.6);
}
// .is-demo 자동 시연 각본 — 사람이 안 만져도 슬라이더가 스스로 움직여 형태가 모프된다.
// 각 구간은 (벌림각 목표, 거리 목표) 쌍. 사인으로 왕복해 끊김 없이 잇는다.
function autoParams(t) {
var ang = 29 + 28 * Math.sin(t * 0.42) + 8 * Math.sin(t * 0.13);
var dist = 15 + 9 * Math.sin(t * 0.31 + 1.2);
if (ang < 10) ang = 10; if (ang > 90) ang = 90;
if (dist < 4) dist = 4; if (dist > 30) dist = 30;
sensorAngleDeg = Math.round(ang);
sensorDist = Math.round(dist);
}
var humanTouch = false;
angRng.addEventListener('input', function () {
humanTouch = true;
sensorAngleDeg = parseInt(angRng.value, 10);
setLabels();
});
distRng.addEventListener('input', function () {
humanTouch = true;
sensorDist = parseInt(distRng.value, 10);
setLabels();
});
function frame(now) {
if (t0 < 0) t0 = now;
var t = (now - t0) / 1000;
if (root.classList.contains('is-demo') && !humanTouch) {
autoParams(t);
setLabels();
}
for (var i = 0; i < SUBSTEPS; i++) { stepAgents(); diffuseEvap(); }
render(t);
raf = requestAnimationFrame(frame);
}
window.addEventListener('resize', function () {
fit();
if (reduce) stillFrame();
});
fit();
setLabels();
if (reduce) {
stillFrame();
root.classList.add('is-still');
} else {
raf = requestAnimationFrame(frame);
}
})();// SensorAngleMorph — vanilla 판(run/320/demo/07-slime-sensor-angle-morph/index.html) 의 React 포트.
// 센서 각도 모프. 센서 벌림각(도)과 센서 거리 두 값을 range 슬라이더로 바꾼다 — 좁은 각도+짧은
// 거리는 촘촘한 산호, 넓은 각도+긴 거리는 성긴 혈관·격자형 도시망을 그린다. 사람이 슬라이더를
// 만지기 전까지는 자동 각본이 두 값을 사인파로 왕복시켜 스스로 형태가 모프된다.
import { useEffect, useRef, useState } from "react";
import type { ChangeEvent, CSSProperties } from "react";
import styles from "./SensorAngleMorph.module.scss";
export type SensorAngleMorphProps = {
duration?: string;
easing?: string;
color?: string;
agents?: number;
decay?: number;
};
type Vars = CSSProperties & { "--duration"?: string; "--easing"?: string; "--color"?: string };
type Box<T> = { current: T };
type RGB = [number, number, number];
const FIELD_LABEL = "센서 각도 모프 점균 실험판";
const TURN = 0.5;
const STEP = 1.05;
const DEPOSIT = 4.2;
const DIFFUSE = 0.5;
const CAP = 7;
const SUBSTEPS = 3;
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 SensorAngleMorph({
duration = "2s",
easing = "cubic-bezier(.2, .8, .2, 1)",
color = "#2c3326",
agents = 1500,
decay = 0.045,
}: SensorAngleMorphProps) {
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<{ floor: RGB; trail: RGB; acct: RGB } | null>(null);
const agentsRef = useRef(agents) as Box<number>;
const decayRef = useRef(decay) as Box<number>;
const randRef = useRef(makePRNG(0x320a07)) as Box<() => number>;
const fwRef = useRef(0) as Box<number>;
const fhRef = useRef(0) as Box<number>;
const trailRef = useRef<Float32Array>(new Float32Array(0)) as Box<Float32Array>;
const trailBRef = useRef<Float32Array>(new Float32Array(0)) as Box<Float32Array>;
const axRef = useRef<Float32Array>(new Float32Array(0)) as Box<Float32Array>;
const ayRef = useRef<Float32Array>(new Float32Array(0)) as Box<Float32Array>;
const ahRef = useRef<Float32Array>(new Float32Array(0)) as Box<Float32Array>;
const imgRef = useRef<ImageData | null>(null) as Box<ImageData | null>;
const permRef = useRef<Uint8Array>(new Uint8Array(512)) as Box<Uint8Array>;
const sensorAngleDegRef = useRef(29) as Box<number>;
const sensorDistRef = useRef(15) as Box<number>;
const humanTouchRef = useRef(false) as Box<boolean>;
const rafRef = useRef(0) as Box<number>;
const [angLab, setAngLab] = useState("벌림각 29°");
const [distLab, setDistLab] = useState("거리 15");
const [angVal, setAngVal] = useState(29);
const [distVal, setDistVal] = useState(15);
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 buildPerm(): void {
const rand = randRef.current;
const p: number[] = [];
for (let i = 0; i < 256; i++) p.push(i);
for (let i2 = 255; i2 > 0; i2--) {
const k2 = Math.floor(rand() * (i2 + 1));
const tmp = p[i2]; p[i2] = p[k2]; p[k2] = tmp;
}
const perm = new Uint8Array(512);
for (let i3 = 0; i3 < 512; i3++) perm[i3] = p[i3 & 255];
permRef.current = perm;
}
function fade(k: number): number { return k * k * (3 - 2 * k); }
function vnoise(x: number, y: number): number {
const perm = permRef.current;
const xi = Math.floor(x), yi = Math.floor(y);
const xf = x - xi, yf = y - yi;
const a2 = perm[(perm[xi & 255] + yi) & 255];
const b2 = perm[(perm[(xi + 1) & 255] + yi) & 255];
const c2 = perm[(perm[xi & 255] + yi + 1) & 255];
const d2 = perm[(perm[(xi + 1) & 255] + yi + 1) & 255];
const u = fade(xf), v = fade(yf);
return (a2 + (b2 - a2) * u + (c2 - a2) * v + (a2 - b2 - c2 + d2) * u * v) / 255;
}
function idx(x: number, y: number): number {
const fw = fwRef.current, fh = fhRef.current;
let xx = x % fw; if (xx < 0) xx += fw;
let yy = y % fh; if (yy < 0) yy += fh;
return (yy * fw + xx) | 0;
}
function clampIdx(x: number, y: number): number {
const fw = fwRef.current, fh = fhRef.current;
const xx = Math.max(0, Math.min(fw - 1, Math.round(x)));
const yy = Math.max(0, Math.min(fh - 1, Math.round(y)));
return yy * fw + xx;
}
function sense(x: number, y: number): number {
return trailRef.current[clampIdx(x, y)];
}
function initAgents(): void {
const rand = randRef.current;
const fw = fwRef.current, fh = fhRef.current;
const A = agentsRef.current;
const ax = new Float32Array(A), ay = new Float32Array(A), ah = new Float32Array(A);
const cx = fw / 2, cy = fh / 2, r = Math.min(fw, fh) * 0.15;
for (let i = 0; i < A; i++) {
const a = rand() * Math.PI * 2, rr = rand() * r;
ax[i] = cx + Math.cos(a) * rr;
ay[i] = cy + Math.sin(a) * rr;
ah[i] = rand() * Math.PI * 2;
}
axRef.current = ax; ayRef.current = ay; ahRef.current = ah;
}
function stepAgents(): void {
const rand = randRef.current;
const A = agentsRef.current;
const fw = fwRef.current, fh = fhRef.current;
const ax = axRef.current, ay = ayRef.current, ah = ahRef.current;
const trail = trailRef.current;
const sa = sensorAngleDegRef.current * Math.PI / 180;
const sd = sensorDistRef.current / 3;
for (let i = 0; i < A; i++) {
const x = ax[i], y = ay[i];
let h = ah[i];
const sf = sense(x + Math.cos(h) * sd, y + Math.sin(h) * sd);
const sl = sense(x + Math.cos(h + sa) * sd, y + Math.sin(h + sa) * sd);
const sr = sense(x + Math.cos(h - sa) * sd, y + Math.sin(h - sa) * sd);
if (sf >= sl && sf >= sr) {
// 직진
} else if (sl > sr) {
h += TURN;
} else if (sr > sl) {
h -= TURN;
} else {
h += (rand() < 0.5 ? 1 : -1) * TURN;
}
h += (rand() - 0.5) * 0.14;
let nx = x + Math.cos(h) * STEP, ny = y + Math.sin(h) * STEP;
nx = ((nx % fw) + fw) % fw; ny = ((ny % fh) + fh) % fh;
ax[i] = nx; ay[i] = ny; ah[i] = h;
const ii = idx(Math.round(nx), Math.round(ny));
trail[ii] = Math.min(CAP, trail[ii] + DEPOSIT);
}
}
function diffuseEvap(): void {
const fw = fwRef.current, fh = fhRef.current;
const trail = trailRef.current, trailB = trailBRef.current;
const dc = decayRef.current;
for (let y = 0; y < fh; y++) {
const ym = y === 0 ? fh - 1 : y - 1, yp = y === fh - 1 ? 0 : y + 1;
const rowY = y * fw, rowYm = ym * fw, rowYp = yp * fw;
for (let x = 0; x < fw; x++) {
const xm = x === 0 ? fw - 1 : x - 1, xp = x === fw - 1 ? 0 : x + 1;
const i = rowY + x;
const avg = (trail[rowY + xm] + trail[rowY + xp] + trail[rowYm + x] + trail[rowYp + x]) * 0.25;
trailB[i] = (trail[i] * (1 - DIFFUSE) + avg * DIFFUSE) * (1 - dc);
}
}
trailRef.current = trailB; trailBRef.current = trail;
}
function render(t: number): void {
const ctx = ctxRef.current;
const col = colRef.current;
const img = imgRef.current;
if (!ctx || !col || !img) return;
const fw = fwRef.current, fh = fhRef.current;
const trail = trailRef.current;
const angDeg = sensorAngleDegRef.current;
const dist = sensorDistRef.current;
const data = img.data;
for (let y = 0; y < fh; y++) {
for (let x = 0; x < fw; x++) {
const i = y * fw + x;
const j = i * 4;
let v = trail[i] / CAP; if (v > 1) v = 1;
const k = v * v * (3 - 2 * v);
let rr = col.floor[0] + (col.trail[0] - col.floor[0]) * k;
let gg = col.floor[1] + (col.trail[1] - col.floor[1]) * k;
let bb = col.floor[2] + (col.trail[2] - col.floor[2]) * k;
const meterX = x / fw;
const inAng = y < 5 && meterX < angDeg / 90;
const inDist = y >= 6 && y < 11 && meterX < (dist - 4) / 26;
if (inAng || inDist) {
rr += (col.acct[0] - rr) * 0.5; gg += (col.acct[1] - gg) * 0.5; bb += (col.acct[2] - bb) * 0.5;
}
const n1 = vnoise(x * 0.09, y * 0.09 + t * 0.9);
const n2 = vnoise(x * 0.03 + 40, y * 0.03 + t * 0.6);
const sh = (n1 - 0.5) * 28 + (n2 - 0.5) * 18;
rr += sh; gg += sh; bb += sh;
data[j] = rr; data[j + 1] = gg; data[j + 2] = bb; data[j + 3] = 255;
}
}
ctx.putImageData(img, 0, 0);
}
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 fw = Math.max(96, Math.min(200, Math.round(W / 3)));
const fh = Math.max(52, Math.min(120, Math.round(H / 3)));
fwRef.current = fw; fhRef.current = fh;
cv.width = fw; cv.height = fh;
cv.style.width = "100%"; cv.style.height = "100%";
const ctx = cv.getContext("2d", { alpha: false });
if (!ctx) return;
ctxRef.current = ctx;
const img = ctx.createImageData(fw, fh);
imgRef.current = img;
trailRef.current = new Float32Array(fw * fh);
trailBRef.current = new Float32Array(fw * fh);
initAgents();
}
function setLabels(): void {
setAngLab(`벌림각 ${sensorAngleDegRef.current}°`);
setDistLab(`거리 ${sensorDistRef.current}`);
setAngVal(sensorAngleDegRef.current);
setDistVal(sensorDistRef.current);
}
function stillFrame(): void {
sensorAngleDegRef.current = 45; sensorDistRef.current = 20; setLabels();
for (let k = 0; k < 280; k++) { stepAgents(); diffuseEvap(); }
render(2.6);
}
function autoParams(t: number): void {
let ang = 29 + 28 * Math.sin(t * 0.42) + 8 * Math.sin(t * 0.13);
let dist = 15 + 9 * Math.sin(t * 0.31 + 1.2);
if (ang < 10) ang = 10; if (ang > 90) ang = 90;
if (dist < 4) dist = 4; if (dist > 30) dist = 30;
sensorAngleDegRef.current = Math.round(ang);
sensorDistRef.current = Math.round(dist);
}
function onAngInput(e: ChangeEvent<HTMLInputElement>): void {
humanTouchRef.current = true;
sensorAngleDegRef.current = parseInt(e.target.value, 10);
setLabels();
}
function onDistInput(e: ChangeEvent<HTMLInputElement>): void {
humanTouchRef.current = true;
sensorDistRef.current = parseInt(e.target.value, 10);
setLabels();
}
let t0 = -1;
function frame(now: number): void {
if (t0 < 0) t0 = now;
const t = (now - t0) / 1000;
if (!humanTouchRef.current) {
autoParams(t);
setLabels();
}
for (let i = 0; i < SUBSTEPS; i++) { stepAgents(); diffuseEvap(); }
render(t);
rafRef.current = requestAnimationFrame(frame);
}
useEffect(() => {
const root = rootRef.current;
if (!root) return;
agentsRef.current = agents;
decayRef.current = decay;
randRef.current = makePRNG(0x320a07);
colRef.current = {
floor: tokRGB(root, "--sm-floor"),
trail: tokRGB(root, "--sm-trail"),
acct: tokRGB(root, "--sm-acct"),
};
buildPerm();
fit();
setLabels();
function onResize(): void {
fit();
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
}, [agents, decay]);
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}>
<label className={styles.ctl}>
<span className={styles.lab}>{angLab}</span>
<input
className={styles.rng}
type="range"
min={10}
max={90}
step={1}
value={angVal}
aria-label="센서 벌림각"
onChange={onAngInput}
/>
</label>
<label className={styles.ctl}>
<span className={styles.lab}>{distLab}</span>
<input
className={styles.rng}
type="range"
min={4}
max={30}
step={1}
value={distVal}
aria-label="센서 거리"
onChange={onDistInput}
/>
</label>
</div>
</div>
</main>
);
}07 센서 각도 모프 — 각도 하나로 산호에서 혈관까지 형태가 바뀌기 — 측정 누적면적 49.385% · 움직인 프레임 23/23GODRICH 원작 · zip 에 SCSS·React 포함 · 슬라임몰드 길찾기 9종 — 점균 네트워크가 스스로 최단경로를 찾는 캔버스
이 데모가 속한 글
슬라임몰드 길찾기 9종 — 점균 네트워크가 스스로 최단경로를 찾는 캔버스슬라임몰드 길찾기를 캔버스 픽셀 계산만으로 재현합니다. 라이브러리·WebGL 없이 화면 위를 기어다니는 점 하나하나가 앞·좌·우 냄새를 맡고 진한 쪽으로 도는 규칙만 반복하는 것으로, 미로의 최단경로를 스스로 찾아내 이 글의 데모 전부 보기


