Add "The Ringed Planet" meditation scene

- New 5-minute pixel-art meditation drifting in high orbit above a golden gas giant with rings
- Ray-traced planet body with differentially rotating cloud bands, storms, polar hexagon, terminator haze, lightning flashes and aurora curtains
- Layered ring sheet with density profile, orbital clumps, spokes, and cast shadows on the planet
- Passing cratered moon that casts a shadow, individual tumbling rocks/ice chunks in the near ring, and a deep-space background with galaxy band, nebulae, twinkling stars and a comet
- Voyager-style probe flies past with dish glints, beacon blink, and fade to a speck
- Registered in the meditation registry, audio track added, README updated
This commit is contained in:
Brian Fertig 2026-10-30 16:33:57 -06:00
parent cfd8c9a7a3
commit 50526614dc
13 changed files with 1470 additions and 1 deletions

View File

@ -37,6 +37,7 @@ so edits on the host reload in the browser; don't run it and `npm run dev` on th
| `northern-cabin` | Northern Cabin — winter sunset by a quiet lake | 5 min |
| `mediterranean-coast` | Mediterranean Coast — clearing skies over a jungle cove | 5 min |
| `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 |
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

Binary file not shown.

View File

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

View File

@ -0,0 +1,84 @@
import type { Surface } from '../../engine/Surface';
import { preparePlanet, shadeHaze, shadePlanet } from './planet';
import { shadeRing } from './rings';
import { drawSpace } from './space';
import { frameAt, type Frame } from './timeline';
import { H, LIT, pixelRay, R_IN, R_OUT, W, ZBUF } from './world';
/** Outer edge of the glowing haze above the limb, in planet radii. */
const HAZE_TOP = 1.035;
const ray = [0, 0, 0];
/**
* The sky, planet and rings shift by under a third of a pixel in 1/20 s, so they are drawn at that
* rate (on a fixed grid of times, keeping the scene a pure function of t) and reused in between.
*/
const STEP = 0.05;
const cached = { t: NaN, pixels: new Uint8ClampedArray(W * H * 4), z: new Float32Array(W * H), lit: new Float32Array(W * H) };
export function drawBackdrop(s: Surface, t: number): void {
const tq = Math.floor(t / STEP) * STEP;
if (tq !== cached.t) {
const f = frameAt(tq);
drawSpace(s, f);
drawBody(s, f);
cached.t = tq;
cached.pixels.set(s.data);
cached.z.set(ZBUF);
cached.lit.set(LIT);
} else {
s.data.set(cached.pixels);
ZBUF.set(cached.z);
LIT.set(cached.lit);
}
}
/**
* Trace every pixel against the planet and the ring plane and draw whichever shows, with the ring
* sheet blended over the planet wherever it passes in front. Also fills ZBUF and LIT for later layers.
*/
function drawBody(s: Surface, f: Frame): void {
preparePlanet(f);
const c = f.cam;
const [cx, cy, cz] = c.pos;
const cc = cx * cx + cy * cy + cz * cz;
for (let y = 0; y < H; y++) {
for (let x = 0; x < W; x++) {
pixelRay(c, x, y, ray);
const dx = ray[0];
const dy = ray[1];
const dz = ray[2];
const i = y * W + x;
ZBUF[i] = Infinity;
LIT[i] = -1;
// Ray against the planet: b is the distance to the closest approach, perp2 its squared radius.
const b = -(cx * dx + cy * dy + cz * dz);
const perp2 = cc - b * b;
let sp = Infinity;
if (b > 0 && perp2 < 1) {
sp = b - Math.sqrt(1 - perp2);
const px = cx + sp * dx;
const py = cy + sp * dy;
const pz = cz + sp * dz;
LIT[i] = shadePlanet(s, x, y, px, py, pz, -(px * dx + py * dy + pz * dz), f);
ZBUF[i] = sp * (dx * c.fwd[0] + dy * c.fwd[1] + dz * c.fwd[2]);
} else if (b > 0 && perp2 < HAZE_TOP * HAZE_TOP) {
const pr = Math.sqrt(perp2);
shadeHaze(s, x, y, (cx + b * dx) / pr, (cy + b * dy) / pr, (cz + b * dz) / pr, (pr - 1) / (HAZE_TOP - 1));
}
// Ray against the ring plane (the camera is always above it).
if (dy < 0) {
const sr = -cy / dy;
if (sr < sp) {
const qx = cx + sr * dx;
const qz = cz + sr * dz;
const r = Math.sqrt(qx * qx + qz * qz);
if (r >= R_IN && r <= R_OUT && shadeRing(s, x, y, qx, qz, r, sr, f) >= 0.5) LIT[i] = -1;
}
}
}
}
}

View File

@ -0,0 +1,32 @@
import type { Meditation, Scene } from '../types';
import { drawBackdrop } from './body';
import { drawMoon } from './moon';
import { drawAurora, drawLightning } from './planet';
import { drawRocks } from './rocks';
import { DURATION, frameAt } from './timeline';
import { drawVoyager } from './voyager';
const scene: Scene = {
render(s, t) {
const f = frameAt(t);
drawBackdrop(s, t);
drawAurora(s, f);
drawLightning(s, f);
drawMoon(s, f);
drawRocks(s, f);
drawVoyager(s, f);
s.darken(f.fade);
},
};
export const ringedPlanet: Meditation = {
id: 'ringed-planet',
title: 'The Ringed Planet',
subtitle: 'Drifting in high orbit above a ringed giant',
description:
'Float in high orbit above a vast golden world as its clouds and storms turn beneath you and its rings sweep slowly by. A moon passes, a comet crosses the stars, and an old probe drifts past on its long journey out into the dark.',
duration: DURATION,
previewTime: 205,
music: 'audio/ringed-planet.mp3',
createScene: () => scene,
};

View File

@ -0,0 +1,51 @@
import { ditherStep, hex } from '../../engine/color';
import { noise2 } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import type { Frame } from './timeline';
import { FOCAL, H, pixelRay, project, proj, SUN, W, ZBUF } from './world';
/** A small cratered moon that passes in front of the planet; its shadow is drawn by the planet. */
export const MOON_R = 0.055;
const GREYS = ['#2c2a2a', '#4c4844', '#6e6862', '#948c84', '#b8b0a6', '#d4ccc0'].map(hex);
const ray = [0, 0, 0];
export function drawMoon(s: Surface, f: Frame): void {
const m = f.moon;
if (!m) return;
const c = f.cam;
const z = project(c, m[0], m[1], m[2]);
if (z <= 0) return;
const R = (FOCAL * MOON_R) / z + 1;
const [cx, cy, cz] = c.pos;
const ox = cx - m[0];
const oy = cy - m[1];
const oz = cz - m[2];
const oo = ox * ox + oy * oy + oz * oz - MOON_R * MOON_R;
const x0 = Math.max(0, Math.floor(proj.x - R));
const x1 = Math.min(W - 1, Math.ceil(proj.x + R));
const y0 = Math.max(0, Math.floor(proj.y - R));
const y1 = Math.min(H - 1, Math.ceil(proj.y + R));
for (let y = y0; y <= y1; y++) {
for (let x = x0; x <= x1; x++) {
pixelRay(c, x, y, ray);
const b = ox * ray[0] + oy * ray[1] + oz * ray[2];
const disc = b * b - oo;
if (disc < 0) continue;
const sd = -b - Math.sqrt(disc);
const depth = sd * (ray[0] * c.fwd[0] + ray[1] * c.fwd[1] + ray[2] * c.fwd[2]);
const i = y * W + x;
if (depth >= ZBUF[i]) continue;
ZBUF[i] = depth;
const nx = (ox + sd * ray[0]) / MOON_R;
const ny = (oy + sd * ray[1]) / MOON_R;
const nz = (oz + sd * ray[2]) / MOON_R;
const lit = Math.max(0, nx * SUN[0] + ny * SUN[1] + nz * SUN[2]);
// Craters as dark blotches fixed to the surface.
const crater = noise2(nx * 3 + 5, ny * 3 + nz * 2, 70) * 0.6 + noise2(nx * 7, nz * 7 - ny * 3, 71) * 0.4;
const tone = (0.15 + 0.85 * lit) * (crater > 0.62 ? 0.72 : 1);
s.set(x, y, GREYS[Math.min(GREYS.length - 1, Math.round(ditherStep(tone, x, y, 5) * (GREYS.length - 1)))]);
}
}
}

View File

@ -0,0 +1,296 @@
import { bayer, ditherStep, hex, mix, type RGB } from '../../engine/color';
import { hash, noise1, noise2 } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import { clamp01 } from '../../engine/Timeline';
import { MOON_R } from './moon';
import { ringDensity } from './rings';
import type { Frame } from './timeline';
import { BANDS, H, LIT, project, proj, spin, SUN, W, ZBUF } from './world';
/**
* The giant itself. Its cloud bands turn at different rates (a fast equatorial jet with slower
* bands either side), so they shear and flow past each other; storms ride along in the bands and
* swirl. The rings and the passing moon cast shadows on it, a hexagonal vortex caps the north pole,
* lightning flickers in the night-side storms and an aurora wavers above the pole.
*/
interface Storm {
lat: number;
/** Longitude at t = 0 (0 faces the camera, positive is to the right). */
lon: number;
/** Half-widths in radians of arc. */
rx: number;
ry: number;
core: RGB;
mid: RGB;
rim: RGB;
/** Rate of the inner swirl. */
swirl: number;
}
const CREAM = hex('#f6e8c2');
const WHITE_OVAL: Pick<Storm, 'core' | 'mid' | 'rim'> = { core: hex('#e6d4a8'), mid: hex('#f8f0d8'), rim: hex('#b08850') };
const STORMS: readonly Storm[] = [
{ lat: 0.47, lon: -0.95, rx: 0.2, ry: 0.085, core: hex('#b4602e'), mid: hex('#d4884a'), rim: CREAM, swirl: 0.06 },
{ lat: 0.27, lon: -2.3, rx: 0.075, ry: 0.045, ...WHITE_OVAL, swirl: 0.09 },
{ lat: 0.72, lon: 0.15, rx: 0.08, ry: 0.05, ...WHITE_OVAL, swirl: 0.08 },
{ lat: -0.28, lon: -1.7, rx: 0.1, ry: 0.05, ...WHITE_OVAL, swirl: 0.07 },
{ lat: 0.12, lon: 0.6, rx: 0.06, ry: 0.035, ...WHITE_OVAL, swirl: 0.1 },
{ lat: 0.6, lon: -3.0, rx: 0.13, ry: 0.06, core: hex('#c47a3e'), mid: hex('#e0a460'), rim: CREAM, swirl: 0.07 },
{ lat: -0.5, lon: 0.9, rx: 0.09, ry: 0.05, ...WHITE_OVAL, swirl: 0.08 },
];
/** Storms drift a touch slower than the band they sit in. */
const stormLon = new Float64Array(STORMS.length);
const POLAR = hex('#7e8a86');
const POLAR_DEEP = hex('#5e6c70');
const POLAR_EYE = hex('#40484e');
const TERMINATOR = hex('#b85a30');
const HAZE = hex('#f8e2b0');
let moon: Frame['moon'];
/** Per-frame setup shared by every planet pixel. */
export function preparePlanet(f: Frame): void {
for (let i = 0; i < STORMS.length; i++) stormLon[i] = STORMS[i].lon + spin(STORMS[i].lat) * 0.96 * f.t;
moon = f.moon;
}
function wrapPi(a: number): number {
a %= Math.PI * 2;
return a > Math.PI ? a - Math.PI * 2 : a < -Math.PI ? a + Math.PI * 2 : a;
}
/** Per-latitude band brightness and spin rate, tabulated. */
const LATS = 2048;
const BAND_V = new Float32Array(LATS + 1);
const SPIN = new Float32Array(LATS + 1);
for (let i = 0; i <= LATS; i++) {
const lat = (i / LATS - 0.5) * Math.PI;
let v = 0.55 + 0.22 * Math.sin(lat * 11 + 0.4) + 0.14 * Math.sin(lat * 23 + 1.7) + 0.07 * Math.sin(lat * 47 + 0.3);
v += 0.28 * Math.exp(-((lat / 0.09) ** 2));
v -= 0.32 * clamp01((Math.abs(lat) - 0.85) / 0.45);
BAND_V[i] = v;
SPIN[i] = spin(lat);
}
function latSlot(lat: number): number {
return Math.max(0, Math.min(LATS, Math.round((lat / Math.PI + 0.5) * LATS)));
}
const col: [number, number, number] = [0, 0, 0];
/** Cloud-top color at a surface point (before lighting). */
function cloudColor(x: number, y: number, lat: number, lon: number, t: number): RGB {
// Polar hexagon.
const colat = Math.PI / 2 - lat;
if (colat < 0.42) {
const a = lon - 0.004 * t;
const sector = (((a % (Math.PI / 3)) + Math.PI / 3) % (Math.PI / 3)) - Math.PI / 6;
const edge = 0.3 / Math.cos(sector);
if (colat < edge - 0.03) {
if (colat < 0.05) return POLAR_EYE;
return noise2(colat * 30, a * 3, 12) + bayer(x, y) * 0.3 > 0.75 ? POLAR_DEEP : POLAR;
}
if (colat < edge) return BANDS[1];
}
const L = lon - SPIN[latSlot(lat)] * t;
const w1 = noise2(L * 3.2, lat * 9, 1) - 0.5;
const w2 = noise2(L * 9, lat * 26, 2) - 0.5;
let v = BAND_V[latSlot(lat + w1 * 0.06 + w2 * 0.018)];
v += (noise2(L * 6, lat * 80, 5) - 0.5) * 0.2;
const cl = Math.cos(lat);
for (let i = 0; i < STORMS.length; i++) {
const st = STORMS[i];
const ey = (lat - st.lat) / st.ry;
if (ey > 1.6 || ey < -1.6) continue;
const ex = (wrapPi(lon - stormLon[i]) * cl) / st.rx;
const d2 = ex * ex + ey * ey;
if (d2 > 2.56) continue;
const d = Math.sqrt(d2);
if (d < 1) {
// Inside, the clouds spiral: the middle turns faster than the edge.
const ang = (1 - d) * (1 - d) * 2.4 + t * st.swirl * (1 - d * 0.7);
const ca = Math.cos(ang);
const sa = Math.sin(ang);
const n = noise2((ex * ca - ey * sa) * 2.6 + i * 13, (ex * sa + ey * ca) * 2.6, 9);
if (d > 0.84 - n * 0.12) return st.rim;
return n + bayer(x, y) * 0.25 > 0.62 ? st.mid : st.core;
}
// A pale collar of disturbed cloud around it.
v += 0.3 * (1 - (d - 1) / 0.6) ** 2;
}
const idx = Math.floor(clamp01(v) * (BANDS.length - 1) + bayer(x, y));
return BANDS[Math.min(BANDS.length - 1, idx)];
}
/** Light and draw the planet at surface point p, seen at cos(view angle) mu; returns its raw sunlit amount. */
export function shadePlanet(s: Surface, x: number, y: number, px: number, py: number, pz: number, mu: number, f: Frame): number {
const lat = Math.asin(Math.max(-1, Math.min(1, py)));
const lon = Math.atan2(px, pz);
let c = cloudColor(x, y, lat, lon, f.t);
const lit = px * SUN[0] + py * SUN[1] + pz * SUN[2];
let k = clamp01(lit * 1.7 + 0.05);
k = Math.sqrt(k) * 0.35 + k * 0.65;
k *= 0.62 + 0.38 * Math.sqrt(mu);
// The rings' shadow: follow the sunward ray up to the ring plane.
if (py < 0) {
const s2 = -py / SUN[1];
const qx = px + s2 * SUN[0];
const qz = pz + s2 * SUN[2];
const rq = Math.sqrt(qx * qx + qz * qz);
k *= 1 - 0.8 * ringDensity(rq);
}
if (moon) {
const mx = moon[0] - px;
const my = moon[1] - py;
const mz = moon[2] - pz;
const along = mx * SUN[0] + my * SUN[1] + mz * SUN[2];
if (along > 0) {
const off = Math.sqrt(Math.max(0, mx * mx + my * my + mz * mz - along * along));
k *= 1 - 0.92 * clamp01((MOON_R * 1.3 - off) / (MOON_R * 0.5));
}
}
if (lit > -0.06 && lit < 0.24) {
c = mix(c, TERMINATOR, 0.35 * clamp01(1 - Math.abs(lit - 0.08) / 0.16));
}
const kq = Math.max(0.05, ditherStep(k, x, y, 10));
col[0] = c[0] * kq;
col[1] = c[1] * kq;
col[2] = c[2] * kq;
s.set(x, y, col);
if (mu < 0.3 && lit > 0) s.blend(x, y, HAZE, ditherStep((1 - mu / 0.3) * 0.4 * Math.min(1, lit * 2.5), x, y, 4));
return Math.max(0, lit);
}
/** The thin glow of atmosphere just beyond the limb; `edge` runs 0 at the limb to 1 at the top of the haze. */
export function shadeHaze(s: Surface, x: number, y: number, nx: number, ny: number, nz: number, edge: number): void {
const lit = nx * SUN[0] + ny * SUN[1] + nz * SUN[2];
if (lit <= 0) return;
s.blend(x, y, HAZE, ditherStep((1 - edge) * 0.55 * Math.min(1, lit * 2), x, y, 4));
}
// ---------------------------------------------------------------------------
// Lightning
// ---------------------------------------------------------------------------
const BOLT = hex('#d8e4ff');
/** Spots in the cloud bands where storms on the night side flash; they drift with their band. */
const SITES = Array.from({ length: 40 }, (_, i) => ({
lat: (hash(i, 1, 40) - 0.5) * 1.3,
lon: hash(i, 2, 40) * Math.PI * 2,
rate: 0.6 + hash(i, 3, 40) * 0.8,
}));
export function drawLightning(s: Surface, f: Frame): void {
if (f.lightning <= 0) return;
const t = f.t;
const c = f.cam;
for (let i = 0; i < SITES.length; i++) {
const site = SITES[i];
const lon = site.lon + spin(site.lat) * t;
const cl = Math.cos(site.lat);
const px = cl * Math.sin(lon);
const py = Math.sin(site.lat);
const pz = cl * Math.cos(lon);
if (px * SUN[0] + py * SUN[1] + pz * SUN[2] > -0.04) continue;
// Only flashes facing the camera, not squashed against the limb.
const [cx, cy, cz] = c.pos;
if ((px * cx + py * cy + pz * cz) / Math.sqrt(cx * cx + cy * cy + cz * cz) < 0.45) continue;
// Each site gets a chance to flash in every short slot; a flash is a quick double flicker.
const slotLen = 1.1 / site.rate;
const slot = Math.floor(t / slotLen);
if (hash(i, slot, 41) > 0.32 * f.lightning) continue;
const ph = t / slotLen - slot;
const flick = Math.exp(-ph * 9) + (ph > 0.18 ? 0.6 * Math.exp(-(ph - 0.18) * 12) : 0);
if (flick < 0.05) continue;
const z = project(c, px, py, pz);
if (z <= 0) continue;
const sx = proj.x;
const sy = proj.y;
const R = 5 + hash(i, slot, 42) * 4;
for (let y = Math.floor(sy - R); y <= sy + R; y++) {
for (let x = Math.floor(sx - R); x <= sx + R; x++) {
if (x < 0 || x >= W || y < 0 || y >= H) continue;
const lit = LIT[y * W + x];
if (lit < 0 || lit > 0.14 || ZBUF[y * W + x] < z - 0.05) continue;
const d = Math.hypot(x + 0.5 - sx, (y + 0.5 - sy) * 1.3) / R;
if (d >= 1) continue;
s.light(x, y, BOLT, ditherStep(flick * (1 - d) ** 1.6 * 0.95, x, y, 5));
}
}
}
}
// ---------------------------------------------------------------------------
// Aurora
// ---------------------------------------------------------------------------
const AURORA_LOW = hex('#4cf0a4');
const AURORA_HIGH = hex('#8a6cf4');
const OVAL_COLAT = 0.3;
const CURTAIN = 0.22;
/** Brightest curtain glow and its height (0 = base, 1 = top) at each pixel, gathered before drawing. */
const AUR = new Float32Array(W * H);
const AUR_U = new Float32Array(W * H);
/** Curtains of light hanging over an oval around the north pole, brightening and wavering over time. */
export function drawAurora(s: Surface, f: Frame): void {
const t = f.t;
const c = f.cam;
let x0 = W;
let x1 = -1;
let y0 = H;
let y1 = -1;
const N = 420;
for (let j = 0; j < N; j++) {
const a = (j / N) * Math.PI * 2;
// The oval sits a little off the pole, toward the night side.
const colat = OVAL_COLAT + 0.04 * Math.sin(a - 0.6) + 0.015 * Math.sin(a * 3 + t * 0.07);
const bright = clamp01(0.25 + 0.5 * noise1(a * 4 + t * 0.06, 50) + 0.35 * Math.sin(a * 6 - t * 0.21)) * f.aurora;
if (bright <= 0.02) continue;
const sc = Math.sin(colat);
const ox = sc * Math.sin(a);
const oy = Math.cos(colat);
const oz = sc * Math.cos(a);
const top = CURTAIN * (0.6 + 0.4 * noise1(a * 9 + t * 0.1, 51));
for (let h = 0; h < 20; h++) {
const u = h / 19;
const r = 1.004 + u * top;
const z = project(c, ox * r, oy * r, oz * r);
if (z <= 0) continue;
const x = Math.floor(proj.x);
const y = Math.floor(proj.y);
if (x < 0 || x >= W || y < 0 || y >= H) continue;
const i = y * W + x;
if (ZBUF[i] < z - 0.02) continue;
// Brightest a little above the base, fading toward the top.
const k = bright * (u < 0.12 ? 0.4 + 5 * u : (1 - u) ** 1.3);
if (k <= AUR[i]) continue;
AUR[i] = k;
AUR_U[i] = u;
if (x < x0) x0 = x;
if (x > x1) x1 = x;
if (y < y0) y0 = y;
if (y > y1) y1 = y;
}
}
for (let y = y0; y <= y1; y++) {
for (let x = x0; x <= x1; x++) {
const i = y * W + x;
const k = AUR[i];
if (k <= 0) continue;
AUR[i] = 0;
s.light(x, y, mix(AURORA_LOW, AURORA_HIGH, AUR_U[i]), ditherStep(k * 0.34, x, y, 6));
}
}
}

View File

@ -0,0 +1,89 @@
import { ditherStep } from '../../engine/color';
import { noise1, noise2 } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import { clamp01 } from '../../engine/Timeline';
import type { Frame } from './timeline';
import { orbit, planetShadow, R_IN, R_OUT, ringColor, spin } from './world';
/**
* The ring sheet: a faint inner ring, a broad bright ring, a wide dark gap, an outer ring with a
* narrow gap of its own, and a thin outermost ringlet. Its material orbits (inner rings faster),
* the planet's shadow falls across it behind the planet, and for a while ghostly spokes drift over it.
*/
/** Radial density of the ring sheet at radius r, 0 (empty) to 1, before the finest ringlets. */
function profile(r: number): number {
const u = (r - R_IN) / (R_OUT - R_IN);
if (u < 0 || u > 1) return 0;
let d: number;
if (u < 0.17) d = 0.16 + 0.14 * (u / 0.17);
else if (u < 0.55) d = 0.74 + 0.24 * Math.sin(((u - 0.17) / 0.38) * Math.PI);
else if (u < 0.6) d = 0.05;
else if (u > 0.885 && u < 0.9) d = 0.05;
else if (u < 0.955) d = 0.6 - 0.14 * (u - 0.6);
else if (u < 0.978) d = 0;
else d = 0.42;
return d * (0.8 + 0.2 * noise1(r * 58, 3));
}
/** Everything about the sheet that depends only on radius, tabulated finely enough to look continuous. */
const TABLE = 4096;
const DENSITY = new Float32Array(TABLE + 1);
const FINE = new Float32Array(TABLE + 1);
const COLOR = new Float32Array((TABLE + 1) * 3);
const ORBIT = new Float32Array(TABLE + 1);
for (let i = 0; i <= TABLE; i++) {
const r = R_IN + ((R_OUT - R_IN) * i) / TABLE;
DENSITY[i] = profile(r);
FINE[i] = DENSITY[i] * 0.2 * (noise1(r * 190, 4) - 0.5);
COLOR.set(ringColor(i / TABLE), i * 3);
ORBIT[i] = orbit(r);
}
function slot(r: number): number {
return Math.max(0, Math.min(TABLE, Math.round(((r - R_IN) / (R_OUT - R_IN)) * TABLE)));
}
/** Radial density of the ring sheet at radius r, 0 (empty) to 1. `detail` adds the finest ringlets up close. */
export function ringDensity(r: number, detail = 0): number {
if (r < R_IN || r > R_OUT) return 0;
const i = slot(r);
return DENSITY[i] + detail * FINE[i];
}
const col: [number, number, number] = [0, 0, 0];
const SPOKE_SPIN = spin(0.3);
/** Shade the ring sheet where a view ray meets it at (qx, 0, qz), `dist` from the camera; returns the alpha drawn. */
export function shadeRing(s: Surface, x: number, y: number, qx: number, qz: number, r: number, dist: number, f: Frame): number {
const i = slot(r);
let a = DENSITY[i] + clamp01(2.4 / dist - 0.5) * FINE[i];
if (a <= 0) return 0;
const t = f.t;
const phi = Math.atan2(qx, qz);
// Clumps and wakes stretched along the orbit, carried round with the material.
const n = noise2(r * 40, (phi - ORBIT[i] * t) * 7, 6);
a *= 0.84 + 0.32 * (n - 0.5);
let k = planetShadow(qx, 0, qz) ? 0.13 : 0.86 + 0.14 * n;
// Spokes turn with the planet's magnetic field rather than with the ring material.
const u = i / TABLE;
if (f.spokes > 0 && u > 0.2 && u < 0.54) {
const ps = phi - SPOKE_SPIN * t;
const wedge = clamp01((noise1(ps * 12 + u * 1.6, 21) - 0.5) * 4);
if (wedge > 0) {
const life = clamp01((noise1(ps * 2.5 - t * 0.025, 22) - 0.35) * 3);
k *= 1 - f.spokes * 0.5 * wedge * life * Math.sin(((u - 0.2) / 0.34) * Math.PI);
}
}
k = ditherStep(k, x, y, 9);
col[0] = COLOR[i * 3] * k;
col[1] = COLOR[i * 3 + 1] * k;
col[2] = COLOR[i * 3 + 2] * k;
const am = Math.min(1, a * 1.3);
const alpha = ditherStep(am * Math.sqrt(am), x, y, 6);
s.blend(x, y, col, alpha);
return alpha;
}

View File

@ -0,0 +1,158 @@
import { ditherStep, hex, mix, scale, type RGB } from '../../engine/color';
import { hash } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import { clamp01 } from '../../engine/Timeline';
import { ringDensity } from './rings';
import type { Frame } from './timeline';
import { FOCAL, H, orbit, planetShadow, project, proj, R_IN, R_OUT, ringColor, SUN, W, ZBUF } from './world';
/**
* Individual rocks and ice chunks in the stretch of ring nearest the camera. Ring material is laid
* out on a grid of cells that orbit with it; each cell may hold one rock, so the rocks drift past
* as a pure function of t. Ice chunks tumble and now and then catch the sun in a sparkle.
*/
/** Radial and along-orbit cell size, in planet radii. */
const CELL = 0.026;
/** Rocks farther than this from the camera are too small to make out. */
const REACH = 2.3;
const WHITE = hex('#fffaf0');
const ICE = hex('#d0dae2');
const ICE_LIGHT = hex('#f4f8fc');
const SPARKLE = hex('#ffffff');
export function drawRocks(s: Surface, f: Frame): void {
const t = f.t;
const c = f.cam;
// Sun direction in screen terms, for lighting each rock as a lumpy ball.
const sr = SUN[0] * c.right[0] + SUN[1] * c.right[1] + SUN[2] * c.right[2];
const su = SUN[0] * c.up[0] + SUN[1] * c.up[1] + SUN[2] * c.up[2];
const sf = SUN[0] * c.fwd[0] + SUN[1] * c.fwd[1] + SUN[2] * c.fwd[2];
const camPhi = Math.atan2(c.pos[0], c.pos[2]);
const D = Math.sqrt(c.pos[0] * c.pos[0] + c.pos[2] * c.pos[2]);
const h2 = c.pos[1] * c.pos[1];
for (let ri = 0; ri * CELL < R_OUT - R_IN; ri++) {
const r0 = R_IN + ri * CELL;
const dens = ringDensity(r0 + CELL / 2);
if (dens < 0.1) continue;
// Only the arc of this ring within reach of the camera.
const cosMax = (D * D + r0 * r0 + h2 - REACH * REACH) / (2 * D * r0);
if (cosMax >= 1) continue;
const window = Math.acos(Math.max(-1, cosMax)) + 0.05;
const dphi = CELL / r0;
const turn = orbit(r0 + CELL / 2) * t;
const j0 = Math.floor((camPhi - window - turn) / dphi);
const j1 = Math.ceil((camPhi + window - turn) / dphi);
for (let j = j0; j <= j1; j++) {
if (hash(ri, j, 80) > dens * 0.5) continue;
const big = hash(ri, j, 83);
const size = 0.003 + 0.028 * big ** 4;
const r = r0 + hash(ri, j, 81) * CELL;
const phi = (j + hash(ri, j, 82)) * dphi + turn;
const wx = r * Math.sin(phi);
const wy = (hash(ri, j, 84) - 0.5) * 0.008;
const wz = r * Math.cos(phi);
const z = project(c, wx, wy, wz);
if (z <= 0.05) continue;
const R = (FOCAL * size) / z;
if (R < 1.1) continue;
const sx = proj.x;
const sy = proj.y;
if (sx < -R - 1 || sx > W + R + 1 || sy < -R - 1 || sy > H + R + 1) continue;
const ice = hash(ri, j, 85) < 0.3;
const shade = planetShadow(wx, wy, wz) ? 0.12 : 1;
const tumble = t * (0.1 + hash(ri, j, 86) * 0.3) + hash(ri, j, 87) * 6.28;
// Small rocks fade in as they come close enough to make out.
const alpha = clamp01((R - 1.1) / 0.9) * clamp01((REACH - z) / 0.5);
if (alpha <= 0) continue;
// Rocks take the color of the ring they belong to, a shade darker or lighter.
const ring = ringColor((r - R_IN) / (R_OUT - R_IN));
const base = ice ? ICE : scale(ring, 0.78 + 0.2 * hash(ri, j, 88));
drawRock(s, sx, sy, R, z, tumble, base, ice ? ICE_LIGHT : mix(ring, WHITE, 0.45), shade, alpha, sr, su, sf);
if (ice && shade === 1) {
const g = Math.max(0, Math.sin(tumble * 2.3)) ** 40;
if (g > 0.2) {
const gx = Math.round(sx + sr * R * 0.4);
const gy = Math.round(sy - su * R * 0.4);
if (gx >= 0 && gx < W && gy >= 0 && gy < H && ZBUF[gy * W + gx] >= z - 0.01) {
s.light(gx, gy, SPARKLE, g);
if (R > 1.5 && g > 0.5) {
const arm = (g - 0.5) * 1.2;
s.light(gx - 1, gy, SPARKLE, arm);
s.light(gx + 1, gy, SPARKLE, arm);
s.light(gx, gy - 1, SPARKLE, arm);
s.light(gx, gy + 1, SPARKLE, arm);
}
}
}
}
}
}
}
const tmp: [number, number, number] = [0, 0, 0];
/** Scratch mask of the current rock's shape, with a one-pixel empty border. */
const MASK = new Uint8Array(64 * 64);
function drawRock(
s: Surface,
sx: number,
sy: number,
R: number,
z: number,
tumble: number,
base: RGB,
light: RGB,
shade: number,
alpha: number,
sr: number,
su: number,
sf: number,
): void {
const x0 = Math.floor(sx - R * 1.1);
const y0 = Math.floor(sy - R * 1.1);
const mw = Math.min(62, Math.ceil(sx + R * 1.1) - x0 + 1);
const mh = Math.min(62, Math.ceil(sy + R * 1.1) - y0 + 1);
const stride = mw + 2;
MASK.fill(0, 0, stride * (mh + 2));
// An irregular outline that slowly changes as the rock tumbles.
for (let my = 0; my < mh; my++) {
for (let mx = 0; mx < mw; mx++) {
const dx = x0 + mx + 0.5 - sx;
const dy = y0 + my + 0.5 - sy;
const a = Math.atan2(dy, dx);
const rr = R * (0.82 + 0.16 * Math.sin(2 * a + tumble) + 0.1 * Math.sin(3 * a - tumble * 1.3));
if (dx * dx + dy * dy <= rr * rr) MASK[(my + 1) * stride + mx + 1] = 1;
}
}
for (let my = 0; my < mh; my++) {
const y = y0 + my;
if (y < 0 || y >= H) continue;
for (let mx = 0; mx < mw; mx++) {
const x = x0 + mx;
const m = (my + 1) * stride + mx + 1;
if (!MASK[m] || x < 0 || x >= W) continue;
const i = y * W + x;
if (ZBUF[i] < z) continue;
// Light it as a ball: screen-space normal, then into sun terms.
const nx = (x + 0.5 - sx) / R;
const ny = (y + 0.5 - sy) / R;
const nz = Math.sqrt(Math.max(0, 1 - nx * nx - ny * ny));
const lam = Math.max(0, nx * sr - ny * su - nz * sf);
let k = (0.5 + 0.5 * lam) * shade;
if (R > 2.4 && !(MASK[m - 1] && MASK[m + 1] && MASK[m - stride] && MASK[m + stride])) k *= 0.7;
const kq = ditherStep(k, x, y, 5);
const cc = mix(base, light, Math.max(0, kq - 0.6) * 2.5);
const b = Math.min(1, kq * 1.25);
tmp[0] = cc[0] * b;
tmp[1] = cc[1] * b;
tmp[2] = cc[2] * b;
s.blend(x, y, tmp, alpha);
if (alpha >= 1) ZBUF[i] = z;
}
}
}

View File

@ -0,0 +1,175 @@
import { ditherStep, hex, mix, type RGB } from '../../engine/color';
import { noise2, Rng } from '../../engine/rng';
import { Surface } from '../../engine/Surface';
import { progress } from '../../engine/Timeline';
import { cameraAt, TIMES, type Frame } from './timeline';
import { FOCAL, H, SUN, W, type Camera } from './world';
/**
* Deep space behind the planet: a dim band of galaxy with dust lanes, two faint nebulae, a dusting
* of stars and brighter ones that twinkle. It is painted once onto a slightly larger canvas that
* slides as the camera drifts, so the sky keeps pace with the view. A comet crosses it for a while.
*/
/** Spare sky around the screen for the camera's drift to reveal. */
const M = 24;
const BW = W + M * 2;
const BH = H + M * 2;
const SPACE = hex('#04050b');
const GALAXY_DIM = hex('#1a1a2c');
const GALAXY = hex('#302c46');
const GALAXY_CORE = hex('#48405a');
const NEBULA_VIOLET = hex('#3c1c4c');
const NEBULA_TEAL = hex('#10384a');
const SKY: Surface = (() => {
const s = new Surface(BW, BH);
s.fill(SPACE);
const r = new Rng(77);
const ang = -0.42;
const sn = Math.sin(ang);
const cs = Math.cos(ang);
const band = (x: number, y: number) => (x - BW * 0.5) * sn - (y - BH * 0.6) * cs;
for (let y = 0; y < BH; y++) {
for (let x = 0; x < BW; x++) {
const dl = band(x, y);
let g = Math.exp(-((dl / 30) ** 2)) * (0.35 + 0.65 * noise2(x / 26, y / 26, 60));
g += Math.exp(-((dl / 14) ** 2)) * 0.35 * noise2(x / 8, y / 8, 61);
// Dark dust lanes along the middle.
g *= 1 - 0.75 * Math.exp(-(((dl - 4) / 6) ** 2)) * noise2(x / 13, y / 13, 62);
if (g > 0.03) {
const c = g > 0.55 ? GALAXY_CORE : g > 0.28 ? GALAXY : GALAXY_DIM;
s.blend(x, y, mix(GALAXY_DIM, c, 0.6), ditherStep(Math.min(1, g * 1.4), x, y, 5));
}
const nv = Math.exp(-(((x - BW * 0.1) / 60) ** 2 + ((y - BH * 0.16) / 34) ** 2)) * noise2(x / 18, y / 18, 63);
const nt = Math.exp(-(((x - BW * 0.93) / 50) ** 2 + ((y - BH * 0.08) / 30) ** 2)) * noise2(x / 16, y / 16, 64);
s.blend(x, y, NEBULA_VIOLET, ditherStep(nv * 0.8, x, y, 4));
s.blend(x, y, NEBULA_TEAL, ditherStep(nt * 0.8, x, y, 4));
}
}
// Faint stars, thicker in the galaxy band.
for (let i = 0; i < 900; i++) {
const x = r.int(0, BW - 1);
const y = r.int(0, BH - 1);
if (r.next() > 0.35 + 0.65 * Math.exp(-((band(x, y) / 34) ** 2))) continue;
s.blend(x, y, hex('#dcdcf0'), r.range(0.12, 0.45));
}
return s;
})();
interface Star {
x: number;
y: number;
mag: number;
twinkle: number;
phase: number;
tint: RGB;
}
const STARS: Star[] = (() => {
const r = new Rng(91);
return Array.from({ length: 140 }, () => ({
x: r.int(0, BW - 1),
y: r.int(0, BH - 1),
mag: Math.pow(r.next(), 2.4),
twinkle: r.range(0.5, 1.8),
phase: r.range(0, Math.PI * 2),
tint: r.next() < 0.25 ? hex('#c8d6ff') : r.next() < 0.3 ? hex('#ffe4c0') : hex('#ffffff'),
}));
})();
/** Where the start-of-meditation view direction lands on screen now, relative to the center. */
function skyOffset(c: Camera, c0: Camera): [number, number] {
const f0 = c0.fwd;
const z = f0[0] * c.fwd[0] + f0[1] * c.fwd[1] + f0[2] * c.fwd[2];
const ox = (FOCAL * (f0[0] * c.right[0] + f0[1] * c.right[1] + f0[2] * c.right[2])) / z;
const oy = (-FOCAL * (f0[0] * c.up[0] + f0[1] * c.up[1] + f0[2] * c.up[2])) / z;
return [ox, oy];
}
const CAM0 = cameraAt(0);
export function drawSpace(s: Surface, f: Frame): void {
const [ox, oy] = skyOffset(f.cam, CAM0);
const sx = Math.round(ox) - M;
const sy = Math.round(oy) - M;
const src = SKY.data;
const dst = s.data;
for (let y = 0; y < H; y++) {
const by = Math.max(0, Math.min(BH - 1, y - sy));
for (let x = 0; x < W; x++) {
const bx = Math.max(0, Math.min(BW - 1, x - sx));
const si = (by * BW + bx) * 4;
const di = (y * W + x) * 4;
dst[di] = src[si];
dst[di + 1] = src[si + 1];
dst[di + 2] = src[si + 2];
dst[di + 3] = 255;
}
}
for (const st of STARS) {
const x = st.x + sx;
const y = st.y + sy;
const a = (0.65 + 0.35 * Math.sin(f.t * st.twinkle + st.phase)) * (0.35 + 0.65 * st.mag);
s.blend(x, y, st.tint, a);
if (st.mag > 0.8) {
const arm = a * 0.3;
s.blend(x - 1, y, st.tint, arm);
s.blend(x + 1, y, st.tint, arm);
s.blend(x, y - 1, st.tint, arm);
s.blend(x, y + 1, st.tint, arm);
}
}
drawComet(s, f, ox, oy);
}
// ---------------------------------------------------------------------------
// Comet
// ---------------------------------------------------------------------------
const COMA = hex('#f4f8ff');
const DUST_TAIL = hex('#f0e2c4');
const ION_TAIL = hex('#9cc4ff');
function drawComet(s: Surface, f: Frame, ox: number, oy: number): void {
const [a, b] = TIMES.comet;
if (f.t <= a || f.t >= b) return;
const vis = progress(f.t, a, a + 14) * (1 - progress(f.t, b - 14, b));
const u = (f.t - a) / (b - a);
const hx = 150 - 116 * u + ox;
const hy = 12 + 22 * u + oy;
// Tails stream away from the sun.
let tx = -(SUN[0] * f.cam.right[0] + SUN[1] * f.cam.right[1] + SUN[2] * f.cam.right[2]);
let ty = SUN[0] * f.cam.up[0] + SUN[1] * f.cam.up[1] + SUN[2] * f.cam.up[2];
const tl = Math.hypot(tx, ty);
tx /= tl;
ty /= tl;
for (let k = 0; k < 44; k += 0.5) {
// Faint straight ion tail.
const ia = (1 - k / 44) ** 1.6 * 0.22 * vis;
const ix = hx + tx * k;
const iy = hy + ty * k;
s.blend(ix, iy, ION_TAIL, ditherStep(ia, ix | 0, iy | 0, 5));
// Broader, curving dust tail.
if (k > 30) continue;
const w = 0.5 + k * 0.09;
const bend = k * k * 0.008;
const da = (1 - k / 30) ** 1.4 * 0.42 * vis;
for (let o = -w; o <= w; o += 0.5) {
const px = hx + tx * k - ty * (bend + o);
const py = hy + ty * k + tx * (bend + o);
s.blend(px, py, DUST_TAIL, ditherStep(da * (1 - Math.abs(o) / (w + 0.5)), px | 0, py | 0, 5));
}
}
for (let y = -2; y <= 2; y++) {
for (let x = -2; x <= 2; x++) {
const d = Math.hypot(x, y);
if (d > 2.5) continue;
s.blend(hx + x, hy + y, COMA, ditherStep((1 - d / 2.5) * 0.7 * vis, (hx + x) | 0, (hy + y) | 0, 4));
}
}
s.blend(hx, hy, COMA, vis);
}

View File

@ -0,0 +1,67 @@
import { progress, track } from '../../engine/Timeline';
import { camera, type Camera, type Vec3 } from './world';
/** All timings for The Ringed Planet, in seconds. */
export const DURATION = 300;
export const TIMES = {
fadeIn: [0, 8],
fadeOut: [291, 300],
moon: [40, 130],
comet: [60, 150],
spokes: [70, 240],
lightning: [105, 165],
aurora: [150, 260],
voyager: 180,
/** Moments Voyager's dish catches the sun. */
glints: [222, 268],
} as const;
/** Over the five minutes the camera rises a little, so the rings slowly open, and eases around the planet. */
const elev = track([
[0, 0.27],
[DURATION, 0.34],
]);
const azim = track([
[0, -0.05],
[DURATION, 0.05],
]);
export function cameraAt(t: number): Camera {
return camera(elev(t), azim(t));
}
/** The moon's straight run in front of the planet, entering on the left and leaving on the right. */
const MOON_FROM: Vec3 = [-2.5, 0.53, 1.22];
const MOON_TO: Vec3 = [1.5, 0.19, 0.98];
export interface Frame {
t: number;
cam: Camera;
/** Moon center, while it is on its run. */
moon?: Vec3;
/** Strength of the passing events, 0..1. */
spokes: number;
lightning: number;
aurora: number;
fade: number;
}
const bell = (t: number, [a, b]: readonly [number, number], edge: number) =>
progress(t, a, a + edge) * (1 - progress(t, b - edge, b));
export function frameAt(t: number): Frame {
const m = (t - TIMES.moon[0]) / (TIMES.moon[1] - TIMES.moon[0]);
return {
t,
cam: cameraAt(t),
moon:
m >= 0 && m <= 1
? [MOON_FROM[0] + (MOON_TO[0] - MOON_FROM[0]) * m, MOON_FROM[1] + (MOON_TO[1] - MOON_FROM[1]) * m, MOON_FROM[2] + (MOON_TO[2] - MOON_FROM[2]) * m]
: undefined,
spokes: bell(t, TIMES.spokes, 30),
lightning: bell(t, TIMES.lightning, 10),
aurora: 0.3 + 0.7 * bell(t, TIMES.aurora, 35),
fade: progress(t, TIMES.fadeIn[0], TIMES.fadeIn[1]) * (1 - progress(t, TIMES.fadeOut[0], TIMES.fadeOut[1])),
};
}

View File

@ -0,0 +1,391 @@
import { ditherStep, hex, mix, type RGB } from '../../engine/color';
import type { Surface } from '../../engine/Surface';
import { clamp01, pathTrack, progress } from '../../engine/Timeline';
import { TIMES, type Frame } from './timeline';
import { cross, FOCAL, H, norm, project, proj, SUN, W, ZBUF, type Vec3 } from './world';
/**
* An old deep-space probe: a big white dish on a ten-sided gold-foil body, with a boom of
* three power generators, a science boom ending in a camera platform, a long magnetometer boom
* and two thin antennas. At three minutes it passes the camera from behind, glides over the
* planet's face and heads out into deep space, its dish catching the sun as it turns.
*
* The model is a cloud of points (in meters, dish facing +z) that is turned, placed and splatted
* into its own small buffer each frame, then drawn with a pixel outline wherever it's in front.
*/
/** World units (planet radii) per meter of probe: far larger than life, so it can be seen. */
const SCALE = 0.02;
const enum Mat {
Dish,
DishRim,
Feed,
Bus,
BusDark,
BusCap,
Record,
Boom,
Rtg,
Platform,
Lens,
}
const COLORS: readonly RGB[] = [
'#ecebe2',
'#b4b2a8',
'#d8d6cc',
'#c89c48',
'#86662e',
'#3c3428',
'#ecc058',
'#a4a298',
'#5c5a56',
'#8c8a84',
'#2c2c34',
].map(hex);
// Point cloud, in local meters. Normals of (0, 0, 0) mark struts and wires, lit without a facing.
const PX: number[] = [];
const PY: number[] = [];
const PZ: number[] = [];
const NX: number[] = [];
const NY: number[] = [];
const NZ: number[] = [];
const SIZE: number[] = [];
const MAT: Mat[] = [];
function pt(p: Vec3, n: Vec3, size: number, mat: Mat): void {
PX.push(p[0]);
PY.push(p[1]);
PZ.push(p[2]);
NX.push(n[0]);
NY.push(n[1]);
NZ.push(n[2]);
SIZE.push(size);
MAT.push(mat);
}
/** A straight rod from a along unit direction d. */
function rod(a: Vec3, d: Vec3, len: number, thick: number, mat: Mat): void {
const step = 0.05;
for (let s = 0; s <= len; s += step) pt([a[0] + d[0] * s, a[1] + d[1] * s, a[2] + d[2] * s], [0, 0, 0], Math.max(thick, step * 1.15), mat);
}
/** A closed cylinder around axis d centered at c. */
function cylinder(c: Vec3, d: Vec3, radius: number, len: number, mat: Mat): void {
const u = norm(cross(d, Math.abs(d[1]) < 0.9 ? [0, 1, 0] : [1, 0, 0]));
const v = cross(d, u);
const step = 0.07;
const n = Math.max(6, Math.round((Math.PI * 2 * radius) / step));
for (let s = -len / 2; s <= len / 2; s += step) {
for (let k = 0; k < n; k++) {
const a = (k / n) * Math.PI * 2;
const nx = u[0] * Math.cos(a) + v[0] * Math.sin(a);
const ny = u[1] * Math.cos(a) + v[1] * Math.sin(a);
const nz = u[2] * Math.cos(a) + v[2] * Math.sin(a);
pt([c[0] + d[0] * s + nx * radius, c[1] + d[1] * s + ny * radius, c[2] + d[2] * s + nz * radius], [nx, ny, nz], step * 1.3, mat);
}
}
}
/** A flat disc facing n. */
function disc(c: Vec3, n: Vec3, radius: number, mat: Mat): void {
const u = norm(cross(n, Math.abs(n[1]) < 0.9 ? [0, 1, 0] : [1, 0, 0]));
const v = cross(n, u);
const step = 0.07;
for (let r = 0; r <= radius; r += step) {
const k = Math.max(1, Math.round((Math.PI * 2 * r) / step));
for (let j = 0; j < k; j++) {
const a = (j / k) * Math.PI * 2;
const ca = Math.cos(a) * r;
const sa = Math.sin(a) * r;
pt([c[0] + u[0] * ca + v[0] * sa, c[1] + u[1] * ca + v[1] * sa, c[2] + u[2] * ca + v[2] * sa], n, step * 1.3, mat);
}
}
}
const DISH_R = 1.85;
const FOCUS = 1.2;
const BUS_R = 0.86;
(function build() {
// High-gain dish: a shallow paraboloid, concave toward +z.
const step = 0.075;
for (let r = 0; r <= DISH_R; r += step) {
const k = Math.max(1, Math.round((Math.PI * 2 * r) / step));
for (let j = 0; j < k; j++) {
const a = (j / k) * Math.PI * 2 + r;
const x = Math.cos(a) * r;
const y = Math.sin(a) * r;
pt([x, y, (r * r) / (4 * FOCUS)], norm([-x / (2 * FOCUS), -y / (2 * FOCUS), 1]), step * 1.35, r > DISH_R - 0.12 ? Mat.DishRim : Mat.Dish);
}
}
// Feed and its three struts.
disc([0, 0, 1.25], [0, 0, 1], 0.2, Mat.Feed);
for (let k = 0; k < 3; k++) {
const a = (k / 3) * Math.PI * 2 + Math.PI / 2;
const from: Vec3 = [Math.cos(a) * 1.65, Math.sin(a) * 1.65, (1.65 * 1.65) / (4 * FOCUS)];
const to: Vec3 = [Math.cos(a) * 0.15, Math.sin(a) * 0.15, 1.25];
const d: Vec3 = [to[0] - from[0], to[1] - from[1], to[2] - from[2]];
rod(from, norm(d), Math.hypot(d[0], d[1], d[2]), 0.05, Mat.Boom);
}
// Ten-sided body behind the dish, in alternating shades of foil.
const side = 2 * 0.9 * Math.sin(Math.PI / 10);
for (let f = 0; f < 10; f++) {
const a = (f / 10) * Math.PI * 2;
const n: Vec3 = [Math.cos(a), Math.sin(a), 0];
const tng: Vec3 = [-Math.sin(a), Math.cos(a), 0];
for (let u = -side / 2; u <= side / 2; u += 0.07) {
for (let z = -0.6; z <= -0.05; z += 0.07) {
pt([n[0] * BUS_R + tng[0] * u, n[1] * BUS_R + tng[1] * u, z], n, 0.1, f % 2 ? Mat.BusDark : Mat.Bus);
}
}
}
disc([0, 0, -0.62], [0, 0, -1], BUS_R, Mat.BusCap);
// The golden record on one face.
const ra = (3 / 10) * Math.PI * 2;
disc([Math.cos(ra) * (BUS_R + 0.02), Math.sin(ra) * (BUS_R + 0.02), -0.32], [Math.cos(ra), Math.sin(ra), 0], 0.16, Mat.Record);
const from = (deg: number, z: number): Vec3 => [Math.cos((deg * Math.PI) / 180) * BUS_R, Math.sin((deg * Math.PI) / 180) * BUS_R, z];
const dir = (deg: number, z: number): Vec3 => norm([Math.cos((deg * Math.PI) / 180), Math.sin((deg * Math.PI) / 180), z]);
// Power boom with three generators.
const rtgDir = dir(216, -0.25);
const rtgAt = from(216, -0.4);
rod(rtgAt, rtgDir, 3.1, 0.1, Mat.Boom);
for (const s of [1.75, 2.3, 2.85]) {
cylinder([rtgAt[0] + rtgDir[0] * s, rtgAt[1] + rtgDir[1] * s, rtgAt[2] + rtgDir[2] * s], rtgDir, 0.2, 0.42, Mat.Rtg);
}
// Science boom and its camera platform.
const sciDir = dir(36, -0.2);
const sciAt = from(36, -0.4);
rod(sciAt, sciDir, 2.3, 0.12, Mat.Boom);
const pc: Vec3 = [sciAt[0] + sciDir[0] * 2.5, sciAt[1] + sciDir[1] * 2.5, sciAt[2] + sciDir[2] * 2.5];
for (let x = -0.25; x <= 0.25; x += 0.07) {
for (let y = -0.22; y <= 0.22; y += 0.07) {
for (const z of [-0.22, 0.22]) pt([pc[0] + x, pc[1] + y, pc[2] + z], [0, 0, Math.sign(z)], 0.1, Mat.Platform);
for (const z of [-0.25, 0.25]) pt([pc[0] + z, pc[1] + y, pc[2] + x * 0.9], [Math.sign(z), 0, 0], 0.1, Mat.Platform);
}
}
cylinder([pc[0] + 0.12, pc[1] + 0.32, pc[2] + 0.1], [0, 0, 1], 0.1, 0.55, Mat.Platform);
disc([pc[0] + 0.12, pc[1] + 0.32, pc[2] + 0.39], [0, 0, 1], 0.08, Mat.Lens);
// Long magnetometer boom and the two thin antennas.
rod(from(144, -0.3), dir(144, -0.05), 13, 0.07, Mat.Boom);
rod([0, -0.2, -0.62], dir(250, -0.3), 10, 0.035, Mat.Boom);
rod([0, -0.2, -0.62], dir(290, -0.3), 10, 0.035, Mat.Boom);
})();
const COUNT = PX.length;
// ---------------------------------------------------------------------------
// Flight
// ---------------------------------------------------------------------------
const T0 = TIMES.voyager;
/** Its course: from just behind the camera, over the planet's face, then out past the left limb. */
const courseXY = pathTrack([
[T0, 0.13, 0.93],
[T0 + 8, 0.1, 0.88],
[T0 + 22, 0.05, 0.8],
[T0 + 40, -0.04, 0.7],
[T0 + 60, -0.2, 0.62],
[T0 + 80, -0.7, 0.62],
[T0 + 100, -1.7, 0.95],
[T0 + 120, -3.4, 1.7],
]);
const courseZ = pathTrack([
[T0, 3.08, 0],
[T0 + 8, 2.92, 0],
[T0 + 22, 2.62, 0],
[T0 + 40, 2.15, 0],
[T0 + 60, 1.6, 0],
[T0 + 80, 0.95, 0],
[T0 + 100, -0.7, 0],
[T0 + 120, -3.6, 0],
]);
/**
* The dish swings slowly either side of the angle that would mirror the sun straight into the
* camera, so it flashes as it passes through, at each of the glint times.
*/
function swing(t: number): number {
const [g1, g2] = TIMES.glints;
return 0.55 * Math.sin((Math.PI * (t - g1)) / (g2 - g1));
}
// Per-frame splat buffers, cleared only over the area the probe covered.
const VZ = new Float32Array(W * H).fill(Infinity);
const VC = new Uint8ClampedArray(W * H * 3);
const OUTLINE = 0.55;
const SPARKLE = hex('#fffbe8');
const BEACON = hex('#ff5a4a');
export function drawVoyager(s: Surface, f: Frame): void {
const t = f.t;
if (t < T0) return;
const c = f.cam;
const [px, py] = courseXY(t);
const [pz] = courseZ(t);
const center = project(c, px, py, pz);
const cx = proj.x;
const cy = proj.y;
// Orientation: dish axis near the sun/camera halfway direction, turned by the swing.
const toCam = norm([c.pos[0] - px, c.pos[1] - py, c.pos[2] - pz]);
const half = norm([SUN[0] + toCam[0], SUN[1] + toCam[1], SUN[2] + toCam[2]]);
const sw = swing(t);
const tilt = 0.12 * Math.sin(t * 0.05);
const cs = Math.cos(sw);
const sn = Math.sin(sw);
let zw = norm([half[0] * cs + half[2] * sn, half[1] + tilt, -half[0] * sn + half[2] * cs]);
const x0 = norm(cross([0, 1, 0], zw));
const y0 = cross(zw, x0);
const roll = 0.6 + 0.01 * (t - T0);
const cr = Math.cos(roll);
const sr = Math.sin(roll);
const xw: Vec3 = [x0[0] * cr + y0[0] * sr, x0[1] * cr + y0[1] * sr, x0[2] * cr + y0[2] * sr];
const yw: Vec3 = [y0[0] * cr - x0[0] * sr, y0[1] * cr - x0[1] * sr, y0[2] * cr - x0[2] * sr];
zw = cross(xw, yw);
let bx0 = W;
let bx1 = -1;
let by0 = H;
let by1 = -1;
for (let i = 0; i < COUNT; i++) {
const lx = PX[i] * SCALE;
const ly = PY[i] * SCALE;
const lz = PZ[i] * SCALE;
const wx = px + xw[0] * lx + yw[0] * ly + zw[0] * lz;
const wy = py + xw[1] * lx + yw[1] * ly + zw[1] * lz;
const wz = pz + xw[2] * lx + yw[2] * ly + zw[2] * lz;
const z = project(c, wx, wy, wz);
if (z <= 0.012) continue;
const sx = proj.x;
const sy = proj.y;
const D = (SIZE[i] * SCALE * FOCAL) / z;
const xa = Math.floor(sx - D / 2);
const xb = Math.max(xa, Math.floor(sx + D / 2 - 0.01));
const ya = Math.floor(sy - D / 2);
const yb = Math.max(ya, Math.floor(sy + D / 2 - 0.01));
if (xb < 0 || xa >= W || yb < 0 || ya >= H) continue;
// Light: two-sided surfaces, plain shading for struts and wires.
const mat = MAT[i];
let k: number;
let spec = 0;
const nl = NX[i] * NX[i] + NY[i] * NY[i] + NZ[i] * NZ[i];
if (nl === 0) {
k = 0.7;
} else {
let nx = xw[0] * NX[i] + yw[0] * NY[i] + zw[0] * NZ[i];
let ny = xw[1] * NX[i] + yw[1] * NY[i] + zw[1] * NZ[i];
let nz = xw[2] * NX[i] + yw[2] * NY[i] + zw[2] * NZ[i];
const vx = c.pos[0] - wx;
const vy = c.pos[1] - wy;
const vz = c.pos[2] - wz;
const facing = nx * vx + ny * vy + nz * vz;
if (facing < 0) {
nx = -nx;
ny = -ny;
nz = -nz;
}
const lam = nx * SUN[0] + ny * SUN[1] + nz * SUN[2];
k = 0.16 + 0.84 * Math.max(0, lam);
if ((mat === Mat.Dish || mat === Mat.Feed) && facing > 0 && lam > 0) {
const vl = Math.sqrt(vx * vx + vy * vy + vz * vz);
const rv = (2 * lam * (nx * vx + ny * vy + nz * vz) - (SUN[0] * vx + SUN[1] * vy + SUN[2] * vz)) / vl;
spec = Math.max(0, rv) ** 40;
}
}
const base = COLORS[mat];
for (let y = Math.max(0, ya); y <= Math.min(H - 1, yb); y++) {
for (let x = Math.max(0, xa); x <= Math.min(W - 1, xb); x++) {
const j = y * W + x;
if (z >= VZ[j]) continue;
VZ[j] = z;
const kq = ditherStep(Math.min(1, k), x, y, 6);
const cc = spec > 0.02 ? mix(base, SPARKLE, Math.min(1, spec * 1.5)) : base;
const m = Math.min(1.25, kq + spec);
VC[j * 3] = cc[0] * m;
VC[j * 3 + 1] = cc[1] * m;
VC[j * 3 + 2] = cc[2] * m;
if (x < bx0) bx0 = x;
if (x > bx1) bx1 = x;
if (y < by0) by0 = y;
if (y > by1) by1 = y;
}
}
}
// Composite: only where the probe is in front, with a dark edge while it is large.
const outline = center > 0 && (DISH_R * SCALE * FOCAL) / center > 4;
const col: [number, number, number] = [0, 0, 0];
for (let y = by0; y <= by1; y++) {
for (let x = bx0; x <= bx1; x++) {
const j = y * W + x;
if (VZ[j] === Infinity || VZ[j] >= ZBUF[j]) continue;
let m = 1;
if (outline) {
const empty = (xx: number, yy: number) => xx < 0 || yy < 0 || xx >= W || yy >= H || VZ[yy * W + xx] === Infinity;
if (empty(x - 1, y) || empty(x + 1, y) || empty(x, y - 1) || empty(x, y + 1)) m = OUTLINE;
}
col[0] = VC[j * 3] * m;
col[1] = VC[j * 3 + 1] * m;
col[2] = VC[j * 3 + 2] * m;
s.set(x, y, col);
}
}
for (let y = by0; y <= by1; y++) VZ.fill(Infinity, y * W + bx0, y * W + bx1 + 1);
if (center <= 0) return;
drawGlint(s, f, px + zw[0] * 0.35 * SCALE, py + zw[1] * 0.35 * SCALE, pz + zw[2] * 0.35 * SCALE, sw);
// Once it is only a few pixels across, a small red light blinks on its body.
const tiny = clamp01(1 - ((DISH_R * SCALE * FOCAL) / center - 1.2) / 1.5);
if (tiny > 0 && (t * 0.55) % 1 < 0.14) {
const bx = Math.round(cx);
const by = Math.round(cy);
if (bx >= 0 && bx < W && by >= 0 && by < H && center < ZBUF[by * W + bx]) {
s.blend(bx, by, BEACON, tiny);
for (const [ox, oy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) s.light(bx + ox, by + oy, BEACON, tiny * 0.3);
}
}
// Keep a faint speck once it's smaller than a pixel.
if (tiny > 0.5) {
const bx = Math.round(cx);
const by = Math.round(cy);
if (bx >= 0 && bx < W && by >= 0 && by < H) s.light(bx, by, SPARKLE, 0.25 * progress(tiny, 0.5, 1));
}
}
/** A four-pointed sparkle when the dish swings through the sun's reflection. */
function drawGlint(s: Surface, f: Frame, gx: number, gy: number, gz: number, sw: number): void {
const g = clamp01(1 - Math.abs(sw) / 0.09);
if (g <= 0) return;
const z = project(f.cam, gx, gy, gz);
if (z <= 0) return;
const x = Math.round(proj.x);
const y = Math.round(proj.y);
if (x < 0 || x >= W || y < 0 || y >= H || z > ZBUF[y * W + x]) return;
const len = 2 + g * 7;
s.light(x, y, SPARKLE, g);
for (let d = 1; d <= len; d++) {
const a = g * (1 - d / (len + 1)) ** 1.5;
s.light(x + d, y, SPARKLE, a);
s.light(x - d, y, SPARKLE, a);
s.light(x, y + d, SPARKLE, a);
s.light(x, y - d, SPARKLE, a);
if (d <= len / 2.5) {
s.light(x + d, y + d, SPARKLE, a * 0.5);
s.light(x - d, y - d, SPARKLE, a * 0.5);
s.light(x + d, y - d, SPARKLE, a * 0.5);
s.light(x - d, y + d, SPARKLE, a * 0.5);
}
}
}

View File

@ -0,0 +1,124 @@
import { gradient, hex, type RGB } from '../../engine/color';
/**
* The scene is a small 3D model seen through a perspective camera: the planet sits at the origin
* with radius 1, spinning about +y, and its rings lie in the y = 0 plane. Longitudes and ring angles
* are measured from +z (the side facing the camera) toward +x, so the seam sits on the far side.
*/
export const W = 320;
export const H = 180;
/** Screen pixels per unit of view-plane distance. */
export const FOCAL = 176;
/** Ring sheet extent, in planet radii. */
export const R_IN = 1.24;
export const R_OUT = 2.32;
export type Vec3 = readonly [number, number, number];
export function dot(a: Vec3, b: Vec3): number {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
export function cross(a: Vec3, b: Vec3): Vec3 {
return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
}
export function norm(v: Vec3): Vec3 {
const l = Math.hypot(v[0], v[1], v[2]);
return [v[0] / l, v[1] / l, v[2] / l];
}
/** Direction toward the sun: upper left and in front, so the planet shows a crescent of night on its right. */
export const SUN: Vec3 = norm([-0.85, 0.36, 0.22]);
export interface Camera {
pos: Vec3;
fwd: Vec3;
right: Vec3;
up: Vec3;
}
const DIST = 3.2;
/** Looking a little left of the planet puts it right of center, leaving open sky on the left. */
const TARGET: Vec3 = [-0.42, 0.06, 0];
/** A slight roll tilts the rings across the frame. */
const ROLL = -0.07;
/** Camera on a sphere around the planet, `elev` above the ring plane and `azim` around the axis (radians). */
export function camera(elev: number, azim: number): Camera {
const pos: Vec3 = [DIST * Math.sin(azim) * Math.cos(elev), DIST * Math.sin(elev), DIST * Math.cos(azim) * Math.cos(elev)];
const fwd = norm([TARGET[0] - pos[0], TARGET[1] - pos[1], TARGET[2] - pos[2]]);
const r0 = norm(cross(fwd, [0, 1, 0]));
const u0 = cross(r0, fwd);
const c = Math.cos(ROLL);
const s = Math.sin(ROLL);
return {
pos,
fwd,
right: [r0[0] * c + u0[0] * s, r0[1] * c + u0[1] * s, r0[2] * c + u0[2] * s],
up: [u0[0] * c - r0[0] * s, u0[1] * c - r0[1] * s, u0[2] * c - r0[2] * s],
};
}
/** Screen position written by the last `project` call. */
export const proj = { x: 0, y: 0 };
/** Project a world point onto the screen (into `proj`); returns its depth along the view axis, <= 0 when behind. */
export function project(c: Camera, x: number, y: number, z: number): number {
const vx = x - c.pos[0];
const vy = y - c.pos[1];
const vz = z - c.pos[2];
const d = vx * c.fwd[0] + vy * c.fwd[1] + vz * c.fwd[2];
if (d <= 1e-4) return d;
proj.x = W / 2 + (FOCAL * (vx * c.right[0] + vy * c.right[1] + vz * c.right[2])) / d;
proj.y = H / 2 - (FOCAL * (vx * c.up[0] + vy * c.up[1] + vz * c.up[2])) / d;
return d;
}
/** Unit view ray through the center of pixel (x, y), written into `out`. */
export function pixelRay(c: Camera, x: number, y: number, out: number[]): void {
const a = (x + 0.5 - W / 2) / FOCAL;
const b = -(y + 0.5 - H / 2) / FOCAL;
const dx = c.fwd[0] + a * c.right[0] + b * c.up[0];
const dy = c.fwd[1] + a * c.right[1] + b * c.up[1];
const dz = c.fwd[2] + a * c.right[2] + b * c.up[2];
const l = Math.sqrt(dx * dx + dy * dy + dz * dz);
out[0] = dx / l;
out[1] = dy / l;
out[2] = dz / l;
}
/** Depth (along the view axis) of the nearest solid surface at each pixel, rebuilt every frame. */
export const ZBUF = new Float32Array(W * H);
/** How sunlit the visible planet surface is at each pixel (0 = night side); -1 where it isn't showing. */
export const LIT = new Float32Array(W * H);
/** Whether the planet blocks the sun from point p (which must lie outside it). */
export function planetShadow(px: number, py: number, pz: number): boolean {
const b = px * SUN[0] + py * SUN[1] + pz * SUN[2];
if (b > 0) return false;
return px * px + py * py + pz * pz - b * b < 1;
}
/** Spin rate of the cloud tops at a latitude: a fast equatorial jet and alternating bands either side. */
export function spin(lat: number): number {
return 0.0105 * (1 + 0.32 * Math.exp(-((lat / 0.22) ** 2)) + 0.1 * Math.sin(lat * 13));
}
/** Orbital rate of ring material at radius r: inner rings run faster, as orbits do. */
export function orbit(r: number): number {
return 0.05 / (r * Math.sqrt(r));
}
/** Gold and cream cloud bands, darkest to lightest. */
export const BANDS: readonly RGB[] = ['#6e4e2c', '#8e6a3c', '#ac844a', '#c89c5a', '#dcb672', '#ead08e', '#f4e2b0'].map(hex);
const RING_STOPS = ['#6e6458', '#887c6c', '#d8ccb4', '#e8e0cc', '#dcd2bc', '#5a5248', '#bcb4a4', '#b0a898', '#c4bcae'].map(hex);
/** Ring color across the sheet, u = 0 at the inner edge to 1 at the outer. */
export function ringColor(u: number): RGB {
return gradient(RING_STOPS, u);
}