住人のいる音量
@Lattice_Node
Components · Toggle
38 views3 copies
<!-- UI by @Lattice_Node — ludion.ai/p/toggle-station (MIT) -->
<!-- UI by @Lattice_Node — ludion.ai/p/toggle-daylight (MIT) -->
<!-- Remixed by Claude -->
<div data-ld-part="toggle-station" lang="ja">
<canvas class="scene" aria-hidden="true"></canvas>
<button class="hit" type="button" role="switch" aria-checked="false" aria-label="夜"></button>
<span class="vh" role="status" aria-live="polite" data-status></span>
<span class="probe" aria-hidden="true"></span>
</div>
<style>
/* UI by @Lattice_Node — ludion.ai/p/toggle-station (MIT) */
/* ページの地。スイッチが書き出す --night(0 = 昼、1 = 夜)に合わせて、管制室の明るさから宇宙の暗さへ */
/* UI by @Lattice_Node — ludion.ai/p/toggle-daylight (MIT) / Remixed by Claude */
[data-ld-part="toggle-station"] {
/* 固定しないトークン。世界の約20色は、この5色を明るさ違いで並べて作る */
/* bg = 船体と雲、surface = 陸とオーロラ、fg = 宇宙、muted = 海と大気、accent = 灯りと金の断熱材 */
--_bg: var(--ld-bg, #f3eee2);
--_surface: var(--ld-surface, #7da868);
--_fg: var(--ld-fg, #171c44);
--_muted: var(--ld-muted, #7397c4);
--_accent: var(--ld-accent, #efa02c);
--_radius: var(--ld-radius, 9999px);
--_font: var(--ld-font, system-ui, sans-serif);
--_space: var(--ld-space, 8px);
--_shadow: var(--ld-shadow, 0 8px 24px rgb(27 33 70 / .2));
--_motion: var(--ld-motion, 200ms);
position: relative;
display: block;
box-sizing: border-box;
/* どの枠にも収まる。横長の丸(1 : 1.85)のまわりに、影と漏れる光の余白を含めた比率 */
width: min(100%, calc((100vh - 64px) * 1.6439));
aspect-ratio: 1.6439;
font-family: var(--_font);
color: var(--_fg);
}
/* 色を読むための見えない目印 */
[data-ld-part="toggle-station"] .probe {
display: none;
}
[data-ld-part="toggle-station"] .vh {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
[data-ld-part="toggle-station"] .scene {
position: absolute;
top: 0;
left: 0;
display: block;
width: 100%;
height: 100%;
pointer-events: none;
/* 小数の表示倍率でも、ブラウザに補間させない。ピクセルをにじませないため */
image-rendering: pixelated;
}
/* 本物のスイッチ。絵は canvas が描き、ここは押す場所だけ */
[data-ld-part="toggle-station"] .hit {
position: absolute;
top: 12.121%;
left: 7.373%;
width: 85.253%;
height: 75.758%;
margin: 0;
padding: 0;
border: 0;
border-radius: var(--_radius);
background: transparent;
cursor: grab;
touch-action: pan-y;
user-select: none;
-webkit-user-select: none;
-webkit-tap-highlight-color: transparent;
}
[data-ld-part="toggle-station"] .hit:active {
cursor: grabbing;
}
[data-ld-part="toggle-station"] .hit:focus {
outline: none;
}
[data-ld-part="toggle-station"] .hit:focus-visible {
outline: 2px solid var(--_accent);
outline-offset: calc(var(--_space) * .5);
transition: outline-offset var(--_motion) ease;
}
@media (prefers-reduced-motion: reduce) {
[data-ld-part="toggle-station"] .hit:focus-visible {
transition: none;
}
}
</style>
<script type="module">
/* UI by @Lattice_Node — ludion.ai/p/toggle-station (MIT) */
/* UI by @Lattice_Node — ludion.ai/p/toggle-daylight (MIT) / Remixed by Claude */
// part.js — ESモジュール。rootの中だけを触る
// 乗組員のいるスイッチ:スイッチのレールの中に、ピクセルの小さな宇宙ステーションがあり、飛行士が1人暮らしている。
//
// 世界:低い解像度で、約20色の番号だけで描く。時刻の変化はディザの置き換えで行い、中間色を作らない。
// 下には地球が丸く見え、陸と雲がゆっくり流れていく。夜の側では街の灯りとオーロラが光る。
// 外側:なめらかな殻、窓の奥行き、液体のレンズを WebGL で描く。ピクセルは常に整数倍のまま写す。
// 灯り:世界の光る画素をぼかした「光の場」を作り、ガラスと外の面を照らす。人影が窓を横切れば、外の光も変わる。
// 時間:左端は昼の側、右端は夜の側。右へ動かすと 昼→日の入り→夜。左へ戻すと 夜→深夜→日の出→朝→昼 と、時間は前へ進む。
// 色は JS に書かない。--_bg、--_surface、--_fg、--_muted、--_accent の色相を、決めた明るさで並べて作る。
const CORE_W = 192; // 景色の中心の幅。窓が広いぶんは、両わきへ広がる
const CORE_H = 112;
const SUN_BASE = 82; // 太陽と月が描く弧の足もと
const LIMB_Y = 70; // 地球のふちの、いちばん高いところ
const LIMB_R = 320; // 地球の丸みの半径
const SKY_SPAN = 80; // ふちからこの高さまで、大気の明るさが届く
const SKY_CURVE = 1.5;
const MARGIN = 14; // レンズが窓の外を覗いてもよいよう、世界を少し広く描く
const WORLD_HZ = 30;
const WORLD_SLACK = 0.004; // 画面の更新の時刻は揺れる。この秒数まで足りなくても、次のコマを出す
const PILL_RATIO = 1.85; // 縦 : 横
const CLOCK_DAY = 12;
const CLOCK_NIGHT = 21.5;
const CLOCK_SLEEP = 23.4;
const NIGHT_CREEP = 26; // 右端に着いてから、灯りを消して眠るまでの秒数の目安
// ステーションの中の場所
const DECK = 62; // 船外で足を置く高さ(トラスの上の面)
const HOME_X = 73; // エアロックの扉
const VIEW_X = 90; // 夕方、地球を眺める場所
const DISH_X = 104; // 朝、アンテナを調整する場所
const WORK_X = 128; // 昼、機器箱を修理する場所
const WX = 46; // 窓(キューポラ)の中:14×12
const WY = 48;
const WW = 14;
const WH = 12;
// ---- パレット:5つのトークン × 4つの明るさ = 20色
const RAMPS = [
['bg', [0.76, 0.85, 0.93, 0.985]],
['surface', [0.4, 0.52, 0.64, 0.76]],
['fg', [0.17, 0.25, 0.33, 0.44]],
['muted', [0.5, 0.62, 0.74, 0.86]],
['accent', [0.5, 0.66, 0.8, 0.92]],
];
const C0 = 0, C1 = 1, C2 = 2, C3 = 3;
const G0 = 4, G1 = 5, G2 = 6, G3 = 7;
const I0 = 8, I1 = 9, I2 = 10, I3 = 11;
const U0 = 12, U1 = 13, U2 = 14, U3 = 15;
const A0 = 16, A1 = 17, A2 = 18, A3 = 19;
// ---- 材質:[昼, 日の入り, 薄明, 夜] のパレット番号
const MATS = [
['SKY', C3, C3, C3, C3],
// 地球(ここから CITY_HI まで。船の灯りは届かない)
['ATMOS', C3, A3, U1, G0],
['OCEAN', U1, U0, I2, I1],
['OCEAN_DK', U0, I3, I2, I1],
['OCEAN_LT', U2, U1, I3, I1],
['LAND', G2, G1, I1, I0],
['LAND_DK', G1, G0, I1, I0],
['SAND', C1, A1, I3, I0],
['CLOUD', C3, A3, U1, I2],
['CLOUD_SH', U3, A2, U0, I1],
['CITY', A2, A2, A2, A2],
['CITY_HI', A3, A3, A3, A3],
// ステーション
['HULL', C3, A3, U1, I2],
['HULL_SH', C2, A2, U0, I1],
['HULL_DK', C1, A1, I3, I1],
['METAL', U1, U0, I2, I1],
['METAL_LT', U2, U1, I3, I2],
['METAL_DK', I3, I2, I1, I0],
['PANEL', I1, I1, I0, I0],
['PANEL_LT', U0, I3, I2, I1],
['PANEL_HI', U2, A2, I3, I1],
['FOIL', A1, A1, I3, I1],
['FOIL_LT', A2, A2, U0, I2],
['FOIL_DK', A0, A0, I2, I0],
['GLASS', I2, A0, I1, I0],
['GLASS_HI', U1, A1, I2, I1],
['ROOM', C1, C0, I3, I1],
['PLANT', G3, G2, I2, I1],
// 飛行士
['SKIN', A3, A3, U2, I3],
['HAIR', I0, I0, I0, I0],
['SHIRT', U1, U0, I3, I1],
['SUIT', C3, C3, U2, I3],
['SUIT_SH', C1, C1, U0, I2],
['VISOR', I0, I0, I0, I0],
['VISOR_HI', A2, A2, A1, I2],
['PACK', U1, U0, I2, I1],
['BOOT', U0, I3, I1, I0],
['STRIPE', A1, A1, A0, I2],
['TETHER', A1, A1, I3, I2],
// 空と光
['PUFF', C1, C1, U2, I3],
['PUFF_DK', U2, U1, U0, I2],
['SUN', C3, C3, A3, A3],
['SUN_RIM', A3, A2, A2, A2],
['MOON', C3, C3, C3, C3],
['MOON_DK', C1, C1, C1, C1],
['STAR', C3, C3, C3, C3],
['STAR_DIM', U2, U2, U2, U2],
['LIT', A2, A2, A2, A2],
['LIT_HI', A3, A3, A3, A3],
['LIT_DK', A1, A1, A1, A1],
['SIL', I0, I0, I0, I0],
['GLINT', C3, C3, C3, C3],
['SHIP', C3, A3, U1, I2],
['SHIP_DK', U0, I3, I2, I1],
['MARK', I0, I0, C3, C3],
['ZZZ', U3, U3, U3, U3],
['AURORA', G2, G2, G2, G2],
['AURORA_HI', G3, G3, G3, G3],
['AURORA_DK', G0, G0, G0, G0],
['BEACON', A1, A1, A1, A1],
['BEACON_G', G3, G3, G3, G3],
];
const M = Object.fromEntries(MATS.map((row, i) => [row[0], i]));
const EARTH_END = M.CITY_HI;
// ---- 時刻のかなめ:[時, 材質の列, 空の色(宇宙から地球のふちへ)]
const SKY_NIGHT = [I0, I0];
const SKY_DAY = [I3, I3, U0, U1, U2, U3, C3];
const KEYS = [
[0, 3, SKY_NIGHT],
[4.8, 3, SKY_NIGHT],
[5.4, 3, [I0, I0, I0, I1, I2, I3]],
[6.0, 2, [I0, I0, I1, I2, I3, U1, A1]],
[6.7, 1, [I1, I2, I3, U0, U1, A2, A3]],
[7.8, 0, SKY_DAY],
[10, 0, SKY_DAY],
[15, 0, SKY_DAY],
[17, 1, [I3, I3, U0, U1, U3, A3, A2]],
[18, 1, [I2, I2, I3, U0, A1, A2, A3]],
[19, 2, [I0, I0, I1, I2, I3, A0, A1]],
[20.3, 3, SKY_NIGHT],
[24, 3, SKY_NIGHT],
];
const clamp = (v, lo = 0, hi = 1) => Math.min(hi, Math.max(lo, v));
const mix = (a, b, t) => a + (b - a) * t;
const smoothstep = (a, b, x) => {
const t = clamp((x - a) / (b - a));
return t * t * (3 - 2 * t);
};
const BAYER = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];
const bayerAt = (x, y) => BAYER[((y & 3) << 2) | (x & 3)];
const limbAt = (x) => LIMB_Y + LIMB_R - Math.sqrt(Math.max(LIMB_R * LIMB_R - (x - 96) * (x - 96), 1));
function seeded(seed) {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function makeNoise(seed) {
const r = seeded(seed);
const table = new Float32Array(65536);
for (let i = 0; i < 65536; i++) table[i] = r();
const at = (x, y) => table[((x & 255) << 8) | (y & 255)];
return (x, y) => {
const xi = Math.floor(x);
const yi = Math.floor(y);
const fx = x - xi;
const fy = y - yi;
const u = fx * fx * (3 - 2 * fx);
const v = fy * fy * (3 - 2 * fy);
return mix(mix(at(xi, yi), at(xi + 1, yi), u), mix(at(xi, yi + 1), at(xi + 1, yi + 1), u), v);
};
}
// ---- 色の計算(OKLab)。色の値は書かず、トークンの色相に明るさだけを与える
const toLinear = (c) => (c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4));
const toGamma = (c) => (c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055);
function rgbToOklab([r8, g8, b8]) {
const r = toLinear(r8 / 255);
const g = toLinear(g8 / 255);
const b = toLinear(b8 / 255);
const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s];
}
function oklabToLinear(L, a, b) {
const l = Math.pow(L + 0.3963377774 * a + 0.2158037573 * b, 3);
const m = Math.pow(L - 0.1055613458 * a - 0.0638541728 * b, 3);
const s = Math.pow(L - 0.0894841775 * a - 1.291485548 * b, 3);
return [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s];
}
function labTone(lab, L) {
// 明るさを決め、色域に入るまで鮮やかさを落とす
let chroma = 1;
for (let i = 0; i < 24; i++) {
const rgb = oklabToLinear(L, lab[1] * chroma, lab[2] * chroma);
if (rgb.every((v) => v >= -0.001 && v <= 1.001)) return rgb.map((v) => Math.round(toGamma(clamp(v)) * 255));
chroma *= 0.9;
}
return oklabToLinear(L, 0, 0).map((v) => Math.round(toGamma(clamp(v)) * 255));
}
// ---- 飛行士の絵
// 船外:W 宇宙服、w 宇宙服の陰、V バイザー、G バイザーの照り、K 背中の装置、B 靴、R 胸の帯
// 船内:H 髪、S 肌、E 目、T つなぎ
const CHARS = { H: 'HAIR', S: 'SKIN', E: 'HAIR', T: 'SHIRT', W: 'SUIT', w: 'SUIT_SH', V: 'VISOR', G: 'VISOR_HI', K: 'PACK', B: 'BOOT', R: 'STRIPE' };
const makeSprite = (rows) => {
const list = [];
rows.forEach((row, y) => {
[...row].forEach((ch, x) => {
if (ch !== '.') list.push([x, y, M[CHARS[ch]], ch === 'E']);
});
});
return { list, w: rows[0].length, h: rows.length };
};
const HEAD = ['..WWW..', '.WWWWW.', '.WWGVV.', '.WWVVV.', '..WWWw.'];
const HEAD_BLINK = ['..WWW..', '.WWWWW.', '.WWVVV.', '.WWVVV.', '..WWWw.'];
const HEAD_UP = ['..WWW..', '.WWGVV.', '.WWVVV.', '.WWWWW.', '..WWWw.'];
const BODY_STAND = ['.KWWW..', 'KKWWWW.', 'KKWRWw.', '..www..', '..WWW..', '..W.W..', '..B.B..'];
const BODY_WALK1 = ['.KWWW..', 'KKWWWW.', 'KKWRWWw', '..www..', '..WWW..', '.WW.W..', '.B..BB.'];
const BODY_WALK2 = ['.KWWW..', 'KKWWWW.', 'KKWRWw.', '..www..', '..WWW..', '..WW...', '..BB...'];
const BODY_WALK3 = ['.KWWW..', 'KKWWWWw', 'KKWRW..', '..www..', '..WWW..', '..W.WW.', '.BB..B.'];
const BODY_ARMS = ['w.WWW.w', 'wWWWWWw', '.KWRW..', '..www..', '..WWW..', '..W.W..', '..B.B..'];
const person = (head, body) => makeSprite([...head, ...body]);
const WORK_BODY = ['.KKWWWw..', 'KKKWWWWww', 'KKKWRWW..', '.KKwww...', '...WWWW..', '...BB.BB.'];
const SPR = {
stand: person(HEAD, BODY_STAND),
blink: person(HEAD_BLINK, BODY_STAND),
walk: [person(HEAD, BODY_WALK1), person(HEAD, BODY_WALK2), person(HEAD, BODY_WALK3), person(HEAD, BODY_WALK2)],
up: person(HEAD_UP, BODY_ARMS),
crouch: person(HEAD, ['.KWWW..', 'KKWWWWw', '.Kwww.w', '..WWW..', '.BB.B..']),
// 機器箱に向かって、工具をのばす
work: makeSprite(['...WWW...', '..WWWWW..', '..WWGVV..', '..WWVVV..', ...WORK_BODY]),
workBlink: makeSprite(['...WWW...', '..WWWWW..', '..WWVVV..', '..WWVVV..', ...WORK_BODY]),
workUp: makeSprite(['...WWW...', '..WWGVV..', '..WWVVV..', '..WWWWW..', ...WORK_BODY]),
bust: makeSprite(['...HHH...', '..HHHHH..', '..HSSES..', '...SSS...', '..TTTTT..', '.TTTTTTT.', '.TTTTTTT.', '.TTTTTTT.']),
bustBlink: makeSprite(['...HHH...', '..HHHHH..', '..HSSSS..', '...SSS...', '..TTTTT..', '.TTTTTTT.', '.TTTTTTT.', '.TTTTTTT.']),
bustUp: makeSprite(['S..HHH..S', 'S.HHHHH.S', 'S.HSSES.S', 'SS.SSS.SS', '.STTTTTS.', '..TTTTT..', '..TTTTT..', '..TTTTT..']),
bustHalf: makeSprite(['...HHH...', '..HHHHH..', 'S.HSSES.S', 'SS.SSS.SS', '.STTTTTS.', '..TTTTT..', '.TTTTTTT.', '.TTTTTTT.']),
sil: makeSprite(['...HHH..', '..HHHHH.', '..HHHHH.', '...HHH..', '..HHHHH.', '.HHHHHHH', 'HHHHHHHH', 'HHHHHHHH']),
};
// ---- 動かない機器の絵
const ART_LEGEND = { H: 'HULL', h: 'HULL_SH', k: 'HULL_DK', M: 'METAL', m: 'METAL_LT', d: 'METAL_DK', F: 'FOIL', f: 'FOIL_LT', g: 'GLASS', i: 'GLASS_HI' };
const ART_DISH = ['....f....', 'H...m...H', 'H...m...H', 'HH..m..HH', '.HHHHHHH.', '..hhhhh..', '....M....', '....M....', '....M....', '....M....', '...MMM...', '..dMMMd..'];
const ART_BOX = ['.MMMMMMMM.', 'MHHHHHHHHM', 'MHddddddHM', 'MHdFfFddHM', 'MHdfFFddHM', 'MHddddddHM', 'MHHHHHHHHM', 'MhhhhhhhhM', '.MMMMMMMM.', '..d....d..'];
// ---- シェーダー
const VERT = `#version 300 es
in vec2 aPos;
void main() { gl_Position = vec4(aPos, 0.0, 1.0); }`;
const FRAG = `#version 300 es
precision highp float;
// 指定しないと標本の精度は lowp になる。PC では無視されるが、スマホの GPU では光の場が段になることがある
precision highp sampler2D;
uniform sampler2D uWorld, uGlowNear;
uniform vec2 uRes, uPill, uOrigin, uWorldSize, uGlowSize;
uniform vec4 uLens;
uniform float uBezel, uK, uNight, uLift, uSeam, uCalm;
uniform vec3 uShellDay, uShellNight, uInk, uLight, uHiNight, uLoNight, uSkyDay, uHomeCol, uSkyCol;
uniform vec2 uHomePos, uSkyPos;
out vec4 outColor;
float rb(vec2 p, vec2 b, float r) {
vec2 q = abs(p) - b + r;
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
}
// なめらかに読む(B スプライン。光の場の格子が見えないように)
vec3 smoothTex(sampler2D t, vec2 uv, vec2 size) {
vec2 st = uv * size - 0.5;
vec2 i = floor(st);
vec2 f = st - i;
vec2 f2 = f * f;
vec2 f3 = f2 * f;
vec2 w0 = (1.0 - 3.0 * f + 3.0 * f2 - f3) / 6.0;
vec2 w1 = (4.0 - 6.0 * f2 + 3.0 * f3) / 6.0;
vec2 w2 = (1.0 + 3.0 * f + 3.0 * f2 - 3.0 * f3) / 6.0;
vec2 w3 = f3 / 6.0;
vec2 g0 = w0 + w1;
vec2 g1 = w2 + w3;
vec2 h0 = (i - 0.5 + w1 / g0 + 0.5) / size;
vec2 h1 = (i + 1.5 + w3 / g1 + 0.5) / size;
return g0.y * (g0.x * texture(t, vec2(h0.x, h0.y)).rgb + g1.x * texture(t, vec2(h1.x, h0.y)).rgb)
+ g1.y * (g0.x * texture(t, vec2(h0.x, h1.y)).rgb + g1.x * texture(t, vec2(h1.x, h1.y)).rgb);
}
vec3 glowNear(vec2 frag) {
vec2 uv = vec2(frag.x / uRes.x, 1.0 - frag.y / uRes.y);
// 光の届かないところでは、なめらかに読む4回を省く。窓の大半はここを通る
vec3 rough = textureLod(uGlowNear, uv, 0.0).rgb;
if (rough.r + rough.g + rough.b < 1.0e-4) return vec3(0.0);
return smoothTex(uGlowNear, uv, uGlowSize);
}
// 光る画素の集まりが、まわりをどれだけ照らすか。遠くまでなだらかに届く
vec3 reach(vec2 p, vec2 pos, vec3 col, float radius) {
vec2 L = pos - p;
float r2 = radius * radius;
return col * r2 / (r2 + dot(L, L));
}
// ピクセルのあいだの、ごく細い継ぎ目。大きく写すときの密度になる
float seamAt(vec2 w, float scale) {
if (scale < 7.0) return 1.0;
vec2 f = fract(w) * scale;
vec2 g = min(f, scale - f);
float edge = min(g.x, g.y);
return 1.0 - 0.075 * (1.0 - smoothstep(0.0, uSeam, edge));
}
// 整数倍のまま、そのまま読む
vec3 worldExact(vec2 frag) {
vec2 w = vec2(frag.x - uOrigin.x, uOrigin.y - frag.y) / uK;
ivec2 t = ivec2(floor(w));
t = clamp(t, ivec2(0), ivec2(uWorldSize) - 1);
return texelFetch(uWorld, t, 0).rgb * seamAt(w, uK);
}
// レンズの中:拡大では、ピクセルの縁は立ったまま。圧縮されるところはミップで読み、模様を出さない
vec3 worldBent(vec2 frag, float scale, float foot) {
vec2 w = vec2(frag.x - uOrigin.x, uOrigin.y - frag.y) / uK;
if (foot > 1.0) return textureLod(uWorld, w / uWorldSize, log2(foot)).rgb;
vec2 r = floor(w + 0.5);
vec2 sharp = r - 0.5 + clamp((w - r) / max(foot, 1.0e-3) + 0.5, 0.0, 1.0);
return textureLod(uWorld, sharp / uWorldSize, 0.0).rgb * seamAt(w, scale);
}
vec3 envLow, envHigh;
float softBox(vec2 p, vec2 c, vec2 h, float s) {
vec2 q = abs(p - c) - h;
float d = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0);
return 1.0 - smoothstep(-s, s, d);
}
// 磨かれた面に映る部屋:上の大きなやわらかい光と、下からの弱い照り返し
vec3 studio(vec3 R) {
vec3 c = mix(envLow, envHigh, smoothstep(-0.55, 0.85, R.y));
vec2 s = R.xy / (1.0 + max(R.z, 0.0));
float key = softBox(s, vec2(-0.1, 0.56), vec2(0.5, 0.11), 0.17);
float fill = softBox(s, vec2(0.34, -0.6), vec2(0.3, 0.05), 0.2);
c += envHigh * key * 1.15;
c += envHigh * fill * 0.14;
return c;
}
vec3 shellColor(vec2 p, vec2 frag, float d) {
// 外の面:丸い厚み。外側は外へ、内側は窓へ向かって傾く
vec2 q = p;
float inner = uPill.x - uPill.y;
q.x = sign(p.x) * max(abs(p.x) - inner, 0.0);
vec2 g = q / max(length(q), 1.0e-3);
float t = clamp(-d / uBezel, 0.0, 1.0);
float a = (1.0 - 2.0 * t);
a = sign(a) * pow(abs(a), 1.35) * 0.96;
vec3 N = normalize(vec3(g * a, sqrt(max(1.0 - a * a, 0.02))));
vec3 R = vec3(2.0 * N.z * N.xy, 2.0 * N.z * N.z - 1.0);
vec3 albedo = mix(uShellDay, uShellNight, uNight);
float diffuse = 0.62 + 0.38 * clamp(dot(N, normalize(vec3(-0.25, 0.75, 0.6))), 0.0, 1.0);
float fresnel = 0.05 + 0.95 * pow(1.0 - N.z, 3.5);
vec3 c = albedo * diffuse;
c = mix(c, studio(R), clamp(fresnel * 0.9 + 0.1, 0.0, 1.0));
// 窓のそばは、奥へ落ちる影
float toWindow = smoothstep(0.62, 1.0, t);
c = mix(c, c * 0.8, toWindow * 0.55);
// 灯りが、磨かれた面を照らす。光に近いところだけが、やわらかく染まる
float radius = uPill.y * 0.62;
for (int i = 0; i < 2; i++) {
vec2 pos = i == 0 ? uHomePos : uSkyPos;
vec3 col = i == 0 ? uHomeCol : uSkyCol;
vec3 e = reach(p, pos, col, radius);
vec2 toL = normalize(pos - p + 1.0e-3);
float wrap = 0.5 + 0.5 * dot(N.xy, toL);
c += e * wrap * mix(albedo * 0.9, vec3(dot(albedo, vec3(0.34))) + 0.34, 0.55) * 3.1;
// 映り込み:線にならないよう、広く弱く
vec3 Ld = normalize(vec3(pos - p, uPill.y * 0.7));
float spec = pow(max(dot(R, Ld), 0.0), 5.0);
c += reach(p, pos, col, uPill.y * 0.4) * spec * 1.4;
}
return c;
}
void main() {
vec2 frag = gl_FragCoord.xy;
vec2 p = frag - 0.5 * uRes;
envLow = mix(uShellDay * 0.74, uLoNight, uNight);
envHigh = mix(uLight, uHiNight, uNight);
float d = rb(p, uPill, uPill.y);
float dw = d + uBezel;
// ---- 外:やわらかい影と、漏れた光
vec3 premul = vec3(0.0);
float alpha = 0.0;
if (d > -2.0) {
float h = uPill.y;
float wide = rb(p + vec2(0.0, h * 0.13), uPill - vec2(h * 0.02, h * 0.02), uPill.y);
float contact = rb(p + vec2(0.0, h * 0.028), uPill, uPill.y);
float shadow = 0.24 * (1.0 - smoothstep(-h * 0.2, h * 0.28, wide)) + 0.22 * (1.0 - smoothstep(-h * 0.03, h * 0.07, contact));
alpha = shadow;
premul = uInk * shadow;
// 漏れた光は、まわりの地を染める。灯りがなければ染まらない
if (uHomeCol.r + uHomeCol.g + uHomeCol.b > 0.0) {
vec3 outside = reach(p, uHomePos, uHomeCol, uPill.y * 0.62) * exp(-max(d, 0.0) / (h * 0.2));
float amount = clamp(dot(outside, vec3(0.34)) * 2.3, 0.0, 0.85);
vec3 tint = outside / max(dot(outside, vec3(0.34)), 1.0e-3) * 0.34;
premul = mix(premul, tint * 1.25, amount);
alpha = mix(alpha, 1.0, amount);
}
// canvas の端までに、なめらかに消す
vec2 toEdge = 0.5 * uRes - abs(p);
float room = min(toEdge.x, toEdge.y) / (h * 0.32);
float fade = smoothstep(0.0, 1.0, clamp(room, 0.0, 1.0));
premul *= fade;
alpha *= fade;
}
vec3 color = premul;
if (d < 1.0) {
// 殻は細い帯。窓に隠れる画素では計算しない(下の mix で捨てるだけなので、絵は変わらない)
vec3 body = dw > -0.8 ? shellColor(p, frag, d) : vec3(0.0);
if (dw < 1.0) {
// ---- 窓の奥の世界
vec3 c = worldExact(frag);
// 灯りのにじみ:ピクセルの上に、ガラスのなめらかな光が乗る
vec3 near = glowNear(frag);
c = 1.0 - (1.0 - c) * (1.0 - clamp(near * 0.82, 0.0, 1.0));
// ガラスの映り込み:広く、なだらかに。縁はなぞらない
float win = uPill.y - uBezel;
float sheen = smoothstep(win * 0.1, win * 1.02, p.y + p.x * 0.09);
c = mix(c, envHigh, sheen * sheen * mix(0.17, 0.05, uNight));
float low = smoothstep(-win * 0.5, -win * 1.05, p.y - p.x * 0.05);
c = mix(c, envHigh, low * mix(0.05, 0.015, uNight));
// くぼみ:上のふちから落ちる影と、まわりの陰り
float top = rb(p - vec2(0.0, win * 0.06), uPill - vec2(uBezel), win);
float inset = 1.0 - smoothstep(-win * 0.2, win * 0.03, top + win * 0.0);
float ring = exp(max(dw, -win) / (win * 0.075));
float depth = clamp(ring * 0.46 + (1.0 - exp(min(top, 0.0) / (win * 0.14))) * 0.0 + exp(min(top, 0.0) / (win * 0.1)) * 0.4 * inset, 0.0, 0.82);
c = mix(c, uInk, depth);
// ---- レンズ
vec2 lc = uLens.xy;
vec2 he = uLens.zw;
float lr = min(he.x, he.y);
vec2 lq = p - lc;
// レンズが窓に落とす影と、集めた光
float lift = 0.055 + uLift * 0.04;
float sd = rb(lq + vec2(0.0, lr * lift * 1.5), he, lr);
float sh = 1.0 - smoothstep(-lr * 0.16, lr * (0.2 + uLift * 0.1), sd);
c = mix(c, uInk, sh * mix(0.36, 0.55, uNight));
float ld = rb(lq, he, lr);
if (ld < 1.0) {
// 中心線からの距離で丸みを決める
vec2 axis = lq;
vec2 inner2 = max(he - lr, vec2(0.0));
axis.x = sign(lq.x) * max(abs(lq.x) - inner2.x, 0.0);
axis.y = sign(lq.y) * max(abs(lq.y) - inner2.y, 0.0);
float rad = length(axis);
vec2 gr = axis / max(rad, 1.0e-3);
float rho = clamp(rad / lr, 0.0, 1.0);
// 拡大:中ほどは平らに、少しだけ大きく見える。縁に近づくと急に曲がり、外の絵を圧縮して見せる
float mag = 1.24;
float bt = clamp((rho - 0.7) / 0.3, 0.0, 1.0);
float band = bt * bt * (3.0 - 2.0 * bt);
float strength = 1.0 - 1.0 / mag + 0.2;
float bend = pow(band, 2.2) * lr * strength;
vec2 base = lc + lq / mag;
vec2 shiftDir = gr * bend;
vec2 center = 0.5 * uRes;
// 1画素が世界の何ピクセルぶんか(曲がる帯では、圧縮されて大きくなる)
float dBand = 6.0 * bt * (1.0 - bt) / 0.3;
float foot = (1.0 / mag + 2.2 * pow(max(band, 1.0e-3), 1.2) * dBand * strength) / uK;
vec3 seen;
float scale = uK * mag;
if (band > 0.02) {
float ca = 0.05 * band;
seen.r = worldBent(center + base + shiftDir * (1.0 - ca), scale, foot).r;
seen.g = worldBent(center + base + shiftDir, scale, foot).g;
seen.b = worldBent(center + base + shiftDir * (1.0 + ca), scale, foot).b;
} else {
seen = worldBent(center + base, scale, foot);
}
vec3 throughGlow = glowNear(center + base + shiftDir);
seen = 1.0 - (1.0 - seen) * (1.0 - clamp(throughGlow * 0.8, 0.0, 1.0));
// ガラスの形:中ほどはゆるい丸み、縁で急に落ちる
vec2 tilt = gr * (0.22 * rho + 0.78 * pow(rho, 7.0));
vec3 N = normalize(vec3(tilt, sqrt(max(1.0 - dot(tilt, tilt), 0.02))));
vec3 R = vec3(2.0 * N.z * N.xy, 2.0 * N.z * N.z - 1.0);
vec2 lp = lq / lr;
vec3 lens = seen * 1.035;
// 縁の厚み:明るい線ではなく、ガラスの奥の暗さで形を見せる
float edge = pow(rho, 16.0);
lens = mix(lens, uInk, edge * 0.42);
// 下の内側に集まる光
float pool = smoothstep(0.05, 0.95, -lp.y * 0.9 + lp.x * 0.2) * smoothstep(1.0, 0.8, rho) * smoothstep(0.42, 0.86, rho);
lens += envHigh * pool * mix(0.3, 0.1, uNight);
// 反射:上の大きなやわらかい光。丸みに沿って歪むが、縁をなぞらない
vec2 sr = R.xy / (1.0 + max(R.z, 0.0));
float broad = softBox(lp, vec2(-0.1, 0.62), vec2(0.5, 0.17), 0.3) * smoothstep(0.98, 0.72, rho);
lens = mix(lens, envHigh, broad * mix(0.44, 0.1, uNight));
float fresnel = pow(1.0 - N.z, 3.0);
float dir = 0.2 + 0.8 * smoothstep(-0.6, 0.85, dot(gr, normalize(vec2(-0.42, 0.9))));
float mirror = clamp(fresnel * dir * dir * 0.6, 0.0, 0.42);
if (mirror > 1.0e-3) lens = mix(lens, studio(R), mirror);
// 灯りと月や太陽も、レンズの面に映る。映るのは縁の近くだけ
if (rho > 0.62) {
for (int i = 0; i < 2; i++) {
vec2 pos = i == 0 ? uHomePos : uSkyPos;
vec3 col = i == 0 ? uHomeCol : uSkyCol;
vec2 toL = normalize(pos - p + 1.0e-3);
float side = max(dot(gr, toL), 0.0);
lens += reach(p, pos, col, uPill.y * 0.9) * side * side * side * smoothstep(0.62, 0.97, rho) * 0.6;
}
}
c = mix(c, lens, 1.0 - smoothstep(-0.8, 0.8, ld));
}
body = mix(body, c, 1.0 - smoothstep(-0.8, 0.8, dw));
}
float cover = 1.0 - smoothstep(-0.8, 0.8, d);
color = mix(premul, body, cover);
alpha = mix(alpha, 1.0, cover);
}
// 大きな階調が縞にならないよう、わずかに散らす
float n = fract(sin(dot(frag, vec2(12.9898, 78.233))) * 43758.5453);
n += fract(sin(dot(frag, vec2(93.989, 67.345))) * 24634.6345) - 1.0;
color += (n * 0.75) / 255.0 * min(alpha * 4.0, 1.0);
outColor = vec4(clamp(color, 0.0, 1.0), alpha);
}`;
function mount(root) {
const cleanups = [];
const on = (target, type, fn, options) => {
target.addEventListener(type, fn, options);
cleanups.push(() => target.removeEventListener(type, fn, options));
};
let canvas = root.querySelector('.scene');
const button = root.querySelector('.hit');
const statusEl = root.querySelector('[data-status]');
const probe = root.querySelector('.probe');
const motionQuery = matchMedia('(prefers-reduced-motion: reduce)');
const schemeQuery = matchMedia('(prefers-color-scheme: dark)');
let calm = motionQuery.matches;
// 画面に出さない canvas。OffscreenCanvas のない古い Safari(16.3 まで)でも動くようにする
const offscreen = (w, h) => (typeof OffscreenCanvas === 'function' ? new OffscreenCanvas(w, h) : Object.assign(root.ownerDocument.createElement('canvas'), { width: w, height: h }));
// ---- パレットをトークンから作る
const paint = offscreen(1, 1).getContext('2d', { willReadFrequently: true });
const palette = new Array(20);
const palette32 = new Uint32Array(20);
const readPalette = () => {
const style = getComputedStyle(root);
RAMPS.forEach(([name, tones], ramp) => {
probe.style.color = style.getPropertyValue(`--_${name}`).trim();
paint.clearRect(0, 0, 1, 1);
paint.fillStyle = getComputedStyle(probe).color;
paint.fillRect(0, 0, 1, 1);
const d = paint.getImageData(0, 0, 1, 1).data;
const lab = rgbToOklab([d[0], d[1], d[2]]);
tones.forEach((L, step) => {
const rgb = labTone(lab, L);
const id = ramp * 4 + step;
palette[id] = rgb;
palette32[id] = (255 << 24) | (rgb[2] << 16) | (rgb[1] << 8) | rgb[0];
});
});
};
const unit = (id) => palette[id].map((v) => v / 255);
// ---- 材質の表:時刻のかなめごと、状態(ふつう、影、灯り)ごと
const STEP_L = RAMPS.flatMap(([, tones]) => tones);
const shadeOf = (id) => {
const step = id % 4;
if (step > 0) return id - 1;
if (id === C0) return U0;
if (id === G0) return I3;
if (id === U0) return I3;
if (id === A0) return I3;
return id;
};
const litOf = (dayId) => {
const L = STEP_L[dayId];
return L < 0.72 ? A0 : L < 0.9 ? A0 : A1;
};
const NM = MATS.length;
const table = KEYS.map(([, col]) => {
const t = new Uint8Array(NM * 3);
MATS.forEach((row, m) => {
const id = row[col + 1];
t[m] = id;
t[NM + m] = shadeOf(id);
t[NM * 2 + m] = litOf(row[1]);
});
return t;
});
// ---- 世界の大きさ(整数倍が決める)
let bw = 1;
let bh = 1;
let ox = 0;
let oy = 0;
let k = 1;
let matBuf = new Uint8Array(1);
let baseBuf = new Uint8Array(1);
let varBuf = new Uint8Array(1);
let thrA = new Uint8Array(1);
let pixels = new Uint32Array(1);
let pixelBytes = new Uint8Array(pixels.buffer);
let skyKeys = [];
let limbCol = new Int16Array(1); // 列ごとの、地球のふちの高さ
let stars = [];
const emitList = [];
const sources = [{ w: 0, x: 0, y: 0, r: 0, g: 0, b: 0 }, { w: 0, x: 0, y: 0, r: 0, g: 0, b: 0 }];
const noiseA = makeNoise(11);
const noiseB = makeNoise(29);
// 地球の丸み:ふちに近いほど、地表は縦に詰まって見える
const V_MAX = 159;
const vTab = new Float32Array(V_MAX + 1);
for (let d = 0; d <= V_MAX; d++) vTab[d] = 12 * Math.sqrt(d);
// ---- 描く道具
const put = (x, y, m) => {
const px = x + ox;
const py = y + oy;
if (px < 0 || py < 0 || px >= bw || py >= bh) return;
matBuf[py * bw + px] = m;
};
const putSky = (x, y, m) => {
const px = x + ox;
const py = y + oy;
if (px < 0 || py < 0 || px >= bw || py >= bh) return;
const i = py * bw + px;
if (matBuf[i] === 0) matBuf[i] = m;
};
const rect = (x, y, w, h, m) => {
for (let j = 0; j < h; j++) for (let i = 0; i < w; i++) put(x + i, y + j, m);
};
const blit = (s, x, y, flip = false, force = -1) => {
for (const [dx, dy, m] of s.list) put(flip ? x + s.w - 1 - dx : x + dx, y + dy, force >= 0 ? force : m);
};
const stamp = (x, y, rows) => {
rows.forEach((row, j) => {
for (let i = 0; i < row.length; i++) {
const ch = row[i];
if (ch !== '.') put(x + i, y + j, M[ART_LEGEND[ch]]);
}
});
};
const emit = (x, y, weight, group = 2) => {
const px = x + ox;
const py = y + oy;
if (px < 0 || py < 0 || px >= bw || py >= bh) return;
emitList.push(py * bw + px, weight);
if (group < 2) {
const c = sources[group];
c.w += weight;
c.x += px * weight;
c.y += py * weight;
c.id = group === 0 ? A2 : c.id;
}
};
// ---- 動かない背景:ステーション
// トラス:居住モジュールから右へのびる骨組み。船外活動の足場になる
const paintTruss = () => {
rect(86, 58, 3, 9, M.METAL);
rect(86, 58, 3, 1, M.METAL_LT);
for (let x = 89; x < bw - ox; x++) {
put(x, DECK, M.METAL);
put(x, DECK + 3, M.METAL_DK);
const p = (x - 89) % 6;
if (p === 0) {
put(x, DECK + 1, M.METAL);
put(x, DECK + 2, M.METAL_DK);
} else if (p === 1 || p === 5) {
put(x, DECK + 1, M.METAL_DK);
} else if (p === 2 || p === 4) {
put(x, DECK + 2, M.METAL_DK);
}
}
};
// 太陽電池の翼:トラスの先から、上と下へ長くのびる
const paintArray = () => {
const AX = 176;
const wing = (y0, y1) => {
for (let y = y0; y <= y1; y++) {
for (const xa of [AX - 13, AX + 2]) {
for (let i = 0; i < 12; i++) {
const x = xa + i;
let m = M.PANEL;
if ((y - y0) % 6 === 5 || i % 4 === 3) m = M.PANEL_LT;
// 日を受けて光る、斜めの帯
else if (Math.abs(x - AX + (y - 34) * 0.62) < 2.6 || Math.abs(x - AX + (y - 58) * 0.62) < 1.2) m = M.PANEL_HI;
if (y === y0 || y === y1) m = M.METAL_LT;
put(x, y, m);
}
}
for (let x = AX - 1; x <= AX + 1; x++) put(x, y, y % 3 === 0 ? M.METAL_LT : M.METAL);
}
};
wing(12, 56);
wing(71, bh - oy + 2);
// 向きを変える回転のつけ根
rect(AX - 6, 58, 13, 11, M.METAL);
rect(AX - 6, 58, 13, 1, M.METAL_LT);
rect(AX - 6, 68, 13, 1, M.METAL_DK);
rect(AX - 2, 61, 5, 5, M.METAL_DK);
put(AX - 1, 62, M.METAL_LT);
rect(AX - 1, 10, 3, 2, M.METAL);
};
// 左につながる、帰りの船
const paintCapsule = () => {
const CY = 54;
for (const y0 of [32, 66]) {
for (let y = y0; y < y0 + 12; y++) {
for (let x = 13; x < 22; x++) {
let m = M.PANEL;
if ((y - y0) % 4 === 3 || x === 17) m = M.PANEL_LT;
if (y === y0) m = M.METAL_LT;
if (y === y0 + 11) m = M.METAL;
put(x, y, m);
}
}
}
put(15, 35, M.PANEL_HI);
put(14, 36, M.PANEL_HI);
rect(17, 44, 1, 2, M.METAL);
rect(17, 63, 1, 3, M.METAL);
for (let x = 9; x <= 29; x++) {
const hh = x < 12 ? 6 + (x - 9) : x <= 21 ? 9 : Math.round(9 - (x - 21) * 0.55);
for (let y = CY - hh; y <= CY + hh; y++) {
const t = (y - (CY - hh)) / (hh * 2);
const v = t + (bayerAt(x, y) / 16 - 0.5) * 0.16;
let m = v > 0.84 ? M.HULL_DK : v > 0.6 ? M.HULL_SH : M.HULL;
if (y === CY + hh) m = M.METAL;
if (x < 12) m = t > 0.55 ? M.METAL_DK : M.METAL; // 熱を受ける底
else if (x === 12 || x === 13) m = t > 0.6 ? M.FOIL_DK : t < 0.25 ? M.FOIL_LT : M.FOIL; // 金の帯
else if (x === 22) m = t > 0.6 ? M.HULL_DK : M.HULL_SH;
put(x, y, m);
}
}
rect(17, 51, 3, 3, M.GLASS);
put(17, 51, M.GLASS_HI);
// つなぎ目の通路
rect(30, 50, 6, 9, M.METAL);
rect(30, 50, 6, 1, M.METAL_LT);
rect(30, 58, 6, 1, M.METAL_DK);
rect(32, 49, 2, 11, M.METAL_DK);
};
// 居住モジュール:丸い筒。窓(キューポラ)とエアロックがある
const paintModule = () => {
const X0 = 36;
const X1 = 86;
const TOP = 42;
const BOT = 66;
const n = BOT - TOP;
for (let y = TOP; y <= BOT; y++) {
const j = y - TOP;
const edge = Math.min(j, n - j);
const inset = edge === 0 ? 3 : edge === 1 ? 2 : edge <= 3 ? 1 : 0;
const t = j / n;
for (let x = X0 + inset; x < X1 - inset; x++) {
// 上から日を受ける筒。下へ向かってディザで陰る
const v = t + (bayerAt(x, y) / 16 - 0.5) * 0.18;
let m = v > 0.86 ? M.HULL_DK : v > 0.62 ? M.HULL_SH : M.HULL;
if (j === n) m = M.METAL;
put(x, y, m);
}
}
// 外板の継ぎ目
for (const x of [80]) {
for (let y = TOP + 1; y < BOT; y++) put(x, y, y - TOP > n * 0.6 ? M.METAL : M.HULL_DK);
}
// 金の断熱材の帯
for (let x = X0 + 1; x < X1 - 1; x++) {
put(x, 63, (x * 3) % 7 === 0 ? M.FOIL_LT : M.FOIL);
put(x, 64, (x * 5) % 9 === 0 ? M.FOIL : M.FOIL_DK);
}
// 胴を締める輪
for (const x of [38, 83]) {
for (let y = TOP - 1; y <= BOT + 1; y++) {
const lower = y - TOP > n * 0.55;
put(x, y, lower ? M.METAL : M.METAL_LT);
put(x + 1, y, lower ? M.METAL_DK : M.METAL);
}
}
// 背中:通信マスト、姿勢制御の噴射口、手すり
rect(74, 30, 2, 12, M.METAL);
rect(71, 34, 8, 1, M.METAL_LT);
rect(72, 37, 6, 1, M.METAL);
rect(40, 40, 5, 2, M.METAL_DK);
put(40, 39, M.METAL);
put(44, 39, M.METAL);
rect(48, 40, 13, 1, M.METAL_LT);
for (const x of [48, 54, 60]) put(x, 41, M.METAL);
// 腹:放熱板
rect(56, 67, 2, 2, M.METAL);
for (let y = 69; y <= 83; y++) {
for (let x = 49; x <= 65; x++) {
let m = (x - 49) % 4 === 3 ? M.HULL_DK : (y - 69) % 5 === 4 ? M.HULL_SH : M.HULL;
if (y === 69) m = M.METAL_LT;
if (y === 83) m = M.METAL;
put(x, y, m);
}
}
// エアロックの扉
rect(68, 47, 10, 16, M.METAL_DK);
rect(67, 48, 12, 14, M.METAL_DK);
rect(68, 48, 10, 14, M.METAL);
rect(68, 48, 10, 1, M.METAL_LT);
rect(71, 51, 4, 3, M.GLASS);
put(71, 51, M.GLASS_HI);
put(72, 51, M.GLASS_HI);
rect(70, 57, 6, 1, M.METAL_DK);
put(76, 57, M.FOIL_LT);
put(69, 50, M.METAL_LT);
put(69, 59, M.METAL_LT);
// 窓の枠と、窓辺で育てている野菜(窓の中は毎フレーム描く)
rect(45, 46, 16, 16, M.METAL_DK);
rect(44, 47, 18, 14, M.METAL_DK);
rect(45, 46, 16, 1, M.METAL);
const r = seeded(77);
for (let x = 46; x < 60; x++) {
if (r() < 0.7) put(x, 60, r() < 0.6 ? M.PLANT : M.FOIL_LT);
}
};
const buildBase = () => {
matBuf.fill(0);
paintTruss();
paintArray();
paintCapsule();
paintModule();
stamp(109, 50, ART_DISH); // 地球へ向けたアンテナ
stamp(138, 52, ART_BOX); // ふたの開いた機器箱
rect(146, 46, 1, 6, M.METAL);
baseBuf.set(matBuf);
limbCol = new Int16Array(bw);
for (let px = 0; px < bw; px++) limbCol[px] = Math.round(limbAt(px - ox));
const r = seeded(808);
stars = [];
for (let i = 0; i < 140; i++) {
stars.push({ x: Math.floor(r() * (CORE_W + 60)) - 30, y: Math.floor(r() * 98) - 8, seed: r(), big: r() < 0.14 });
}
// 空を時刻のかなめごとに描いておく。色の帯は、地球のふちの丸みに沿う
const pos = new Float32Array(bw * bh);
for (let py = 0; py < bh; py++) {
for (let px = 0; px < bw; px++) {
const above = limbAt(px - ox) - (py - oy);
pos[py * bw + px] = Math.pow(clamp(1 - above / SKY_SPAN), SKY_CURVE);
}
}
const CHECKER = [0, 2, 3, 1];
skyKeys = KEYS.map(([, , stops]) => {
const sky = new Uint8Array(bw * bh);
const n = stops.length - 1;
for (let py = 0; py < bh; py++) {
for (let px = 0; px < bw; px++) {
const at = pos[py * bw + px] * n;
const a = Math.min(Math.floor(at), n);
const b = Math.min(a + 1, n);
// 帯のあいだだけを、市松の点で埋める
const f = smoothstep(0.3, 0.7, at - a) * 4;
sky[py * bw + px] = f > CHECKER[((py & 1) << 1) | (px & 1)] ? stops[b] : stops[a];
}
}
return sky;
});
};
// ---- 飛行士と世界の動き
const res = { x: HOME_X, inside: false, face: 1, step: 0, doorOpen: 0, startle: 0, hop: 0, blink: 0, nextBlink: 2, page: 0, nextPage: 4, pageT: 0, hurry: 0 };
const puffs = [];
const zees = [];
const ship = { t: -1, next: 8, y: 20, dir: 1 };
const shoot = { t: -1, next: 14 };
const glints = Array.from({ length: 8 }, (_, i) => ({ seed: i * 7.3 + 1, x: 138 + (i - 3.5) * 10, y: 40 + (i % 3) * 8 }));
let anim = 0;
let puffAcc = 0;
let zeeAcc = 0;
let lampFlick = 1;
let windowL = 0;
let lanternL = 0;
let shutter = 0;
const hourOf = (clock) => ((clock % 24) + 24) % 24;
// 時刻から、飛行士の予定を決める
const planFor = (h) => {
if (h >= 9.6 && h < 11) return { outside: true, x: DISH_X, act: 'tend' };
if (h >= 11 && h < 16.2) return { outside: true, x: WORK_X, act: 'read' };
if (h >= 16.2 && h < 17.2) return { outside: true, x: VIEW_X, act: 'stroll' };
return { outside: false, x: HOME_X, act: 'in' };
};
const stepResident = (dt, h, speedHint) => {
const plan = planFor(h);
const want = plan.outside ? plan.x : HOME_X;
if (calm) {
res.inside = !plan.outside;
res.x = want;
return plan;
}
res.startle = Math.max(0, res.startle - dt);
res.hop = res.startle > 0.55 ? Math.sin(((0.9 - res.startle) / 0.35) * Math.PI) * 3 : 0;
res.doorOpen = Math.max(0, res.doorOpen - dt);
if (res.startle > 0) return plan;
if (res.inside && plan.outside) {
res.inside = false;
res.x = HOME_X;
res.doorOpen = 0.5;
}
if (!res.inside) {
const delta = want - res.x;
if (Math.abs(delta) > 0.5) {
const speed = 17 + clamp(speedHint, 0, 1) * 72 + (Math.abs(delta) > 34 ? 8 : 0);
const move = Math.min(Math.abs(delta), speed * dt);
res.x += Math.sign(delta) * move;
res.face = Math.sign(delta);
res.step += move * 0.28;
res.hurry = speedHint;
} else {
res.x = want;
res.step = 0;
if (plan.outside) res.face = 1;
else {
res.inside = true;
res.doorOpen = 0.45;
}
}
}
// バイザーのきらめき、工具を回す、ページをめくる
res.nextBlink -= dt;
if (res.nextBlink <= 0) {
res.blink = 0.13;
res.nextBlink = 1.8 + Math.random() * 3.4;
}
res.blink = Math.max(0, res.blink - dt);
res.nextPage -= dt;
if (res.nextPage <= 0) {
res.pageT = 0.42;
res.nextPage = 3.6 + Math.random() * 3.2;
}
res.pageT = Math.max(0, res.pageT - dt);
return plan;
};
// ---- 地球:下に丸く見える。陸と雲は、軌道を進むぶんだけ流れていく
const drawEarth = (h) => {
const drift = calm ? 0 : anim;
const se = Math.floor(drift * 1.6);
const sc = Math.floor(drift * 2.2);
const night = clamp(smoothstep(19.2, 20.4, h) + (1 - smoothstep(4.6, 5.6, h)));
// 昼と夜の境目:日の入りは左から陰り、日の出は左から明ける
let termX = 0;
let termDir = 0;
let termAmt = 0;
if (h > 16.6 && h < 19.4) {
termDir = 1;
termX = mix(-60, 300, smoothstep(16.6, 19.4, h));
termAmt = smoothstep(16.6, 17.2, h) * (1 - smoothstep(18.8, 19.4, h));
} else if (h > 5.2 && h < 8) {
termDir = -1;
termX = mix(-110, 250, smoothstep(5.2, 8, h));
termAmt = smoothstep(5.2, 5.8, h) * (1 - smoothstep(7.4, 8, h));
}
const yEnd = bh - oy;
for (let px = 0; px < bw; px++) {
const x = px - ox;
const top = limbCol[px];
const u = x + se;
const uc = x + sc;
const shade = termDir > 0 ? clamp((termX - x) / 70) * termAmt * 16 : termDir < 0 ? clamp((x - termX) / 70) * termAmt * 16 : 0;
for (let y = Math.max(top, -oy); y < yEnd; y++) {
const i = (y + oy) * bw + px;
if (matBuf[i] !== 0) continue;
const d = y - top;
if (d === 0) {
matBuf[i] = M.ATMOS; // 大気の薄い線。夜は大気光になる
continue;
}
const b = bayerAt(x, y);
const v = vTab[Math.min(d, V_MAX)];
let m;
const cloud = noiseB(uc * 0.045 + 30, v * 0.06 + 9) * 0.66 + noiseA(uc * 0.15 + 3, v * 0.2 + 40) * 0.34;
if (cloud > 0.62) {
m = cloud > 0.655 || b < 6 ? M.CLOUD : M.CLOUD_SH;
} else {
const land = noiseA(u * 0.024 + 5, v * 0.026 + 2) * 0.74 + noiseB(u * 0.09 + 1, v * 0.1 + 7) * 0.26;
if (land > 0.56) {
m = land > 0.65 ? M.LAND_DK : M.LAND;
if (land <= 0.65 && noiseA(u * 0.035 + 90, v * 0.04 + 30) + (b / 16 - 0.5) * 0.1 > 0.56) m = M.SAND;
// 夜の側では、街の灯りがともる
if (night > 0.02) {
const cz = noiseB(u * 0.83 + 11, v * 0.83 + 3);
if (cz > 0.76 && noiseA(u * 0.06 + 60, v * 0.07 + 20) > 0.47 && (cz * 37) % 1 < night) {
m = cz > 0.88 ? M.CITY_HI : M.CITY;
emitList.push(i, 110 * night);
}
}
} else if (land > 0.535) {
m = M.OCEAN_LT;
} else {
m = noiseB(u * 0.04 + 60, v * 0.05 + 80) + (b / 16 - 0.5) * 0.25 < 0.42 ? M.OCEAN_DK : M.OCEAN;
}
// ふちの近くは、大気でかすむ
if (d <= 3 && b < (4 - d) * 4.5 && m !== M.CITY && m !== M.CITY_HI) m = M.OCEAN_LT;
}
matBuf[i] = m;
if (shade > b) varBuf[i] = 1;
}
}
};
// ---- オーロラ:夜の側の、地球のふちの上にゆれる
const drawAurora = (night) => {
if (night < 0.45) return;
const t = calm ? 0 : anim;
const gain = smoothstep(0.45, 1, night);
for (let px = 0; px < bw; px++) {
const x = px - ox;
const env = smoothstep(84, 116, x) * (1 - smoothstep(200, 230, x));
if (env <= 0) continue;
const wave = noiseA(x * 0.05 + t * 0.1, 20.5 + t * 0.04);
const tall = Math.round((2 + wave * 14) * env * gain);
const ray = noiseB(x * 0.8 + t * 0.25, 5.5 - t * 0.07);
const top = limbCol[px];
for (let j = 0; j < tall; j++) {
const y = top - 2 - j;
const py = y + oy;
if (py < 0 || py >= bh) continue;
const f = j / tall;
const dens = (1 - f * f) * (0.35 + ray * 0.75);
if (dens * 16 <= bayerAt(x, y)) continue;
const i = py * bw + px;
if (matBuf[i] !== 0) continue;
matBuf[i] = f < 0.35 && ray > 0.45 ? M.AURORA_HI : f > 0.7 ? M.AURORA_DK : M.AURORA;
emitList.push(i, 46 * (1 - f) * gain);
}
}
};
const drawSky = (h) => {
const dark = smoothstep(18.2, 20.2, h) + (1 - smoothstep(4.6, 6.2, h));
const night = clamp(dark);
drawAurora(night);
// 星:夜の側だけ。またたく
if (night > 0.02) {
for (const s of stars) {
if (s.seed > night * 1.05) continue;
const twinkle = calm ? 1 : Math.sin(anim * (1.3 + s.seed * 4.4) + s.seed * 40);
if (twinkle < -0.72) continue;
const m = twinkle < 0.1 && !s.big ? M.STAR_DIM : M.STAR;
putSky(s.x, s.y, m);
if (s.big && twinkle > 0.55) {
putSky(s.x - 1, s.y, M.STAR_DIM);
putSky(s.x + 1, s.y, M.STAR_DIM);
putSky(s.x, s.y - 1, M.STAR_DIM);
putSky(s.x, s.y + 1, M.STAR_DIM);
}
}
// 流れ星
if (!calm && night > 0.9) {
if (shoot.t >= 0) {
const f = shoot.t / 0.55;
for (let i = 0; i < 7; i++) {
const u = f * 42 - i * 2;
if (u > 0 && u < 42) putSky(Math.round(shoot.x + u), Math.round(shoot.y + u * 0.45), i < 2 ? M.STAR : M.STAR_DIM);
}
}
}
}
// 太陽:空を弧を描いて動き、地球のふちへ沈む
if (h > 5.2 && h < 19) {
const a = ((h - 6) / 12) * Math.PI;
const sx = Math.round(96 - Math.cos(a) * 102);
const sy = Math.round(SUN_BASE - 2 - Math.sin(a) * 70);
const low = 1 - clamp(Math.sin(a) * 1.6);
const R = 5 + Math.round(low * 2);
for (let dy = -R - 5; dy <= R + 5; dy++) {
for (let dx = -R - 5; dx <= R + 5; dx++) {
const d = Math.hypot(dx, dy);
const x = sx + dx;
const y = sy + dy;
if (d <= R - 1) {
putSky(x, y, M.SUN);
emit(x, y, 26 + low * 90, 1);
} else if (d <= R) {
putSky(x, y, M.SUN_RIM);
} else if (d <= R + 4 && bayerAt(x, y) < (R + 4.6 - d) * 2.2) {
putSky(x, y, M.SUN_RIM);
}
}
}
}
// 月
const mh = h >= 17.6 ? h : h + 24;
if (mh > 17.6 && mh < 30.4) {
const a = ((mh - 18) / 12) * Math.PI;
const mx = Math.round(96 - Math.cos(a) * 102);
const my = Math.round(SUN_BASE - 2 - Math.sin(a) * 66);
const R = 6;
for (let dy = -R - 3; dy <= R + 3; dy++) {
for (let dx = -R - 3; dx <= R + 3; dx++) {
const d = Math.hypot(dx, dy);
const x = mx + dx;
const y = my + dy;
if (d <= R) {
const crater = (dx === -2 && dy === -2) || (dx === 2 && dy === 1) || (dx === -3 && dy === 2) || (dx === 1 && dy === -3) || (dx === 3 && dy === -1) || (dx === -1 && dy === 3);
const shaded = dx * 0.7 + dy * 0.7 > R * 0.45;
putSky(x, y, crater || shaded ? M.MOON_DK : M.MOON);
emit(x, y, 12, 1);
} else if (d <= R + 3 && bayerAt(x, y) < (R + 3.4 - d) * 1.6) {
putSky(x, y, M.STAR_DIM);
}
}
}
}
// 補給船:昼の側で、ときどき遠くを横切る
if (!calm && h > 7 && h < 18.5 && ship.t >= 0) {
const x = Math.round(ship.dir > 0 ? -14 + ship.t * 15 : CORE_W + 14 - ship.t * 15);
const y = ship.y;
const d = ship.dir;
for (let i = 0; i < 4; i++) {
putSky(x - d * i, y, M.SHIP);
putSky(x - d * i, y + 1, i === 0 ? M.SHIP : M.SHIP_DK);
}
putSky(x + d, y, M.SHIP);
putSky(x - d * 2, y - 1, M.SHIP_DK);
putSky(x - d * 2, y - 2, M.SHIP_DK);
putSky(x - d * 2, y + 2, M.SHIP_DK);
putSky(x - d * 2, y + 3, M.SHIP_DK);
if (Math.floor(anim * 8) % 2) putSky(x - d * 4, y, M.LIT_HI);
}
};
const drawWindow = (h) => {
const lamp = h >= 19.6 && h < 22.9;
const cook = h >= 17.2 && h < 19.6;
const morning = h >= 7 && h < 9.6;
const asleep = h >= 22.9 || h < 6.5;
if (lamp || cook) {
const flick = lamp ? lampFlick : 0.6 + 0.08 * Math.sin(anim * 9);
for (let y = 0; y < WH; y++) {
for (let x = 0; x < WW; x++) {
let m;
if (lamp) {
// 天井の灯りの下に、広がる光の円すい
const cone = Math.abs(x - 4.5) - (y - 1) * 0.62;
m = cone < 0 && y >= 2 ? M.LIT_HI : cone < 2.2 ? M.LIT : M.LIT_DK;
} else {
m = Math.hypot(x - 6.5, y - 8) < 5 && bayerAt(x, y) < 8 ? M.LIT : M.LIT_DK;
}
if (y >= WH - 1) m = M.LIT_DK;
put(WX + x, WY + y, m);
emit(WX + x, WY + y, (m === M.LIT_HI ? 255 : m === M.LIT ? 210 : 130) * flick, 0);
}
}
if (lamp) {
// 天井に埋めた灯り
rect(WX + 2, WY, 5, 1, M.SIL);
rect(WX + 3, WY + 1, 3, 1, M.LIT_HI);
// 操作卓と、開いた手順書
rect(WX + 1, WY + 10, 9, 1, M.SIL);
rect(WX + 2, WY + 11, 7, 1, M.SIL);
const pageUp = res.pageT > 0 && !calm;
rect(WX + 4, WY + 9, 3, 1, M.SIL);
if (pageUp) put(WX + 5, WY + 8, M.SIL);
// 操作卓に向かう人影。ときどき顔を上げる。まだ外にいるあいだは、誰もいない
if (res.inside) {
const startled = res.startle > 0;
const look = startled || (!calm && Math.sin(anim * 0.46) > 0.72);
const nod = !calm && !look && Math.sin(anim * 1.7) > 0.86 ? 1 : 0;
const hy = WY + 3 + nod - (startled ? 1 : 0);
const hx = WX + 8;
// 頭
rect(hx, hy + (look ? 0 : 1), 4, 3, M.SIL);
put(hx + 1, hy + (look ? -1 : 0), M.SIL);
put(hx + 2, hy + (look ? -1 : 0), M.SIL);
if (!look) put(hx - 1, hy + 2, M.SIL);
// 肩と背
rect(WX + 8, WY + 7, 5, 3, M.SIL);
rect(WX + 9, WY + 10, 4, 2, M.SIL);
// 卓へのばした腕
rect(WX + 6, WY + 8, 3, 1, M.SIL);
}
} else {
// 夕方:食事の支度。人影がただよい、水の玉が浮かぶ
const sway = calm ? 0 : Math.sin(anim * 0.8) * 3;
const bob = calm ? 0 : Math.sin(anim * 0.55) > 0.2 ? -1 : 0;
if (res.inside) blit(SPR.sil, Math.round(WX + 3 + sway), WY + 4 + bob, false, M.SIL);
if (!calm) {
for (let i = 0; i < 3; i++) {
const s = (anim * 0.5 + i * 0.33) % 1;
put(WX + 11 + Math.round(Math.sin(s * 8 + i)), WY + 7 - Math.round(s * 6), M.LIT_HI);
}
}
rect(WX + 10, WY + 8, 4, 1, M.SIL);
}
} else if (morning) {
// 朝:覆いを開けて、伸びをする
rect(WX, WY, WW, WH, M.ROOM);
for (let y = 0; y < 2; y++) for (let x = 0; x < WW; x++) put(WX + x, WY + y, M.GLASS_HI);
let bust = SPR.bust;
if (!calm) {
const c = (anim % 5.4) / 5.4;
if (c > 0.16 && c < 0.24) bust = SPR.bustHalf;
else if (c >= 0.24 && c < 0.5) bust = SPR.bustUp;
else if (c >= 0.5 && c < 0.58) bust = SPR.bustHalf;
else if (res.blink > 0) bust = SPR.bustBlink;
}
const dy = res.startle > 0 ? -1 : 0;
if (res.inside) blit(bust, WX + 3, WY + 4 + dy);
} else {
// 昼間と夜中:暗いガラス。斜めの映り込み
rect(WX, WY, WW, WH, M.GLASS);
for (let i = 0; i < 6; i++) {
put(WX + 2 + i, WY + 7 - i, M.GLASS_HI);
if (i < 4) put(WX + 6 + i, WY + 8 - i, M.GLASS_HI);
}
}
// 窓の骨
rect(WX + 6, WY, 2, 2, M.METAL_DK);
rect(WX, WY + 4, 1, 1, M.METAL_DK);
rect(WX + 13, WY + 4, 1, 1, M.METAL_DK);
// 窓の覆い:眠る時間は閉じ、朝に開く
const closed = asleep ? 1 : 0;
shutter += calm ? closed - shutter : clamp(closed - shutter, -0.09, 0.09);
const leaf = Math.round(shutter * 7);
const drawLeaf = (x0, w) => {
for (let i = 0; i < w; i++) {
for (let y = 0; y < 14; y++) put(x0 + i, WY - 1 + y, y % 2 === 0 ? M.METAL : M.METAL_LT);
}
};
// 開いている覆いは窓の両わきに、閉じると窓の上に
const open = 4 - Math.min(4, leaf);
if (open > 0) {
drawLeaf(WX - 2 - open, open);
drawLeaf(WX + 16, open);
}
if (leaf > 0) {
drawLeaf(WX, leaf);
drawLeaf(WX + 14 - leaf, leaf);
}
return { lamp, cook, asleep };
};
const drawHatch = () => {
if (res.doorOpen > 0) {
rect(68, 48, 10, 14, M.SIL);
rect(68, 48, 2, 14, M.METAL_LT);
}
};
const drawResident = (plan) => {
if (res.inside) return;
const dy = -Math.round(res.hop);
const startled = res.startle > 0;
const moving = Math.abs((plan.outside ? plan.x : HOME_X) - res.x) > 0.5;
const rx = Math.round(res.x);
// 無重力:止まっているあいだも、ゆっくり浮き沈みする
const bobY = calm || startled ? 0 : Math.sin(anim * 1.2) > 0.25 ? -1 : 0;
const working = !moving && plan.act === 'read' && Math.abs(res.x - WORK_X) < 1;
// 命綱:エアロックのわきから、背中の装置まで。近いほどたるむ
const tx = working ? WORK_X : rx + (res.face < 0 ? 3 : -3);
const ty = DECK - 5 + dy;
if (tx - 80 > 3) {
const n = Math.max(2, Math.round((tx - 80) / 2));
const sag = 2 + clamp(1 - (tx - 80) / 60) * 3 + (calm ? 0 : Math.sin(anim * 0.9) * 0.8);
for (let s = 1; s < n; s++) {
const t = s / n;
put(Math.round(mix(80, tx, t)), Math.round(mix(DECK - 3, ty, t) + Math.sin(t * Math.PI) * sag), M.TETHER);
}
}
if (working) {
// 機器箱のふたを開けて、中を直す
const spr = startled ? SPR.workUp : res.blink > 0 ? SPR.workBlink : SPR.work;
const x = WORK_X;
const y = DECK - 10 + dy + bobY;
blit(spr, x, y);
const hx = x + 9;
const hy = y + 5;
if (!startled) {
put(hx, hy, M.METAL_DK);
if (res.pageT > 0.28) {
// 工具の先の火花
put(hx, hy - 1, M.LIT_HI);
emit(hx, hy - 1, 200);
} else if (res.pageT > 0.14) {
put(hx + 1, hy - 2, M.LIT);
}
} else {
// 驚いて、工具が手を離れる
put(hx + 1, hy - 4, M.METAL_DK);
rect(x + 3, y - 7, 1, 4, M.MARK);
put(x + 3, y - 2, M.MARK);
}
return;
}
if (!moving && plan.act === 'tend') {
const bob = !calm && Math.sin(anim * 2.2) > 0;
blit(bob ? SPR.crouch : SPR.stand, rx - 3, bob ? DECK - 10 : DECK - 12, false);
return;
}
let spr = SPR.stand;
if (startled) spr = SPR.up;
else if (moving) spr = SPR.walk[Math.floor(res.step) % 4];
else if (res.blink > 0) spr = SPR.blink;
blit(spr, rx - 3, DECK - 12 + dy + (moving ? -1 : bobY), res.face < 0);
if (startled) {
rect(rx, DECK - 19 + dy, 1, 4, M.MARK);
put(rx, DECK - 14 + dy, M.MARK);
}
};
const drawParticles = (h, dt) => {
// 姿勢制御の噴射:日の入りと朝に、軌道を整える
const firing = (h >= 17.2 && h < 19.8) || (h >= 7 && h < 8.2);
if (!calm && firing) {
puffAcc += dt * (h >= 17 ? 3.2 : 1.4);
while (puffAcc >= 1) {
puffAcc -= 1;
puffs.push({ x: 40 + Math.random() * 2, y: 37, t: 0, seed: Math.random() * 10 });
}
}
for (let i = puffs.length - 1; i >= 0; i--) {
const s = puffs[i];
s.t += dt;
s.y -= dt * (6 - s.t * 0.7);
s.x -= dt * (3.2 + Math.sin(s.t * 1.7 + s.seed) * 1.6);
if (s.t > 4.2 || s.y < -8) {
puffs.splice(i, 1);
continue;
}
const size = 1 + Math.floor(s.t * 0.75);
const thin = s.t * 2.6;
for (let dy = 0; dy < size; dy++) {
for (let dx = 0; dx < size; dx++) {
const x = Math.round(s.x) + dx;
const y = Math.round(s.y) + dy;
if (bayerAt(x, y) < 16 - thin * 1.3) put(x, y, s.t > 2.3 ? M.PUFF_DK : M.PUFF);
}
}
}
if (calm && firing) {
for (let i = 0; i < 5; i++) rect(40 - i * 3, 36 - i * 4, 1 + (i >> 1), 2, M.PUFF);
}
// 眠りの Z
if (!calm && (h >= 23.4 || h < 6)) {
zeeAcc += dt * 0.62;
while (zeeAcc >= 1) {
zeeAcc -= 1;
zees.push({ x: WX + 14, y: WY - 3, t: 0 });
}
}
for (let i = zees.length - 1; i >= 0; i--) {
const z = zees[i];
z.t += dt;
z.y -= dt * 4;
z.x += dt * (1.2 + Math.sin(z.t * 2) * 2);
if (z.t > 3 || (h >= 6 && h < 23)) {
zees.splice(i, 1);
continue;
}
const x = Math.round(z.x);
const y = Math.round(z.y);
const big = z.t > 1.2;
const n = big ? 3 : 2;
rect(x, y, n, 1, M.ZZZ);
put(x + n - 2, y + 1, M.ZZZ);
if (big) put(x, y + 2, M.ZZZ);
rect(x, y + (big ? 3 : 2), n, 1, M.ZZZ);
}
// 氷の粒:船体からはがれて、蛍のように光りながらただよう
const night = clamp(smoothstep(19.4, 20.8, h) + (1 - smoothstep(3.6, 5, h)));
if (night > 0.3 && !calm) {
for (const f of glints) {
const wx = f.x + Math.sin(anim * 0.33 + f.seed) * 14 + Math.sin(anim * 0.9 + f.seed * 2) * 3;
const wy = f.y + Math.sin(anim * 0.47 + f.seed * 1.4) * 5;
const pulse = Math.sin(anim * 1.4 + f.seed * 3);
if (pulse < 0.1) continue;
put(Math.round(wx), Math.round(wy), M.GLINT);
emit(Math.round(wx), Math.round(wy), 170 * pulse);
}
}
// 見回りのドローン:昼のあいだ、飛行士のそばを飛ぶ
if (!calm && h > 8 && h < 17) {
const x = Math.round(101 + Math.sin(anim * 0.31) * 9 + Math.sin(anim * 1.1) * 2);
const y = Math.round(43 + Math.sin(anim * 0.72) * 4);
put(x, y - 1, M.FOIL_LT);
put(x - 1, y, M.FOIL);
put(x + 1, y, M.FOIL);
put(x, y + 1, M.FOIL_DK);
put(x, y, Math.floor(anim * 1.6) % 4 === 0 ? M.GLINT : M.VISOR);
}
};
const drawLights = (state, h) => {
// 灯りの強さ
const targetWin = state.lamp ? 1 : state.cook ? 0.46 : 0;
const targetLan = h >= 18.4 && h < 22.9 ? 1 : 0;
windowL += (targetWin - windowL) * (calm ? 1 : 0.28);
lanternL += (targetLan - lanternL) * (calm ? 1 : 0.28);
// エアロックの上の外灯
rect(71, 43, 4, 1, M.METAL_DK);
if (lanternL > 0.02) {
const flick = calm ? 1 : 0.94 + 0.06 * Math.sin(anim * 11) * Math.sin(anim * 3.7);
rect(71, 44, 4, 2, M.LIT_HI);
for (let y = 44; y < 46; y++) for (let x = 71; x < 75; x++) emit(x, y, 255 * lanternL * flick, 0);
} else {
rect(71, 44, 4, 2, M.GLASS);
}
// 位置を知らせる灯:マストの先と、太陽電池の先で、かわるがわる光る
const dusk = clamp(smoothstep(17.6, 19.6, h) + (1 - smoothstep(5, 6.6, h)));
const onA = calm ? dusk > 0.5 : anim % 1.8 < 0.24;
const onB = calm ? dusk > 0.5 : (anim + 0.9) % 1.8 < 0.24;
rect(74, 28, 2, 2, onA ? M.BEACON : M.METAL_DK);
rect(175, 8, 3, 2, onB ? M.BEACON_G : M.METAL_DK);
if (dusk > 0.05) {
if (onA) for (let x = 74; x < 76; x++) for (let y = 28; y < 30; y++) emit(x, y, 230 * dusk);
if (onB) for (let x = 175; x < 178; x++) for (let y = 8; y < 10; y++) emit(x, y, 200 * dusk);
}
const pool = (cx, cy, rx, ry, L) => {
if (L <= 0.01) return;
for (let y = Math.max(cy - ry, -oy); y <= cy + ry; y++) {
for (let x = cx - rx; x <= cx + rx; x++) {
const px = x + ox;
const py = y + oy;
if (px < 0 || py < 0 || px >= bw || py >= bh) continue;
const i = py * bw + px;
const m = matBuf[i];
// 空と地球には届かない。船の面だけを照らす
if (m <= EARTH_END || m === M.SIL || m === M.LIT || m === M.LIT_HI || m === M.LIT_DK) continue;
const d = Math.hypot((x - cx) / rx, (y - cy) / ry);
const v = (1 - d) * L * 1.5;
if (v * 16 > bayerAt(x, y)) varBuf[i] = 2;
}
}
};
// 窓から船体と放熱板へ落ちる光、外灯が扉を照らす光
pool(53, 54, 19, 11, windowL * 0.42);
pool(54, 74, 20, 12, windowL * 0.9);
pool(73, 47, 13, 8, lanternL * 0.55);
pool(73, 57, 17, 8, lanternL * 0.6);
};
// ---- 世界を1枚描く
let keyA = 0;
let keyB = 1;
let keyP = 0;
const pickKeys = (h) => {
for (let i = 0; i < KEYS.length - 1; i++) {
if (h >= KEYS[i][0] && h < KEYS[i + 1][0]) {
keyA = i;
keyB = i + 1;
keyP = clamp(((h - KEYS[i][0]) / (KEYS[i + 1][0] - KEYS[i][0]) - 0.32) / 0.36);
return;
}
}
keyA = 0;
keyB = 1;
keyP = 0;
};
const renderWorld = (clock, dt, hurry) => {
const h = hourOf(clock);
if (!calm) anim += dt;
matBuf.set(baseBuf);
varBuf.fill(0);
emitList.length = 0;
for (const c of sources) {
c.w = 0;
c.x = 0;
c.y = 0;
}
lampFlick = calm ? 1 : 0.95 + 0.05 * Math.sin(anim * 13) * Math.sin(anim * 5.3);
if (!calm) {
ship.next -= dt;
if (ship.t >= 0) {
ship.t += dt;
if (ship.t > 15.5) ship.t = -1;
} else if (ship.next <= 0) {
ship.t = 0;
ship.next = 14 + Math.random() * 14;
ship.y = 14 + Math.round(Math.random() * 16);
ship.dir = Math.random() < 0.5 ? 1 : -1;
}
shoot.next -= dt;
if (shoot.t >= 0) {
shoot.t += dt;
if (shoot.t > 0.6) shoot.t = -1;
} else if (shoot.next <= 0) {
shoot.t = 0;
shoot.next = 9 + Math.random() * 16;
shoot.x = 10 + Math.random() * 130;
shoot.y = 2 + Math.random() * 20;
}
}
const plan = stepResident(dt, h, hurry);
drawEarth(h);
drawSky(h);
const state = drawWindow(h);
drawHatch();
drawLights(state, h);
drawResident(plan);
drawParticles(h, dt);
// ---- 材質 → パレット。時刻のかなめのあいだは、ディザで置き換える
pickKeys(h);
const ta = table[keyA];
const tb = table[keyB];
const sa = skyKeys[keyA];
const sb = skyKeys[keyB];
const p = keyP * 16;
const n = bw * bh;
for (let i = 0; i < n; i++) {
const m = matBuf[i];
const useB = thrA[i] < p;
const idx = m === 0 ? (useB ? sb[i] : sa[i]) : (useB ? tb : ta)[varBuf[i] * NM + m];
pixels[i] = palette32[idx];
}
};
// ---- 光の場:世界の光る画素を格子に集めて、ぼかす
const GRID_W = 72;
let GRID_H = 44;
let glowRaw = new Float32Array(1);
let glowNearBuf = new Float32Array(1);
let glowFarBuf = new Float32Array(1);
let glowTemp = new Float32Array(1);
const boxBlur = (src, dst, w, h, r) => {
const size = r * 2 + 1;
for (let y = 0; y < h; y++) {
const row = y * w * 4;
for (let c = 0; c < 3; c++) {
let sum = 0;
for (let x = -r; x <= r; x++) sum += src[row + clamp(x, 0, w - 1) * 4 + c];
for (let x = 0; x < w; x++) {
dst[row + x * 4 + c] = sum / size;
sum += src[row + clamp(x + r + 1, 0, w - 1) * 4 + c] - src[row + clamp(x - r, 0, w - 1) * 4 + c];
}
}
}
for (let x = 0; x < w; x++) {
for (let c = 0; c < 3; c++) {
let sum = 0;
for (let y = -r; y <= r; y++) sum += dst[clamp(y, 0, h - 1) * w * 4 + x * 4 + c];
for (let y = 0; y < h; y++) {
src[y * w * 4 + x * 4 + c] = sum / size;
sum += dst[clamp(y + r + 1, 0, h - 1) * w * 4 + x * 4 + c] - dst[clamp(y - r, 0, h - 1) * w * 4 + x * 4 + c];
}
}
}
};
// ---- WebGL
let gl = null;
try {
gl = canvas.getContext('webgl2', { alpha: true, premultipliedAlpha: true, antialias: false, depth: false, stencil: false, powerPreference: 'high-performance' });
} catch {
gl = null;
}
let program = null;
const loc = {};
let vao = null;
let quad = null;
let texWorld = null;
let texNear = null;
const compile = (type, source) => {
const s = gl.createShader(type);
gl.shaderSource(s, source);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s) || 'shader');
return s;
};
const setupGl = () => {
if (!gl) return false;
try {
program = gl.createProgram();
const v = compile(gl.VERTEX_SHADER, VERT);
const f = compile(gl.FRAGMENT_SHADER, FRAG);
gl.attachShader(program, v);
gl.attachShader(program, f);
gl.bindAttribLocation(program, 0, 'aPos');
gl.linkProgram(program);
gl.deleteShader(v);
gl.deleteShader(f);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(program) || 'link');
} catch (error) {
console.warn('toggle-station: シェーダーを作れないので、2D で描く', error);
return false;
}
gl.useProgram(program);
for (const name of ['uWorld', 'uGlowNear', 'uRes', 'uPill', 'uOrigin', 'uWorldSize', 'uGlowSize', 'uLens', 'uBezel', 'uK', 'uNight', 'uLift', 'uSeam', 'uCalm', 'uShellDay', 'uShellNight', 'uInk', 'uLight', 'uHiNight', 'uLoNight', 'uSkyDay', 'uHomeCol', 'uSkyCol', 'uHomePos', 'uSkyPos']) {
loc[name] = gl.getUniformLocation(program, name);
}
vao = gl.createVertexArray();
gl.bindVertexArray(vao);
quad = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, quad);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
const makeTex = () => {
const t = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, t);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
return t;
};
texWorld = makeTex();
texNear = makeTex();
gl.uniform1i(loc.uWorld, 0);
gl.uniform1i(loc.uGlowNear, 1);
gl.disable(gl.BLEND);
return true;
};
let ready = setupGl();
// 文脈が失われているだけなら、2D へ落とさず戻るのを待つ(スマホでは、タブを離れて戻ると起きる)
let lost = !ready && !!gl && gl.isContextLost();
let ctx2d = null;
let lowCanvas = null;
const useCanvas2d = () => {
// 1つの canvas に2種類の文脈は持てないので、作り直す
const fresh = canvas.cloneNode(false);
canvas.replaceWith(fresh);
canvas = fresh;
ctx2d = canvas.getContext('2d');
};
if (!ready && !lost) useCanvas2d();
// ---- 形と大きさ
const shape = { W: 1, H: 1, cssW: 1, cssH: 1, dpr: 1, pillW: 1, pillH: 1, bezel: 1, winW: 1, winH: 1, r0: 1, travel: 1, travelCss: 1, ox: 0, oy: 0 };
let renderScale = 1;
let fullK = 1; // 解像度を落としていないときの整数倍
let thumbSeam = 1;
// 整数倍を高さで決める。切れるのが 12% までなら大きい方。横は景色が両わきへ広がる
const pickK = (winH) => {
const whole = Math.max(1, Math.floor(winH / CORE_H));
return ((whole + 1) * CORE_H) / winH <= 1.12 ? whole + 1 : whole;
};
const measure = () => {
const box = root.getBoundingClientRect();
const fullDpr = Math.min(2, devicePixelRatio || 1);
const nextFullK = pickK((Math.round(box.height * fullDpr) / 1.32) * (1 - 0.046 * 2));
if (nextFullK !== fullK) {
fullK = nextFullK;
renderScale = 1;
}
const dpr = fullDpr * renderScale;
const W = Math.max(2, Math.round(box.width * dpr));
const H = Math.max(2, Math.round(box.height * dpr));
const changed = W !== shape.W || H !== shape.H;
shape.W = W;
shape.H = H;
shape.cssW = box.width;
shape.cssH = box.height;
shape.dpr = dpr;
// 丸の大きさ:根の中に、1 : 1.85 で置く
shape.pillH = H / 1.32;
shape.pillW = shape.pillH * PILL_RATIO;
shape.bezel = shape.pillH * 0.046;
shape.winW = shape.pillW - shape.bezel * 2;
shape.winH = shape.pillH - shape.bezel * 2;
const gap = shape.pillH * 0.032;
shape.r0 = shape.winH / 2 - gap;
shape.travel = shape.winW - (shape.r0 + gap) * 2;
shape.travelCss = shape.travel / dpr;
// 画素の格子に合わせる(半端な位置だと、全体がにじむ)
canvas.style.width = `${W / dpr}px`;
canvas.style.height = `${H / dpr}px`;
// DPR が上限の 2 を超える端末では、ブラウザが canvas を拡大する。合わせる格子は端末の画素
const grid = Math.max(devicePixelRatio || 1, dpr);
const fx = (box.left * grid) % 1;
const fy = (box.top * grid) % 1;
canvas.style.transform = `translate(${-fx / grid}px, ${-fy / grid}px)`;
if (!changed) return false;
canvas.width = W;
canvas.height = H;
// 解像度を落としても、景色の見え方は変えない(renderScale は整数倍が割り切れる値だけを取る)
k = Math.max(1, Math.round(fullK * renderScale));
const needW = Math.ceil(shape.winW / k) + MARGIN * 2;
const needH = Math.ceil(shape.winH / k) + MARGIN * 2;
bw = needW + (needW & 1);
bh = needH + (needH & 1);
ox = (bw - CORE_W) >> 1;
oy = (bh - CORE_H) >> 1;
matBuf = new Uint8Array(bw * bh);
baseBuf = new Uint8Array(bw * bh);
varBuf = new Uint8Array(bw * bh);
pixels = new Uint32Array(bw * bh);
pixelBytes = new Uint8Array(pixels.buffer);
thrA = new Uint8Array(bw * bh);
for (let y = 0; y < bh; y++) {
for (let x = 0; x < bw; x++) {
// 時刻の置き換えは、空の市松と重ならないよう、位置をずらす
thrA[y * bw + x] = bayerAt(x + 1, y + 2);
}
}
buildBase();
// 世界の左上の、画面の画素での位置(必ず整数)
shape.ox = Math.floor(W / 2 - (bw * k) / 2);
shape.oy = Math.floor(H / 2 + (bh * k) / 2);
thumbSeam = Math.max(1, Math.round(k * 0.055));
GRID_H = Math.max(8, Math.round((GRID_W * H) / W));
const size = GRID_W * GRID_H * 4;
glowRaw = new Float32Array(size);
glowNearBuf = new Float32Array(size);
glowFarBuf = new Float32Array(size);
glowTemp = new Float32Array(size);
if (ready) {
gl.viewport(0, 0, W, H);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texWorld);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, bw, bh, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, texNear);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, GRID_W, GRID_H, 0, gl.RGBA, gl.FLOAT, null);
} else {
lowCanvas = offscreen(bw, bh);
}
return true;
};
const uploadWorld = () => {
// 光の場
glowRaw.fill(0);
for (let e = 0; e < emitList.length; e += 2) {
const i = emitList[e];
const w = emitList[e + 1] / 255;
const px = i % bw;
const py = (i - px) / bw;
const fx = ((shape.ox + (px + 0.5) * k) / shape.W) * GRID_W;
const fy = ((shape.H - shape.oy + (py + 0.5) * k) / shape.H) * GRID_H;
const gx = clamp(Math.floor(fx), 0, GRID_W - 1);
const gy = clamp(Math.floor(fy), 0, GRID_H - 1);
const c = pixels[i];
const at = (gy * GRID_W + gx) * 4;
glowRaw[at] += (c & 255) * w * 0.0007;
glowRaw[at + 1] += ((c >>> 8) & 255) * w * 0.0007;
glowRaw[at + 2] += ((c >>> 16) & 255) * w * 0.0007;
}
glowNearBuf.set(glowRaw);
boxBlur(glowNearBuf, glowTemp, GRID_W, GRID_H, 1);
boxBlur(glowNearBuf, glowTemp, GRID_W, GRID_H, 1);
// 芯のにじみに、広いにじみを足す
glowFarBuf.set(glowRaw);
boxBlur(glowFarBuf, glowTemp, GRID_W, GRID_H, 3);
boxBlur(glowFarBuf, glowTemp, GRID_W, GRID_H, 3);
for (let i = 0; i < glowNearBuf.length; i++) glowNearBuf[i] += glowFarBuf[i] * 0.55;
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texWorld);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, bw, bh, gl.RGBA, gl.UNSIGNED_BYTE, pixelBytes);
gl.generateMipmap(gl.TEXTURE_2D);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, texNear);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, GRID_W, GRID_H, gl.RGBA, gl.FLOAT, glowNearBuf);
};
// ---- つまみの状態
let x = 0; // 0 = 昼、1 = 夜
let velocity = 0;
let target = 0;
let moving = false;
let checked = false;
let stretch = 0;
let stretchV = 0;
let lift = 0;
let liftTarget = 0;
let hurry = 0;
// 時間の流れ:右へは昼から夜へ。右端から戻るときは、日の出を通って次の昼へ
let branch = 'pm';
let amStart = CLOCK_NIGHT;
let nightClock = CLOCK_NIGHT;
const clockOf = () => {
if (branch === 'am') return mix(36, amStart, x);
if (x >= 1) return nightClock;
return CLOCK_DAY + (CLOCK_NIGHT - CLOCK_DAY) * x;
};
const beginTravel = () => {
if (x <= 0.0005) branch = 'pm';
else if (x >= 0.9995) {
branch = 'am';
amStart = nightClock;
}
};
const setStatus = (text) => {
if (statusEl.textContent !== text) statusEl.textContent = text;
};
const phaseName = (h) => (h < 5 || h >= 20 ? '夜' : h < 7 ? '夜明け' : h < 10 ? '朝' : h < 16.5 ? '昼' : '夕方');
const commit = (value) => {
const night = value >= 1;
x = night ? 1 : 0;
velocity = 0;
moving = false;
if (night) {
nightClock = branch === 'am' ? amStart : CLOCK_NIGHT;
branch = 'pm';
} else {
branch = 'pm';
}
if (checked !== night) {
checked = night;
button.setAttribute('aria-checked', String(night));
root.dispatchEvent(new CustomEvent('daylight:change', { bubbles: true, composed: true, detail: { night } }));
}
setStatus(night ? '夜' : '昼');
};
// ---- 描く
const drawGl = (night) => {
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(program);
gl.bindVertexArray(vao);
gl.uniform2f(loc.uRes, shape.W, shape.H);
gl.uniform2f(loc.uPill, shape.pillW / 2, shape.pillH / 2);
gl.uniform2f(loc.uOrigin, shape.ox, shape.oy);
gl.uniform2f(loc.uWorldSize, bw, bh);
gl.uniform2f(loc.uGlowSize, GRID_W, GRID_H);
gl.uniform1f(loc.uBezel, shape.bezel);
gl.uniform1f(loc.uK, k);
gl.uniform1f(loc.uNight, night);
gl.uniform1f(loc.uLift, lift);
gl.uniform1f(loc.uSeam, thumbSeam);
gl.uniform1f(loc.uCalm, calm ? 1 : 0);
// レンズの形:動くと伸び、離すと弾んで戻る
const s = clamp(stretch, -0.5, 1.2);
const r = shape.r0 * (1 + 0.012 * lift);
const halfX = r * (1 + 0.2 * s);
const halfY = r * (1 - 0.075 * s);
const lim = shape.winW / 2 - (shape.winH / 2 - shape.r0) - halfX;
const raw = (x - 0.5) * shape.travel;
const cx = clamp(raw, -lim, lim);
gl.uniform4f(loc.uLens, cx, 0, halfX, halfY);
gl.uniform3fv(loc.uShellDay, unit(C3));
gl.uniform3fv(loc.uShellNight, unit(I1));
gl.uniform3fv(loc.uInk, unit(I0));
gl.uniform3fv(loc.uLight, unit(C3));
gl.uniform3fv(loc.uHiNight, unit(I3));
gl.uniform3fv(loc.uLoNight, unit(I0));
gl.uniform3fv(loc.uSkyDay, unit(U2));
// 光る画素の重心と強さ。人影が窓を隠せば弱くなる
const homeW = sources[0].w;
const home = unit(A2);
const homeI = (homeW / 255 / 150) * 1.05;
const hx = homeW > 0 ? shape.ox + (sources[0].x / homeW + 0.5) * k - shape.W / 2 : 0;
const hy = homeW > 0 ? shape.oy - (sources[0].y / homeW + 0.5) * k - shape.H / 2 : 0;
gl.uniform2f(loc.uHomePos, hx, hy);
gl.uniform3f(loc.uHomeCol, home[0] * homeI, home[1] * homeI, home[2] * homeI);
const skyW = sources[1].w;
const skyU = unit(A3);
const skyI = (skyW / 255 / 110) * 0.55;
const sx = skyW > 0 ? shape.ox + (sources[1].x / skyW + 0.5) * k - shape.W / 2 : 0;
const sy = skyW > 0 ? shape.oy - (sources[1].y / skyW + 0.5) * k - shape.H / 2 : 0;
gl.uniform2f(loc.uSkyPos, sx, sy);
gl.uniform3f(loc.uSkyCol, skyU[0] * skyI, skyU[1] * skyI, skyU[2] * skyI);
gl.drawArrays(gl.TRIANGLES, 0, 3);
};
const draw2d = (night) => {
// WebGL が使えないとき:世界だけを整数倍で写し、丸く切って、つまみを置く
const g = ctx2d;
const low = lowCanvas.getContext('2d');
low.putImageData(new ImageData(new Uint8ClampedArray(pixels.buffer), bw, bh), 0, 0);
g.clearRect(0, 0, shape.W, shape.H);
const px = (shape.W - shape.pillW) / 2;
const py = (shape.H - shape.pillH) / 2;
g.save();
g.beginPath();
g.roundRect(px, py, shape.pillW, shape.pillH, shape.pillH / 2);
g.clip();
g.imageSmoothingEnabled = false;
g.drawImage(lowCanvas, shape.ox, shape.H - shape.oy, bw * k, bh * k);
g.restore();
const cx = shape.W / 2 + (x - 0.5) * shape.travel;
const light = unit(C3).map((v) => Math.round(v * 255));
g.fillStyle = `rgb(${light[0]} ${light[1]} ${light[2]} / 0.5)`;
g.beginPath();
g.arc(cx, shape.H / 2, shape.r0, 0, Math.PI * 2);
g.fill();
return night;
};
// ---- 時間を進める
let raf = 0;
let last = 0;
let visible = true;
let pageVisible = root.ownerDocument.visibilityState !== 'hidden';
let worldAcc = 1;
let dirty = true;
let slow = 0;
let good = 0;
let frames = 0;
let lastWorldClock = -1;
let lastNightText = '';
let drag = null;
const nightAmount = (h) => clamp(smoothstep(17.4, 20.2, h) + (1 - smoothstep(4.8, 7.2, h)));
// 描くのに本当に時間がかかっているときだけ、細かさを落とす。
// コマが少ないだけでは決めない。省電力モードやブラウザの間引きで 30 コマになっている端末では、解像度を下げても速くならず、絵だけが悪くなる。
const OVERLOAD_MS = 12;
const COST_SAMPLES = 5;
const onePixel = new Uint8Array(4);
let costLeft = 0;
let costs = [];
let weighedOnce = false;
const lowerResolution = () => {
// 整数倍が割り切れる値にだけ下げる。景色の見え方は変わらない
const next = (k - 1) / fullK;
if (k < 2 || next < 0.5) {
frames = -600; // もう下げられない。しばらく測らない
return;
}
renderScale = next;
measure();
dirty = true;
lastWorldClock = -1;
frames = 0;
};
const adapt = (dt) => {
++frames;
// 重い GPU でも、世界だけが動く 30 コマなら遅れが見えないことがある。つまみを動かす前に、一度は測っておく
if (frames === 40 && !weighedOnce) {
weighedOnce = true;
costLeft = COST_SAMPLES;
costs = [];
}
if (frames < 40) return;
if (dt > 0.0225) slow++;
else good++;
if (slow + good < 50) return;
const suspect = slow > 30;
slow = 0;
good = 0;
if (suspect) {
costLeft = COST_SAMPLES;
costs = [];
}
};
const weighCost = (startedAt) => {
// readPixels は、ここまでの描画が終わるのを待つ。これで GPU の分も含めた1コマの重さがわかる
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, onePixel);
costs.push(performance.now() - startedAt);
if (--costLeft > 0) return;
const median = costs.sort((a, b) => a - b)[costs.length >> 1];
if (median > OVERLOAD_MS) lowerResolution();
else frames = -600; // 重くないなら、しばらく測らない
};
const tick = (ms) => {
raf = 0;
if (lost) return;
const t = ms / 1000;
const dt = last ? Math.min(0.05, t - last) : 1 / 60;
last = t;
if (!calm && ready) adapt(dt);
// ---- つまみ
if (drag) {
const before = x;
x += (clamp(drag.want) - x) * (1 - Math.exp(-dt * 34));
velocity = (x - before) / Math.max(dt, 1 / 240);
dirty = true;
} else if (moving) {
// なめらかに減速して吸い付く
const omega = calm ? 16 : 9.5;
const accel = omega * omega * (target - x) - 2 * omega * velocity;
velocity += accel * dt;
x += velocity * dt;
dirty = true;
if (Math.abs(target - x) < 0.0015 && Math.abs(velocity) < 0.03) {
x = target;
if (x <= 0 || x >= 1) {
if (!calm) stretchV -= 3.2;
commit(x);
} else {
velocity = 0;
moving = false;
}
}
x = clamp(x);
} else {
velocity = 0;
}
// ---- レンズの弾み
if (!calm) {
const goal = clamp(Math.abs(velocity) * 0.42);
stretchV += (170 * (goal - stretch) - 11 * stretchV) * dt;
stretch += stretchV * dt;
lift += (liftTarget - lift) * (1 - Math.exp(-dt * 14));
if (Math.abs(stretch) > 0.002 || Math.abs(stretchV) > 0.01 || Math.abs(liftTarget - lift) > 0.002) dirty = true;
} else {
stretch = 0;
stretchV = 0;
lift = liftTarget;
}
// ---- 右端では、時間が静かに進み、やがて灯りを消して眠る
if (!calm && x >= 1 && !moving && !drag && nightClock < CLOCK_SLEEP) {
nightClock = Math.min(CLOCK_SLEEP, nightClock + (dt * (CLOCK_SLEEP - CLOCK_NIGHT)) / NIGHT_CREEP);
}
const clock = clockOf();
hurry = Math.max(hurry - dt * 1.4, clamp(Math.abs(velocity) * 0.6));
// ---- 世界は 30 コマで動く
worldAcc += dt;
const worldStep = calm ? Math.abs(clock - lastWorldClock) > 1e-4 || dirty : worldAcc >= 1 / WORLD_HZ - WORLD_SLACK;
if (worldStep) {
renderWorld(clock, Math.min(worldAcc, 0.1), hurry);
worldAcc = 0;
lastWorldClock = clock;
if (ready) uploadWorld();
dirty = true;
}
if (dirty) {
const night = nightAmount(hourOf(clock));
// 世界の暗さ(0 = 昼、1 = 夜)。使い手はこの値で、ページの地を合わせられる。変わったときだけ書く
const nightText = night.toFixed(3);
if (nightText !== lastNightText) {
lastNightText = nightText;
root.style.setProperty('--night', nightText);
}
if (ready) {
const startedAt = costLeft > 0 ? performance.now() : 0;
drawGl(night);
if (startedAt) weighCost(startedAt);
} else {
draw2d(night);
}
dirty = false;
}
// 動きを減らす設定で止まっているときは、次の操作まで描かない
const idleCalm = calm && !moving && !drag;
if (visible && pageVisible && !idleCalm) raf = requestAnimationFrame(tick);
};
function stopDrawing() {
if (raf) cancelAnimationFrame(raf);
raf = 0;
}
function wake() {
if (!raf && visible && pageVisible && !lost) {
last = 0;
raf = requestAnimationFrame(tick);
}
}
// ---- 速く動かすと、飛行士が驚いて手足を広げる
let startleCool = 0;
const startle = () => {
if (calm || performance.now() < startleCool) return;
startleCool = performance.now() + 1500;
res.startle = 0.9;
};
// ---- 入力
let suppressClick = 0;
on(button, 'pointerdown', (event) => {
if (event.button !== 0) return;
beginTravel();
moving = false;
drag = { id: event.pointerId, start: event.clientX, from: x, want: x, moved: false, lastX: event.clientX, lastT: performance.now(), speed: 0 };
liftTarget = 1;
try {
button.setPointerCapture(event.pointerId);
} catch {
/* 取れなくても、動きは受けられる */
}
wake();
});
on(button, 'pointermove', (event) => {
if (!drag || event.pointerId !== drag.id) return;
const dx = event.clientX - drag.start;
if (Math.abs(dx) > 3) drag.moved = true;
drag.want = drag.from + dx / Math.max(shape.travelCss, 1);
const nowMs = performance.now();
const dtMs = Math.max(nowMs - drag.lastT, 4);
const speed = (event.clientX - drag.lastX) / Math.max(shape.travelCss, 1) / (dtMs / 1000);
drag.speed = drag.speed * 0.6 + speed * 0.4;
drag.lastX = event.clientX;
drag.lastT = nowMs;
if (Math.abs(drag.speed) > 3.4) startle();
wake();
});
const release = (event) => {
if (!drag || event.pointerId !== drag.id) return;
const wasMoved = drag.moved;
const speed = drag.speed;
drag = null;
liftTarget = 0;
if (wasMoved) {
suppressClick = performance.now() + 300;
// 近い方の端へ。勢いも少し数える
target = x + speed * 0.09 >= 0.5 ? 1 : 0;
velocity = clamp(speed, -3, 3);
moving = true;
}
wake();
};
on(button, 'pointerup', release);
on(button, 'pointercancel', release);
on(button, 'lostpointercapture', release);
const toggle = () => {
beginTravel();
target = (moving ? target >= 0.5 : x >= 0.5) ? 0 : 1;
moving = true;
wake();
};
on(button, 'click', () => {
if (performance.now() < suppressClick) return;
toggle();
});
const STEP = 0.04;
on(button, 'keydown', (event) => {
let dir = 0;
if (event.key === 'ArrowRight' || event.key === 'ArrowUp') dir = 1;
else if (event.key === 'ArrowLeft' || event.key === 'ArrowDown') dir = -1;
if (!dir) return;
event.preventDefault();
beginTravel();
const from = moving ? target : x;
target = clamp(from + dir * STEP);
moving = true;
setStatus(phaseName(hourOf(branch === 'am' ? mix(36, amStart, target) : CLOCK_DAY + (CLOCK_NIGHT - CLOCK_DAY) * target)));
wake();
});
// ---- 見えていないときは止める
const io = new IntersectionObserver((entries) => {
visible = entries.some((e) => e.isIntersecting);
if (visible) {
dirty = true;
wake();
} else {
stopDrawing();
}
});
io.observe(root);
on(root.ownerDocument, 'visibilitychange', () => {
pageVisible = root.ownerDocument.visibilityState !== 'hidden';
if (pageVisible) {
dirty = true;
wake();
if (lost) waitForRestore();
} else {
stopDrawing();
clearTimeout(restoreTimer);
}
});
const ro = new ResizeObserver(() => {
measure();
dirty = true;
lastWorldClock = -1;
wake();
});
ro.observe(root);
const applyCalm = () => {
calm = motionQuery.matches;
dirty = true;
lastWorldClock = -1;
wake();
};
on(motionQuery, 'change', applyCalm);
on(schemeQuery, 'change', () => {
readPalette();
dirty = true;
lastWorldClock = -1;
wake();
});
// ---- WebGL の文脈が失われたら、戻るのを待って描き直す。戻らなければ 2D で描く
const RESTORE_WAIT_MS = 3000;
let restoreTimer = 0;
const redrawAll = () => {
shape.W = 0; // 大きさが同じでも、画像を作り直す
measure();
dirty = true;
lastWorldClock = -1;
worldAcc = 1;
wake();
};
function waitForRestore() {
clearTimeout(restoreTimer);
restoreTimer = setTimeout(() => {
if (!lost || !pageVisible) return;
lost = false;
useCanvas2d();
redrawAll();
}, RESTORE_WAIT_MS);
}
on(canvas, 'webglcontextlost', (event) => {
event.preventDefault();
ready = false;
lost = true;
costLeft = 0;
stopDrawing();
if (pageVisible) waitForRestore();
});
on(canvas, 'webglcontextrestored', () => {
if (ctx2d) return; // もう 2D で描いている
clearTimeout(restoreTimer);
lost = false;
ready = setupGl();
if (!ready) useCanvas2d();
redrawAll();
});
// ---- 組み立て
readPalette();
measure();
if (lost) waitForRestore();
res.x = WORK_X;
res.inside = false;
// 最初の絵を、はじめのフレームまでに用意する
renderWorld(clockOf(), 0, 0);
if (ready) uploadWorld();
wake();
return () => {
stopDrawing();
clearTimeout(restoreTimer);
visible = false;
io.disconnect();
ro.disconnect();
for (const off of cleanups) off();
if (gl && ready) {
gl.deleteProgram(program);
gl.deleteBuffer(quad);
gl.deleteVertexArray(vao);
gl.deleteTexture(texWorld);
gl.deleteTexture(texNear);
const lose = gl.getExtension('WEBGL_lose_context');
if (lose) lose.loseContext();
}
};
}
mount(document.querySelector('[data-ld-part="toggle-station"]'));
</script>
@Lattice_Node
@Lattice_Node
@Lattice_Node
@Lattice_Node
@Lattice_Node
@Lattice_Node
@Lattice_Node
@Lattice_Node
@Lattice_Node
@Lattice_Node
@Lattice_Node
@Lattice_Node
@Lattice_Node
@Lattice_Node
@Lattice_Node
@Lattice_Node
@Lattice_Node
@Lattice_Node