diff --git a/README.md b/README.md index 9259bb8..a97ad55 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ so edits on the host reload in the browser; don't run it and `npm run dev` on th | `the-reef` | The Reef — drifting along a sunlit coral reef | 5 min | | `ringed-planet` | The Ringed Planet — drifting in high orbit above a ringed giant | 5 min | | `desert-sunrise` | Desert Sunrise — dawn breaks over a canyon stream | 5 min | +| `tibetan-monastery` | Monastery Above the Clouds — prayer flags and snowfall on a high summit | 5 min | Each meditation lives in `src/meditations//` 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 diff --git a/public/audio/tibetan-monestary.mp3 b/public/audio/tibetan-monestary.mp3 new file mode 100644 index 0000000..17e9629 Binary files /dev/null and b/public/audio/tibetan-monestary.mp3 differ diff --git a/src/meditations/registry.ts b/src/meditations/registry.ts index baa3ef2..0740a94 100644 --- a/src/meditations/registry.ts +++ b/src/meditations/registry.ts @@ -4,9 +4,10 @@ import { mediterraneanCoast } from './mediterranean-coast'; import { northernCabin } from './northern-cabin'; import { ringedPlanet } from './ringed-planet'; import { theReef } from './the-reef'; +import { tibetanMonastery } from './tibetan-monastery'; /** Every meditation listed on the main menu, in display order. Add new ones here. */ -export const meditations: readonly Meditation[] = [northernCabin, mediterraneanCoast, theReef, ringedPlanet, desertSunrise]; +export const meditations: readonly Meditation[] = [northernCabin, mediterraneanCoast, theReef, ringedPlanet, desertSunrise, tibetanMonastery]; export function findMeditation(id: string): Meditation | undefined { return meditations.find((m) => m.id === id); diff --git a/src/meditations/tibetan-monastery/clouds.ts b/src/meditations/tibetan-monastery/clouds.ts new file mode 100644 index 0000000..648796e --- /dev/null +++ b/src/meditations/tibetan-monastery/clouds.ts @@ -0,0 +1,105 @@ +import { bayer } from '../../engine/color'; +import { noise1, noise2 } from '../../engine/rng'; +import { HORIZON, W } from './world'; + +/** Cloud density sampled once per cached step over the sky. */ +export interface CloudField { + /** Density per sky pixel (row-major, W x HORIZON). */ + d: Float32Array; + /** Density above which a pixel is cloud. */ + th: number; +} + +/** + * Clouds blow in from the east (left) on the rising wind. `gap` tears a ragged opening around the + * sun for the last sun break. + */ +export function computeClouds( + drift: number, + cover: number, + gap: number, + sunX: number, + sunY: number, + out?: CloudField, +): CloudField { + const d = out?.d ?? new Float32Array(W * HORIZON); + for (let y = 0; y < HORIZON; y++) { + // Clouds flatten toward the horizon and drift more slowly there. + const p = y / HORIZON; + const sx = 52 * (1 - 0.5 * p); + const sy = 13 * (1 - 0.6 * p); + const xd = drift * (1 - 0.45 * p); + for (let x = 0; x < W; x++) { + const xs = x - xd; + let v = + 0.56 * noise2(xs / sx, y / sy, 11) + + 0.3 * noise2((xs * 1.3 + 40) / (sx * 0.45), y / (sy * 0.5), 12) + + 0.14 * noise2(x / 6 - drift * 0.3, y / 4, 13); + // Low cloud piles up over the far ranges first. + v += p * p * 0.12; + if (gap > 0) { + const dx = (x - sunX) * 0.8; + const dy = (y - sunY) * 1.3; + v -= gap * 0.75 * Math.exp(-(dx * dx + dy * dy) / (2 * 34 * 34)); + } + d[y * W + x] = v; + } + } + return { d, th: 0.24 + (1 - cover) * 0.56 }; +} + +export function cloudAt(c: CloudField, x: number, y: number): number { + const xi = Math.max(0, Math.min(W - 1, Math.round(x))); + const yi = Math.max(0, Math.min(HORIZON - 1, Math.round(y))); + return c.d[yi * W + xi]; +} + +/** 0 = solid cloud, 1 = clear sky at a point (soft edge). */ +export function openness(c: CloudField, x: number, y: number): number { + if (y >= HORIZON) return 1; + return Math.max(0, Math.min(1, (c.th - cloudAt(c, x, y)) * 9 + 0.5)); +} + +/** Per-pixel cloud tone: 0 clear, 1 lit, 2 mid, 3 shadowed; +4 marks a thin, translucent edge. */ +export function shadeClouds(c: CloudField, sunX: number, cover: number, out?: Uint8Array): Uint8Array { + const tone = out ?? new Uint8Array(W * HORIZON); + for (let y = 0; y < HORIZON; y++) { + for (let x = 0; x < W; x++) { + const e = c.d[y * W + x] - c.th; + if (e <= 0) { + tone[y * W + x] = 0; + continue; + } + // Tops and sun-facing sides are lit; undersides and thick middles fall into shade. + const toward = Math.sign(sunX - x) || 1; + const vertical = cloudAt(c, x, y + 3) - cloudAt(c, x, y - 3); + const facing = cloudAt(c, x - toward * 3, y) - cloudAt(c, x + toward * 3, y); + const score = 0.5 + vertical * 2.6 + facing * 1.6 - e * 1.3 - cover * 0.1 + (bayer(x, y) - 0.5) * 0.35; + tone[y * W + x] = (score > 0.62 ? 1 : score > 0.36 ? 2 : 3) + (e < 0.03 ? 4 : 0); + } + } + return tone; +} + +/** Angles (y down, so 0..π fans downward) covered by the sunbeam table. */ +export const RAY_A0 = -0.4; +export const RAY_A1 = Math.PI + 0.4; +const RAY_BINS = 720; + +/** Brightness of the beam leaving the sun at each angle: lit where the clouds around the sun are open. */ +export function computeRayTable(c: CloudField, sunX: number, sunY: number, t: number, out?: Float32Array): Float32Array { + const table = out ?? new Float32Array(RAY_BINS); + for (let i = 0; i < RAY_BINS; i++) { + const a = RAY_A0 + ((RAY_A1 - RAY_A0) * i) / (RAY_BINS - 1); + const ca = Math.cos(a); + const sa = Math.sin(a); + const open = Math.min(openness(c, sunX + ca * 16, sunY + sa * 16), openness(c, sunX + ca * 28, sunY + sa * 28)); + table[i] = open * (0.45 + 0.55 * noise1(a * 36 + t * 0.04, 17)); + } + return table; +} + +export function rayAt(table: Float32Array, a: number): number { + if (a < RAY_A0 || a > RAY_A1) return 0; + return table[Math.round(((a - RAY_A0) / (RAY_A1 - RAY_A0)) * (RAY_BINS - 1))]; +} diff --git a/src/meditations/tibetan-monastery/creatures.ts b/src/meditations/tibetan-monastery/creatures.ts new file mode 100644 index 0000000..cee1614 --- /dev/null +++ b/src/meditations/tibetan-monastery/creatures.ts @@ -0,0 +1,179 @@ +import { hex, mix, type RGB } from '../../engine/color'; +import { drawSprite, type SpriteArt } from '../../engine/sprite'; +import { pathTrack, progress } from '../../engine/Timeline'; +import type { Surface } from '../../engine/Surface'; +import { lit, sunlit, TIMES, type Frame } from './timeline'; +import { LEDGE } from './world'; + +// --------------------------------------------------------------------------- +// Lammergeier: circles on the afternoon air above the eastern ranges, then glides away +// --------------------------------------------------------------------------- + +const VULTURE_GLIDE: SpriteArt = ['kk.......kk', '.kkk.o.kkk.', '...kkokk...', '....kkk....', '.....k.....']; +const VULTURE_BANK: SpriteArt = ['k..........', '.kk......kk', '..kkkokkkk.', '....kkk....', '.....k.....']; + +const [V0, V1] = TIMES.vulture; +const LEAVE = V1 - 14; +const CIRCLE = 19; +const circle = (t: number): [number, number] => { + const a = ((t - V0) / CIRCLE) * Math.PI * 2; + return [208 + 44 * Math.cos(a) - (t - V0) * 0.35, 46 + 9 * Math.sin(a) + (t - V0) * 0.08]; +}; +const leave = pathTrack([ + [LEAVE, ...circle(LEAVE)], + [LEAVE + 2, ...circle(LEAVE + 2)], + [LEAVE + 8, 90, 38], + [V1, -20, 30], +]); + +export function drawVulture(s: Surface, f: Frame): void { + const t = f.t; + if (t < V0 || t > V1) return; + const [x, y] = t < LEAVE + 2 ? circle(t) : leave(t); + const [px] = t < LEAVE + 2 ? circle(t - 0.2) : leave(t - 0.2); + // It is far off, so it takes on some of the haze. + const pal: Record = { + k: mix(lit(f, hex('#3a3030')), f.horizonColor, 0.25), + o: mix(sunlit(f, hex('#c8803c'), 0.4), f.horizonColor, 0.2), + }; + const a = ((t - V0) / CIRCLE) * Math.PI * 2; + const banking = t < LEAVE && Math.abs(Math.cos(a)) > 0.85; + const flip = x < px; + // Faded in from a speck as it rises into view, and out as it leaves. + const alpha = progress(t, V0, V0 + 3) * (1 - progress(t, V1 - 3, V1)); + drawSprite(s, banking ? VULTURE_BANK : VULTURE_GLIDE, Math.round(x) - 5, Math.round(y) - 2, pal, flip, alpha); +} + +// --------------------------------------------------------------------------- +// Snow leopard: pads onto the ledge east of the monastery, rests a while, slips away +// --------------------------------------------------------------------------- + +/** Facing left; the tail is drawn separately so it can flick. 16 wide, feet on the bottom row. */ +const LEOPARD_STAND: SpriteArt = [ + '.e.e............', + 'hhhh............', + 'yhhhbbbbsbbbs...', + '.hnbbsbbbbsbbb..', + '..bwwwwwwbbbb...', + '..l.l....l.l....', + '..l.l....l.l....', + '..k.k....k.k....', +]; +const LEOPARD_LOOK: SpriteArt = [ + 'e..e............', + 'hhhh............', + 'yhyhbbbbsbbbs...', + '.nhbbsbbbbsbbb..', + '..bwwwwwwbbbb...', + '..l.l....l.l....', + '..l.l....l.l....', + '..k.k....k.k....', +]; +const LEOPARD_WALK_A: SpriteArt = [ + '.e.e............', + 'hhhh............', + 'yhhhbbbbsbbbs...', + '.hnbbsbbbbsbbb..', + '..bwwwwwwbbbb...', + '..l..l..l...l...', + '.l...l..l....l..', + '.k....k.k....k..', +]; +const LEOPARD_WALK_B: SpriteArt = [ + '.e.e............', + 'hhhh............', + 'yhhhbbbbsbbbs...', + '.hnbbsbbbbsbbb..', + '..bwwwwwwbbbb...', + '...ll....ll.....', + '...ll....ll.....', + '...kk....kk.....', +]; +const LEOPARD_SIT: SpriteArt = [ + '................', + '.e.e............', + 'hhhh............', + 'yhhhbbbbs.......', + '.hnbbsbbbbbs....', + '..bwwwwbbbbbb...', + '..l.l..bbbbbb...', + '..k.k..kkkkk....', +]; + +const [L0, L1] = TIMES.leopard; +const REST_X = (LEDGE.x0 + LEDGE.x1) / 2 + 3; +const leopardPath = pathTrack([ + [L0, 304, 146], + [L0 + 4, 290, 149], + [L0 + 9, REST_X, LEDGE.y - 1], + [L1 - 14, REST_X, LEDGE.y - 1], + [L1 - 10, 284, LEDGE.y - 1], + [L1, 312, 146], +]); + +interface LeopardPose { + art: SpriteArt; + facing: -1 | 1; + walking: boolean; + sitting: boolean; +} + +function leopardPose(t: number): LeopardPose { + if (t < L0 + 9) return { art: LEOPARD_WALK_A, facing: -1, walking: true, sitting: false }; + if (t < L0 + 16) return { art: LEOPARD_STAND, facing: -1, walking: false, sitting: false }; + if (t < L0 + 23) return { art: LEOPARD_LOOK, facing: -1, walking: false, sitting: false }; + if (t < L1 - 18) return { art: LEOPARD_SIT, facing: -1, walking: false, sitting: true }; + if (t < L1 - 14) return { art: LEOPARD_STAND, facing: -1, walking: false, sitting: false }; + return { art: LEOPARD_WALK_A, facing: 1, walking: true, sitting: false }; +} + +export function drawLeopard(s: Surface, f: Frame): void { + const t = f.t; + if (t < L0 || t > L1) return; + const [x, y] = leopardPath(t); + const pose = leopardPose(t); + const art = pose.walking && Math.floor(x / 2.5) % 2 ? LEOPARD_WALK_B : pose.art; + // Grey on grey: it fades from sight into the cloud as it leaves. + const fog = progress(t, L1 - 6, L1); + const tint = (c: RGB) => mix(sunlit(f, c, 0.2), f.fog, fog * 0.6); + const pal: Record = { + h: tint(hex('#d8d2c6')), + b: tint(hex('#cdc6b8')), + s: tint(hex('#5e5852')), + w: tint(hex('#eeeae2')), + l: tint(hex('#bcb4a6')), + k: tint(hex('#a29a8c')), + e: tint(hex('#8a847a')), + y: tint(hex('#b8c870')), + n: tint(hex('#c89090')), + }; + const alpha = 1 - progress(t, L1 - 3, L1); + const flip = pose.facing > 0; + const sx = Math.round(x) - 8; + const sy = Math.round(y) - 7; + + // The long, thick tail: low with an upturned tip, flicking now and then as it rests. + const flick = pose.sitting || !pose.walking ? Math.max(0, Math.sin(t * 1.7)) * (Math.sin(t * 0.37) > 0.2 ? 1 : 0.2) : 0.3; + const dir = flip ? -1 : 1; + const rootX = flip ? sx + 15 - 13 : sx + 13; + const rootY = sy + (pose.sitting ? 5 : 3); + for (let i = 0; i < 10; i++) { + const tx = rootX + dir * i * 0.85; + const ty = rootY + 1 + Math.min(i, 6) * 0.6 - Math.max(0, i - 6) * (0.7 + 0.9 * flick); + const c = i > 7 ? pal.s : i % 3 === 2 ? pal.s : pal.b; + s.blend(Math.round(tx), Math.round(ty), c, alpha); + if (i < 8) s.blend(Math.round(tx), Math.round(ty) + 1, pal.l, alpha); + } + // A soft dark outline keeps the pale cat readable against pale cloud. + const outline: Record = {}; + for (const k in pal) outline[k] = lit(f, hex('#4a4448')); + for (const [ox, oy] of [ + [-1, 0], + [1, 0], + [0, -1], + [0, 1], + ]) { + drawSprite(s, art, sx + ox, sy + oy, outline, flip, alpha * 0.55); + } + drawSprite(s, art, sx, sy, pal, flip, alpha); +} diff --git a/src/meditations/tibetan-monastery/flags.ts b/src/meditations/tibetan-monastery/flags.ts new file mode 100644 index 0000000..4976ce5 --- /dev/null +++ b/src/meditations/tibetan-monastery/flags.ts @@ -0,0 +1,109 @@ +import { hex, mix, scale, type RGB } from '../../engine/color'; +import { hash } from '../../engine/rng'; +import type { Surface } from '../../engine/Surface'; +import { lit, sunlit, type Frame } from './timeline'; +import { FLAG_LINES, POLE, type FlagLine } from './world'; + +/** Lungta flags always run blue, white, red, green, yellow: sky, air, fire, water, earth. */ +const COLORS: readonly RGB[] = [hex('#2f5fbf'), hex('#eeeee8'), hex('#d03a30'), hex('#2f9a52'), hex('#f0c83a')]; +const STRING = hex('#3a3236'); +const POLE_WOOD = hex('#5a4030'); +const POLE_DARK = hex('#3a281e'); +const GOLD = hex('#e0b040'); + +/** How far flags stream out downwind (east → west, i.e. to the right), 0 hanging to 1 flying flat. */ +function liftOf(f: Frame): number { + return Math.min(1, 0.12 + f.wind * 0.72); +} + +function linePoint(l: FlagLine, f: Frame, li: number, u: number): [number, number] { + const bow = 4 * u * (1 - u); + // Lines bow and bounce a little in the gusts. + const sway = f.wind * (0.6 + 0.8 * Math.sin(f.t * (0.9 + li * 0.13) + li * 2.1)) * bow * 1.6; + return [l.ax + (l.bx - l.ax) * u, l.ay + (l.by - l.ay) * u + l.sag * bow + sway]; +} + +function drawLine(s: Surface, f: Frame, l: FlagLine, li: number): void { + const len = Math.hypot(l.bx - l.ax, l.by - l.ay) + l.sag; + const string = l.near ? scale(lit(f, STRING), 0.8) : lit(f, STRING); + const steps = Math.ceil(len * 1.4); + for (let i = 0; i <= steps; i++) { + const [x, y] = linePoint(l, f, li, i / steps); + s.blend(x, y, string, l.near ? 1 : 0.8); + } + const lift = liftOf(f); + const freq = 3 + f.wind * 7; + const amp = 0.3 + f.wind * 1.4; + const shade = l.near ? 0.78 : 1; + const n = Math.floor(len / l.gap); + for (let j = 1; j < n; j++) { + const [x, y] = linePoint(l, f, li, j / n); + const base = COLORS[(j + li) % 5]; + const col = scale(sunlit(f, base, 0.35), shade); + const dark = scale(col, 0.72); + const print = mix(col, dark, 0.8); + // Flags fly shorter as they lift, their free edge rippling. + const rows = Math.max(2, Math.round(l.fh * (1 - 0.45 * lift))); + const phase = j * 1.37 + li * 0.7; + for (let r = 0; r < rows; r++) { + const k = (r + 1) / rows; + const wave = Math.sin(f.t * freq + phase - r * 0.9); + const off = k * (lift * l.fh * 0.95 + amp * wave); + const fx = Math.round(x + off); + const fy = Math.round(y) + 1 + r; + const rowCol = wave < -0.35 ? dark : col; + for (let c = 0; c < l.fw; c++) { + // A frayed bottom edge where years of wind have worn the cotton. + if (r === rows - 1 && hash(j * 7 + c, li, 40) < 0.35) continue; + let pc = rowCol; + if (l.near && r > 1 && r < rows - 2 && c > 1 && c < l.fw - 2 && hash(j * 13 + c, r, 41 + li) < 0.4) pc = print; + s.set(fx + c, fy, pc); + } + } + } +} + +/** The tall darchor pole on the west knob, with its long banner. */ +function drawPole(s: Surface, f: Frame): void { + const wood = sunlit(f, POLE_WOOD, 0.3); + const dark = lit(f, POLE_DARK); + for (let y = POLE.top; y <= POLE.base; y++) { + s.set(POLE.x, y, dark); + s.set(POLE.x + 1, y, wood); + } + const gold = sunlit(f, GOLD, 0.5); + s.set(POLE.x, POLE.top - 1, gold); + s.set(POLE.x + 1, POLE.top - 1, gold); + s.set(POLE.x, POLE.top - 2, gold); + s.set(POLE.x, POLE.top - 3, gold); + + // The banner is lashed along the pole and streams out to the right, drooping when the air is still. + const lift = liftOf(f); + const len = 6 + Math.round(lift * 4); + const top = POLE.top + 3; + const height = 25; + const freq = 2.4 + f.wind * 5; + for (let c = 0; c < len; c++) { + const k = (c + 1) / len; + const droop = (1 - lift) * c * 1.3; + const wave = Math.sin(f.t * freq - c * 0.8) * (0.4 + f.wind * 1.2) * k; + const shade = Math.cos(f.t * freq - c * 0.8) < -0.4; + for (let r = 0; r < height - Math.round(c * 0.4); r++) { + const col = sunlit(f, COLORS[Math.floor(r / 5) % 5], 0.35); + s.set(POLE.x + 2 + c, Math.round(top + r + droop + wave), shade ? scale(col, 0.75) : col); + } + } +} + +export function drawBackFlags(s: Surface, f: Frame): void { + drawPole(s, f); + FLAG_LINES.forEach((l, i) => { + if (!l.near) drawLine(s, f, l, i); + }); +} + +export function drawNearFlags(s: Surface, f: Frame): void { + FLAG_LINES.forEach((l, i) => { + if (l.near) drawLine(s, f, l, i); + }); +} diff --git a/src/meditations/tibetan-monastery/index.ts b/src/meditations/tibetan-monastery/index.ts new file mode 100644 index 0000000..5dbe218 --- /dev/null +++ b/src/meditations/tibetan-monastery/index.ts @@ -0,0 +1,46 @@ +import type { Meditation, Scene } from '../types'; +import { drawLeopard, drawVulture } from './creatures'; +import { drawBackFlags, drawNearFlags } from './flags'; +import { drawChorten, drawLamplight, drawMonastery } from './monastery'; +import { drawMonksBehind, drawMonksFront } from './monks'; +import { drawCloudSea, drawRanges, drawSummit } from './mountains'; +import { drawSky, drawSunbeams } from './sky'; +import { DURATION, frameAt } from './timeline'; +import { drawFarSnow, drawMist, drawNearSnow, drawSpindrift } from './weather'; + +const scene: Scene = { + render(s, t) { + const f = frameAt(t); + drawSky(s, f); + drawRanges(s, f); + drawCloudSea(s, f); + drawVulture(s, f); + drawSummit(s, f); + drawLeopard(s, f); + drawMonksBehind(s, f); + drawChorten(s, f); + drawMonastery(s, f); + drawBackFlags(s, f); + drawMonksFront(s, f); + drawSunbeams(s, f); + drawFarSnow(s, f); + drawMist(s, f); + drawSpindrift(s, f); + drawLamplight(s, f); + drawNearFlags(s, f); + drawNearSnow(s, f); + s.darken(f.fade); + }, +}; + +export const tibetanMonastery: Meditation = { + id: 'tibetan-monastery', + title: 'Monastery Above the Clouds', + subtitle: 'Prayer flags and snowfall on a high summit', + description: + 'Sit with an old monastery on a Himalayan summit as a clear afternoon turns to cloud. Monks walk their circuit past the prayer wheels, a lammergeier circles and a snow leopard pauses on the rocks. Then the mist rises, the snow begins and the butter lamps are lit, one window at a time.', + music: 'audio/tibetan-monestary.mp3', + duration: DURATION, + previewTime: 252, + createScene: () => scene, +}; diff --git a/src/meditations/tibetan-monastery/monastery.ts b/src/meditations/tibetan-monastery/monastery.ts new file mode 100644 index 0000000..514e14b --- /dev/null +++ b/src/meditations/tibetan-monastery/monastery.ts @@ -0,0 +1,504 @@ +import { bayer, hex, mix, scale, type RGB } from '../../engine/color'; +import { drawSprite, type SpriteArt } from '../../engine/sprite'; +import { progress } from '../../engine/Timeline'; +import { hash } from '../../engine/rng'; +import type { Surface } from '../../engine/Surface'; +import { GATE_OPEN, wheelTurn } from './monks'; +import { lampTime, lit, sunlit, type Frame } from './timeline'; +import { + BLOCK_A, + BLOCK_B, + blockSpan, + CHORTEN, + GALLERIES, + GALLERY_ROOF, + GATE, + GROUND_Y, + LIP_Y, + PAVILION, + WHEEL_BOTTOM, + WHEEL_TOP, + WHEELS, + WINDOWS, + type Block, +} from './world'; + +const WALL = hex('#eee8dc'); +const WALL_SHADE = hex('#cfc6b8'); +const STAIN = hex('#c9b89c'); +const PLINTH = hex('#8a8078'); +const PEMBE = hex('#6e2a2a'); +const PEMBE_DARK = hex('#4e1c20'); +const CAP = hex('#2e2224'); +const TRIM = hex('#e4d8c4'); +const MAROON = hex('#8a2a26'); +const MAROON_DARK = hex('#4a1a1c'); +const WOOD = hex('#4a2c22'); +const FRAME = hex('#1c1416'); +const LINTEL = hex('#b03a2e'); +const SHAMBU: readonly RGB[] = [hex('#ece4d4'), hex('#c23c30'), hex('#2f5ca2')]; +const GLASS = hex('#2a2228'); +const GOLD = hex('#d8a83c'); +const GOLD_LIGHT = hex('#ffe486'); +const GOLD_DARK = hex('#94661e'); +const BRASS = hex('#c49a4c'); +const BRASS_LIGHT = hex('#f0d488'); +const BRASS_DARK = hex('#7a5a2c'); +const SNOW = hex('#f4f6fc'); +const SNOW_SHADE = hex('#c4cce2'); +const DOORWAY = hex('#1c1210'); +const LAMP_CORE = hex('#ffe4a0'); +const LAMP_MID = hex('#ffae4a'); +const LAMP_EDGE = hex('#d8642a'); +const GLOW = hex('#ffa850'); + +/** How dark the evening has got, 0 (bright day) to ~0.65 (stormy dusk); lamplight reads stronger as it rises. */ +function darkness(f: Frame): number { + return 1 - (f.amb[0] * 0.3 + f.amb[1] * 0.5 + f.amb[2] * 0.2); +} + +/** Butter-lamp light behind a pane: warmest low down where the lamps stand, wavering a little. */ +function lampColor(f: Frame, i: number, y01: number): RGB { + const w = Math.sin(f.t * (2.1 + i * 0.6) + i * 1.7) * 0.12; + const k = Math.max(0, Math.min(1, y01 * 0.75 + 0.25 + w)); + return k > 0.55 ? mix(LAMP_MID, LAMP_CORE, (k - 0.55) / 0.45) : mix(LAMP_EDGE, LAMP_MID, k / 0.55); +} + +// --------------------------------------------------------------------------- +// Walls +// --------------------------------------------------------------------------- + +function drawBlock(s: Surface, f: Frame, b: Block, medallions: readonly number[]): void { + // Four wall tones across the face, warmer toward the sun on the right. + const tones: RGB[] = [lit(f, WALL_SHADE), sunlit(f, WALL, 0.08), sunlit(f, WALL, 0.2), sunlit(f, WALL, 0.34)]; + const stain = sunlit(f, STAIN, 0.15); + const pembe = sunlit(f, PEMBE, 0.2); + const pembeDark = lit(f, PEMBE_DARK); + const cap = lit(f, CAP); + const trim = sunlit(f, TRIM, 0.2); + const under = lit(f, scale(WALL_SHADE, 0.72)); + const plinth = sunlit(f, PLINTH, 0.15); + const gold = sunlit(f, GOLD, 0.5); + for (let y = b.top; y <= b.base; y++) { + const [l, r] = blockSpan(b, y); + const ry = y - b.top; + if (ry === 0) { + for (let x = l - 1; x <= r + 1; x++) s.set(x, y, cap); + continue; + } + if (ry === 1) { + for (let x = l; x <= r; x++) s.set(x, y, trim); + continue; + } + if (ry <= 7) { + // The pembe band: stacked brushwood under the roof, painted maroon. + for (let x = l; x <= r; x++) s.set(x, y, hash(x, ry >> 1, 21) < 0.3 || ry === 7 ? pembeDark : pembe); + if (ry === 3 || ry === 4) for (const mx of medallions) for (let x = mx; x < mx + 2; x++) s.set(x, y, gold); + continue; + } + if (ry === 8) { + for (let x = l; x <= r; x++) s.set(x, y, under); + continue; + } + for (let x = l; x <= r; x++) { + let c: RGB; + if (x === l) c = tones[0]; + else { + const u = (x - l) / (r - l); + c = tones[Math.max(1, Math.min(3, Math.floor(1 + u * 2.6 + (bayer(x, y) - 0.5) * 0.8)))]; + } + // Ochre runs where rain has washed down from the band. + const run = hash(x, 0, b.top) < 0.2 ? 1 + hash(x, 1, b.top) * 5 : 0; + if (ry - 8 < run && x !== l) c = stain; + if (b === BLOCK_A && y >= b.base - 1) c = plinth; + s.set(x, y, c); + } + } +} + +// --------------------------------------------------------------------------- +// Windows, with the lamp-lighter passing behind them at dusk +// --------------------------------------------------------------------------- + +function drawWindows(s: Surface, f: Frame): void { + const frame = lit(f, FRAME); + const wood = lit(f, WOOD); + const lintel = sunlit(f, LINTEL, 0.2); + const shambu = SHAMBU.map((c) => sunlit(f, c, 0.2)); + const glass = lit(f, GLASS); + for (let i = 0; i < WINDOWS.length; i++) { + const w = WINDOWS[i]; + const half = w.w >> 1; + const x0 = w.cx - half; + const x1 = w.cx + half; + const y1 = w.y0 + w.h - 1; + const small = w.w < 5; + if (!small) { + // Wooden cap, a short pleated shambu curtain, then the red lintel. + for (let x = x0 - 2; x <= x1 + 2; x++) { + s.set(x, w.y0 - 4, wood); + s.set(x, w.y0 - 3, shambu[(x + 3) % 3]); + s.set(x, w.y0 - 2, shambu[(x + 4) % 3]); + } + for (let x = x0 - 1; x <= x1 + 1; x++) s.set(x, w.y0 - 1, lintel); + } + // The black frame flares outward toward the sill. + for (let y = w.y0; y <= y1 + 1; y++) { + const ext = small ? 1 : 1 + Math.floor(((y - w.y0) * 1.6) / (w.h + 1)); + for (let k = 1; k <= ext; k++) { + s.set(x0 - k, y, frame); + s.set(x1 + k, y, frame); + } + if (y === y1 + 1) for (let x = x0; x <= x1; x++) s.set(x, y, frame); + } + + const g = f.windows[i]; + const tL = lampTime(w.order); + const walking = f.t > tL - 2.4 && f.t < tL + 1.6; + const dir = w.order % 2 ? -1 : 1; + const u = (f.t - (tL - 2.4)) / 4; + const lx = x0 + (dir > 0 ? u : 1 - u) * (x1 - x0); + const lampX = lx + dir * 1.5; + const lampY = y1 - 1; + for (let y = w.y0; y <= y1; y++) { + const y01 = (y - w.y0) / Math.max(1, w.h - 1); + for (let x = x0; x <= x1; x++) { + let k = g; + if (walking) k = Math.max(k, 0.9 * (1 - Math.hypot(x - lampX, (y - lampY) * 1.3) / 3)); + let c = mix(glass, lampColor(f, i, y01), Math.max(0, k)); + if (x === w.cx || y === w.y0 + (w.h >> 1)) c = mix(frame, c, 0.45); + // The lamp-lighter's silhouette against the glow. + if (walking && !small && k > 0.12) { + const dx = x - lx; + const head = y >= y1 - 3 && y <= y1 - 2 && dx >= -1 && dx < 1; + const body = y >= y1 - 1 && dx >= -2 && dx < 2; + if (head || body) c = scale(c, 0.3); + } + s.set(x, y, c); + } + } + if (walking) s.blend(Math.round(lampX), lampY, LAMP_CORE, 1); + } +} + +// --------------------------------------------------------------------------- +// Pavilion, roof ornaments +// --------------------------------------------------------------------------- + +const FINIAL: SpriteArt = ['..G..', '..g..', '.gGg.', '.gGg.', '..g..', '.ggg.', 'gGGgd', '.ggd.', '..d..']; +const GYALTSEN: SpriteArt = ['.G.', 'gGg', 'kKk', 'kKk', 'gGg', 'kKk', 'www', 'rrr']; +const DEER: SpriteArt = ['...G.', '..gg.', 'gggg.', 'ggggd']; + +function goldPalette(f: Frame): Record { + return { + g: sunlit(f, GOLD, 0.45), + G: sunlit(f, GOLD_LIGHT, 0.5), + d: lit(f, GOLD_DARK), + k: lit(f, hex('#2a2426')), + K: lit(f, hex('#4a4246')), + w: sunlit(f, hex('#e8e0d0'), 0.2), + r: lit(f, MAROON), + }; +} + +function drawPavilion(s: Surface, f: Frame, pal: Record): void { + const P = PAVILION; + const wall = sunlit(f, MAROON, 0.2); + const wallDark = lit(f, MAROON_DARK); + for (let y = P.top; y <= P.base; y++) { + for (let x = P.x0; x <= P.x1; x++) { + s.set(x, y, y === P.top ? wallDark : y === P.top + 1 ? pal.g : x === P.x0 ? wallDark : wall); + } + } + // Gilded roof with ribs, its eaves turned up at the corners. + const roofBottom = P.top - 1; + for (let y = P.roofTop; y <= roofBottom; y++) { + const hw = 5 + (y - P.roofTop) * 2; + for (let x = P.cx - hw; x <= P.cx + hw; x++) { + const rib = (x - P.cx) % 3 === 0; + let c = y === P.roofTop ? pal.G : y === roofBottom ? pal.d : rib ? pal.d : x > P.cx ? pal.G : pal.g; + if (x === P.cx - hw) c = pal.d; + s.set(x, y, c); + } + } + const eave = 5 + (roofBottom - P.roofTop) * 2; + for (const side of [-1, 1]) { + s.set(P.cx + side * (eave + 1), roofBottom - 1, pal.G); + s.set(P.cx + side * (eave + 2), roofBottom - 2, pal.G); + } + drawSprite(s, FINIAL, P.cx - 2, P.finialTop, pal); +} + +function drawOrnaments(s: Surface, pal: Record): void { + // Victory banners on the roof corners. + const [al, ar] = blockSpan(BLOCK_A, BLOCK_A.top); + const [bl, br] = blockSpan(BLOCK_B, BLOCK_B.top); + for (const [x, y] of [ + [al, BLOCK_A.top], + [ar, BLOCK_A.top], + [bl, BLOCK_B.top], + [br, BLOCK_B.top], + ]) { + drawSprite(s, GYALTSEN, x - 1, y - GYALTSEN.length, pal); + } + // The golden dharma wheel between two resting deer, above the gate. + const cx = PAVILION.cx; + const cy = BLOCK_A.top - 5; + for (let y = cy - 4; y <= cy + 4; y++) { + for (let x = cx - 4; x <= cx + 4; x++) { + const d = Math.hypot(x - cx, y - cy); + const ring = d > 2.5 && d < 3.7; + const spoke = d < 2.6 && (x === cx || y === cy || Math.abs(x - cx) === Math.abs(y - cy)); + if (ring) s.set(x, y, x > cx || y < cy ? pal.G : pal.g); + else if (spoke) s.set(x, y, pal.d); + } + } + for (let x = cx - 2; x <= cx + 2; x++) s.set(x, cy + 4, pal.g); + drawSprite(s, DEER, cx - 10, cy + 1, pal); + drawSprite(s, DEER, cx + 6, cy + 1, pal, true); +} + +// --------------------------------------------------------------------------- +// Gate and prayer-wheel galleries +// --------------------------------------------------------------------------- + +/** How far the gate stands open, 0–1. */ +function gateOpen(t: number): number { + return progress(t, GATE_OPEN[0], GATE_OPEN[1]) * (1 - progress(t, GATE_OPEN[2], GATE_OPEN[3])); +} + +function drawGate(s: Surface, f: Frame, pal: Record): void { + const G = GATE; + const wood = lit(f, WOOD); + const frame = lit(f, FRAME); + const door = sunlit(f, MAROON, 0.2); + const doorDark = lit(f, MAROON_DARK); + const shambu = SHAMBU.map((c) => sunlit(f, c, 0.2)); + // A small roofed canopy over the door. + for (let x = G.x0 - 2; x <= G.x1 + 2; x++) s.set(x, G.y0 - 4, wood); + for (let x = G.x0 - 3; x <= G.x1 + 3; x++) { + s.set(x, G.y0 - 3, wood); + s.set(x, G.y0 - 2, pal.g); + } + for (let x = G.x0 - 1; x <= G.x1 + 1; x++) s.set(x, G.y0 - 1, shambu[(x + 1) % 3]); + + const o = gateOpen(f.t); + const mid = (G.x0 + G.x1) / 2; + const leafW = (mid - G.x0 - 1) * (1 - o * 0.85); + for (let y = G.y0; y <= G.y1; y++) { + for (let x = G.x0; x <= G.x1; x++) { + if (x === G.x0 || x === G.x1 || y === G.y0) { + s.set(x, y, frame); + continue; + } + const fromJamb = x < mid ? x - G.x0 : G.x1 - x; + if (fromJamb > leafW + 0.5 || x === mid) { + // The doorway: dark, with lamplight glowing from deep inside. + const k = o * (0.25 + 0.35 * ((y - G.y0) / (G.y1 - G.y0))); + s.set(x, y, x === mid && o < 0.05 ? frame : mix(DOORWAY, LAMP_MID, k)); + continue; + } + let c = fromJamb === Math.round(leafW) ? doorDark : door; + if ((y - G.y0) % 4 === 2 && fromJamb % 2 === 1) c = pal.g; + s.set(x, y, c); + } + } + if (o < 0.05) { + s.set(mid - 2, G.y0 + 8, pal.G); + s.set(mid + 2, G.y0 + 8, pal.G); + } +} + +function drawGalleries(s: Surface, f: Frame, pal: Record): void { + const wood = lit(f, WOOD); + const back = lit(f, MAROON_DARK); + const fascia = sunlit(f, MAROON, 0.2); + const sill = sunlit(f, PLINTH, 0.15); + for (const g of GALLERIES) { + for (let x = g.x0 - 1; x <= g.x1 + 1; x++) { + s.set(x, GALLERY_ROOF, wood); + s.set(x, GALLERY_ROOF + 1, x % 4 === 0 ? pal.g : fascia); + } + for (let y = GALLERY_ROOF + 2; y <= GROUND_Y; y++) { + for (let x = g.x0; x <= g.x1; x++) s.set(x, y, y >= GROUND_Y - 1 ? sill : back); + } + } + const brass = [lit(f, BRASS_DARK), sunlit(f, BRASS, 0.3), sunlit(f, BRASS_LIGHT, 0.4), sunlit(f, BRASS, 0.4)]; + const ink = lit(f, hex('#5a3a1e')); + for (const wx of WHEELS) { + const turn = wheelTurn(f.t, wx); + s.set(wx, WHEEL_TOP - 1, wood); + s.set(wx + 1, WHEEL_TOP - 1, wood); + for (let y = WHEEL_TOP; y <= WHEEL_BOTTOM; y++) { + for (let c = 0; c < 4; c++) { + const x = wx - 1 + c; + if (y === WHEEL_TOP || y === WHEEL_BOTTOM) { + s.set(x, y, brass[0]); + continue; + } + let col = brass[c]; + if (y === WHEEL_TOP + 2 || y === WHEEL_BOTTOM - 2) col = brass[Math.min(3, c + 1)]; + else { + // Engraved mantra bands slide round the drum as it turns. + const around = Math.asin((c - 1.5) / 2) / (Math.PI * 2) + turn; + if (((around * 4) % 1 + 1) % 1 < 0.35) col = mix(col, ink, 0.7); + } + s.set(x, y, col); + } + } + } +} + +// --------------------------------------------------------------------------- +// Settled snow +// --------------------------------------------------------------------------- + +function snowLedge(s: Surface, f: Frame, x0: number, x1: number, y: number, seed: number, snow: RGB, shade: RGB): void { + for (let x = x0; x <= x1; x++) { + const n = Math.floor(f.snowCover * 2.4 + hash(x, seed, 33) * 0.9 - (x === x0 || x === x1 ? 0.6 : 0)); + for (let k = 1; k <= n; k++) s.set(x, y - k, k === 1 && n > 1 ? shade : snow); + } +} + +function drawSettledSnow(s: Surface, f: Frame): void { + if (f.snowCover <= 0) return; + const snow = lit(f, SNOW); + const shade = lit(f, SNOW_SHADE); + const [al, ar] = blockSpan(BLOCK_A, BLOCK_A.top); + const [bl, br] = blockSpan(BLOCK_B, BLOCK_B.top); + snowLedge(s, f, al - 1, ar + 1, BLOCK_A.top, 1, snow, shade); + snowLedge(s, f, bl - 1, br + 1, BLOCK_B.top, 2, snow, shade); + snowLedge(s, f, PAVILION.cx - 4, PAVILION.cx + 4, PAVILION.roofTop, 3, snow, shade); + snowLedge(s, f, GATE.x0 - 2, GATE.x1 + 2, GATE.y0 - 4, 4, snow, shade); + for (const g of GALLERIES) snowLedge(s, f, g.x0 - 1, g.x1 + 1, GALLERY_ROOF, 5, snow, shade); + if (f.snowCover > 0.45) { + for (const w of WINDOWS) { + if (w.w < 5) continue; + const half = w.w >> 1; + for (let x = w.cx - half - 2; x <= w.cx + half + 2; x++) if (hash(x, w.y0, 34) < f.snowCover) s.set(x, w.y0 - 5, snow); + } + } +} + +export function drawMonastery(s: Surface, f: Frame): void { + const pal = goldPalette(f); + drawBlock(s, f, BLOCK_B, [148, 177]); + drawPavilion(s, f, pal); + drawBlock(s, f, BLOCK_A, []); + drawOrnaments(s, pal); + drawWindows(s, f); + drawGate(s, f, pal); + drawGalleries(s, f, pal); + drawSettledSnow(s, f); +} + +// --------------------------------------------------------------------------- +// Chorten +// --------------------------------------------------------------------------- + +/** Half-widths of the chorten's tiers from the base up: [rows, half-width]. */ +const TIERS: readonly (readonly [number, number])[] = [ + [5, 11], + [3, 9], + [2, 7], + [2, 6], +]; +/** Bumpa (dome) half-widths from its bottom row up: broad at the shoulder like an upturned bell. */ +const BUMPA = [5, 6, 6, 7, 7, 7, 7, 6, 4]; +const SPIRE_ROWS = 13; + +export function drawChorten(s: Surface, f: Frame): void { + const pal = goldPalette(f); + const cx = CHORTEN.cx; + const lightW = sunlit(f, WALL, 0.34); + const midW = sunlit(f, WALL, 0.12); + const shadeW = lit(f, WALL_SHADE); + const edge = lit(f, scale(WALL_SHADE, 0.75)); + const snow = lit(f, SNOW); + const white = (x: number, hw: number) => (x - cx < -hw * 0.35 ? shadeW : x - cx > hw * 0.35 ? lightW : midW); + + let y = CHORTEN.base; + for (let i = 0; i < TIERS.length; i++) { + const [rows, hw] = TIERS[i]; + for (let r = 0; r < rows; r++, y--) { + for (let x = cx - hw; x <= cx + hw; x++) s.set(x, y, r === rows - 1 ? edge : white(x, hw)); + } + // Snow gathers on each step's tread. + const nextHw = TIERS[i + 1]?.[1] ?? BUMPA[0]; + for (let x = cx - hw; x <= cx + hw; x++) { + if (Math.abs(x - cx) > nextHw && hash(x, i, 35) < f.snowCover * 1.4) s.set(x, y, snow); + } + } + for (let r = 0; r < BUMPA.length; r++, y--) { + const hw = BUMPA[r]; + for (let x = cx - hw; x <= cx + hw; x++) s.set(x, y, x === cx - hw ? edge : white(x, hw)); + } + // A small dark niche in the dome. + for (let yy = y + 3; yy <= y + 6; yy++) for (let x = cx - 1; x <= cx + 1; x++) s.set(x, yy, yy === y + 3 && x !== cx ? midW : lit(f, DOORWAY)); + s.set(cx, y + 5, pal.g); + // Harmika, then the thirteen gilded rings of the spire. + for (let r = 0; r < 3; r++, y--) for (let x = cx - 3; x <= cx + 3; x++) s.set(x, y, r === 2 ? edge : white(x, 3)); + for (let r = 0; r < SPIRE_ROWS; r++, y--) { + const hw = r < 5 ? 2 : r < 10 ? 1.5 : 1; + for (let x = Math.round(cx - hw); x <= cx + hw; x++) s.set(x, y, r % 2 ? pal.d : x > cx ? pal.G : pal.g); + } + for (let x = cx - 3; x <= cx + 3; x++) s.set(x, y, pal.g); + y--; + // Crescent moon cradling the sun. + s.set(cx - 2, y, pal.g); + s.set(cx + 2, y, pal.g); + y--; + for (let x = cx - 1; x <= cx + 1; x++) s.set(x, y, pal.g); + y--; + s.set(cx, y, pal.G); + s.set(cx, y - 1, pal.G); +} + +// --------------------------------------------------------------------------- +// Lamplight against the cold, drawn after the mist so it glows through it +// --------------------------------------------------------------------------- + +/** Quantize soft light into a few flat rings, the pixel-art way to draw a glow. */ +const band = (k: number) => Math.floor(k * 14) / 14; + +export function drawLamplight(s: Surface, f: Frame): void { + const dark = darkness(f); + const R = 7 + f.mist * 10; + for (let i = 0; i < WINDOWS.length; i++) { + const g = f.windows[i]; + if (g <= 0.02) continue; + const w = WINDOWS[i]; + const cy = w.y0 + w.h / 2; + const k = g * (0.06 + 0.5 * dark) * (1 + f.mist * 0.5) * (w.w < 5 ? 0.6 : 1); + for (let y = Math.floor(cy - R); y <= cy + R; y++) { + for (let x = Math.floor(w.cx - R); x <= w.cx + R; x++) { + const d = Math.hypot(x - w.cx, (y - cy) * 1.15); + if (d > R) continue; + s.light(x, y, GLOW, band(k * Math.pow(1 - d / R, 2))); + } + } + } + // Light from the open gate pools on the walkway. + const o = gateOpen(f.t); + if (o > 0) { + for (let y = GROUND_Y; y < LIP_Y; y++) { + const spread = 3 + (y - GROUND_Y) * 0.8; + for (let x = Math.floor(163 - spread - 4); x <= 163 + spread + 4; x++) { + const fall = 1 - Math.min(1, Math.abs(x - 163) / (spread + 4)); + s.light(x, y, GLOW, band(o * 0.3 * fall * (1 - (y - GROUND_Y) / (LIP_Y - GROUND_Y)))); + } + } + } + // Once the lamps are lit, a faint warmth falls on the snow below the lower windows. + for (let i = 0; i < 5; i++) { + const g = f.windows[i] * dark; + if (g <= 0.02) continue; + const cx = WINDOWS[i].cx; + for (let y = GROUND_Y; y < LIP_Y; y++) { + for (let x = cx - 7; x <= cx + 7; x++) { + const fall = (1 - Math.abs(x - cx) / 8) * (1 - (y - GROUND_Y) / (LIP_Y - GROUND_Y + 2)); + s.light(x, y, GLOW, band(g * 0.22 * fall)); + } + } + } +} diff --git a/src/meditations/tibetan-monastery/monks.ts b/src/meditations/tibetan-monastery/monks.ts new file mode 100644 index 0000000..b602094 --- /dev/null +++ b/src/meditations/tibetan-monastery/monks.ts @@ -0,0 +1,144 @@ +import { hex, mix, type RGB } from '../../engine/color'; +import { drawSprite, type SpriteArt } from '../../engine/sprite'; +import type { Surface } from '../../engine/Surface'; +import { sunlit, TIMES, type Frame } from './timeline'; +import { GATE } from './world'; + +// --------------------------------------------------------------------------- +// The kora: a clockwise loop, so the monastery is always on the walkers' right. They walk west +// along the front (spinning the prayer wheels), round the chorten, back east behind the building. +// --------------------------------------------------------------------------- + +const EAST = 232; +const WEST = 66; +const FRONT_Y = 147; +const BACK_Y = 142; +const RUN = EAST - WEST; +const TURN = 8; +const LAP = 2 * (RUN + TURN); +/** Walking pace in pixels a second; three easy laps fill the clear afternoon. */ +const SPEED = 5.6; +/** The second monk walks a few steps behind the first. */ +const FOLLOW = 16; +const START = -30; +/** Distance along the loop at which each monk turns in at the gate, on the third lap. */ +const GATE_S = EAST - (GATE.x0 + GATE.x1) / 2 + 2 * LAP; +const ENTER = 2.2; + +interface Pose { + x: number; + y: number; + /** 1 faces right, -1 left, 0 walking away from the camera. */ + facing: number; + behind: boolean; + /** 0–1 while stepping in through the gate. */ + entering: number; +} + +function poseAt(s: number): Pose { + const u = ((s % LAP) + LAP) % LAP; + if (u < RUN) return { x: EAST - u, y: FRONT_Y, facing: -1, behind: false, entering: 0 }; + if (u < RUN + TURN) { + const k = (u - RUN) / TURN; + return { x: WEST - 4 * Math.sin(Math.PI * k), y: FRONT_Y - 5 * k, facing: k < 0.5 ? -1 : 1, behind: k > 0.5, entering: 0 }; + } + if (u < 2 * RUN + TURN) return { x: WEST + (u - RUN - TURN), y: BACK_Y, facing: 1, behind: true, entering: 0 }; + const k = (u - 2 * RUN - TURN) / TURN; + return { x: EAST + 4 * Math.sin(Math.PI * k), y: BACK_Y + 5 * k, facing: k < 0.5 ? 1 : -1, behind: k < 0.5, entering: 0 }; +} + +function monkS(t: number, i: number): number { + return START - i * FOLLOW + Math.max(0, t - TIMES.kora) * SPEED; +} + +/** Time a monk's loop distance reaches s. */ +function timeAt(s: number, i: number): number { + return TIMES.kora + (s - START + i * FOLLOW) / SPEED; +} + +/** When each monk reaches the gate and steps inside. */ +export const MONK_IN = [timeAt(GATE_S, 0), timeAt(GATE_S, 1)] as const; +/** The gate stands open while the monks go in. */ +export const GATE_OPEN: readonly [number, number, number, number] = [MONK_IN[0] - 3, MONK_IN[0] - 1, MONK_IN[1] + ENTER + 1, MONK_IN[1] + ENTER + 4]; + +function monkPose(t: number, i: number): Pose | undefined { + const s = monkS(t, i); + if (s < GATE_S) return poseAt(s); + const k = (t - timeAt(GATE_S, i)) / ENTER; + if (k >= 1) return undefined; + const cx = (GATE.x0 + GATE.x1) / 2; + return { x: cx, y: FRONT_Y - 5 * k, facing: 0, behind: false, entering: k }; +} + +/** + * Revolutions of the prayer wheel at column wx: each monk gives it a turn as they pass along the + * front, and it coasts to a stop. + */ +export function wheelTurn(t: number, wx: number): number { + let revs = 0; + for (let i = 0; i < 2; i++) { + for (let lap = 0; lap < 3; lap++) { + const s = EAST - wx + lap * LAP; + if (s > GATE_S) break; + const tp = timeAt(s, i); + if (t > tp) revs += 1.4 * (1 - Math.exp(-(t - tp) / 3.5)); + } + } + return revs; +} + +// --------------------------------------------------------------------------- +// Sprites (facing left; mirrored when walking right). 6 wide, 11 tall, feet on the bottom row. +// --------------------------------------------------------------------------- + +const UPPER: SpriteArt = ['..hh..', '.shh..', '..yr..', '.yrrr.', '.yrRr.', 'arrRr.', '.rrRr.', '.rrRr.', '.rrRrr']; +const LEGS_STRIDE: SpriteArt = ['.r..r.', 'k....k']; +const LEGS_PASS: SpriteArt = ['..rr..', '..kk..']; +const AWAY: SpriteArt = ['..hh..', '.hhhh.', '..rr..', '.rrrr.', '.rRrr.', 'rrRrrr', '.rRrr.', '.rRrr.', '.rRrr.', '.r..r.', '.k..k.']; + +const BASE: Record = { + h: hex('#5a3e32'), + s: hex('#c08a62'), + y: hex('#e0a632'), + r: hex('#8a2428'), + R: hex('#5e161c'), + a: hex('#b07a56'), + k: hex('#2a1c1c'), +}; + +function drawMonk(s: Surface, f: Frame, p: Pose, i: number, dark: RGB): void { + const pal: Record = {}; + for (const k in BASE) pal[k] = sunlit(f, BASE[k], 0.25); + const x = Math.round(p.x) - 3; + const y = Math.round(p.y) - 10; + if (p.facing === 0) { + // Stepping into the dim doorway: the figure darkens and fades into it. + const a = 1 - p.entering; + for (const k in pal) pal[k] = mix(pal[k], dark, p.entering * 0.7); + drawSprite(s, AWAY, x, y, pal, false, Math.min(1, a * 1.6)); + return; + } + // Unhurried steps; the second monk's are out of phase with the first's. + const step = Math.floor(p.x / 3 + i * 0.5) % 2 === 0; + const flip = p.facing > 0; + drawSprite(s, UPPER, x, y, pal, flip); + drawSprite(s, step ? LEGS_STRIDE : LEGS_PASS, x, y + 9, pal, flip); +} + +const DOORWAY = hex('#1c1210'); + +/** Monks on the far side of the kora, drawn before the buildings so they pass behind them. */ +export function drawMonksBehind(s: Surface, f: Frame): void { + for (let i = 0; i < 2; i++) { + const p = monkPose(f.t, i); + if (p?.behind) drawMonk(s, f, p, i, DOORWAY); + } +} + +export function drawMonksFront(s: Surface, f: Frame): void { + // The follower first, so the leader overlaps them when they bunch up at the gate. + for (let i = 1; i >= 0; i--) { + const p = monkPose(f.t, i); + if (p && !p.behind) drawMonk(s, f, p, i, DOORWAY); + } +} diff --git a/src/meditations/tibetan-monastery/mountains.ts b/src/meditations/tibetan-monastery/mountains.ts new file mode 100644 index 0000000..e80b3ae --- /dev/null +++ b/src/meditations/tibetan-monastery/mountains.ts @@ -0,0 +1,179 @@ +import { bayer, hex, mix, scale, type RGB } from '../../engine/color'; +import { hash, noise1, noise2 } from '../../engine/rng'; +import type { Surface } from '../../engine/Surface'; +import { lit, sunlit, type Frame } from './timeline'; +import { GROUND_Y, H, LIP_Y, RANGES, SUMMIT, W, WALK } from './world'; + +const SNOW = hex('#f4f6fc'); +const SNOW_SHADE = hex('#b4c0dc'); +const RANGE_ROCK = hex('#5e6a86'); +const RANGE_ROCK_SHADE = hex('#3c4662'); +const ROSE = hex('#ff9ca8'); + +// --------------------------------------------------------------------------- +// Distant ranges +// --------------------------------------------------------------------------- + +/** Per range, per pixel: 0 none, 1 rock shade, 2 rock lit, 3 snow shade, 4 snow lit. */ +const RANGE_KIND: Uint8Array[] = RANGES.map((r, ri) => { + const k = new Uint8Array(W * H); + for (let x = 0; x < W; x++) { + // Slopes west of their peak (to the right) face the low sun. + const litSide = x >= r.peakX[x]; + for (let y = r.ridge[x]; y < H; y++) { + const below = y - r.ridge[x]; + // Snow reaches down gullies in ragged streaks. + const streak = (noise2(x / 4.5, y / 12, 80 + ri) - 0.45) * 12 + (noise1(x / 9, 90 + ri) - 0.5) * 10; + const snow = below < r.snowDepth + streak; + // A rocky band just under the ridge on steep faces breaks up the snow. + const rib = noise2(x / 3, y / 5, 70 + ri) > 0.8; + k[y * W + x] = (snow && !rib ? 3 : 1) + (litSide ? 1 : 0); + } + } + return k; +}); + +/** Haze toward the horizon color for each range, far → near. */ +const RANGE_HAZE = [0.48, 0.32, 0.18]; + +export function drawRanges(s: Surface, f: Frame): void { + for (let ri = 0; ri < RANGES.length; ri++) { + const r = RANGES[ri]; + const kind = RANGE_KIND[ri]; + const glow = f.alpenglow * (1 - f.veil[ri] * 0.6); + const snowLit = mix(sunlit(f, SNOW, 0.35), ROSE, glow * 0.5); + const base: RGB[] = [lit(f, RANGE_ROCK_SHADE), mix(sunlit(f, RANGE_ROCK, 0.3), ROSE, glow * 0.18), lit(f, SNOW_SHADE), snowLit]; + const haze = RANGE_HAZE[ri]; + let top = H; + for (let x = 0; x < W; x++) top = Math.min(top, r.ridge[x]); + // Colors per row: hazier toward the valleys, then lost in cloud as the veil closes. + const rows: RGB[][] = []; + for (let y = top; y < H; y++) { + const low = Math.min(1, (y - top) / 50) * 0.25; + rows.push(base.map((c) => mix(mix(c, f.horizonColor, Math.min(1, haze + low)), f.fog, f.veil[ri] * 0.5))); + } + // A veiled range dissolves into whatever cloud lies behind it rather than leaving a silhouette. + const alpha = 1 - f.veil[ri]; + if (alpha <= 0) continue; + for (let x = 0; x < W; x++) { + for (let y = r.ridge[x]; y < H; y++) { + const k = kind[y * W + x]; + if (k) s.blend(x, y, rows[y - top][k - 1], alpha); + } + } + } +} + +// --------------------------------------------------------------------------- +// Cloud sea filling the valleys +// --------------------------------------------------------------------------- + +export function seaTop(f: Frame, x: number): number { + const xs = x - f.drift * 0.12; + return f.sea + (noise1(xs / 18, 70) - 0.5) * 8 + (noise1(xs / 6 + f.t * 0.05, 71) - 0.5) * 2.5; +} + +export function drawCloudSea(s: Surface, f: Frame): void { + const sunTint = f.warm * 0.25 + f.alpenglow * 0.15; + const top = mix(mix(f.fog, f.sunColor, sunTint), ROSE, f.alpenglow * 0.15); + const mid = mix(f.fog, f.horizonColor, 0.3); + const shade = mix(scale(f.fog, 0.8), f.horizonColor, 0.4); + for (let x = 0; x < W; x++) { + const y0 = seaTop(f, x); + for (let y = Math.max(0, Math.floor(y0)); y < H; y++) { + const depth = y - y0; + if (depth < 1) { + s.blend(x, y, top, 0.55 * depth + 0.2); + continue; + } + // Billows: bright rounded tops with shaded undersides, fading to an even layer below. + const v = noise2((x - f.drift * 0.1) / 14, depth / 5 + f.t * 0.01, 72) - depth / 40; + const d = bayer(x, y) * 0.2; + const c = depth < 3 || v + d > 0.62 ? top : v + d > 0.38 ? mid : shade; + s.set(x, y, depth > 26 ? mid : c); + } + } +} + +// --------------------------------------------------------------------------- +// The summit +// --------------------------------------------------------------------------- + +const ROCK_LIGHT = hex('#8c7c70'); +const ROCK = hex('#6a5e5c'); +const ROCK_DARK = hex('#4a4048'); +const CRACK = hex('#2e2830'); +const FLAG = hex('#8e857a'); +const FLAG_JOINT = hex('#665c56'); +const LIP = hex('#3a3238'); + +/** + * Per pixel: 0 air, 1–3 rock (dark → light), 4 crack, 5 flagstone, 6 joint, 7 lip. + * SUMMIT_SNOW holds the settled-snow amount at which each pixel turns white (ledges first). + */ +const SUMMIT_KIND = new Uint8Array(W * H); +const SUMMIT_SNOW = new Float32Array(W * H); +(() => { + for (let x = 0; x < W; x++) { + const slope = (SUMMIT[Math.min(W - 1, x + 3)] - SUMMIT[Math.max(0, x - 3)]) / 6; + for (let y = SUMMIT[x]; y < H; y++) { + const i = y * W + x; + const walk = x >= WALK.x0 && x <= WALK.x1 && y >= GROUND_Y && y < LIP_Y; + if (walk) { + // Flagstones in courses, foreshortened toward the building. + const course = Math.floor((y - GROUND_Y) / 3); + const joint = (y - GROUND_Y) % 3 === 2 || (x + course * 5) % (9 + course) === 0; + SUMMIT_KIND[i] = joint ? 6 : 5; + SUMMIT_SNOW[i] = 0.1 + noise2(x / 9, y / 2.5, 3) * 0.8 + (y - GROUND_Y) * 0.02 + hash(x, y, 4) * 0.06; + continue; + } + if (x >= WALK.x0 && x <= WALK.x1 && y === LIP_Y) { + SUMMIT_KIND[i] = 7; + SUMMIT_SNOW[i] = 0.9; + continue; + } + const below = y - SUMMIT[x]; + // Strata run gently across the cliffs; cracks run down them. + const strata = noise2(x / 22, y / 3.2, 5) + (noise2(x / 5, y / 9, 6) - 0.5) * 0.4; + const crack = noise2(x / 3.5, y / 10, 7) > 0.84; + // Faces turned toward the sun (falling away to the right) are lighter. + const face = slope > 0.15 ? 1 : slope < -0.15 ? -1 : 0; + let tone = strata > 0.62 ? 3 : strata > 0.38 ? 2 : 1; + tone = Math.max(1, Math.min(3, tone + (face > 0 ? 1 : face < 0 ? -1 : 0) * (hash(x, y, 8) < 0.6 ? 1 : 0))); + SUMMIT_KIND[i] = crack ? 4 : tone; + // Snow lies on top of the rock and on strata ledges; it builds up from there. + const ledge = noise2(x / 22, (y - 1) / 3.2, 5) < 0.45 && strata > 0.55; + SUMMIT_SNOW[i] = + below < 2 + ? 0.05 + hash(x, y, 9) * 0.25 + : 0.42 + below * 0.008 + (noise2(x / 7, y / 4, 12) - 0.5) * 0.9 - (ledge ? 0.25 : 0) + hash(x, y, 11) * 0.06; + } + } +})(); + +export function drawSummit(s: Surface, f: Frame): void { + const pal: RGB[] = [ + [0, 0, 0], + lit(f, ROCK_DARK), + sunlit(f, ROCK, 0.2), + sunlit(f, ROCK_LIGHT, 0.35), + lit(f, CRACK), + sunlit(f, FLAG, 0.15), + lit(f, FLAG_JOINT), + lit(f, LIP), + ]; + const snow = sunlit(f, SNOW, 0.25); + const snowShade = lit(f, SNOW_SHADE); + // High-altitude snow is always lying about; the storm adds more. + const level = 0.3 + f.snowCover * 0.55; + for (let x = 0; x < W; x++) { + for (let y = SUMMIT[x]; y < H; y++) { + const i = y * W + x; + const k = SUMMIT_KIND[i]; + if (!k) continue; + const st = SUMMIT_SNOW[i]; + if (st < level) s.set(x, y, st < level - 0.12 || k === 6 ? snow : snowShade); + else s.set(x, y, pal[k]); + } + } +} diff --git a/src/meditations/tibetan-monastery/sky.ts b/src/meditations/tibetan-monastery/sky.ts new file mode 100644 index 0000000..6cde180 --- /dev/null +++ b/src/meditations/tibetan-monastery/sky.ts @@ -0,0 +1,122 @@ +import { bayer, ditherStep, hex, mix, type RGB } from '../../engine/color'; +import type { Surface } from '../../engine/Surface'; +import { rayAt } from './clouds'; +import { CLOUD_LIT, CLOUD_MID, CLOUD_SHADE, SKY_BANDS, SUN_R, type Frame } from './timeline'; +import { H, HORIZON, W } from './world'; + +const HALO = hex('#fff0c8'); +const ROSE = hex('#ff9c9a'); +const WHITE: RGB = [255, 255, 255]; + +/** Which gradient band each sky pixel uses, with dithered seams; fixed by the layout. */ +const BAND_MAP: Uint8Array = (() => { + const map = new Uint8Array(W * HORIZON); + 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; + map[y * W + x] = Math.max(0, Math.min(SKY_BANDS - 1, Math.round(v))); + } + } + return map; +})(); + +export function drawSky(s: Surface, f: Frame): void { + for (let y = 0; y < HORIZON; y++) { + for (let x = 0; x < W; x++) { + const tone = f.cloudTone[y * W + x]; + if (tone & 3 && !(tone & 4)) continue; // solid cloud covers it + s.set(x, y, f.skyBands[BAND_MAP[y * W + x]]); + } + } + // Below the horizon: the haze the ranges and cloud sea stand in. + const below = mix(f.horizonColor, f.fog, 0.5); + for (let y = HORIZON; y < H; y++) for (let x = 0; x < W; x++) s.set(x, y, below); + drawSun(s, f); + drawClouds(s, f); + drawBloom(s, f); +} + +function drawSun(s: Surface, f: Frame): void { + if (f.warm <= 0.01) return; + const cx = Math.round(f.sunX); + const cy = Math.round(f.sunY); + const glowR = 38; + 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); + if (d > glowR) continue; + s.blend(x, y, mix(f.sunColor, HALO, 0.3), ditherStep(Math.pow(1 - d / glowR, 2.2) * 0.55 * f.warm, x, y)); + } + } + for (let y = -SUN_R; y <= SUN_R; y++) { + for (let x = -SUN_R; x <= SUN_R; x++) { + if (x * x + y * y <= SUN_R * SUN_R + SUN_R * 0.8) s.blend(cx + x, cy + y, mix(f.sunColor, WHITE, 0.35), Math.min(1, f.warm * 1.6)); + } + } +} + +function drawClouds(s: Surface, f: Frame): void { + const lining = mix(f.sunColor, WHITE, 0.4); + // During the sun break the cloud tops facing the sun catch a rose-gold light. + const glow = mix(f.sunColor, ROSE, 0.4); + const base = [CLOUD_LIT(f.t), CLOUD_MID(f.t), CLOUD_SHADE(f.t)]; + base[0] = mix(base[0], glow, f.alpenglow * 0.45); + base[1] = mix(base[1], glow, f.alpenglow * 0.25); + for (let y = 0; y < HORIZON; y++) { + const haze = (y / HORIZON) * 0.3; + const row = base.map((c) => mix(c, f.horizonColor, haze)); + for (let x = 0; x < W; x++) { + const tone = f.cloudTone[y * W + x]; + if (tone === 0) continue; + let col: RGB = row[(tone & 3) - 1]; + if (tone & 4) { + // Thin edges: a bright lining close to the sun, translucent elsewhere. + const near = f.warm * Math.max(0, 1 - Math.hypot(x - f.sunX, y - f.sunY) / 50); + if (near > 0) col = mix(col, lining, 0.75 * near); + s.blend(x, y, col, near > 0.2 ? 1 : 0.65); + continue; + } + s.set(x, y, col); + } + } +} + +/** Light bleeding through and around the clouds near the sun. */ +function drawBloom(s: Surface, f: Frame): void { + if (f.warm <= 0.01) return; + const R = 24; + const k = (0.08 + 0.28 * f.sunOpen) * f.warm; + for (let y = Math.max(0, Math.floor(f.sunY - R)); y < Math.min(HORIZON, f.sunY + R); y++) { + for (let x = Math.floor(f.sunX - R); x <= f.sunX + R; x++) { + const d = Math.hypot(x - f.sunX, y - f.sunY); + if (d > R) continue; + s.light(x, y, f.sunColor, ditherStep(k * Math.pow(1 - d / R, 2), x, y, 5)); + } + } +} + +/** Sunbeams fanning down from the sun through the gap in the clouds during the last sun break. */ +export function drawSunbeams(s: Surface, f: Frame): void { + if (f.rays <= 0.01) return; + const sx = f.sunX; + const sy = f.sunY; + const { d, th } = f.clouds; + // Beams are soft, so their strength is worked out per 2x2 block, in flat steps. + for (let by = Math.max(0, Math.floor(sy - 4)) & ~1; by < H; by += 2) { + const dy = by + 0.5 - sy; + for (let bx = 0; bx < W; bx += 2) { + const dx = bx + 0.5 - sx; + const r = Math.hypot(dx, dy); + if (r < 14) continue; + const ray = rayAt(f.rayTable, Math.atan2(dy, dx)); + if (ray <= 0) continue; + const k = f.rays * ray * Math.exp(-r / 170) * Math.min(1, (r - 14) / 24) * 0.24; + for (let y = by; y < by + 2; y++) { + for (let x = bx; x < bx + 2; x++) { + const kk = y < HORIZON && d[y * W + x] > th ? k * 0.35 : k; + s.light(x, y, f.sunColor, Math.floor(kk * 16) / 16); + } + } + } + } +} diff --git a/src/meditations/tibetan-monastery/timeline.ts b/src/meditations/tibetan-monastery/timeline.ts new file mode 100644 index 0000000..7a01dc6 --- /dev/null +++ b/src/meditations/tibetan-monastery/timeline.ts @@ -0,0 +1,242 @@ +import { add, gradient, hex, mul, scale, type RGB } from '../../engine/color'; +import { colorTrack, ease, progress, track } from '../../engine/Timeline'; +import { noise1 } from '../../engine/rng'; +import { computeClouds, computeRayTable, openness, shadeClouds, type CloudField } from './clouds'; +import { WINDOWS } from './world'; + +/** All timings for the Monastery Above the Clouds meditation, in seconds. */ +export const DURATION = 300; + +export const TIMES = { + fadeIn: [0, 6], + fadeOut: [291, 300], + vulture: [8, 82], + /** Monks start their circuit; see monks.ts for the laps. */ + kora: 12, + leopard: [90, 140], + /** The lamp-lighter reaches the first window, then one window every `lampStep` seconds. */ + lamp0: 188, + lampStep: 5.6, +} as const; + +/** Light phases: clear late afternoon → clouding over → grey mist → blue-grey stormy dusk. */ +const P = [0, 105, 175, 250] 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('#2856a6', '#46679a', '#59637a', '#1d2537'), + phase('#3c74bc', '#6283ae', '#6a7388', '#263045'), + phase('#6496cc', '#88a0bc', '#7c8597', '#2f3a51'), + phase('#9ebedc', '#adbccc', '#8c94a3', '#39445e'), + phase('#e2e0d4', '#d6d2cc', '#9aa1ab', '#434e69'), +]; + +/** Light falling on everything in the scene, as a per-channel multiplier. */ +const AMBIENT = phase('#fff2e0', '#e6dedc', '#9298ae', '#4a5472'); + +export const CLOUD_LIT = phase('#ffffff', '#f2ecea', '#a6aab8', '#505a76'); +export const CLOUD_MID = phase('#d6e0ee', '#c8c8d2', '#8a909f', '#404962'); +export const CLOUD_SHADE = phase('#98a8c2', '#8e92a8', '#6c7284', '#323a52'); +/** Cloud sea and summit mist. */ +const FOG = phase('#eef0f6', '#dcdae0', '#a0a6b6', '#4e5874'); + +const sunX = track([[0, 286], [180, 274]], ease.linear); +const sunY = track([[0, 24], [180, 80]], ease.linear); +const sunColor = colorTrack([ + [0, hex('#fff6dc')], + [100, hex('#ffe4ae')], + [145, hex('#ffb676')], + [180, hex('#ff946c')], +]); +/** Strength of direct sun before clouds, fading as it drops toward the haze. */ +const sunPower = track([[0, 1], [110, 0.9], [160, 0.75], [185, 0]]); +const cover = track([ + [0, 0.1], + [40, 0.18], + [80, 0.45], + [115, 0.8], + [165, 0.95], + [195, 1.1], +]); +/** The last sun break: a hole tears open around the sun, then closes for good. */ +const gap = track([[120, 0], [134, 1], [150, 1], [164, 0]]); +/** Top row of the cloud sea in the valleys. */ +const sea = track([ + [0, 172], + [50, 165], + [80, 146], + [105, 127], + [130, 119], + [180, 111], + [300, 104], +]); +/** How far each range (far → near) has disappeared into the cloud. */ +const VEIL = [track([[125, 0], [178, 1]]), track([[100, 0], [140, 1]]), track([[78, 0], [108, 1]])]; +const mist = track([[148, 0], [185, 0.35], [235, 0.5], [300, 0.62]]); +const windBase = track([[0, 0.22], [100, 0.32], [160, 0.55], [220, 0.85], [300, 1]]); +const snow = track([[166, 0], [200, 0.35], [240, 0.7], [291, 1]]); +const snowCover = track([[172, 0], [290, 1]]); + +/** Wind with slow gusts layered on the rising base, 0–~1.3. */ +export function windAt(t: number): number { + const g = 0.7 * noise1(t * 0.3, 3) + 0.3 * noise1(t * 1.1, 4); + return windBase(t) * (0.72 + 0.56 * g); +} + +/** + * How far the air has moved since t = 0, in pixels at the snow's depth. Integrated from a table so + * that particles riding the wind never jump when it changes, while staying a pure function of t. + */ +const DRIFT_DT = 0.05; +const DRIFT_SPEED = 24; +const DRIFT: Float64Array = (() => { + const n = Math.ceil(DURATION / DRIFT_DT) + 2; + const out = new Float64Array(n); + for (let i = 1; i < n; i++) out[i] = out[i - 1] + windAt((i - 0.5) * DRIFT_DT) * DRIFT_SPEED * DRIFT_DT; + return out; +})(); + +export function driftAt(t: number): number { + const u = Math.max(0, t) / DRIFT_DT; + const i = Math.min(DRIFT.length - 2, Math.floor(u)); + return DRIFT[i] + (DRIFT[i + 1] - DRIFT[i]) * (u - i); +} + +/** When the lamp-lighter reaches a window. */ +export function lampTime(order: number): number { + return TIMES.lamp0 + order * TIMES.lampStep; +} + +export const SUN_R = 6; +export const SKY_BANDS = 22; + +export interface Frame { + t: number; + /** Ambient light multiplier, 0–1 per channel. */ + amb: RGB; + skyBands: RGB[]; + horizonColor: RGB; + sunX: number; + sunY: number; + sunColor: RGB; + /** How much of the sun is unobstructed by cloud, 0–1. */ + sunOpen: number; + /** Strength of warm direct sunlight on the scene (0 once the sun is gone). */ + warm: number; + /** Pink light on the snow peaks during the sun break. */ + alpenglow: number; + /** Sunbeams fanning down through the gap. */ + rays: number; + cover: number; + clouds: CloudField; + /** Cached per-pixel cloud tones (see shadeClouds). */ + cloudTone: Uint8Array; + /** Beam brightness by angle from the sun (see clouds.ts). */ + rayTable: Float32Array; + /** Top row of the cloud sea. */ + sea: number; + /** Per range (far → near), 0 clear to 1 lost in cloud. */ + veil: number[]; + /** Lit color of the cloud sea and mist. */ + fog: RGB; + /** Mist streaming over the summit, 0–1. */ + mist: number; + wind: number; + /** Total wind travel in pixels (see driftAt). */ + drift: number; + /** Falling snow density, 0–1. */ + snow: number; + /** Snow settled on ledges and rocks, 0–1. */ + snowCover: number; + /** Lamp glow behind each window in WINDOWS, including flicker. */ + windows: number[]; + /** Overall brightness for the fade in/out. */ + fade: number; +} + +/** + * Clouds move about a pixel a second, so the field is recomputed only every 1/12 s of scene time. + * Keying the cache on quantized time keeps the scene a pure function of t. + */ +const CLOUD_STEP = 1 / 12; +let cache: { key: number; clouds: CloudField; tone: Uint8Array; rays: Float32Array; sunOpen: number } | undefined; + +function cloudsAt(t: number) { + const key = Math.round(t / CLOUD_STEP); + if (cache?.key === key) return cache; + const tq = key * CLOUD_STEP; + const sx = sunX(tq); + const sy = sunY(tq); + const cv = cover(tq); + const clouds = computeClouds(tq * 0.9 + driftAt(tq) * 0.22, cv, gap(tq), sx, sy, cache?.clouds); + let open = 0; + for (let i = 0; i < 9; i++) { + const a = (i / 9) * Math.PI * 2; + open += openness(clouds, sx + Math.cos(a) * (i ? 4 : 0), sy + Math.sin(a) * (i ? 4 : 0)); + } + cache = { + key, + clouds, + tone: shadeClouds(clouds, sx, cv, cache?.tone), + rays: computeRayTable(clouds, sx, sy, tq, cache?.rays), + sunOpen: open / 9, + }; + return cache; +} + +export function frameAt(t: number): Frame { + const sky = SKY.map((c) => c(t)); + const { clouds, tone: cloudTone, rays: rayTable, sunOpen } = cloudsAt(t); + const warm = sunPower(t) * (0.15 + 0.85 * sunOpen); + const g = gap(t); + const amb = scale(AMBIENT(t), 1 / 255); + return { + t, + // The sun break lifts the light a little, warmly. + amb: add(amb, [0.12, 0.07, 0.02], g * sunOpen), + skyBands: Array.from({ length: SKY_BANDS }, (_, i) => gradient(sky, i / (SKY_BANDS - 1))), + horizonColor: sky[4], + sunX: sunX(t), + sunY: sunY(t), + sunColor: sunColor(t), + sunOpen, + warm, + alpenglow: g * sunOpen, + rays: g * sunOpen, + cover: cover(t), + clouds, + cloudTone, + rayTable, + sea: sea(t), + veil: VEIL.map((v) => v(t)), + fog: FOG(t), + mist: mist(t), + wind: windAt(t), + drift: driftAt(t), + snow: snow(t), + snowCover: snowCover(t), + windows: WINDOWS.map((w, i) => { + const flicker = 0.84 + 0.1 * noise1(t * 3.1 + i * 7, 50 + i) + 0.06 * noise1(t * 9 + i, 60 + i); + const lamp = progress(t, lampTime(w.order), lampTime(w.order) + 3.5); + return Math.max(w.shrine ? 0.3 : 0, lamp) * flicker; + }), + 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); +} + +/** Ambient light plus a share of warm direct sun, for surfaces facing the sun. */ +export function sunlit(f: Frame, base: RGB, k = 0.25): RGB { + return add(mul(base, f.amb), mul(base, scale(f.sunColor, 1 / 255)), k * f.warm); +} diff --git a/src/meditations/tibetan-monastery/weather.ts b/src/meditations/tibetan-monastery/weather.ts new file mode 100644 index 0000000..4ba7a37 --- /dev/null +++ b/src/meditations/tibetan-monastery/weather.ts @@ -0,0 +1,116 @@ +import { bayer, hex, mix, mul, type RGB } from '../../engine/color'; +import { hash, noise2, Rng } from '../../engine/rng'; +import type { Surface } from '../../engine/Surface'; +import type { Frame } from './timeline'; +import { BLOCK_A, BLOCK_B, blockSpan, H, PAVILION, 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 stay hidden. */ + 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(13, 20) : r.range(5, 9), + sway: near ? r.range(2, 5) : r.range(1, 3), + freq: r.range(0.4, 1.1), + phase: r.range(0, Math.PI * 2), + big: near && r.next() < 0.4, + alpha: near ? r.range(0.75, 0.95) : r.range(0.4, 0.65), + rank: i / n, + })); +} + +const FAR = makeFlakes(17, 170, false); +const NEAR = makeFlakes(18, 60, true); +const FLAKE = hex('#ffffff'); +const FLAKE_TINT = hex('#dfe6ff'); + +function drawFlakes(s: Surface, f: Frame, flakes: Flake[], color: RGB, windK: number): void { + const wrapW = W + 16; + const wrapH = H + 8; + // In the stronger gusts, near flakes smear into short streaks. + const streak = windK > 1 && f.wind > 0.8; + for (const fl of flakes) { + const on = Math.max(0, Math.min(1, (f.snow - fl.rank) * 12)); + if (on <= 0) continue; + const y = ((fl.y0 + fl.speed * f.t) % wrapH) - 4; + const xRaw = fl.x0 + f.drift * windK * (0.8 + fl.rank * 0.4) + fl.sway * Math.sin(f.t * fl.freq + fl.phase); + const x = (((xRaw % wrapW) + wrapW) % wrapW) - 8; + const a = fl.alpha * on; + s.blend(x, y, color, a); + if (streak) s.blend(x - 1, y, color, a * 0.45); + 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 { + if (f.snow <= 0) return; + drawFlakes(s, f, FAR, mix(mul(FLAKE, f.amb), FLAKE_TINT, 0.25), 0.6); +} + +export function drawNearSnow(s: Surface, f: Frame): void { + if (f.snow <= 0) return; + drawFlakes(s, f, NEAR, mix(mul(FLAKE, f.amb), FLAKE_TINT, 0.4), 1.4); +} + +/** Banks of cloud streaming over the summit on the wind, thicker low down where the cloud sea is. */ +export function drawMist(s: Surface, f: Frame): void { + if (f.mist <= 0.01) return; + const fog = f.fog; + // The mist is soft, so its density is sampled per 2x2 block. + for (let by = 0; by < H; by += 2) { + const low = 0.5 + 0.5 * (by / H); + for (let bx = 0; bx < W; bx += 2) { + const n = + noise2((bx - f.drift * 0.45) / 46, by / 13, 90) * 0.65 + + noise2((bx - f.drift * 0.9) / 17, by / 6 + f.t * 0.02, 91) * 0.35; + const a = f.mist * low * Math.max(0, Math.min(1, (n - 0.28) / 0.5)); + if (a <= 0.02) continue; + for (let y = by; y < by + 2; y++) { + for (let x = bx; x < bx + 2; x++) s.blend(x, y, fog, Math.floor(a * 7 + bayer(x, y) * 0.35) / 7); + } + } + } +} + +/** Snow torn off the roof corners and the eastern knob in the strongest gusts. */ +const SOURCES: readonly (readonly [number, number])[] = [ + [blockSpan(BLOCK_A, BLOCK_A.top)[1] + 1, BLOCK_A.top - 2], + [blockSpan(BLOCK_B, BLOCK_B.top)[1] + 1, BLOCK_B.top - 2], + [PAVILION.cx + 4, PAVILION.roofTop - 1], + [302, 145], +]; +const SPIN_N = 16; +const SPIN_LIFE = 1.8; + +export function drawSpindrift(s: Surface, f: Frame): void { + const strength = f.snowCover * Math.max(0, f.wind - 0.7) * 2.4; + if (strength <= 0.02) return; + const c = mix(mul(FLAKE, f.amb), FLAKE_TINT, 0.3); + SOURCES.forEach(([sx, sy], si) => { + for (let i = 0; i < SPIN_N; i++) { + const age = (f.t + (i * SPIN_LIFE) / SPIN_N + si * 0.37) % SPIN_LIFE; + const cycle = Math.floor((f.t + (i * SPIN_LIFE) / SPIN_N + si * 0.37) / SPIN_LIFE); + const jitter = hash(cycle, i, 95 + si); + const x = sx + age * (16 + jitter * 14) * f.wind; + const y = sy - age * (2 + jitter * 3) + age * age * 3.5; + s.blend(x, y, c, Math.min(1, strength) * (1 - age / SPIN_LIFE) * 0.8); + } + }); +} diff --git a/src/meditations/tibetan-monastery/world.ts b/src/meditations/tibetan-monastery/world.ts new file mode 100644 index 0000000..fa5f10d --- /dev/null +++ b/src/meditations/tibetan-monastery/world.ts @@ -0,0 +1,212 @@ +import { noise1 } from '../../engine/rng'; + +/** Fixed layout of the scene on the 320x180 canvas. The sun sits low in the west, on the right. */ +export const W = 320; +export const H = 180; + +/** Bottom of the sky; everything below is mountains, cloud sea or the summit. */ +export const HORIZON = 118; + +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); +}; + +// --------------------------------------------------------------------------- +// Distant ranges, far → near. The rising cloud sea swallows the lower, nearer ones first. +// --------------------------------------------------------------------------- + +export interface Range { + /** Top row per column. */ + ridge: readonly number[]; + /** Column of the peak that each column's slope belongs to, for sun-facing shading. */ + peakX: readonly number[]; + /** Rows below the ridge that stay snow covered, before streaks. */ + snowDepth: number; + /** 0 = farthest; scales haze and contrast. */ + depth: number; +} + +function range(peaks: readonly (readonly [number, number, number])[], wobble: number, seed: number, snowDepth: number, depth: number): Range { + const ridge: number[] = []; + const peakX: number[] = []; + for (let x = 0; x < W; x++) { + let best = Infinity; + let px = 0; + for (const [cx, cy, k] of peaks) { + const y = cy + Math.abs(x - cx) * k; + if (y < best) { + best = y; + px = cx; + } + } + ridge.push(Math.round(best + (noise1(x / 4, seed) - 0.5) * wobble + (noise1(x / 13, seed + 1) - 0.5) * wobble * 1.6)); + peakX.push(px); + } + return { ridge, peakX, snowDepth, depth }; +} + +export const RANGES: readonly Range[] = [ + range( + [ + [22, 74, 0.62], + [70, 84, 0.5], + [128, 70, 0.58], + [196, 80, 0.52], + [246, 66, 0.6], + [300, 78, 0.55], + ], + 2, + 31, + 16, + 0, + ), + range( + [ + [-4, 92, 0.5], + [48, 96, 0.6], + [104, 100, 0.48], + [226, 98, 0.55], + [282, 90, 0.62], + ], + 3, + 35, + 9, + 1, + ), + range( + [ + [14, 112, 0.55], + [78, 118, 0.45], + [250, 114, 0.5], + [318, 108, 0.6], + ], + 3, + 39, + 5, + 2, + ), +]; + +// --------------------------------------------------------------------------- +// The summit the monastery stands on +// --------------------------------------------------------------------------- + +/** Row the walkway and building stand on. */ +export const GROUND_Y = 141; +/** Front edge of the walkway, where the cliffs begin. */ +export const LIP_Y = 150; + +/** Top row of the near rock per column: a plateau in the middle, shoulders falling away to both sides. */ +export const SUMMIT: readonly number[] = Array.from({ length: W }, (_, x) => { + const left = 186 - 46 * smoothstep(0, 66, x); + const right = 182 - 41 * smoothstep(320, 232, x); + let y = Math.max(GROUND_Y, Math.max(left, right)); + // Knob for the flag pole on the left and the snow leopard's ledge on the right. + y = Math.min(y, 151 + Math.abs(x - 36) * 0.9); + y = Math.min(y, x > 246 && x < 282 ? 151 + (noise1(x / 3, 44) - 0.5) * 1.5 : y); + y = Math.min(y, 147 + Math.abs(x - 302) * 0.8); + return Math.round(y + (noise1(x / 3.5, 41) - 0.5) * 2.4 * (y > GROUND_Y + 1 ? 1 : 0)); +}); + +/** Walkway in front of the building, from the chorten to past the east wall. */ +export const WALK = { x0: 64, x1: 236 }; + +// --------------------------------------------------------------------------- +// Monastery: whitewashed, battered walls stepping up the summit (see monastery.ts) +// --------------------------------------------------------------------------- + +export interface Block { + x0: number; + x1: number; + top: number; + base: number; + /** Pixels each side wall leans in from base to top. */ + taper: number; +} + +export const BLOCK_A: Block = { x0: 110, x1: 216, top: 100, base: GROUND_Y, taper: 4 }; +export const BLOCK_B: Block = { x0: 134, x1: 192, top: 74, base: 99, taper: 3 }; + +/** Left and right wall columns of a block at a row. */ +export function blockSpan(b: Block, y: number): [number, number] { + const k = Math.round(b.taper * (1 - (y - b.top) / (b.base - b.top))); + return [b.x0 + k, b.x1 - k]; +} + +/** The small maroon shrine room with the gilded roof on top. */ +export const PAVILION = { x0: 152, x1: 174, top: 64, base: 73, roofTop: 57, finialTop: 48, cx: 163 }; + +export const GATE = { x0: 157, x1: 169, y0: 125, y1: GROUND_Y }; + +/** Covered galleries of prayer wheels either side of the gate. */ +export const GALLERIES = [ + { x0: 116, x1: 153 }, + { x0: 173, x1: 210 }, +] as const; +export const GALLERY_ROOF = 128; +export const WHEEL_TOP = 131; +export const WHEEL_BOTTOM = 139; +export const WHEELS: readonly number[] = GALLERIES.flatMap((g) => { + const out: number[] = []; + for (let x = g.x0 + 3; x + 3 <= g.x1; x += 6) out.push(x); + return out; +}); + +export interface Window { + cx: number; + y0: number; + /** Glass width and height. */ + w: number; + h: number; + /** Order the lamp-lighter reaches it, 0 first. */ + order: number; + /** Butter lamps already burning before dusk (shrine rooms). */ + shrine?: boolean; +} + +export const WINDOWS: readonly Window[] = [ + { cx: 124, y0: 114, w: 5, h: 6, order: 0 }, + { cx: 141, y0: 114, w: 5, h: 6, order: 1 }, + { cx: 163, y0: 113, w: 7, h: 6, order: 2, shrine: true }, + { cx: 185, y0: 114, w: 5, h: 6, order: 3 }, + { cx: 202, y0: 114, w: 5, h: 6, order: 4 }, + { cx: 179, y0: 87, w: 5, h: 6, order: 5 }, + { cx: 147, y0: 87, w: 5, h: 6, order: 6 }, + { cx: 163, y0: 67, w: 3, h: 4, order: 7, shrine: true }, +]; + +// --------------------------------------------------------------------------- +// Chorten, flag pole, flag lines, the leopard's ledge +// --------------------------------------------------------------------------- + +export const CHORTEN = { cx: 86, base: 146 }; + +/** Darchor pole on the knob west of the monastery. */ +export const POLE = { x: 36, base: 152, top: 48 }; + +export interface FlagLine { + ax: number; + ay: number; + bx: number; + by: number; + /** Extra drop at the middle of the line. */ + sag: number; + /** Flag width/height in pixels and spacing along the line. */ + fw: number; + fh: number; + gap: number; + /** Lines close to the camera are drawn after the mist, larger and darker. */ + near?: boolean; +} + +export const FLAG_LINES: readonly FlagLine[] = [ + { ax: POLE.x, ay: POLE.top + 2, bx: 136, by: 74, sag: 9, fw: 3, fh: 4, gap: 5 }, + { ax: POLE.x, ay: POLE.top + 2, bx: -6, by: 132, sag: 6, fw: 3, fh: 4, gap: 5 }, + { ax: PAVILION.cx, ay: PAVILION.finialTop + 4, bx: 304, by: 145, sag: 14, fw: 3, fh: 4, gap: 5 }, + { ax: 190, ay: 74, bx: 330, by: 116, sag: 8, fw: 3, fh: 4, gap: 5 }, + { ax: CHORTEN.cx, ay: 105, bx: 111, by: 100, sag: 3, fw: 2, fh: 3, gap: 4 }, + { ax: -14, ay: -6, bx: 168, by: -12, sag: 30, fw: 7, fh: 9, gap: 10, near: true }, +]; + +export const LEDGE = { x0: 250, x1: 280, y: 151 };