Initial commit for Pixeltation pixel art meditation app

- Browser-based calm pixel art meditations with a main menu and player UI
- Rendering engine (Surface, PixelCanvas, Loop, Timeline, color/rng/sprite/audio)
  that draws scenes as pure functions of time into a 320x180 buffer
- First "Northern Cabin" meditation: sunset-to-night lake scene with animated
  snow, stars, aurora, moon, fire, and a man gathering wood
- Dev tools: hash-based routing, time/speed query params, and a headless PNG
  snapshot script for checking frames without a browser
This commit is contained in:
Brian Fertig 2026-10-29 19:33:35 -06:00
commit 42bf83c3ca
32 changed files with 4429 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
node_modules
dist
snapshots
*.log

32
README.md Normal file
View File

@ -0,0 +1,32 @@
# Pixeltation
Calm pixel art meditations for the browser. Pick a journey from the main menu, settle in, and watch.
## Run
```bash
npm install
npm run dev # http://localhost:5173
npm run build # static site in dist/
```
## Meditations
| id | Title | Length |
|---|---|---|
| `northern-cabin` | Northern Cabin — winter sunset by a quiet lake | 5 min |
Each meditation lives in `src/meditations/<id>/` and is registered in `src/meditations/registry.ts`.
A scene is a pure function of time (`render(surface, t)`), drawn pixel by pixel into a 320×180 buffer
that is scaled up crisply, so all art is generated in code.
## Music
Drop an audio file in `public/audio/` and set `music: 'audio/<file>.mp3'` on the meditation
(e.g. in `src/meditations/northern-cabin/index.ts`). It fades in at the start and out over the last 10 seconds.
## Dev tools
- `#/m/northern-cabin?t=150&speed=10` starts at 150 s and plays at 10× (dev server only).
- `[` / `]` skip back/forward 10 s while playing (dev server only).
- `npm run snapshot -- northern-cabin 0 120 200` renders frames to `snapshots/` as PNGs without a browser.

21
index.html Normal file
View File

@ -0,0 +1,21 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Pixeltation — calm pixel art meditations." />
<meta name="theme-color" content="#0b0f1e" />
<title>Pixeltation</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8' shape-rendering='crispEdges'%3E%3Crect width='8' height='8' fill='%230b0f1e'/%3E%3Cpath d='M1 5h6v2H1z' fill='%23e8eeff'/%3E%3Cpath d='M2 3h4v2H2z' fill='%237c4e34'/%3E%3Cpath d='M3 2h2v1H3z' fill='%23e8eeff'/%3E%3Cpath d='M3 4h1v1H3z' fill='%23ffb866'/%3E%3C/svg%3E" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Pixelify+Sans:wght@400;500;600&family=Silkscreen&display=swap"
rel="stylesheet"
/>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

1696
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

20
package.json Normal file
View File

@ -0,0 +1,20 @@
{
"name": "pixeltation",
"private": true,
"version": "0.1.0",
"type": "module",
"description": "Pixel art meditations",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview",
"typecheck": "tsc --noEmit",
"snapshot": "tsx scripts/snapshot.ts"
},
"devDependencies": {
"@types/node": "^26.6.6",
"tsx": "^4.23.15",
"typescript": "^7.0.2",
"vite": "^8.3.5"
}
}

0
public/audio/.gitkeep Normal file
View File

Binary file not shown.

61
scripts/snapshot.ts Normal file
View File

@ -0,0 +1,61 @@
/**
* Render frames of a meditation to PNG without a browser, for checking timing and art.
* npm run snapshot -- northern-cabin 0 120 200 280
* Output goes to snapshots/<id>-<t>.png at 3x scale.
*/
import { mkdirSync, writeFileSync } from 'node:fs';
import { crc32, deflateSync } from 'node:zlib';
import { Surface } from '../src/engine/Surface';
import { findMeditation, meditations } from '../src/meditations/registry';
const SCALE = 3;
function png(w: number, h: number, rgba: Uint8ClampedArray): Buffer {
const raw = Buffer.alloc((w * 4 + 1) * h);
for (let y = 0; y < h; y++) {
raw[y * (w * 4 + 1)] = 0;
Buffer.from(rgba.buffer, rgba.byteOffset + y * w * 4, w * 4).copy(raw, y * (w * 4 + 1) + 1);
}
const chunk = (type: string, data: Buffer) => {
const len = Buffer.alloc(4);
len.writeUInt32BE(data.length);
const td = Buffer.concat([Buffer.from(type), data]);
const crc = Buffer.alloc(4);
crc.writeUInt32BE(crc32(td));
return Buffer.concat([len, td, crc]);
};
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(w, 0);
ihdr.writeUInt32BE(h, 4);
ihdr[8] = 8;
ihdr[9] = 6;
return Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
chunk('IHDR', ihdr),
chunk('IDAT', deflateSync(raw)),
chunk('IEND', Buffer.alloc(0)),
]);
}
const [id, ...times] = process.argv.slice(2);
const m = findMeditation(id ?? '');
if (!m) {
console.error(`Usage: npm run snapshot -- <id> <seconds...>\nKnown ids: ${meditations.map((x) => x.id).join(', ')}`);
process.exit(1);
}
const scene = m.createScene();
const s = new Surface(320, 180);
mkdirSync('snapshots', { recursive: true });
for (const t of times.length ? times.map(Number) : [m.previewTime]) {
scene.render(s, t);
const big = new Uint8ClampedArray(s.w * SCALE * s.h * SCALE * 4);
for (let y = 0; y < s.h * SCALE; y++) {
for (let x = 0; x < s.w * SCALE; x++) {
const si = (((y / SCALE) | 0) * s.w + ((x / SCALE) | 0)) * 4;
big.set(s.data.subarray(si, si + 4), (y * s.w * SCALE + x) * 4);
}
}
const file = `snapshots/${m.id}-${String(t).padStart(3, '0')}.png`;
writeFileSync(file, png(s.w * SCALE, s.h * SCALE, big));
console.log(file);
}

27
src/engine/Loop.ts Normal file
View File

@ -0,0 +1,27 @@
/** requestAnimationFrame loop that reports elapsed seconds (clamped so a background tab doesn't jump). */
export class Loop {
private raf = 0;
private last = 0;
private running = false;
constructor(private readonly tick: (dt: number) => void) {}
start(): void {
if (this.running) return;
this.running = true;
this.last = performance.now();
this.raf = requestAnimationFrame(this.frame);
}
stop(): void {
this.running = false;
cancelAnimationFrame(this.raf);
}
private frame = (now: number): void => {
const dt = Math.min(0.1, (now - this.last) / 1000);
this.last = now;
this.tick(dt);
if (this.running) this.raf = requestAnimationFrame(this.frame);
};
}

50
src/engine/PixelCanvas.ts Normal file
View File

@ -0,0 +1,50 @@
import { Surface } from './Surface';
/**
* Presents a low-res Surface on a <canvas>, scaled up by the largest whole number of
* device pixels that fits the parent so pixels stay perfectly square and crisp.
*/
export class PixelCanvas {
readonly canvas: HTMLCanvasElement;
readonly surface: Surface;
private readonly ctx: CanvasRenderingContext2D;
private readonly image: ImageData;
constructor(
private readonly parent: HTMLElement,
w = 320,
h = 180,
) {
this.canvas = document.createElement('canvas');
this.canvas.width = w;
this.canvas.height = h;
this.canvas.className = 'pixel-canvas';
this.ctx = this.canvas.getContext('2d')!;
this.surface = new Surface(w, h);
this.image = new ImageData(this.surface.data, w, h);
parent.appendChild(this.canvas);
window.addEventListener('resize', this.resize);
document.addEventListener('fullscreenchange', this.resize);
this.resize();
}
resize = (): void => {
const { w, h } = this.surface;
const dpr = window.devicePixelRatio || 1;
const fit = Math.min(this.parent.clientWidth / w, this.parent.clientHeight / h) * dpr;
// Whole-number scaling keeps every art pixel the same size; tiny screens fall back to a plain fit.
const scale = fit >= 2 ? Math.floor(fit) : fit;
this.canvas.style.width = `${(w * scale) / dpr}px`;
this.canvas.style.height = `${(h * scale) / dpr}px`;
};
present(): void {
this.ctx.putImageData(this.image, 0, 0);
}
destroy(): void {
window.removeEventListener('resize', this.resize);
document.removeEventListener('fullscreenchange', this.resize);
this.canvas.remove();
}
}

92
src/engine/Surface.ts Normal file
View File

@ -0,0 +1,92 @@
import { bayer, type RGB } from './color';
/**
* A low-resolution RGBA framebuffer that scenes draw into pixel by pixel.
* It has no DOM dependency so frames can also be rendered in Node (see scripts/snapshot.ts).
*/
export class Surface {
readonly data: Uint8ClampedArray<ArrayBuffer>;
constructor(
readonly w: number,
readonly h: number,
) {
this.data = new Uint8ClampedArray(new ArrayBuffer(w * h * 4));
}
fill(c: RGB): void {
const d = this.data;
for (let i = 0; i < d.length; i += 4) {
d[i] = c[0];
d[i + 1] = c[1];
d[i + 2] = c[2];
d[i + 3] = 255;
}
}
set(x: number, y: number, c: RGB): void {
x |= 0;
y |= 0;
if (x < 0 || y < 0 || x >= this.w || y >= this.h) return;
const i = (y * this.w + x) * 4;
const d = this.data;
d[i] = c[0];
d[i + 1] = c[1];
d[i + 2] = c[2];
d[i + 3] = 255;
}
/** Alpha-blend a color over the existing pixel. */
blend(x: number, y: number, c: RGB, a: number): void {
if (!(a > 0)) return; // also rejects NaN
if (a >= 1) return this.set(x, y, c);
x |= 0;
y |= 0;
if (x < 0 || y < 0 || x >= this.w || y >= this.h) return;
const i = (y * this.w + x) * 4;
const d = this.data;
d[i] += (c[0] - d[i]) * a;
d[i + 1] += (c[1] - d[i + 1]) * a;
d[i + 2] += (c[2] - d[i + 2]) * a;
}
/** Additive light: brightens the existing pixel by c * k. */
light(x: number, y: number, c: RGB, k: number): void {
if (!(k > 0)) return;
x |= 0;
y |= 0;
if (x < 0 || y < 0 || x >= this.w || y >= this.h) return;
const i = (y * this.w + x) * 4;
const d = this.data;
d[i] += c[0] * k;
d[i + 1] += c[1] * k;
d[i + 2] += c[2] * k;
}
/** Set the pixel only where the ordered-dither threshold falls under `a` — a pixel-art friendly "alpha". */
dither(x: number, y: number, c: RGB, a: number): void {
if (a > bayer(x | 0, y | 0)) this.set(x, y, c);
}
get(x: number, y: number): [number, number, number] {
x = Math.max(0, Math.min(this.w - 1, x | 0));
y = Math.max(0, Math.min(this.h - 1, y | 0));
const i = (y * this.w + x) * 4;
return [this.data[i], this.data[i + 1], this.data[i + 2]];
}
rect(x: number, y: number, w: number, h: number, c: RGB, a = 1): void {
for (let yy = y; yy < y + h; yy++) for (let xx = x; xx < x + w; xx++) this.blend(xx, yy, c, a);
}
/** Fade the whole frame toward black; k = 1 leaves it untouched. */
darken(k: number): void {
if (k >= 1) return;
const d = this.data;
for (let i = 0; i < d.length; i += 4) {
d[i] *= k;
d[i + 1] *= k;
d[i + 2] *= k;
}
}
}

44
src/engine/Timeline.ts Normal file
View File

@ -0,0 +1,44 @@
import { mix, type RGB } from './color';
export type Ease = (x: number) => number;
export const ease = {
linear: (x: number) => x,
/** Gentle start and end — the default for anything meant to feel calm. */
sine: (x: number) => 0.5 - 0.5 * Math.cos(Math.PI * x),
in: (x: number) => x * x,
out: (x: number) => 1 - (1 - x) * (1 - x),
} satisfies Record<string, Ease>;
export const clamp01 = (x: number): number => (x < 0 ? 0 : x > 1 ? 1 : x);
/** Eased 0→1 progress of t through [a, b]. */
export function progress(t: number, a: number, b: number, e: Ease = ease.sine): number {
return e(clamp01((t - a) / (b - a)));
}
/** Keyframed number: holds the first/last value outside the keyed range. */
export function track(keys: readonly (readonly [number, number])[], e: Ease = ease.sine): (t: number) => number {
return (t) => {
if (t <= keys[0][0]) return keys[0][1];
for (let i = 0; i < keys.length - 1; i++) {
const [t0, v0] = keys[i];
const [t1, v1] = keys[i + 1];
if (t < t1) return v0 + (v1 - v0) * e((t - t0) / (t1 - t0));
}
return keys[keys.length - 1][1];
};
}
/** Keyframed color, same semantics as `track`. */
export function colorTrack(keys: readonly (readonly [number, RGB])[], e: Ease = ease.sine): (t: number) => RGB {
return (t) => {
if (t <= keys[0][0]) return keys[0][1];
for (let i = 0; i < keys.length - 1; i++) {
const [t0, c0] = keys[i];
const [t1, c1] = keys[i + 1];
if (t < t1) return mix(c0, c1, e((t - t0) / (t1 - t0)));
}
return keys[keys.length - 1][1];
};
}

47
src/engine/audio.ts Normal file
View File

@ -0,0 +1,47 @@
/**
* Optional background music for a meditation. Fades in at the start and out at the end,
* and does nothing at all when no track is configured.
*/
export class Music {
private readonly el?: HTMLAudioElement;
constructor(
src?: string,
private readonly volume = 0.8,
private readonly fadeIn = 4,
private readonly fadeOut = 10,
) {
if (!src) return;
this.el = new Audio(src);
this.el.preload = 'auto';
this.el.volume = 0;
}
play(): void {
this.el?.play().catch(() => {
/* autoplay blocked or file missing — the meditation works fine without sound */
});
}
pause(): void {
this.el?.pause();
}
seek(t: number): void {
if (this.el && Number.isFinite(this.el.duration)) this.el.currentTime = t % this.el.duration;
}
/** Call every frame with the meditation clock. */
update(t: number, duration: number): void {
if (!this.el) return;
const k = Math.max(0, Math.min(1, t / this.fadeIn, (duration - t) / this.fadeOut));
this.el.volume = k * this.volume;
}
destroy(): void {
if (!this.el) return;
this.el.pause();
this.el.removeAttribute('src');
this.el.load();
}
}

47
src/engine/color.ts Normal file
View File

@ -0,0 +1,47 @@
export type RGB = readonly [number, number, number];
export function hex(h: string): RGB {
const n = parseInt(h.replace('#', ''), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
export function lerp(a: number, b: number, t: number): number {
return a + (b - a) * t;
}
export function mix(a: RGB, b: RGB, t: number): RGB {
return [lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t)];
}
/** Component-wise multiply, used to apply ambient light to a base color. */
export function mul(c: RGB, k: RGB): RGB {
return [c[0] * k[0], c[1] * k[1], c[2] * k[2]];
}
export function scale(c: RGB, k: number): RGB {
return [c[0] * k, c[1] * k, c[2] * k];
}
export function add(a: RGB, b: RGB, k = 1): RGB {
return [a[0] + b[0] * k, a[1] + b[1] * k, a[2] + b[2] * k];
}
export function css(c: RGB, a = 1): string {
return `rgba(${c[0] | 0},${c[1] | 0},${c[2] | 0},${a})`;
}
/** Sample a list of evenly spaced color stops at u in [0, 1]. */
export function gradient(stops: readonly RGB[], u: number): RGB {
if (u <= 0) return stops[0];
if (u >= 1) return stops[stops.length - 1];
const f = u * (stops.length - 1);
const i = Math.floor(f);
return mix(stops[i], stops[i + 1], f - i);
}
const BAYER4 = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];
/** Ordered-dither threshold in (0, 1) for a pixel position. */
export function bayer(x: number, y: number): number {
return (BAYER4[(y & 3) * 4 + (x & 3)] + 0.5) / 16;
}

54
src/engine/rng.ts Normal file
View File

@ -0,0 +1,54 @@
/** Seeded PRNG (mulberry32) so every playthrough of a scene looks identical. */
export class Rng {
private s: number;
constructor(seed: number) {
this.s = seed >>> 0;
}
next(): number {
let t = (this.s += 0x6d2b79f5);
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
range(a: number, b: number): number {
return a + (b - a) * this.next();
}
int(a: number, b: number): number {
return Math.floor(this.range(a, b + 1));
}
}
/** Stateless hash of integer coordinates to [0, 1). */
export function hash(x: number, y = 0, seed = 0): number {
let h = (x | 0) * 374761393 + (y | 0) * 668265263 + seed * 2147483647;
h = Math.imul(h ^ (h >>> 13), 1274126177);
h ^= h >>> 16;
return (h >>> 0) / 4294967296;
}
/** Smooth 1D value noise in [0, 1). */
export function noise1(x: number, seed = 0): number {
const i = Math.floor(x);
const f = x - i;
const u = f * f * (3 - 2 * f);
return hash(i, 0, seed) * (1 - u) + hash(i + 1, 0, seed) * u;
}
/** Smooth 2D value noise in [0, 1). */
export function noise2(x: number, y: number, seed = 0): number {
const ix = Math.floor(x);
const iy = Math.floor(y);
const fx = x - ix;
const fy = y - iy;
const ux = fx * fx * (3 - 2 * fx);
const uy = fy * fy * (3 - 2 * fy);
const a = hash(ix, iy, seed);
const b = hash(ix + 1, iy, seed);
const c = hash(ix, iy + 1, seed);
const d = hash(ix + 1, iy + 1, seed);
return a + (b - a) * ux + (c - a) * uy + (a - b - c + d) * ux * uy;
}

30
src/engine/sprite.ts Normal file
View File

@ -0,0 +1,30 @@
import type { RGB } from './color';
import type { Surface } from './Surface';
/**
* A sprite authored as rows of characters; each character is a palette key and '.' is transparent.
* Kept as data so colors can be re-lit every frame.
*/
export type SpriteArt = readonly string[];
export function drawSprite(
s: Surface,
art: SpriteArt,
x: number,
y: number,
palette: Readonly<Record<string, RGB>>,
flip = false,
alpha = 1,
): void {
const w = art[0].length;
for (let r = 0; r < art.length; r++) {
const row = art[r];
for (let c = 0; c < w; c++) {
const ch = row[c];
if (ch === '.' || ch === undefined) continue;
const col = palette[ch];
if (!col) continue;
s.blend(x + (flip ? w - 1 - c : c), y + r, col, alpha);
}
}
}

28
src/main.ts Normal file
View File

@ -0,0 +1,28 @@
import './styles.css';
import { findMeditation } from './meditations/registry';
import { Menu, type View } from './ui/Menu';
import { Player } from './ui/Player';
const app = document.getElementById('app')!;
let current: View | undefined;
/** Dev helpers: #/m/<id>?t=150&speed=10 jumps into a meditation at 150s, running 10x. */
function devParams(query: string): { startAt?: number; speed?: number } {
if (!import.meta.env.DEV) return {};
const p = new URLSearchParams(query);
const num = (k: string) => (p.has(k) ? Number(p.get(k)) : undefined);
return { startAt: num('t'), speed: num('speed') };
}
function route(): void {
current?.destroy();
const [path, query = ''] = location.hash.replace(/^#/, '').split('?');
const match = path.match(/^\/m\/([\w-]+)$/);
const meditation = match ? findMeditation(match[1]) : undefined;
current = meditation
? new Player(app, meditation, { onExit: () => (location.hash = '#/'), ...devParams(query) })
: new Menu(app, (id) => (location.hash = `#/m/${id}`));
}
window.addEventListener('hashchange', route);
route();

View File

@ -0,0 +1,300 @@
import { add, hex, mix, type RGB } from '../../engine/color';
import { hash } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import { doorOpen, logsTaken } from './man';
import { lit, type Frame } from './timeline';
import { CABIN, CHIMNEY, DOOR, GABLE_WINDOW, GROUND, WINDOWS, WOODPILE } from './world';
const LOG = hex('#7c4e34');
const LOG_TOP = hex('#94603e');
const LOG_GAP = hex('#3e2418');
const LOG_END = hex('#caa070');
const LOG_END_RING = hex('#8a6040');
const BOARD = hex('#6a4430');
const BOARD_SEAM = hex('#4a2e20');
const FASCIA = hex('#3a2622');
const SNOW = hex('#f4f6ff');
const SNOW_SHADE = hex('#c2cae8');
const ICICLE = hex('#cfe4ff');
const STONE = hex('#8c8a98');
const STONE_LIGHT = hex('#a8a4b2');
const MORTAR = hex('#5a5868');
const FRAME = hex('#3a2820');
const GLASS = hex('#6d80b8');
const DOOR_WOOD = hex('#6a4028');
const DOOR_DARK = hex('#4a2a1a');
const INTERIOR = hex('#120c0c');
const FIRE_CORE = hex('#ffd27a');
const FIRE_MID = hex('#ff9a3a');
const FIRE_EDGE = hex('#e0582a');
const SUN_WARM = hex('#ffb080');
/** Warm colors for a window pane: brighter toward the hearth (bottom) and wavering a little per pane. */
function fireColor(f: Frame, pane: number, y01: number): RGB {
const w = Math.sin(f.t * (2.3 + pane * 0.7) + pane * 1.9) * 0.15;
const k = Math.max(0, Math.min(1, y01 * 0.8 + 0.2 + w));
return k > 0.55 ? mix(FIRE_MID, FIRE_CORE, (k - 0.55) / 0.45) : mix(FIRE_EDGE, FIRE_MID, k / 0.55);
}
function drawChimney(s: Surface, f: Frame): void {
const stone = lit(f, STONE);
const stoneLight = add(lit(f, STONE_LIGHT), SUN_WARM, f.warm * 0.15);
const mortar = lit(f, MORTAR);
for (let y = CHIMNEY.top + 1; y <= CHIMNEY.bottom; y++) {
const row = Math.floor((y - CHIMNEY.top - 1) / 3);
const within = (y - CHIMNEY.top - 1) % 3;
for (let x = CHIMNEY.x0; x <= CHIMNEY.x1; x++) {
const joint = (x - CHIMNEY.x0 + (row % 2) * 2) % 4 === 0;
let c = within === 2 || joint ? mortar : stone;
if (c === stone && (x === CHIMNEY.x1 || hash(x, y, 81) > 0.8)) c = stoneLight;
s.set(x, y, c);
}
}
const snow = lit(f, SNOW);
for (let x = CHIMNEY.x0 - 1; x <= CHIMNEY.x1 + 1; x++) {
s.set(x, CHIMNEY.top, mortar);
if (x !== CHIMNEY.x0 + 3) s.set(x, CHIMNEY.top - 1, snow);
}
// The flue opening glows faintly once the fire is going.
s.blend(CHIMNEY.x0 + 3, CHIMNEY.top - 1, FIRE_MID, f.fire * 0.5);
}
function drawWalls(s: Surface, f: Frame): void {
const log = lit(f, LOG);
const logTop = add(lit(f, LOG_TOP), SUN_WARM, f.warm * 0.1);
const gap = lit(f, LOG_GAP);
const end = add(lit(f, LOG_END), SUN_WARM, f.warm * 0.1);
const ring = lit(f, LOG_END_RING);
for (let y = CABIN.wallTop; y <= CABIN.base; y++) {
const r = y - CABIN.wallTop;
const within = r % 3;
for (let x = CABIN.x0; x <= CABIN.x1; x++) {
let c = within === 0 ? logTop : within === 2 ? gap : log;
if (within === 1 && hash(x, y, 82) > 0.86) c = gap;
s.set(x, y, c);
}
// Round log ends at the corners, alternating overhang like notched logs.
const stick = Math.floor(r / 3) % 2 === 0 ? 2 : 3;
for (let k = 1; k <= stick; k++) {
const c = within === 2 ? gap : k === stick ? ring : end;
s.set(CABIN.x0 - k, y, c);
s.set(CABIN.x1 + k, y, c);
}
}
// Shadow under the eaves.
const shadow = lit(f, hex('#1a1014'));
for (let y = CABIN.wallTop; y < CABIN.wallTop + 3; y++) {
for (let x = CABIN.x0 - 3; x <= CABIN.x1 + 3; x++) s.blend(x, y, shadow, y === CABIN.wallTop ? 0.6 : 0.3);
}
// Snow drifted against the base.
const snow = lit(f, SNOW);
const snowShade = lit(f, SNOW_SHADE);
for (let x = CABIN.x0 - 4; x <= CABIN.x1 + 4; x++) {
if (x >= DOOR.x0 - 1 && x <= DOOR.x1 + 1) continue;
const h = 1 + Math.floor(hash(x >> 1, 0, 83) * 3);
for (let y = CABIN.base - h + 1; y <= CABIN.base; y++) s.set(x, y, y === CABIN.base - h + 1 ? snow : snowShade);
}
}
function drawGableAndRoof(s: Surface, f: Frame): void {
const board = lit(f, BOARD);
const seam = lit(f, BOARD_SEAM);
const fascia = lit(f, FASCIA);
const snow = add(lit(f, SNOW), SUN_WARM, f.warm * 0.18);
const snowShade = lit(f, SNOW_SHADE);
for (let y = CABIN.peakY - 2; y <= CABIN.eaveY + 1; y++) {
const hw = Math.floor(CABIN.roofHalf(y));
for (let dx = -hw; dx <= hw; dx++) {
const x = CABIN.centerX + dx;
const edge = hw - Math.abs(dx);
const lump = hash(x >> 1, 0, 84) > 0.6 ? 1 : 0;
let c: RGB;
if (y < CABIN.peakY) c = snow;
else if (edge < 2 + lump) c = dx > 0 ? snow : edge === 0 ? snow : snowShade;
else if (edge < 4 + lump) c = fascia;
else c = (x - CABIN.centerX + 64) % 4 === 0 ? seam : board;
s.set(x, y, c);
}
}
// Snow cap over the peak.
for (let dx = -2; dx <= 2; dx++) s.set(CABIN.centerX + dx, CABIN.peakY - 3, snow);
// Snow overhanging the eaves, with a few icicles.
const ice = lit(f, ICICLE);
for (const side of [-1, 1]) {
const tip = CABIN.centerX + side * Math.floor(CABIN.roofHalf(CABIN.eaveY));
for (let k = 0; k < 6; k++) s.set(tip - side * k, CABIN.eaveY + 1, k < 4 ? snow : snowShade);
for (const [off, len] of [
[1, 3],
[3, 2],
[5, 4],
]) {
for (let j = 0; j < len; j++) s.blend(tip - side * off, CABIN.eaveY + 2 + j, ice, 0.85 - j * 0.18);
}
}
}
function drawWindow(s: Surface, f: Frame, x0: number, y0: number, w: number, h: number, pane0: number): void {
const frame = lit(f, FRAME);
const glass = mix(lit(f, GLASS), f.horizonColor, 0.35);
const midX = x0 + Math.floor(w / 2);
const midY = y0 + Math.floor(h / 2);
for (let y = y0; y < y0 + h; y++) {
for (let x = x0; x < x0 + w; x++) {
const border = x === x0 || y === y0 || x === x0 + w - 1 || y === y0 + h - 1;
if (border || x === midX || y === midY) {
s.set(x, y, frame);
continue;
}
const pane = pane0 + (x > midX ? 1 : 0) + (y > midY ? 2 : 0);
let c = glass;
// Cold reflection glint on the upper-left of each pane.
const glint = (x === x0 + 1 || x === midX + 1) && (y === y0 + 1 || y === midY + 1);
if (glint) c = mix(glass, [255, 255, 255], 0.25 * (1 - f.fire));
c = mix(c, fireColor(f, pane, (y - y0) / h), Math.min(1, f.fire * 1.1));
s.set(x, y, c);
}
}
// Snowy sill.
const snow = lit(f, SNOW);
for (let x = x0 - 1; x <= x0 + w; x++) s.set(x, y0 + h, snow);
// Warm halo on the logs around the window.
if (f.fire > 0) {
for (let y = y0 - 4; y < y0 + h + 4; y++) {
for (let x = x0 - 4; x < x0 + w + 4; x++) {
const dx = Math.max(x0 - x, 0, x - (x0 + w - 1));
const dy = Math.max(y0 - y, 0, y - (y0 + h - 1));
const d = Math.max(dx, dy);
if (d === 0 || d > 4) continue;
s.blend(x, y, FIRE_MID, f.fire * 0.2 * (1 - d / 5));
}
}
}
}
function drawDoor(s: Surface, f: Frame): void {
const open = doorOpen(f.t);
const wood = lit(f, DOOR_WOOD);
const dark = lit(f, DOOR_DARK);
const frame = lit(f, FRAME);
const w = DOOR.x1 - DOOR.x0 + 1;
// Hinged on the left, swinging inward: the slab narrows as it opens.
const slab = Math.round((1 - open) * (w - 2)) + 2;
for (let y = DOOR.y0; y <= DOOR.y1; y++) {
for (let x = DOOR.x0; x <= DOOR.x1; x++) {
const border = x === DOOR.x0 || x === DOOR.x1 || y === DOOR.y0;
let c: RGB;
if (border) c = frame;
else if (x - DOOR.x0 < slab) c = (x - DOOR.x0) % 3 === 0 || open > 0 ? dark : wood;
else c = INTERIOR;
s.set(x, y, c);
}
}
if (open === 0) {
s.set(DOOR.x1 - 2, DOOR.y0 + 8, lit(f, hex('#c8a060')));
// Firelight leaks through the gaps around a closed door.
if (f.fire > 0) {
for (let y = DOOR.y0 + 1; y <= DOOR.y1; y++) s.blend(DOOR.x1 - 1, y, FIRE_MID, f.fire * 0.35);
for (let x = DOOR.x0 + 1; x < DOOR.x1; x++) s.blend(x, DOOR.y1, FIRE_MID, f.fire * 0.5);
}
}
// Wooden step.
const step = lit(f, hex('#5a3a28'));
const snow = lit(f, SNOW);
for (let x = DOOR.x0 - 2; x <= DOOR.x1 + 2; x++) {
s.set(x, DOOR.y1 + 1, hash(x, 0, 85) > 0.6 ? snow : step);
}
}
/** Log ends stacked in the woodpile; the first entries are taken first. */
const PILE_LOGS: { x: number; y: number; capped: boolean }[] = [
// top row (snow-capped), taken on the first trip and the start of the second
{ x: 120, y: 138, capped: true },
{ x: 123, y: 138, capped: true },
{ x: 117, y: 138, capped: true },
{ x: 114, y: 138, capped: true },
{ x: 121, y: 141, capped: false },
{ x: 118, y: 141, capped: false },
{ x: 124, y: 141, capped: true },
{ x: 115, y: 141, capped: false },
{ x: 112, y: 141, capped: true },
...[111, 114, 117, 120, 123, 126].map((x) => ({ x, y: 144, capped: x === 126 })),
];
function drawWoodpile(s: Surface, f: Frame): void {
const post = lit(f, hex('#4a3226'));
const roof = lit(f, FASCIA);
const snow = add(lit(f, SNOW), SUN_WARM, f.warm * 0.15);
const snowShade = lit(f, SNOW_SHADE);
// Lean-to roof sloping away from the cabin wall.
for (let x = CABIN.x1 + 1; x <= WOODPILE.x1 + 2; x++) {
const yy = 131 + Math.round(((x - CABIN.x1 - 1) * 3) / 24);
s.set(x, yy + 1, roof);
s.set(x, yy + 2, roof);
s.set(x, yy, snow);
if (hash(x, 0, 86) > 0.4) s.set(x, yy - 1, snow);
}
for (let y = 134; y <= WOODPILE.base; y++) s.set(WOODPILE.x1 + 1, y, post);
// Dark back of the shelter.
const back = lit(f, hex('#24161a'));
for (let y = 134; y <= WOODPILE.base; y++) for (let x = WOODPILE.x0; x <= WOODPILE.x1; x++) s.set(x, y, back);
const end = add(lit(f, LOG_END), SUN_WARM, f.warm * 0.1);
const ring = lit(f, LOG_END_RING);
const bark = lit(f, hex('#4a3020'));
const taken = logsTaken(f.t);
PILE_LOGS.forEach((l, i) => {
if (i < taken) return;
for (let dy = 0; dy < 3; dy++) {
for (let dx = 0; dx < 3; dx++) {
const corner = (dx === 0 || dx === 2) && (dy === 0 || dy === 2);
s.set(l.x + dx, l.y + dy, corner ? bark : dx === 1 && dy === 1 ? ring : end);
}
}
if (l.capped) for (let dx = 0; dx < 3; dx++) s.set(l.x + dx, l.y - 1, dx === 1 ? snow : snowShade);
});
// Chopping stump with a resting axe.
const sx = 142;
const sy = 146;
for (let x = sx; x < sx + 6; x++) {
s.set(x, sy, end);
for (let y = sy + 1; y < sy + 4; y++) s.set(x, y, x === sx || x === sx + 5 ? bark : lit(f, LOG));
}
const handle = lit(f, hex('#8a6a48'));
for (let k = 0; k < 6; k++) s.set(sx + 1 + k, sy - 5 + k, handle);
s.set(sx + 1, sy - 5, lit(f, hex('#9a9eae')));
s.set(sx + 2, sy - 6, lit(f, hex('#9a9eae')));
s.set(sx, sy - 6, lit(f, hex('#6a6e7e')));
}
/** Window light pooling on the snow in front of the cabin. */
function drawLightSpill(s: Surface, f: Frame): void {
if (f.fire <= 0) return;
const light = hex('#ff9a48');
const pools = [...WINDOWS.map((w) => w.x0 + w.w / 2 - 0.5), DOOR.x0 + 4];
for (let y = CABIN.base + 1; y < CABIN.base + 18; y++) {
for (let x = CABIN.x0 - 14; x <= CABIN.x1 + 14; x++) {
if (y < GROUND[x]) continue;
let k = 0;
pools.forEach((cx, i) => {
const strength = i < WINDOWS.length ? 1 : 0.35;
const d = Math.hypot((x - cx) / 16, (y - CABIN.base - 1) / 12);
k += strength * Math.pow(Math.max(0, 1 - d), 1.4);
});
// Hard-edged bands of light read as pixel art without speckle.
s.light(x, y, light, (Math.floor(Math.min(1, k) * 5) / 5) * 0.62 * f.fire);
}
}
}
export function drawCabin(s: Surface, f: Frame): void {
drawChimney(s, f);
drawWalls(s, f);
drawGableAndRoof(s, f);
WINDOWS.forEach((w, i) => drawWindow(s, f, w.x0, w.y0, w.w, w.h, i * 4));
const g = GABLE_WINDOW;
drawWindow(s, f, g.x0, g.y0, g.w, g.h, 8);
drawDoor(s, f);
drawWoodpile(s, f);
drawLightSpill(s, f);
}

View File

@ -0,0 +1,38 @@
import type { Meditation, Scene } from '../types';
import { drawCabin } from './cabin';
import { drawForegroundPines, drawGround, drawLake, drawMidPines, drawMountains } from './landscape';
import { drawFootprints, drawMan } from './man';
import { drawSky } from './sky';
import { DURATION, frameAt } from './timeline';
import { drawFarSnow, drawNearSnow, drawSmoke } from './weather';
const scene: Scene = {
render(s, t) {
const f = frameAt(t);
drawSky(s, f);
drawMountains(s, f);
drawLake(s, f);
drawGround(s, f);
drawFootprints(s, f);
drawFarSnow(s, f);
drawMidPines(s, f);
drawCabin(s, f);
drawMan(s, f);
drawSmoke(s, f);
drawForegroundPines(s, f);
drawNearSnow(s, f);
s.darken(f.fade);
},
};
export const northernCabin: Meditation = {
id: 'northern-cabin',
title: 'Northern Cabin',
subtitle: 'Winter sunset by a quiet lake',
description:
'Light snow drifts over a lakeside cabin as the sun slips behind the mountains. Watch the evening settle, the stars come out, and a fire bring the cabin to life.',
music: 'audio/northern-cabin.mp3',
duration: DURATION,
previewTime: 236,
createScene: () => scene,
};

View File

@ -0,0 +1,202 @@
import { add, bayer, hex, mix, scale, type RGB } from '../../engine/color';
import { progress } from '../../engine/Timeline';
import { hash, noise1, noise2 } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import { lit, type Frame } from './timeline';
import { GROUND, H, HORIZON, RIDGE_FAR, RIDGE_NEAR, W } from './world';
const ROCK = hex('#6c6e9c');
const ROCK_SHADE = hex('#4e4c7c');
const SNOW = hex('#f4f6ff');
const SNOW_MID = hex('#d4dbf2');
const SNOW_SHADE = hex('#a6b0d8');
const ALPENGLOW = hex('#ff9aa4');
const SUN_WARM = hex('#ffb080');
const HILLS = hex('#33465a');
const HILLS_DARK = hex('#24334a');
const FAR_TREES = hex('#22323e');
const WATER = hex('#2a3c6e');
const ICE = hex('#c4d2ee');
const PINE_DARK = hex('#1c3832');
const PINE_LIGHT = hex('#2f5a48');
const PINE_SNOW = hex('#e8eeff');
const TRUNK = hex('#3a2a22');
export function drawMountains(s: Surface, f: Frame): void {
const fogFar = 0.42;
const rock = mix(lit(f, ROCK), f.horizonColor, fogFar);
const rockShade = mix(lit(f, ROCK_SHADE), f.horizonColor, fogFar);
let snowLit = add(lit(f, SNOW), SUN_WARM, f.warm * 0.12);
snowLit = mix(snowLit, ALPENGLOW, f.alpenglow * 0.6);
snowLit = mix(snowLit, f.horizonColor, fogFar * 0.7);
const snowShade = mix(lit(f, SNOW_SHADE), f.horizonColor, fogFar * 0.8);
for (let x = 0; x < W; x++) {
const top = RIDGE_FAR[x];
const facesSun = (RIDGE_FAR[Math.min(W - 1, x + 2)] ?? top) >= (RIDGE_FAR[Math.max(0, x - 2)] ?? top);
const capDepth = top < 86 ? 3 + Math.floor(noise1(x / 6, 31) * 6) + Math.floor((86 - top) * 0.35) : 1;
for (let y = top; y < HORIZON; y++) {
const d = y - top;
// Snow-filled gullies running diagonally down the faces.
const gully = noise1((x + (facesSun ? -d : d) * 0.9) / 2.2, 33);
const streak = gully > 0.72 - d * 0.004 && d < capDepth + 9 && hash(x, y, 34) > 0.2;
let c: RGB;
if (d < capDepth || streak) c = facesSun ? snowLit : snowShade;
else c = facesSun ? rock : rockShade;
s.set(x, y, c);
}
}
// Forested hills, with a bumpy treetop silhouette.
const hills = mix(lit(f, HILLS), f.horizonColor, 0.22);
const hillsDark = mix(lit(f, HILLS_DARK), f.horizonColor, 0.2);
for (let x = 0; x < W; x++) {
const top = RIDGE_NEAR[x] - (hash(x, 0, 41) > 0.55 ? 1 : 0) - (hash(x >> 1, 0, 42) > 0.8 ? 1 : 0);
for (let y = top; y < HORIZON; y++) {
s.set(x, y, noise2(x / 4, y / 3, 43) + (y - top) * 0.04 > 0.75 ? hillsDark : hills);
}
}
// Tiny pines along the far shore.
const trees = mix(lit(f, FAR_TREES), f.horizonColor, 0.18);
for (let x = 0; x < W; x += 2) {
const dense = noise1(x / 25, 51);
if (hash(x, 0, 52) > dense + 0.25) continue;
const h = 3 + Math.floor(hash(x, 1, 53) * 4 + dense * 4);
const cx = x + (hash(x, 2, 54) > 0.5 ? 1 : 0);
for (let k = 0; k < h; k++) {
const hw = Math.floor(k * 0.4);
for (let dx = -hw; dx <= hw; dx++) s.set(cx + dx, HORIZON - h + k, trees);
}
}
for (let x = 0; x < W; x++) s.set(x, HORIZON - 1, trees);
}
/** The lake mirrors whatever was drawn above the horizon, with gentle ripples. */
export function drawLake(s: Surface, f: Frame): void {
const t = f.t;
const tint = lit(f, WATER);
const ice = lit(f, ICE);
const glitter = f.sunColor;
const moonGlitter = hex('#e8ecff');
const maxY = Math.max(...GROUND);
for (let y = HORIZON; y < maxY; y++) {
const depth = y - HORIZON;
const sy = HORIZON - 1 - depth;
for (let x = 0; x < W; x++) {
if (y >= GROUND[x]) continue;
const wob = Math.round(Math.sin(y * 0.9 + t * 1.1 + x * 0.04) * (0.4 + depth / 28));
const src = s.get(x + wob, sy);
let c = mix(scale(src, 0.86), tint, 0.14 + depth * 0.006);
const ripple = noise2(x * 0.07 - t * 0.04, y * 0.8, 61);
if (ripple > 0.74) c = scale(c, 1.14);
else if (ripple < 0.2) c = scale(c, 0.9);
s.set(x, y, c);
// Broken glitter path beneath the sun, and later the moon.
const sunW = 3 + depth * 0.12;
if (f.sunVis > 0 && Math.abs(x - f.sunX) < sunW && noise2(x * 0.18, y * 1.7 + t * 0.6, 62) > 0.6) {
s.blend(x, y, glitter, 0.6 * f.sunVis * (1 - Math.abs(x - f.sunX) / sunW));
}
const moonVis = progress(f.night, 0.3, 0.8);
const moonW = 1.5 + depth * 0.15;
if (moonVis > 0 && f.moonY < HORIZON - 4 && Math.abs(x - f.moonX) < moonW && noise2(x * 0.2, y * 1.7 + t * 0.5, 63) > 0.66) {
s.blend(x, y, moonGlitter, 0.3 * moonVis);
}
if (y >= GROUND[x] - 2) s.blend(x, y, ice, 0.45);
}
}
}
export function drawGround(s: Surface, f: Frame): void {
const warmth = f.warm * 0.22;
const tones: RGB[] = [
add(add(lit(f, SNOW), SUN_WARM, warmth), [6, 6, 10]),
add(lit(f, SNOW_MID), SUN_WARM, warmth * 0.6),
lit(f, SNOW_SHADE),
];
for (let x = 0; x < W; x++) {
const top = GROUND[x];
for (let y = top; y < H; y++) {
let idx: number;
if (y - top < 2) idx = 0;
else {
const v = noise2(x * 0.028, y * 0.17, 71) + (y - top) * 0.002;
idx = Math.max(0, Math.min(2, Math.floor(v * 2.4 + (bayer(x, y) - 0.5) * 0.6 - 0.35)));
}
s.set(x, y, tones[idx]);
// Occasional glints of light on the crust.
const g = hash(x, y, 72);
if (g > 0.996) {
const tw = 0.5 + 0.5 * Math.sin(f.t * 1.7 + g * 4000);
s.blend(x, y, [255, 255, 255], tw * (0.35 + 0.4 * (1 - f.night)));
}
}
}
}
export interface PineOpts {
seed: number;
/** Mix toward the horizon color for distance. */
fog?: number;
/** Extra darkening for foreground silhouettes. */
dim?: number;
/** How quickly the branches widen toward the base. */
spread?: number;
}
const pineHalf = (r: number, h: number, spread: number) => {
if (r < 0) return -1;
const tiers = Math.max(3, Math.round(h / 8));
const th = h / tiers;
const local = (r % th) / th;
return Math.floor((r * spread + 1) * (0.42 + 0.58 * local));
};
export function drawPine(s: Surface, f: Frame, cx: number, baseY: number, h: number, o: PineOpts): void {
const fog = o.fog ?? 0;
const dim = o.dim ?? 1;
const spread = o.spread ?? 0.3;
const tone = (c: RGB) => mix(scale(lit(f, c), dim), f.horizonColor, fog);
const dark = tone(PINE_DARK);
const light = mix(tone(PINE_LIGHT), dark, f.night * 0.6);
const snow = tone(add(PINE_SNOW, SUN_WARM, f.warm * 0.15));
const trunk = tone(TRUNK);
const top = baseY - h - 3;
for (let r = 0; r < h; r++) {
const hw = pineHalf(r, h, spread);
const above = pineHalf(r - 1, h, spread);
for (let dx = -hw; dx <= hw; dx++) {
const x = cx + dx;
const y = top + r;
const exposed = Math.abs(dx) > above || r === 0;
let c = dx > 0 && hash(x, y, o.seed) > 0.25 ? light : dark;
if (exposed && hash(x, y, o.seed + 1) < 0.85) c = snow;
else if (Math.abs(dx) === hw && hash(x, y, o.seed + 2) < 0.3) c = snow;
s.set(x, y, c);
}
}
for (let y = baseY - 3; y < baseY; y++) {
s.set(cx - 1, y, trunk);
s.set(cx, y, trunk);
}
}
/** Pines on the shore around the cabin (drawn before the cabin). */
export function drawMidPines(s: Surface, f: Frame): void {
drawPine(s, f, 62, 129, 54, { seed: 101, fog: 0.08 });
drawPine(s, f, 97, 128, 46, { seed: 102, fog: 0.08 });
drawPine(s, f, 22, 141, 62, { seed: 103 });
drawPine(s, f, 36, 143, 46, { seed: 104 });
drawPine(s, f, 138, 138, 42, { seed: 105 });
drawPine(s, f, 152, 134, 32, { seed: 106, fog: 0.05 });
drawPine(s, f, 165, 133, 22, { seed: 107, fog: 0.1 });
}
/** Large near pines framing the edges of the view. */
export function drawForegroundPines(s: Surface, f: Frame): void {
drawPine(s, f, 4, 186, 168, { seed: 201, dim: 0.55, spread: 0.17 });
drawPine(s, f, 310, 186, 140, { seed: 202, dim: 0.55, spread: 0.18 });
drawPine(s, f, 289, 184, 64, { seed: 203, dim: 0.7, spread: 0.26 });
}

View File

@ -0,0 +1,322 @@
import { hex, mix, type RGB } from '../../engine/color';
import { drawSprite, type SpriteArt } from '../../engine/sprite';
import { ease, progress } from '../../engine/Timeline';
import type { Surface } from '../../engine/Surface';
import { lit, TIMES, type Frame } from './timeline';
import { MAN } from './world';
// ---------------------------------------------------------------------------
// Sprites (facing right; mirrored when walking left). Upper body is 9 rows, legs 4 rows.
// ---------------------------------------------------------------------------
const UPPER_STAND: SpriteArt = [
'..hhh..',
'.hHhhh.',
'..hses.',
'..bsss.',
'..bbb..',
'.cCccc.',
'.cCcccc',
'.cCccc.',
'.gcccg.',
];
const UPPER_CARRY: SpriteArt = [
'..hhh..',
'.hHhhh.',
'..hses.',
'..bsss.',
'..bbb..',
'.cCcccc',
'.cCccgg',
'.cCccc.',
'.cCccc.',
];
const LEGS_STAND: SpriteArt = ['..pppp.', '..p..p.', '..p..p.', '..kk.kk'];
const LEGS_STRIDE: SpriteArt = ['..pppp.', '.pp..pp', '.p....p', 'kk....k'];
const LEGS_PASS: SpriteArt = ['..ppp..', '..ppp..', '...pp..', '...kkk.'];
/** Bent over the woodpile, reaching down (13 rows, same baseline). */
const BEND: SpriteArt = [
'.......',
'.......',
'.......',
'.......',
'...hhh.',
'..hhHhh',
'.cCchse',
'cCcccbs',
'cCccccb',
'.cpppcg',
'..p..pg',
'..p..p.',
'..kk.kk',
];
const BASE: Record<string, RGB> = {
h: hex('#5a3e2c'),
H: hex('#7a5a40'),
s: hex('#e6ac8a'),
e: hex('#2a1c18'),
b: hex('#8a5a3a'),
c: hex('#c24a3c'),
C: hex('#8a302c'),
g: hex('#3a2c26'),
p: hex('#3c4258'),
k: hex('#2a2222'),
};
const LOG_BARK_DARK = hex('#4a3020');
const LOG_END = hex('#d2a46c');
const DOORWAY_DARK = hex('#120c0c');
const BREATH = hex('#f0f4ff');
// ---------------------------------------------------------------------------
// Choreography
// ---------------------------------------------------------------------------
type Action = 'doorOpen' | 'emerge' | 'idle' | 'walkOut' | 'gather' | 'turn' | 'walkBack' | 'enter' | 'doorClose';
interface Beat {
action: Action;
t0: number;
t1: number;
}
interface Trip {
beats: Beat[];
logs: number;
start: number;
end: number;
}
function makeTrip(start: number, logs: number, d: Record<Action, number>): Trip {
const order: Action[] = ['doorOpen', 'emerge', 'idle', 'walkOut', 'gather', 'turn', 'walkBack', 'enter', 'doorClose'];
let t = start;
const beats = order.map((action) => {
const b = { action, t0: t, t1: t + d[action] };
t = b.t1;
return b;
});
return { beats, logs, start, end: t };
}
/** Two unhurried trips to the woodpile; the second is a little slower, as evening settles in. */
const TRIPS: Trip[] = [
makeTrip(TIMES.trip1, 3, {
doorOpen: 3,
emerge: 1.5,
idle: 4.5,
walkOut: 5.5,
gather: 9.5,
turn: 1,
walkBack: 6.5,
enter: 1.5,
doorClose: 3,
}),
makeTrip(TIMES.trip2, 3, {
doorOpen: 3,
emerge: 1.5,
idle: 2,
walkOut: 6,
gather: 10.5,
turn: 1,
walkBack: 7,
enter: 1.5,
doorClose: 3,
}),
];
const beatOf = (trip: Trip, a: Action) => trip.beats.find((b) => b.action === a)!;
function currentBeat(t: number): { trip: Trip; beat: Beat; index: number } | undefined {
for (let i = 0; i < TRIPS.length; i++) {
const trip = TRIPS[i];
if (t < trip.start || t >= trip.end) continue;
const beat = trip.beats.find((b) => t >= b.t0 && t < b.t1)!;
return { trip, beat, index: i };
}
return undefined;
}
/** How far the door is open, 0–1. */
export function doorOpen(t: number): number {
for (const trip of TRIPS) {
const open = beatOf(trip, 'doorOpen');
const close = beatOf(trip, 'doorClose');
if (t >= open.t0 && t < close.t1) return progress(t, open.t0, open.t1) * (1 - progress(t, close.t0, close.t1));
}
return 0;
}
/** Logs picked up during a trip's gather beat by time t. */
function pickedInTrip(trip: Trip, t: number): number {
const g = beatOf(trip, 'gather');
if (t < g.t0) return 0;
const per = (g.t1 - g.t0) / trip.logs;
// Each log is lifted a little before the middle of its bend-and-stand cycle.
return Math.min(trip.logs, Math.floor((t - g.t0) / per + 0.55));
}
/** Total logs removed from the woodpile so far. */
export function logsTaken(t: number): number {
return TRIPS.reduce((n, trip) => n + pickedInTrip(trip, t), 0);
}
/** Footprints pressed into the snow on the first walk out; they slowly soften under new snow. */
const PRINTS = (() => {
const walk = beatOf(TRIPS[0], 'walkOut');
const out: { x: number; y: number; at: number }[] = [];
for (let x = MAN.doorX + 3, i = 0; x < MAN.pileX - 1; x += 3, i++) {
const u = (x - MAN.doorX) / (MAN.pileX - MAN.doorX);
// Invert the eased walk to find when he passed this spot.
let lo = 0;
let hi = 1;
for (let k = 0; k < 20; k++) {
const mid = (lo + hi) / 2;
if (ease.sine(mid) < u) lo = mid;
else hi = mid;
}
out.push({ x, y: MAN.feetY + 1 + (i % 2), at: walk.t0 + lo * (walk.t1 - walk.t0) });
}
return out;
})();
export function drawFootprints(s: Surface, f: Frame): void {
const c = lit(f, hex('#8e98c8'));
for (const p of PRINTS) {
if (f.t < p.at) continue;
const a = 0.75 - Math.min(0.4, (f.t - p.at) / 300);
s.blend(p.x, p.y, c, a);
s.blend(p.x + 1, p.y, c, a * 0.8);
}
}
// ---------------------------------------------------------------------------
// Drawing
// ---------------------------------------------------------------------------
function compose(upper: SpriteArt, legs: SpriteArt): SpriteArt {
return [...upper, ...legs];
}
/** Logs cradled in his arms are seen end-on: a little pyramid of pale end grain at his chest. */
const CARRY_SPOTS = [
[4, 6],
[6, 6],
[5, 4],
] as const;
function drawCarriedLogs(s: Surface, f: Frame, x: number, top: number, n: number, flip: boolean, k: number): void {
const end = mix(lit(f, LOG_END), DOORWAY_DARK, 1 - k);
const bark = mix(lit(f, LOG_BARK_DARK), DOORWAY_DARK, 1 - k);
for (let i = 0; i < Math.min(n, CARRY_SPOTS.length); i++) {
const [ox, oy] = CARRY_SPOTS[i];
for (let dy = 0; dy < 2; dy++) {
for (let dx = 0; dx < 2; dx++) {
const px = flip ? x + 6 - (ox + dx) : x + ox + dx;
s.set(px, top + oy + dy, dx === 1 && dy === 1 ? bark : end);
}
}
}
}
function drawBreath(s: Surface, f: Frame, x: number, top: number, flip: boolean): void {
const period = 3.4;
const age = f.t % period;
if (age > 1.5) return;
const u = age / 1.5;
const mouthX = flip ? x : x + 6;
const dir = flip ? -1 : 1;
const a = 0.55 * (1 - u) * Math.min(1, age * 4);
const c = mix(lit(f, BREATH), BREATH, 0.3);
const px = mouthX + dir * (1 + u * 3);
const py = top + 3 - u * 3;
s.blend(px, py, c, a);
if (u > 0.3) {
s.blend(px + dir, py, c, a * 0.7);
s.blend(px, py - 1, c, a * 0.6);
}
}
export function drawMan(s: Surface, f: Frame): void {
const cur = currentBeat(f.t);
if (!cur) return;
const { trip, beat } = cur;
const t = f.t;
const { doorX, pileX, feetY } = MAN;
const top = feetY - 12;
const local = (t - beat.t0) / (beat.t1 - beat.t0);
let x = doorX;
let flip = false;
let art: SpriteArt = compose(UPPER_STAND, LEGS_STAND);
let carry = 0;
/** 0 = lost in the dark doorway, 1 = fully outside. */
let presence = 1;
let breathe = true;
const walkLegs = (dist: number) => {
const phase = Math.floor(dist / 2.5) % 4;
return phase === 0 ? LEGS_STRIDE : phase === 2 ? LEGS_STRIDE : LEGS_PASS;
};
switch (beat.action) {
case 'doorOpen':
case 'doorClose':
return;
case 'emerge':
presence = ease.sine(local);
breathe = false;
break;
case 'idle':
break;
case 'walkOut': {
const u = ease.sine(local);
x = doorX + (pileX - doorX) * u;
art = compose(UPPER_STAND, walkLegs(x - doorX));
break;
}
case 'gather': {
x = pileX;
const per = 1 / trip.logs;
const cycle = (local % per) / per;
carry = pickedInTrip(trip, t);
if (cycle < 0.55) {
art = BEND;
breathe = false;
} else {
art = compose(carry > 0 ? UPPER_CARRY : UPPER_STAND, LEGS_STAND);
}
break;
}
case 'turn':
x = pileX;
carry = trip.logs;
flip = local > 0.4;
art = compose(UPPER_CARRY, LEGS_STAND);
break;
case 'walkBack': {
const u = ease.sine(local);
x = pileX + (doorX - pileX) * u;
flip = true;
carry = trip.logs;
art = compose(UPPER_CARRY, walkLegs(pileX - x));
break;
}
case 'enter':
flip = true;
carry = trip.logs;
art = compose(UPPER_CARRY, LEGS_STAND);
presence = 1 - ease.sine(local);
breathe = false;
break;
}
const sx = Math.round(x) - 3;
const palette: Record<string, RGB> = {};
for (const [k, c] of Object.entries(BASE)) palette[k] = mix(lit(f, c), DOORWAY_DARK, 1 - presence);
drawSprite(s, art, sx, top, palette, flip, Math.min(1, presence * 1.5));
if (carry > 0 && art !== BEND) drawCarriedLogs(s, f, sx, top, carry, flip, presence);
if (breathe) drawBreath(s, f, sx, top, flip);
}

View File

@ -0,0 +1,141 @@
import { bayer, hex, mix, type RGB } from '../../engine/color';
import { progress } from '../../engine/Timeline';
import { Rng } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import { SKY_BANDS, SUN_R, TIMES, type Frame } from './timeline';
import { HORIZON, W } from './world';
interface Star {
x: number;
y: number;
mag: number;
appear: number;
twinkle: number;
phase: number;
tint: RGB;
}
const STARS: Star[] = (() => {
const r = new Rng(42);
const out: Star[] = [];
for (let i = 0; i < 150; i++) {
const mag = Math.pow(r.next(), 2.2);
const span = TIMES.starsTo - TIMES.starsFrom;
out.push({
x: r.int(0, W - 1),
y: r.int(0, HORIZON - 14),
mag,
// Brightest stars come out first, like a real dusk.
appear: TIMES.starsFrom + (1 - mag) * span * 0.75 + r.range(0, span * 0.2),
twinkle: r.range(0.4, 1.6),
phase: r.range(0, Math.PI * 2),
tint: r.next() < 0.2 ? hex('#cfdcff') : r.next() < 0.3 ? hex('#ffe8c8') : hex('#ffffff'),
});
}
return out;
})();
const AURORA_LOW = hex('#3dffa2');
const AURORA_HIGH = hex('#9a6cff');
const MOON = hex('#f2f0e0');
const MOON_SHADE = hex('#c9c6b4');
/** Quantize an alpha to a few dithered steps so soft light still looks like pixel art. */
const steps = (a: number, x: number, y: number, n = 6) => Math.floor(a * n + bayer(x, y)) / n;
export function drawSky(s: Surface, f: Frame): void {
// Banded gradient with dithered seams.
for (let y = 0; y < HORIZON; y++) {
for (let x = 0; x < W; x++) {
const v = (y / (HORIZON - 1)) * (SKY_BANDS - 1) + (bayer(x, y) - 0.5) * 0.95;
const band = Math.max(0, Math.min(SKY_BANDS - 1, Math.round(v)));
s.set(x, y, f.skyBands[band]);
}
}
if (f.aurora > 0) drawAurora(s, f);
drawStars(s, f);
if (f.night > 0.05) drawMoon(s, f);
drawSun(s, f);
}
function drawAurora(s: Surface, f: Frame): void {
const t = f.t;
for (let x = 0; x < W; x++) {
const base = 38 + 9 * Math.sin(x * 0.018 + t * 0.04) + 5 * Math.sin(x * 0.047 - t * 0.065);
const curtain = 0.5 + 0.5 * Math.sin(x * 0.12 + t * 0.22 + 2.2 * Math.sin(x * 0.027 + t * 0.03));
const height = 26 + 8 * Math.sin(x * 0.033 + 1.5);
const strength = f.aurora * (0.25 + 0.75 * curtain) * 0.32;
for (let y = Math.max(0, Math.floor(base - height)); y <= base + 3; y++) {
const k = (y - (base - height)) / height;
const fall = y > base ? 1 - (y - base) / 3 : Math.pow(Math.min(1, k), 1.6);
const a = steps(strength * fall, x, y, 5);
if (a > 0) s.blend(x, y, mix(AURORA_HIGH, AURORA_LOW, Math.min(1, k * 1.2)), a);
}
}
}
function drawStars(s: Surface, f: Frame): void {
for (const st of STARS) {
const on = progress(f.t, st.appear, st.appear + 12);
if (on <= 0) continue;
const tw = 0.65 + 0.35 * Math.sin(f.t * st.twinkle + st.phase);
const a = on * tw * (0.35 + 0.65 * st.mag);
s.blend(st.x, st.y, st.tint, a);
if (st.mag > 0.85) {
const arm = a * 0.35;
s.blend(st.x - 1, st.y, st.tint, arm);
s.blend(st.x + 1, st.y, st.tint, arm);
s.blend(st.x, st.y - 1, st.tint, arm);
s.blend(st.x, st.y + 1, st.tint, arm);
}
}
}
function drawMoon(s: Surface, f: Frame): void {
const mx = Math.round(f.moonX);
const my = Math.round(f.moonY);
const vis = progress(f.night, 0.05, 0.6);
const R = 5;
// Halo.
for (let y = my - 16; y <= my + 16; y++) {
for (let x = mx - 16; x <= mx + 16; x++) {
const d = Math.hypot(x - mx, y - my);
if (d <= R || d > 16) continue;
s.blend(x, y, MOON, steps(vis * 0.16 * Math.pow(1 - d / 16, 2), x, y, 4));
}
}
for (let y = -R; y <= R; y++) {
for (let x = -R; x <= R; x++) {
if (x * x + y * y > R * R + R * 0.6) continue;
// A soft gibbous shadow on the lower left plus a couple of maria.
const shade = (x + 2) * (x + 2) + (y - 1) * (y - 1) > 30 && x < 0;
const mare = (x === 1 && y === -1) || (x === -1 && y === 1) || (x === 2 && y === 2);
s.blend(mx + x, my + y, shade || mare ? MOON_SHADE : MOON, vis);
}
}
}
function drawSun(s: Surface, f: Frame): void {
if (f.sunVis <= 0) return;
const cx = Math.round(f.sunX);
const cy = Math.round(f.sunY);
const glowR = 46;
const glow = mix(f.sunColor, hex('#ff7a50'), 0.5);
for (let y = Math.max(0, cy - glowR); y < Math.min(HORIZON, cy + glowR); y++) {
for (let x = cx - glowR; x <= cx + glowR; x++) {
const d = Math.hypot(x - cx, (y - cy) * 1.25);
if (d > glowR) continue;
const a = Math.pow(1 - d / glowR, 2.2) * 0.55 * (0.4 + 0.6 * f.sunVis);
s.blend(x, y, glow, steps(a, x, y));
}
}
const rim = mix(f.sunColor, hex('#ff8a4a'), 0.5);
for (let y = -SUN_R; y <= SUN_R; y++) {
for (let x = -SUN_R; x <= SUN_R; x++) {
const d2 = x * x + y * y;
if (d2 > SUN_R * SUN_R + SUN_R * 0.8) continue;
s.set(cx + x, cy + y, d2 > (SUN_R - 1.5) * (SUN_R - 1.5) ? rim : f.sunColor);
}
}
}

View File

@ -0,0 +1,118 @@
import { gradient, hex, mul, scale, type RGB } from '../../engine/color';
import { colorTrack, ease, progress, track } from '../../engine/Timeline';
import { noise1 } from '../../engine/rng';
import { RIDGE_FAR } from './world';
/** All timings for the Northern Cabin meditation, in seconds. */
export const DURATION = 300;
export const TIMES = {
fadeIn: [0, 6],
fadeOut: [291, 300],
/** The man's two trips to the woodpile (see man.ts for the beat-by-beat breakdown). */
trip1: 118,
trip2: 160,
fireStart: 198,
fireFull: 228,
smokeStart: 205,
starsFrom: 135,
starsTo: 245,
} as const;
/** Light phases: golden sunset → low sun → dusk → night. */
const P = [0, 100, 165, 235] as const;
const phase = (a: string, b: string, c: string, d: string) =>
colorTrack([
[P[0], hex(a)],
[P[1], hex(b)],
[P[2], hex(c)],
[P[3], hex(d)],
]);
/** Sky gradient stops from zenith to horizon. */
const SKY = [
phase('#34437a', '#262f63', '#121735', '#04060f'),
phase('#6a5a9a', '#573f7e', '#231f4a', '#070b1c'),
phase('#c46f8a', '#a84a74', '#4a2b5c', '#0b1430'),
phase('#f3955e', '#e8665a', '#8a3f5f', '#122040'),
phase('#ffd480', '#ff9d4f', '#c4605a', '#1a2c4c'),
];
/** Light falling on everything in the scene, as a per-channel multiplier. */
const AMBIENT = phase('#ffdccc', '#ebb3a8', '#7a709e', '#38426b');
const sunX = track([[0, 212], [160, 228]], ease.linear);
const sunY = track([[0, 38], [100, 79], [160, 104]], ease.linear);
const warm = track([[0, 1], [85, 0.9], [140, 0]]);
const alpenglow = track([[60, 0], [115, 1], [150, 0.55], [185, 0]]);
const night = track([[140, 0], [240, 1]]);
const fire = track([[TIMES.fireStart, 0], [206, 0.22], [TIMES.fireFull, 1]]);
const snow = track([[0, 1], [150, 0.85], [300, 0.65]]);
const moonX = track([[170, 36], [300, 58]], ease.linear);
const moonY = track([[170, 98], [300, 30]], ease.out);
const aurora = track([[215, 0], [258, 1]]);
export const SUN_R = 8;
export interface Frame {
t: number;
/** Ambient light multiplier, 0–1 per channel. */
amb: RGB;
/** Sky gradient sampled into discrete pixel-art bands, zenith → horizon. */
skyBands: RGB[];
horizonColor: RGB;
sunX: number;
sunY: number;
sunColor: RGB;
/** Fraction of the sun still above the mountains. */
sunVis: number;
/** Strength of warm direct sunlight (0 after sunset). */
warm: number;
alpenglow: number;
night: number;
moonX: number;
moonY: number;
aurora: number;
/** Fire glow in the cabin windows, already including flicker. */
fire: number;
snow: number;
/** Overall brightness for the fade in/out. */
fade: number;
}
export const SKY_BANDS = 20;
export function frameAt(t: number): Frame {
const sky = SKY.map((c) => c(t));
const skyBands = Array.from({ length: SKY_BANDS }, (_, i) => gradient(sky, i / (SKY_BANDS - 1)));
const sx = sunX(t);
const sy = sunY(t);
const ridge = RIDGE_FAR[Math.round(sx)];
const sunVis = Math.max(0, Math.min(1, (ridge - (sy - SUN_R)) / (SUN_R * 2)));
const flicker = 0.82 + 0.12 * noise1(t * 4.3, 5) + 0.06 * noise1(t * 11, 6);
const amb = scale(AMBIENT(t), 1 / 255);
return {
t,
amb,
skyBands,
horizonColor: sky[4],
sunX: sx,
sunY: sy,
sunColor: mul(hex('#fff2b8'), [1, 1 - progress(t, 30, 140) * 0.35, 1 - progress(t, 30, 140) * 0.6]),
sunVis,
warm: warm(t),
alpenglow: alpenglow(t),
night: night(t),
moonX: moonX(t),
moonY: moonY(t),
aurora: aurora(t),
fire: fire(t) * flicker,
snow: snow(t),
fade: progress(t, TIMES.fadeIn[0], TIMES.fadeIn[1]) * (1 - progress(t, TIMES.fadeOut[0], TIMES.fadeOut[1])),
};
}
/** Apply the frame's ambient light to a base (daylight) color. */
export function lit(f: Frame, base: RGB): RGB {
return mul(base, f.amb);
}

View File

@ -0,0 +1,114 @@
import { hex, mix, mul, type RGB } from '../../engine/color';
import { progress } from '../../engine/Timeline';
import { hash, Rng } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import { TIMES, type Frame } from './timeline';
import { CHIMNEY, H, W } from './world';
interface Flake {
x0: number;
y0: number;
speed: number;
sway: number;
freq: number;
phase: number;
big: boolean;
alpha: number;
/** 0–1 rank; flakes above the current density fade out. */
rank: number;
}
function makeFlakes(seed: number, n: number, near: boolean): Flake[] {
const r = new Rng(seed);
return Array.from({ length: n }, (_, i) => ({
x0: r.range(0, W),
y0: r.range(0, H),
speed: near ? r.range(11, 17) : r.range(4.5, 8),
sway: near ? r.range(3, 7) : r.range(1.5, 4),
freq: r.range(0.25, 0.7),
phase: r.range(0, Math.PI * 2),
big: near && r.next() < 0.45,
alpha: near ? r.range(0.75, 0.95) : r.range(0.4, 0.65),
rank: i / n,
}));
}
const FAR = makeFlakes(7, 120, false);
const NEAR = makeFlakes(8, 42, true);
const WIND = 2.2;
const FLAKE = hex('#ffffff');
const FLAKE_TINT = hex('#dfe6ff');
function drawFlakes(s: Surface, f: Frame, flakes: Flake[], color: RGB): void {
const wrapW = W + 8;
const wrapH = H + 8;
for (const fl of flakes) {
const fadeIn = Math.max(0, Math.min(1, (f.snow - fl.rank) * 12));
if (fadeIn <= 0) continue;
const y = ((fl.y0 + fl.speed * f.t) % wrapH) - 4;
const xRaw = fl.x0 + WIND * f.t + fl.sway * Math.sin(f.t * fl.freq + fl.phase);
const x = (((xRaw % wrapW) + wrapW) % wrapW) - 4;
const a = fl.alpha * fadeIn;
s.blend(x, y, color, a);
if (fl.big) {
s.blend(x + 1, y, color, a * 0.6);
s.blend(x, y + 1, color, a * 0.6);
s.blend(x + 1, y + 1, color, a * 0.3);
}
}
}
export function drawFarSnow(s: Surface, f: Frame): void {
drawFlakes(s, f, FAR, mix(mul(FLAKE, f.amb), FLAKE_TINT, 0.25));
}
export function drawNearSnow(s: Surface, f: Frame): void {
drawFlakes(s, f, NEAR, mix(mul(FLAKE, f.amb), FLAKE_TINT, 0.4));
}
const SMOKE_N = 40;
const SMOKE_LIFE = 16;
const SMOKE = hex('#a4a6b4');
const EMBER = hex('#ffb050');
export function drawSmoke(s: Surface, f: Frame): void {
const t = f.t;
if (t < TIMES.smokeStart) return;
// Smoke stays a little lighter than its surroundings so it still reads against the night sky.
const amb: RGB = [Math.max(0.46, f.amb[0]), Math.max(0.48, f.amb[1]), Math.max(0.56, f.amb[2])];
const base = mul(SMOKE, amb);
for (let i = 0; i < SMOKE_N; i++) {
const offset = (i * SMOKE_LIFE) / SMOKE_N;
const age = ((((t - offset) % SMOKE_LIFE) + SMOKE_LIFE) % SMOKE_LIFE);
const birth = t - age;
if (birth < TIMES.smokeStart) continue;
const u = age / SMOKE_LIFE;
const ramp = progress(birth, TIMES.smokeStart, TIMES.smokeStart + 22);
const cx = CHIMNEY.smokeX + age * 1.25 + Math.sin(age * 0.45 + i * 1.7) * age * 0.22;
const cy = CHIMNEY.smokeY - age * 3.1;
const r = 0.9 + u * 4.5;
const alpha = 0.8 * ramp * Math.pow(1 - u, 1.2) * Math.min(1, age / 0.8);
const c = mix(base, EMBER, Math.max(0, 0.35 - u * 2) * f.fire);
for (let y = Math.floor(cy - r); y <= cy + r; y++) {
for (let x = Math.floor(cx - r); x <= cx + r; x++) {
const d = Math.hypot(x - cx, y - cy) / r;
if (d > 1) continue;
s.dither(x, y, c, alpha * Math.sqrt(1 - d));
}
}
}
// An occasional spark drifting up out of the flue.
if (f.fire < 0.5) return;
const period = 4.5;
for (let i = 0; i < 4; i++) {
const cycleT = t + i * 1.13;
const cycle = Math.floor(cycleT / period);
if (hash(cycle, i, 91) < 0.55) continue;
const age = cycleT % period;
if (age > 1.8) continue;
const x = CHIMNEY.smokeX + (hash(cycle, i, 92) - 0.5) * 3 + age * 2 + Math.sin(age * 6) * 0.8;
const y = CHIMNEY.smokeY - age * 8;
s.blend(x, y, EMBER, (1 - age / 1.8) * 0.9);
}
}

View File

@ -0,0 +1,71 @@
import { noise1 } from '../../engine/rng';
/** Fixed layout of the scene on the 320x180 canvas. */
export const W = 320;
export const H = 180;
/** Far shore of the lake; the water mirrors everything above this row. */
export const HORIZON = 101;
const smoothstep = (a: number, b: number, x: number) => {
const u = Math.max(0, Math.min(1, (x - a) / (b - a)));
return u * u * (3 - 2 * u);
};
/** Top row of snow on the near shore for each column: a rise on the left for the cabin, low shore on the right. */
export const GROUND: readonly number[] = Array.from({ length: W }, (_, x) => {
const left = 117 + Math.sin(x * 0.07) * 1.5;
const right = 134 + Math.sin(x * 0.045 + 1) * 2.5;
return Math.round(left + (right - left) * smoothstep(150, 225, x));
});
/** Distinct peaks [x, top row, slope]; the saddle around x≈222 is where the sun sets. */
const PEAKS: readonly (readonly [number, number, number])[] = [
[18, 72, 0.6],
[62, 79, 0.55],
[112, 64, 0.62],
[150, 76, 0.5],
[190, 73, 0.55],
[262, 65, 0.5],
[306, 74, 0.6],
];
/** Snow-capped far mountains. */
export const RIDGE_FAR: readonly number[] = Array.from({ length: W }, (_, x) => {
const y = Math.min(...PEAKS.map(([px, py, k]) => py + Math.abs(x - px) * k));
return Math.round(Math.min(93, y + (noise1(x / 5, 13) - 0.5) * 3));
});
/** Lower forested hills in front of the mountains. */
export const RIDGE_NEAR: readonly number[] = Array.from({ length: W }, (_, x) => {
const h = 0.7 * noise1(x / 45, 21) + 0.3 * noise1(x / 12, 22);
return Math.round(99 - h * 12);
});
export const CABIN = {
x0: 46,
x1: 106,
centerX: 76,
wallTop: 126,
base: 147,
peakY: 104,
/** Half-width of the roof at a row, growing from the peak to the eaves. */
roofHalf: (y: number) => 1 + (y - 104) * 1.5,
eaveY: 125,
};
export const DOOR = { x0: 72, x1: 80, y0: 133, y1: 147 };
export const WINDOWS = [
{ x0: 53, y0: 131, w: 11, h: 10 },
{ x0: 89, y0: 131, w: 11, h: 10 },
] as const;
export const GABLE_WINDOW = { x0: 73, y0: 111, w: 7, h: 7 };
export const CHIMNEY = { x0: 91, x1: 97, top: 99, bottom: 121, smokeX: 94, smokeY: 97 };
export const WOODPILE = { x0: 110, x1: 129, base: 147 };
/** Horizontal positions the man walks between, and the row his boots stand on. */
export const MAN = { doorX: 76, pileX: 117, feetY: 149 };

View File

@ -0,0 +1,9 @@
import type { Meditation } from './types';
import { northernCabin } from './northern-cabin';
/** Every meditation listed on the main menu, in display order. Add new ones here. */
export const meditations: readonly Meditation[] = [northernCabin];
export function findMeditation(id: string): Meditation | undefined {
return meditations.find((m) => m.id === id);
}

23
src/meditations/types.ts Normal file
View File

@ -0,0 +1,23 @@
import type { Surface } from '../engine/Surface';
/**
* A scene renders a complete frame for any moment t (seconds). Keeping it a pure function of t
* makes pausing, scrubbing and menu thumbnails trivial.
*/
export interface Scene {
render(s: Surface, t: number): void;
}
export interface Meditation {
id: string;
title: string;
subtitle: string;
description: string;
/** Length in seconds. */
duration: number;
/** Moment used for the menu thumbnail. */
previewTime: number;
/** Optional music file, e.g. 'audio/northern-cabin.mp3' (placed in /public). */
music?: string;
createScene(): Scene;
}

431
src/styles.css Normal file
View File

@ -0,0 +1,431 @@
:root {
--bg: #0b0f1e;
--bg-deep: #070a14;
--ink: #ece8f6;
--muted: #9c98bc;
--accent: #ffb866;
--accent-deep: #e0782a;
--card: #141a31;
--card-hi: #1c2342;
--line: #2b3256;
--pixel: 4px;
--title-font: 'Silkscreen', ui-monospace, monospace;
--body-font: 'Pixelify Sans', ui-monospace, monospace;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
height: 100%;
background: var(--bg);
color: var(--ink);
font-family: var(--body-font);
-webkit-font-smoothing: antialiased;
}
#app {
position: fixed;
inset: 0;
overflow: hidden;
}
button {
font: inherit;
color: inherit;
}
.pixel-canvas {
display: block;
image-rendering: pixelated;
image-rendering: crisp-edges;
}
/* ---------- Pixel buttons ---------- */
.btn {
font-family: var(--title-font);
font-size: 14px;
letter-spacing: 0.06em;
background: var(--card-hi);
color: var(--ink);
border: none;
padding: 12px 20px;
cursor: pointer;
box-shadow:
0 calc(-1 * var(--pixel)) 0 0 var(--line),
0 var(--pixel) 0 0 var(--line),
calc(-1 * var(--pixel)) 0 0 0 var(--line),
var(--pixel) 0 0 0 var(--line);
transition:
background 0.4s ease,
color 0.4s ease;
}
.btn:hover,
.btn:focus-visible {
background: var(--line);
outline: none;
}
.btn.primary {
background: var(--accent);
color: #2a1608;
box-shadow:
0 calc(-1 * var(--pixel)) 0 0 var(--accent-deep),
0 var(--pixel) 0 0 var(--accent-deep),
calc(-1 * var(--pixel)) 0 0 0 var(--accent-deep),
var(--pixel) 0 0 0 var(--accent-deep);
}
.btn.primary:hover,
.btn.primary:focus-visible {
background: #ffcb8a;
}
.icon-btn {
background: none;
border: none;
padding: 8px;
cursor: pointer;
color: var(--ink);
opacity: 0.8;
display: grid;
place-items: center;
}
.icon-btn:hover,
.icon-btn:focus-visible {
opacity: 1;
outline: none;
}
.icon-btn svg {
width: 20px;
height: 20px;
shape-rendering: crispEdges;
}
/* ---------- Menu ---------- */
.menu {
position: absolute;
inset: 0;
overflow-y: auto;
animation: fade-in 1.2s ease both;
}
.menu-sky {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
z-index: 0;
}
.menu-inner {
position: relative;
z-index: 1;
max-width: 1040px;
margin: 0 auto;
padding: clamp(40px, 9vh, 96px) 16px 64px;
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
}
.menu-title {
font-family: var(--title-font);
font-weight: 400;
font-size: clamp(34px, 7vw, 72px);
letter-spacing: 0.04em;
margin: 0;
color: var(--ink);
text-shadow:
0 var(--pixel) 0 #3b2a6a,
0 calc(2 * var(--pixel)) 0 #1c1838;
}
.menu-title .glow {
color: var(--accent);
}
.menu-welcome {
margin: 28px 0 6px;
font-size: clamp(18px, 2.4vw, 22px);
color: var(--ink);
}
.menu-sub {
margin: 0 0 clamp(32px, 6vh, 56px);
font-size: 16px;
color: var(--muted);
max-width: 34em;
line-height: 1.5;
}
.breath {
display: inline-block;
width: 10px;
height: 10px;
margin-right: 10px;
vertical-align: middle;
background: var(--accent);
animation: breathe 8s ease-in-out infinite;
}
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(300px, 100%), 360px));
justify-content: center;
gap: 28px;
width: 100%;
text-align: left;
}
.card {
display: flex;
flex-direction: column;
background: var(--card);
border: none;
padding: 0;
cursor: pointer;
text-align: left;
box-shadow:
0 calc(-1 * var(--pixel)) 0 0 var(--line),
0 var(--pixel) 0 0 var(--line),
calc(-1 * var(--pixel)) 0 0 0 var(--line),
var(--pixel) 0 0 0 var(--line);
transition:
transform 0.6s ease,
box-shadow 0.6s ease;
}
.card:hover,
.card:focus-visible {
outline: none;
transform: translateY(-4px);
box-shadow:
0 calc(-1 * var(--pixel)) 0 0 var(--accent),
0 var(--pixel) 0 0 var(--accent),
calc(-1 * var(--pixel)) 0 0 0 var(--accent),
var(--pixel) 0 0 0 var(--accent);
}
.card canvas {
width: 100%;
aspect-ratio: 16 / 9;
height: auto;
}
.card-body {
padding: 16px 18px 18px;
display: grid;
gap: 6px;
}
.card-title {
font-family: var(--title-font);
font-size: 18px;
margin: 0;
}
.card-sub {
color: var(--muted);
font-size: 15px;
margin: 0;
}
.card-meta {
display: flex;
gap: 8px;
margin-top: 6px;
font-size: 13px;
color: var(--accent);
}
.card.soon {
cursor: default;
background: transparent;
box-shadow: none;
border: var(--pixel) dashed var(--line);
justify-content: center;
align-items: center;
min-height: 220px;
color: var(--muted);
text-align: center;
}
.card.soon:hover {
transform: none;
}
.menu-foot {
margin-top: 56px;
font-size: 13px;
color: var(--muted);
opacity: 0.7;
}
/* ---------- Player ---------- */
.player {
position: absolute;
inset: 0;
background: #000;
display: grid;
place-items: center;
}
.player.idle {
cursor: none;
}
.overlay {
position: absolute;
inset: 0;
display: grid;
place-items: center;
padding: 16px;
background: rgba(4, 6, 14, 0.82);
transition: opacity 1.6s ease;
text-align: center;
z-index: 3;
}
.overlay.hidden {
opacity: 0;
pointer-events: none;
}
.overlay-box {
max-width: 34em;
display: grid;
gap: 18px;
justify-items: center;
}
.overlay h2 {
font-family: var(--title-font);
font-weight: 400;
font-size: clamp(24px, 4vw, 36px);
margin: 0;
}
.overlay p {
margin: 0;
color: var(--muted);
line-height: 1.55;
font-size: 17px;
}
.overlay .hint {
font-size: 14px;
opacity: 0.8;
}
.overlay .row {
display: flex;
gap: 24px;
flex-wrap: wrap;
justify-content: center;
margin-top: 8px;
}
.controls {
position: absolute;
left: 0;
right: 0;
bottom: 0;
padding: 28px 16px 14px;
display: flex;
align-items: center;
gap: 10px;
background: linear-gradient(to top, rgba(4, 6, 14, 0.7), transparent);
transition: opacity 1.2s ease;
z-index: 2;
}
.player.idle .controls,
.controls.hidden {
opacity: 0;
pointer-events: none;
}
.progress {
flex: 1;
height: var(--pixel);
background: rgba(255, 255, 255, 0.14);
position: relative;
}
.progress > div {
position: absolute;
inset: 0 auto 0 0;
background: var(--accent);
}
.time {
font-size: 15px;
color: var(--muted);
min-width: 3.2em;
text-align: right;
font-variant-numeric: tabular-nums;
}
.paused-label {
position: absolute;
top: 24px;
left: 50%;
transform: translateX(-50%);
font-family: var(--title-font);
font-size: 14px;
letter-spacing: 0.2em;
color: var(--muted);
transition: opacity 0.8s ease;
z-index: 2;
}
.dev-time {
position: absolute;
top: 8px;
right: 10px;
font-size: 12px;
color: #7f7;
opacity: 0.7;
z-index: 2;
}
@keyframes fade-in {
from {
opacity: 0;
}
}
@keyframes breathe {
0%,
100% {
transform: scale(0.6);
opacity: 0.5;
}
50% {
transform: scale(1.3);
opacity: 1;
}
}
@media (prefers-reduced-motion: reduce) {
.breath {
animation: none;
}
.card,
.card:hover {
transition: none;
transform: none;
}
}

149
src/ui/Menu.ts Normal file
View File

@ -0,0 +1,149 @@
import { hex, mix } from '../engine/color';
import { Loop } from '../engine/Loop';
import { Rng } from '../engine/rng';
import { Surface } from '../engine/Surface';
import { meditations } from '../meditations/registry';
import type { Meditation } from '../meditations/types';
export interface View {
destroy(): void;
}
const SKY_W = 192;
const SKY_H = 108;
/** Slowly twinkling pixel night sky behind the menu. */
function createMenuSky(parent: HTMLElement): { canvas: HTMLCanvasElement; draw: (t: number) => void } {
const canvas = document.createElement('canvas');
canvas.width = SKY_W;
canvas.height = SKY_H;
canvas.className = 'menu-sky pixel-canvas';
parent.appendChild(canvas);
const ctx = canvas.getContext('2d')!;
const s = new Surface(SKY_W, SKY_H);
const image = new ImageData(s.data, SKY_W, SKY_H);
const r = new Rng(9);
const stars = Array.from({ length: 90 }, () => ({
x: r.int(0, SKY_W - 1),
y: r.int(0, SKY_H - 22),
mag: r.next(),
speed: r.range(0.3, 1.1),
phase: r.range(0, Math.PI * 2),
}));
const top = hex('#070a14');
const bottom = hex('#1a1f3e');
const hills = hex('#0d1124');
const hillLine = Array.from({ length: SKY_W }, (_, x) =>
Math.round(SKY_H - 12 - 5 * Math.sin(x * 0.045) - 3 * Math.sin(x * 0.13 + 1)),
);
const draw = (t: number) => {
for (let y = 0; y < SKY_H; y++) {
const c = mix(top, bottom, Math.round((y / SKY_H) * 8) / 8);
for (let x = 0; x < SKY_W; x++) s.set(x, y, c);
}
for (const st of stars) {
const a = (0.25 + 0.75 * st.mag) * (0.55 + 0.45 * Math.sin(t * st.speed + st.phase));
s.blend(st.x, st.y, [255, 248, 230], a);
}
for (let x = 0; x < SKY_W; x++) for (let y = hillLine[x]; y < SKY_H; y++) s.set(x, y, hills);
ctx.putImageData(image, 0, 0);
};
return { canvas, draw };
}
function formatMinutes(seconds: number): string {
return `${Math.round(seconds / 60)} min`;
}
/** A card whose thumbnail is the meditation itself, gently playing while hovered. */
function createCard(m: Meditation, onSelect: (id: string) => void): { el: HTMLElement; destroy(): void } {
const el = document.createElement('button');
el.className = 'card';
el.setAttribute('aria-label', `${m.title} — ${m.subtitle}, ${formatMinutes(m.duration)}`);
const canvas = document.createElement('canvas');
canvas.width = 320;
canvas.height = 180;
canvas.className = 'pixel-canvas';
const body = document.createElement('div');
body.className = 'card-body';
body.innerHTML = `
<h3 class="card-title"></h3>
<p class="card-sub"></p>
<div class="card-meta"><span>${formatMinutes(m.duration)}</span><span aria-hidden="true">·</span><span>Visual meditation</span></div>`;
body.querySelector('.card-title')!.textContent = m.title;
body.querySelector('.card-sub')!.textContent = m.subtitle;
el.append(canvas, body);
const scene = m.createScene();
const s = new Surface(320, 180);
const ctx = canvas.getContext('2d')!;
const image = new ImageData(s.data, 320, 180);
let t = m.previewTime;
const render = () => {
scene.render(s, t);
ctx.putImageData(image, 0, 0);
};
const loop = new Loop((dt) => {
t += dt;
render();
});
render();
el.addEventListener('mouseenter', () => loop.start());
el.addEventListener('mouseleave', () => loop.stop());
el.addEventListener('focus', () => loop.start());
el.addEventListener('blur', () => loop.stop());
el.addEventListener('click', () => onSelect(m.id));
return { el, destroy: () => loop.stop() };
}
export class Menu implements View {
private readonly root: HTMLElement;
private readonly loop: Loop;
private readonly cards: { destroy(): void }[] = [];
constructor(parent: HTMLElement, onSelect: (id: string) => void) {
this.root = document.createElement('div');
this.root.className = 'menu';
const sky = createMenuSky(this.root);
const inner = document.createElement('div');
inner.className = 'menu-inner';
inner.innerHTML = `
<h1 class="menu-title">Pixel<span class="glow">t</span>ation</h1>
<p class="menu-welcome"><span class="breath" aria-hidden="true"></span>Welcome. Take a slow breath.</p>
<p class="menu-sub">Choose a place to rest your mind. Each meditation is a short pixel art journey to simply watch, breathe, and let go.</p>
<div class="cards" role="list"></div>
<p class="menu-foot">Tip: press F for fullscreen once your meditation begins.</p>`;
const list = inner.querySelector('.cards')!;
for (const m of meditations) {
const card = createCard(m, onSelect);
card.el.setAttribute('role', 'listitem');
list.appendChild(card.el);
this.cards.push(card);
}
const soon = document.createElement('div');
soon.className = 'card soon';
soon.setAttribute('role', 'listitem');
soon.textContent = 'More journeys coming soon';
list.appendChild(soon);
this.root.appendChild(inner);
parent.appendChild(this.root);
let t = 0;
this.loop = new Loop((dt) => {
t += dt;
sky.draw(t);
});
sky.draw(0);
this.loop.start();
}
destroy(): void {
this.loop.stop();
this.cards.forEach((c) => c.destroy());
this.root.remove();
}
}

234
src/ui/Player.ts Normal file
View File

@ -0,0 +1,234 @@
import { Music } from '../engine/audio';
import { Loop } from '../engine/Loop';
import { PixelCanvas } from '../engine/PixelCanvas';
import type { Meditation, Scene } from '../meditations/types';
import type { View } from './Menu';
export interface PlayerOptions {
onExit: () => void;
/** Dev only: start at this time (seconds). */
startAt?: number;
/** Dev only: playback speed multiplier. */
speed?: number;
}
const IDLE_MS = 3000;
const ICONS = {
back: '<svg viewBox="0 0 10 10" fill="currentColor"><path d="M4 1h1v1H4zM3 2h1v1H3zM2 3h1v1H2zM1 4h8v2H1zM2 6h1v1H2zM3 7h1v1H3zM4 8h1v1H4z"/></svg>',
pause: '<svg viewBox="0 0 10 10" fill="currentColor"><path d="M2 1h2v8H2zM6 1h2v8H6z"/></svg>',
play: '<svg viewBox="0 0 10 10" fill="currentColor"><path d="M2 1h1v8H2zM3 2h1v6H3zM4 3h1v4H4zM5 4h2v2H5zM5 3h1v1H5zM5 6h1v1H5z"/></svg>',
fullscreen:
'<svg viewBox="0 0 10 10" fill="currentColor"><path d="M1 1h3v1H2v2H1zM6 1h3v3H8V2H6zM1 6h1v2h2v1H1zM8 6h1v3H6V8h2z"/></svg>',
};
function formatTime(s: number): string {
const v = Math.max(0, Math.ceil(s));
return `${Math.floor(v / 60)}:${String(v % 60).padStart(2, '0')}`;
}
type State = 'ready' | 'playing' | 'paused' | 'ended';
/** Hosts one meditation: begin screen, playback with auto-hiding controls, and a gentle ending. */
export class Player implements View {
private readonly root: HTMLElement;
private readonly view: PixelCanvas;
private readonly loop: Loop;
private readonly music: Music;
private readonly scene: Scene;
private t: number;
private state: State = 'ready';
private idleTimer = 0;
private readonly begin: HTMLElement;
private readonly end: HTMLElement;
private readonly controls: HTMLElement;
private readonly bar: HTMLElement;
private readonly time: HTMLElement;
private readonly playBtn: HTMLButtonElement;
private readonly pausedLabel: HTMLElement;
private readonly devTime?: HTMLElement;
constructor(
parent: HTMLElement,
private readonly m: Meditation,
private readonly opts: PlayerOptions,
) {
this.root = document.createElement('div');
this.root.className = 'player';
parent.appendChild(this.root);
this.view = new PixelCanvas(this.root);
this.scene = m.createScene();
this.music = new Music(m.music);
this.t = opts.startAt ?? 0;
this.begin = this.overlay(`
<h2></h2>
<p class="desc"></p>
<p class="hint">Settle in, soften your gaze, and breathe slowly. ${Math.round(m.duration / 60)} minutes.</p>
<div class="row"><button class="btn primary" data-act="begin">Begin</button><button class="btn" data-act="exit">Back</button></div>
<p class="hint">Space pauses · F toggles fullscreen · Esc returns to the menu</p>`);
this.begin.querySelector('h2')!.textContent = m.title;
this.begin.querySelector('.desc')!.textContent = m.description;
this.end = this.overlay(`
<h2>Be well</h2>
<p>Carry a little of this stillness with you.</p>
<div class="row"><button class="btn primary" data-act="again">Experience again</button><button class="btn" data-act="exit">Return to menu</button></div>`);
this.end.classList.add('hidden');
this.controls = document.createElement('div');
this.controls.className = 'controls hidden';
this.controls.innerHTML = `
<button class="icon-btn" data-act="exit" aria-label="Return to menu">${ICONS.back}</button>
<button class="icon-btn" data-act="toggle" aria-label="Pause">${ICONS.pause}</button>
<div class="progress" role="progressbar" aria-label="Progress"><div></div></div>
<span class="time"></span>
<button class="icon-btn" data-act="fullscreen" aria-label="Toggle fullscreen">${ICONS.fullscreen}</button>`;
this.root.appendChild(this.controls);
this.bar = this.controls.querySelector('.progress > div')!;
this.time = this.controls.querySelector('.time')!;
this.playBtn = this.controls.querySelector('[data-act="toggle"]')!;
this.pausedLabel = document.createElement('div');
this.pausedLabel.className = 'paused-label';
this.pausedLabel.textContent = 'PAUSED';
this.pausedLabel.style.opacity = '0';
this.root.appendChild(this.pausedLabel);
if (import.meta.env.DEV) {
this.devTime = document.createElement('div');
this.devTime.className = 'dev-time';
this.root.appendChild(this.devTime);
}
this.root.addEventListener('click', this.onClick);
this.root.addEventListener('mousemove', this.wake);
this.root.addEventListener('touchstart', this.wake, { passive: true });
window.addEventListener('keydown', this.onKey);
document.addEventListener('visibilitychange', this.onVisibility);
this.loop = new Loop(this.tick);
this.render();
this.loop.start();
(this.begin.querySelector('[data-act="begin"]') as HTMLElement).focus();
}
private overlay(html: string): HTMLElement {
const el = document.createElement('div');
el.className = 'overlay';
el.innerHTML = `<div class="overlay-box">${html}</div>`;
this.root.appendChild(el);
return el;
}
private tick = (dt: number): void => {
if (this.state === 'playing') {
this.t += dt * (this.opts.speed ?? 1);
if (this.t >= this.m.duration) {
this.t = this.m.duration;
this.finish();
}
}
this.music.update(this.t, this.m.duration);
this.render();
};
private render(): void {
this.scene.render(this.view.surface, this.t);
this.view.present();
this.bar.style.width = `${(this.t / this.m.duration) * 100}%`;
this.time.textContent = formatTime(this.m.duration - this.t);
if (this.devTime) this.devTime.textContent = `t=${this.t.toFixed(1)}s [ / ] skip`;
}
private start(): void {
this.state = 'playing';
this.begin.classList.add('hidden');
this.end.classList.add('hidden');
this.controls.classList.remove('hidden');
this.music.seek(this.t);
this.music.play();
this.wake();
}
private finish(): void {
this.state = 'ended';
this.music.pause();
this.controls.classList.add('hidden');
this.root.classList.remove('idle');
this.end.classList.remove('hidden');
(this.end.querySelector('[data-act="again"]') as HTMLElement).focus();
}
private setPaused(paused: boolean): void {
if (this.state !== 'playing' && this.state !== 'paused') return;
this.state = paused ? 'paused' : 'playing';
if (paused) this.music.pause();
else this.music.play();
this.playBtn.innerHTML = paused ? ICONS.play : ICONS.pause;
this.playBtn.setAttribute('aria-label', paused ? 'Play' : 'Pause');
this.pausedLabel.style.opacity = paused ? '1' : '0';
this.wake();
}
private toggleFullscreen(): void {
if (document.fullscreenElement) void document.exitFullscreen();
else void this.root.requestFullscreen?.().catch(() => {});
}
/** Show the controls and cursor; they fade away again after a few still seconds. */
private wake = (): void => {
this.root.classList.remove('idle');
clearTimeout(this.idleTimer);
if (this.state !== 'playing') return;
this.idleTimer = window.setTimeout(() => {
if (this.state === 'playing') this.root.classList.add('idle');
}, IDLE_MS);
};
private onClick = (e: MouseEvent): void => {
const act = (e.target as HTMLElement).closest<HTMLElement>('[data-act]')?.dataset.act;
switch (act) {
case 'begin':
return this.start();
case 'again':
this.t = 0;
return this.start();
case 'exit':
return this.opts.onExit();
case 'toggle':
return this.setPaused(this.state === 'playing');
case 'fullscreen':
return this.toggleFullscreen();
}
};
private onKey = (e: KeyboardEvent): void => {
if (e.key === 'Escape' && !document.fullscreenElement) return this.opts.onExit();
if (e.key === 'f' || e.key === 'F') return this.toggleFullscreen();
if (e.key === ' ' && (this.state === 'playing' || this.state === 'paused')) {
e.preventDefault();
return this.setPaused(this.state === 'playing');
}
if (import.meta.env.DEV && (e.key === '[' || e.key === ']')) {
this.t = Math.max(0, Math.min(this.m.duration - 0.01, this.t + (e.key === ']' ? 10 : -10)));
this.music.seek(this.t);
}
};
private onVisibility = (): void => {
if (document.hidden && this.state === 'playing') this.setPaused(true);
};
destroy(): void {
this.loop.stop();
this.music.destroy();
clearTimeout(this.idleTimer);
window.removeEventListener('keydown', this.onKey);
document.removeEventListener('visibilitychange', this.onVisibility);
if (document.fullscreenElement) void document.exitFullscreen().catch(() => {});
this.view.destroy();
this.root.remove();
}
}

19
tsconfig.json Normal file
View File

@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"types": ["vite/client", "node"],
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"isolatedModules": true,
"verbatimModuleSyntax": true,
"allowImportingTsExtensions": true,
"noEmit": true,
"skipLibCheck": true
},
"include": ["src", "scripts", "vite.config.ts"]
}

5
vite.config.ts Normal file
View File

@ -0,0 +1,5 @@
import { defineConfig } from 'vite';
export default defineConfig({
base: './',
});