Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(ui): the background is a vibrating plate, and the voice plays it
Harald0f5b1c3b14e2
diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsxindex 696fbcb3a5..5943450374 100644--- a/jarvis/ui/web/frontend/src/App.tsx+++ b/jarvis/ui/web/frontend/src/App.tsx@@ -29,6 +29,7 @@ import { OnboardingGate } from "@/components/onboarding/OnboardingGate";import { installDictationFocusTracker } from "@/lib/dictationTarget";import { SubscriptionRealtimeTransportBroker } from "@/components/voice/SubscriptionRealtimeTransportBroker";import { MascotGigi } from "@/components/MascotGigi";+import { ChladniField } from "@/components/ChladniField";import { useDesktopWallpaper } from "@/hooks/useDesktopWallpaper";import { installWallpaperSync, useWallpaperStore } from "@/store/wallpaper";import { cn } from "@/lib/utils";@@ -63,6 +64,10 @@ function DesktopWallpaper({ hideMascot = false }: { hideMascot?: boolean }) {className="jarvis-desktop-wallpaper absolute inset-0"style={{ backgroundImage: `url(${wallpaperUrl})` }}/>+ {/* The vibrating plate, on top of the picture and under the veil, so it+ works with whichever wallpaper the user picked instead of replacing+ it. It reads the voice itself — see ChladniField. */}+ <ChladniField className="jarvis-chladni-field absolute inset-0 h-full w-full" />{mascotOn && !hideMascot ? (<divclassName="jarvis-desktop-wallpaper-mascot"diff --git a/jarvis/ui/web/frontend/src/components/ChladniField.tsx b/jarvis/ui/web/frontend/src/components/ChladniField.tsxnew file mode 100644index 0000000000..0479f3b810--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/ChladniField.tsx@@ -0,0 +1,255 @@+import { useEffect, useRef } from "react";++import { useEventStore } from "@/store/events";+import { driveTarget, orbDriveFor, smoothOrbLevel } from "@/lib/orbLevel";+import { readVoiceInputLevel } from "@/lib/voiceInputLevel";+import {+ createField,+ driveFor,+ excitedModes,+ fillField,+ grainCountFor,+ grainThrow,+ plateModes,+ reflect,+ sampleField,+ THROW_THRESHOLD,+ type PlateField,+ type PlateMode,+} from "@/lib/chladni";++/**+ * The whole background is a vibrating plate with sand on it.+ *+ * The physics is in `lib/chladni.ts` — a driven rectangular Kirchhoff plate,+ * its modes picked by a drive frequency and an impact point, and grains that+ * are thrown only where the plate actually moves. This file is the wiring:+ * it owns the canvas, the clock and the two budgets that make a permanent+ * background animation affordable.+ *+ * TWO CLOCKS, deliberately. The FIELD is expensive and slow-moving, so it is+ * rebuilt about ten times a second. The GRAINS are cheap and are what the eye+ * follows, so they walk every frame at up to thirty. Rebuilding the field per+ * frame would triple the cost to animate something nobody can see change.+ *+ * It also stops dead when the window is hidden, settles to one still figure+ * under reduced motion, and scales its grain count to the window's area.+ *+ * Both themes are first class and are not inversions of each other. On the+ * dark ground the sand is hot yellow drawn ADDITIVELY, so grains piling onto+ * a node line glow. On the light ground additive blending is invisible, so+ * the sand turns dark and is drawn normally — ink on paper instead of light+ * in a room. Trails are erased with `destination-out` rather than painted+ * over with translucent black, because this canvas sits ON TOP of the user's+ * wallpaper and a black wash would dim the picture they chose.+ */+export function ChladniField({ className }: { className?: string }) {+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const voiceState = useEventStore((s) => s.voiceState);+ // The loop reads the voice through a ref so a state change retunes the+ // plate instead of tearing the whole simulation down and scattering it.+ const voiceRef = useRef(voiceState);+ voiceRef.current = voiceState;++ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ const ctx = canvas.getContext("2d", { alpha: true });+ if (!ctx) return;++ const reduced = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;+ const dpr = Math.min(2, window.devicePixelRatio || 1);++ /** The field grid. Coarse on purpose — the plate is smooth, and the+ grains read it with bilinear interpolation, so more columns would buy+ arithmetic and no detail. */+ const COLS = 168;+ const MAX_MODES = 8;++ let w = 0;+ let h = 0;+ let aspect = 1;+ let rows = 94;+ let field: PlateField = createField(COLS, rows, MAX_MODES);+ let modes: PlateMode[] = plateModes(aspect, 1, 11);+ let px = new Float32Array(0);+ let py = new Float32Array(0);+ let count = 0;++ const measure = () => {+ const rect = canvas.getBoundingClientRect();+ const nextW = Math.max(1, Math.round(rect.width));+ const nextH = Math.max(1, Math.round(rect.height));+ if (nextW === w && nextH === h) return;+ w = nextW;+ h = nextH;+ canvas.width = Math.round(w * dpr);+ canvas.height = Math.round(h * dpr);+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);++ // A wide plate is a wide plate: the aspect ratio goes into the+ // eigenvalues, so the modes come out with square-ish cells instead of+ // a square figure stretched across a widescreen window.+ aspect = w / h;+ rows = Math.max(24, Math.round(COLS / Math.max(0.2, aspect)));+ field = createField(COLS, rows, MAX_MODES);+ modes = plateModes(aspect, 1, 11);++ const next = grainCountFor(w, h);+ if (next !== count) {+ count = next;+ px = new Float32Array(count);+ py = new Float32Array(count);+ for (let i = 0; i < count; i++) {+ px[i] = Math.random();+ py[i] = Math.random();+ }+ }+ };+ measure();++ const isDark = () => document.documentElement.classList.contains("dark");++ let level = 0;+ let raf = 0;+ let lastGrain = 0;+ let lastFieldAt = -1e9;+ let stopped = false;+ const t0 = performance.now();++ /** Rebuild the standing wave for the drive as it is right now. */+ function retune(now: number) {+ const { f, q } = driveFor(voiceRef.current, level);+ // The stick wanders. A plate struck in one fixed spot rings the same+ // handful of modes forever; moving the impact keeps the figure turning+ // over without anyone animating the figure itself.+ const t = (now - t0) / 1000;+ const strikeX = 0.5 + 0.28 * Math.sin(t * 0.07) * Math.cos(t * 0.031);+ const strikeY = 0.5 + 0.24 * Math.cos(t * 0.053);+ fillField(field, excitedModes(modes, f, q, strikeX, strikeY, MAX_MODES));+ }++ /** Scratch for one grain's displacement — see grainThrow. */+ const out = new Float32Array(2);++ function walk(dt: number) {+ // How far a thrown grain travels. The voice is the hammer: louder means+ // the plate throws harder and the sand rearranges faster.+ const step = (0.01 + level * 0.03) * Math.min(2, dt * 60);+ const { cols, w: fw, gx: fgx, gy: fgy } = field;+ const r = rows;+ for (let i = 0; i < count; i++) {+ const x = px[i];+ const y = py[i];+ const wv = sampleField(fw, cols, r, x, y);+ // A grain the plate cannot throw does not move, so it does not need+ // the slope either. Once the figure has settled most of the sand is+ // sitting on a node line, which makes this the difference between+ // three field reads per grain and one.+ if ((wv < 0 ? -wv : wv) <= THROW_THRESHOLD) continue;+ const gx = sampleField(fgx, cols, r, x, y);+ const gy = sampleField(fgy, cols, r, x, y);+ if (grainThrow(wv, gx, gy, step, Math.random(), Math.random(), out)) {+ px[i] = reflect(x + out[0]);+ py[i] = reflect(y + out[1]);+ }+ }+ }++ // An arrow, not a `function` declaration: a hoisted declaration is+ // analysed as if it ran before the `if (!ctx) return` above it, so the+ // narrowing is lost and every use of ctx reads as possibly null.+ const paint = () => {+ const dark = isDark();+ ctx.globalCompositeOperation = "destination-out";+ ctx.fillStyle = "rgba(0, 0, 0, 0.3)";+ ctx.fillRect(0, 0, w, h);++ ctx.globalCompositeOperation = dark ? "lighter" : "source-over";+ ctx.fillStyle = dark+ ? `rgba(255, 232, 120, ${(0.3 + level * 0.34).toFixed(3)})`+ : `rgba(58, 46, 16, ${(0.26 + level * 0.26).toFixed(3)})`;+ const size = dark ? 1.25 : 1.15;+ for (let i = 0; i < count; i++) {+ ctx.fillRect(px[i] * w, py[i] * h, size, size);+ }+ ctx.globalCompositeOperation = "source-over";+ };++ /** Let the sand find the node lines before anyone looks at it. */+ const settle = (rounds: number) => {+ retune(performance.now());+ for (let i = 0; i < rounds; i++) walk(1 / 30);+ };++ if (reduced) {+ settle(220);+ paint();+ const ro = new ResizeObserver(() => {+ measure();+ settle(220);+ paint();+ });+ ro.observe(canvas);+ return () => ro.disconnect();+ }++ const tick = (now: number) => {+ if (stopped) return;+ raf = requestAnimationFrame(tick);++ const drive = orbDriveFor(voiceRef.current);+ const target =+ drive === "idle" ? 0 : driveTarget(drive, (now - t0) / 1000, readVoiceInputLevel(now));++ // A quiet plate is redrawn ten times a second, a busy one thirty. The+ // figure at rest barely moves, and nobody is watching the wallpaper+ // while nothing is being said.+ const budget = level > 0.02 || target > 0.02 ? 1000 / 30 : 1000 / 10;+ const elapsed = now - lastGrain;+ if (elapsed < budget) return;+ lastGrain = now;++ const dt = Math.min(0.2, elapsed / 1000);+ level = smoothOrbLevel(level, target, dt);++ // The slow clock: the standing wave itself.+ if (now - lastFieldAt > 100) {+ lastFieldAt = now;+ retune(now);+ }++ walk(dt);+ paint();+ };++ const start = () => {+ if (stopped || raf) return;+ lastGrain = 0;+ raf = requestAnimationFrame(tick);+ };+ const halt = () => {+ if (raf) cancelAnimationFrame(raf);+ raf = 0;+ };+ // Nothing runs behind a hidden window. This is the whole reason a+ // permanent background animation is affordable at all.+ const onVisibility = () => (document.hidden ? halt() : start());+ document.addEventListener("visibilitychange", onVisibility);++ const ro = new ResizeObserver(() => measure());+ ro.observe(canvas);++ settle(120);+ if (!document.hidden) start();++ return () => {+ stopped = true;+ halt();+ ro.disconnect();+ document.removeEventListener("visibilitychange", onVisibility);+ };+ }, []);++ return <canvas ref={canvasRef} aria-hidden data-testid="chladni-field" className={className} />;+}diff --git a/jarvis/ui/web/frontend/src/lib/chladni.test.ts b/jarvis/ui/web/frontend/src/lib/chladni.test.tsnew file mode 100644index 0000000000..62b668dfe3--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/chladni.test.ts@@ -0,0 +1,300 @@+import { describe, expect, it } from "vitest";++import {+ createField,+ driveFor,+ excitedModes,+ fillField,+ grainCountFor,+ grainThrow,+ modeEigenvalue,+ modeShape,+ plateModes,+ reflect,+ resonance,+ resonancePhase,+ sampleField,+ THROW_THRESHOLD,+ type ExcitedMode,+} from "@/lib/chladni";++/** One mode at full strength, for checking the field on its own terms. */+function only(n: number, m: number): ExcitedMode[] {+ return [{ mode: { n, m, lambda: modeEigenvalue(n, m, 1, 1) }, weight: 1 }];+}++/** grainThrow writes into a caller's buffer to keep the hot loop allocation+ free; the tests want the pair back, so they unpack it here. */+const OUT = new Float32Array(2);+function thrown(+ w: number,+ gx: number,+ gy: number,+ step: number,+ rndX: number,+ rndY: number,+): { dx: number; dy: number; moved: boolean } {+ const moved = grainThrow(w, gx, gy, step, rndX, rndY, OUT);+ return { dx: OUT[0], dy: OUT[1], moved };+}++describe("the plate's modes", () => {+ it("is symmetric only while it is square — which is why the square shortcut breaks", () => {+ // On a square plate (n,m) and (m,n) ring at the same frequency, and that+ // degeneracy is the ONLY reason the classic sin·sin − sin·sin figure is a+ // solution at all. Make the plate 16:9 and the pair splits apart, so that+ // formula stops describing anything on a widescreen window.+ expect(modeEigenvalue(3, 2, 1, 1)).toBeCloseTo(modeEigenvalue(2, 3, 1, 1), 12);+ const a = 16 / 9;+ expect(modeEigenvalue(3, 2, a, 1)).not.toBeCloseTo(modeEigenvalue(2, 3, a, 1), 3);+ });++ it("lists every mode, cheapest first", () => {+ const modes = plateModes(16 / 9, 1, 6);+ expect(modes).toHaveLength(36);+ for (let i = 1; i < modes.length; i++) {+ expect(modes[i].lambda).toBeGreaterThanOrEqual(modes[i - 1].lambda);+ }+ });+});++describe("how a mode answers the drive", () => {+ it("answers fully on resonance and falls away off it", () => {+ expect(resonance(40, 40, 20)).toBeCloseTo(1, 12);+ // Two bandwidths off — Q·detune = 2 — is R = 1/(1 + 2²) = 0.2 exactly.+ expect(resonance(44, 40, 20)).toBeCloseTo(0.2, 9);+ // A drive at twice the mode's frequency barely reaches it: 1/401.+ expect(resonance(80, 40, 20)).toBeCloseTo(1 / 401, 9);+ });++ it("is half as strong exactly one bandwidth off, so Q really is the width", () => {+ // R = 1/(1 + Q²·detune²) is 1/2 when Q·detune = 1.+ const q = 25;+ const f = 60;+ expect(resonance(f * (1 + 1 / q), f, q)).toBeCloseTo(0.5, 6);+ });++ it("gets narrower as the plate gets less damped", () => {+ const loose = resonance(45, 40, 8);+ const tight = resonance(45, 40, 40);+ expect(loose).toBeGreaterThan(tight);+ });++ it("flips phase through resonance", () => {+ // Below its own frequency a mode pushes with the driver, above it pushes+ // against. Without the flip neighbouring modes only ever add up, and the+ // figure fills in instead of cancelling into lines.+ expect(resonancePhase(30, 40)).toBe(1);+ expect(resonancePhase(50, 40)).toBe(-1);+ });++ it("never answers a drive of nothing", () => {+ expect(resonance(40, 0, 20)).toBe(0);+ });+});++describe("where the plate is struck", () => {+ it("leaves every even mode silent when struck dead centre", () => {+ // The centre is a node for every even mode — sin(nπ/2) = 0 — so hitting+ // it cannot drive them, however close they sit to the drive frequency.+ // This is the check that coupling is real and not decoration.+ const modes = plateModes(1, 1, 8);+ const excited = excitedModes(modes, 25, 6, 0.5, 0.5, 40);+ expect(excited.length).toBeGreaterThan(0);+ for (const e of excited) {+ expect(e.mode.n % 2).toBe(1);+ expect(e.mode.m % 2).toBe(1);+ }+ });++ it("wakes modes the centre cannot, once the stick moves off it", () => {+ const modes = plateModes(1, 1, 8);+ const centre = excitedModes(modes, 25, 6, 0.5, 0.5, 40);+ const offset = excitedModes(modes, 25, 6, 0.31, 0.42, 40);+ const evenSomewhere = offset.some((e) => e.mode.n % 2 === 0 || e.mode.m % 2 === 0);+ expect(evenSomewhere).toBe(true);+ expect(offset.length).toBeGreaterThan(centre.length);+ });++ it("hands back a normalised set, so the plate's shape never runs away", () => {+ const modes = plateModes(16 / 9, 1, 10);+ for (const f of [12, 40, 95]) {+ const excited = excitedModes(modes, f, 14, 0.37, 0.44, 8);+ const total = excited.reduce((s, e) => s + Math.abs(e.weight), 0);+ expect(total).toBeCloseTo(1, 6);+ expect(excited.length).toBeLessThanOrEqual(8);+ }+ });+});++describe("the field on the grid", () => {+ it("stands still on a single mode's node lines", () => {+ const field = createField(101, 101, 4);+ fillField(field, only(2, 1));+ // w = sin(2πx)·sin(πy): x = 0.5 is a node line for every y.+ for (const y of [0.2, 0.5, 0.8]) {+ expect(Math.abs(sampleField(field.w, 101, 101, 0.5, y))).toBeLessThan(1e-5);+ }+ // And it is emphatically not standing still between them.+ expect(Math.abs(sampleField(field.w, 101, 101, 0.25, 0.5))).toBeGreaterThan(0.9);+ });++ it("scales the shape to a peak of one, whatever it is driven at", () => {+ for (const [n, m] of [+ [1, 1],+ [3, 2],+ [5, 4],+ ]) {+ const field = createField(101, 101, 4);+ fillField(field, only(n, m));+ let peak = 0;+ for (const v of field.w) peak = Math.max(peak, Math.abs(v));+ expect(peak).toBeCloseTo(1, 4);+ }+ });++ it("slopes away from the node lines, which is the way the sand comes back", () => {+ const field = createField(101, 101, 4);+ fillField(field, only(2, 1));+ // Just left of the node at x = 0.5, |w| is falling as x grows, so the+ // downhill direction — where a thrown grain lands — points at the node.+ const gx = sampleField(field.gx, 101, 101, 0.42, 0.5);+ expect(gx).toBeLessThan(0);+ // Mirrored on the other side.+ expect(sampleField(field.gx, 101, 101, 0.58, 0.5)).toBeGreaterThan(0);+ });++ it("reads a grid point back exactly, and interpolates between them", () => {+ const field = createField(11, 11, 2);+ fillField(field, only(1, 1));+ const direct = field.w[5 * 11 + 5];+ expect(sampleField(field.w, 11, 11, 0.5, 0.5)).toBeCloseTo(direct, 6);+ const between = sampleField(field.w, 11, 11, 0.55, 0.5);+ expect(between).toBeLessThan(direct);+ expect(between).toBeGreaterThan(0);+ });+});++describe("the sand", () => {+ it("is never moved where the plate stands still", () => {+ // The reason a node line is a LINE and not a smear: a grain sitting on+ // one is never thrown, so it stays exactly where it is, forever.+ const still = thrown(THROW_THRESHOLD * 0.5, -1, -1, 0.02, 0.9, 0.1);+ expect(still.moved).toBe(false);+ expect(still.dx).toBe(0);+ expect(still.dy).toBe(0);+ });++ it("is thrown down the slope, toward the quiet", () => {+ // Randoms at 0.5 cancel the scatter, leaving the drift alone — the whole+ // reason the randoms are arguments and not calls to Math.random.+ const { dx, dy, moved } = thrown(0.9, 4, 0, 0.02, 0.5, 0.5);+ expect(moved).toBe(true);+ expect(dx).toBeLessThan(0); // slope rises to the right → grain goes left+ expect(dy).toBeCloseTo(0, 12);+ });++ it("is thrown further the harder the plate moves", () => {+ const gentle = thrown(THROW_THRESHOLD + 0.02, 1, 0, 0.02, 0.5, 0.5).dx;+ const violent = thrown(1, 1, 0, 0.02, 0.5, 0.5).dx;+ expect(Math.abs(violent)).toBeGreaterThan(Math.abs(gentle));+ });++ it("does not care which way the plate bends, only how hard", () => {+ const up = thrown(0.8, 3, 0, 0.02, 0.5, 0.5).dx;+ const down = thrown(-0.8, 3, 0, 0.02, 0.5, 0.5).dx;+ expect(down).toBeCloseTo(up, 12);+ });++ it("scatters when the randoms say so", () => {+ const straight = thrown(0.9, 0, 0, 0.02, 0.5, 0.5);+ const scattered = thrown(0.9, 0, 0, 0.02, 0.95, 0.05);+ expect(straight.dx).toBeCloseTo(0, 12);+ expect(scattered.dx).toBeGreaterThan(0);+ expect(scattered.dy).toBeLessThan(0);+ });++ it("walks a grain that left the plate back onto it", () => {+ expect(reflect(-0.2)).toBeCloseTo(0.2, 12);+ expect(reflect(1.3)).toBeCloseTo(0.7, 12);+ for (const v of [-0.9, -0.01, 0, 0.5, 1, 1.05, 1.9]) {+ const back = reflect(v);+ expect(back).toBeGreaterThanOrEqual(0);+ expect(back).toBeLessThanOrEqual(1);+ }+ });++ it("settles onto the node line when the simulation is actually run", () => {+ // The end-to-end claim: start with sand everywhere, run the real loop,+ // and the sand should be sitting on x = 0.5 and nowhere else.+ const field = createField(101, 101, 4);+ fillField(field, only(2, 1));+ const N = 400;+ const xs = new Float32Array(N);+ const ys = new Float32Array(N);+ for (let i = 0; i < N; i++) {+ xs[i] = (i % 20) / 19;+ ys[i] = Math.floor(i / 20) / 19;+ }+ for (let step = 0; step < 900; step++) {+ for (let i = 0; i < N; i++) {+ const wv = sampleField(field.w, 101, 101, xs[i], ys[i]);+ const gx = sampleField(field.gx, 101, 101, xs[i], ys[i]);+ const gy = sampleField(field.gy, 101, 101, xs[i], ys[i]);+ const { dx, dy } = thrown(wv, gx, gy, 0.02, Math.random(), Math.random());+ xs[i] = reflect(xs[i] + dx);+ ys[i] = reflect(ys[i] + dy);+ }+ }+ // Node lines of sin(2πx)sin(πy): x = 0 , 0.5 , 1 and y = 0 , 1.+ let onNode = 0;+ for (let i = 0; i < N; i++) {+ const nearX = Math.min(xs[i], Math.abs(xs[i] - 0.5), 1 - xs[i]);+ const nearY = Math.min(ys[i], 1 - ys[i]);+ if (Math.min(nearX, nearY) < 0.06) onNode++;+ }+ expect(onNode / N).toBeGreaterThan(0.85);+ });+});++describe("what the conversation does to the plate", () => {+ it("drives it higher the more is going on", () => {+ expect(driveFor("speaking", 0).f).toBeGreaterThan(driveFor("listening", 0).f);+ expect(driveFor("listening", 0).f).toBeGreaterThan(driveFor("idle", 0).f);+ });++ it("drives it higher the louder the voice", () => {+ expect(driveFor("listening", 1).f).toBeGreaterThan(driveFor("listening", 0).f);+ });++ it("loosens the plate while the assistant talks, so several modes ring at once", () => {+ expect(driveFor("speaking", 0).q).toBeLessThan(driveFor("idle", 0).q);+ });+});++describe("the grain budget", () => {+ it("asks a small window for less sand than a big one, and caps both", () => {+ const laptop = grainCountFor(1536, 864);+ expect(grainCountFor(320, 240)).toBeLessThan(laptop);+ // A 4K window is nine times the area but must not be nine times the+ // frame: past the cap the extra sand lands on lines already drawn.+ expect(grainCountFor(7680, 4320)).toBeLessThan(laptop * 2);+ // Even a sliver of a window gets enough sand to draw a figure at all.+ expect(grainCountFor(40, 40)).toBeGreaterThanOrEqual(2000);+ });+});++describe("a mode's shape", () => {+ it("is zero on the plate's edges, whichever mode it is", () => {+ for (const [n, m] of [+ [1, 1],+ [4, 3],+ ]) {+ const mode = { n, m, lambda: modeEigenvalue(n, m, 1, 1) };+ expect(modeShape(mode, 0, 0.5)).toBeCloseTo(0, 12);+ expect(modeShape(mode, 1, 0.5)).toBeCloseTo(0, 12);+ expect(modeShape(mode, 0.5, 0)).toBeCloseTo(0, 12);+ expect(modeShape(mode, 0.5, 1)).toBeCloseTo(0, 12);+ }+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/chladni.ts b/jarvis/ui/web/frontend/src/lib/chladni.tsnew file mode 100644index 0000000000..f6d4baef0c--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/chladni.ts@@ -0,0 +1,355 @@+import type { VoiceState } from "@/store/events";++/**+ * A driven rectangular plate, and the sand lying on it.+ *+ * This is the real thing, not the square-plate shortcut. That shortcut —+ * `sin(nπx)sin(mπy) − sin(mπx)sin(nπy)` — is only a solution when the plate+ * is SQUARE, because it leans on (n,m) and (m,n) being degenerate, which they+ * stop being the moment the plate is 16:9. Run it on a wide window and the+ * figure is not a Chladni figure, it is decoration shaped like one.+ *+ * What actually happens on a plate:+ *+ * 1. A simply supported rectangular plate a×b has mode shapes+ * φ(x,y) = sin(nπx/a)·sin(mπy/b)+ * with eigenvalue λ = (n/a)² + (m/b)², and ω ∝ λ.+ *+ * 2. You drive it at ONE frequency f, at ONE point. Two things decide how+ * much each mode answers:+ * · RESONANCE — a damped oscillator driven off its own frequency+ * answers along a Lorentzian of width f/Q, and its phase flips by π+ * as the drive passes through it. Below resonance a mode pushes with+ * the driver, above it pushes against — which is what makes modes+ * cancel into clean lines instead of piling into mush.+ * · COUPLING — a mode is only driven at all to the extent it MOVES at+ * the point you are hitting: c ∝ φ(x₀,y₀). Strike the dead centre of+ * a plate and every even mode stays silent, because the centre is a+ * node for all of them. This is also what settles the degenerate+ * pairs on a square plate without anyone hand-picking a combination:+ * (n,m) and (m,n) couple differently unless you strike the diagonal.+ *+ * 3. The sand does not diffuse. A grain is thrown when the plate's+ * acceleration under it beats what holds it down — |w| above a threshold+ * — and while it is airborne it lands preferentially DOWN the slope of+ * |w|, toward the quiet. On a node line the plate is still, the grain is+ * never thrown, and it stays put forever. That is why real figures have+ * sharp lines, and why this needs no artificial jitter floor to keep+ * re-forming: retune the plate and the node moves out from under the+ * grain, which is thrown again all by itself.+ *+ * Everything here is a pure function over numbers so the physics can be+ * checked without a canvas — see `chladni.test.ts`. The field is evaluated on+ * a grid and the grains read it, rather than every grain evaluating every+ * mode: the mode shapes are SEPARABLE, so one table of sin(nπx/a) per column+ * and one of sin(mπy/b) per row turn the whole field into multiplications.+ */++export interface PlateMode {+ n: number;+ m: number;+ /** (n/a)² + (m/b)² — proportional to the mode's own frequency. */+ lambda: number;+}++export interface ExcitedMode {+ mode: PlateMode;+ /** Signed amplitude: Lorentzian response × coupling at the striking point. */+ weight: number;+}++/** The plate's grid: displacement and the slope of its magnitude. */+export interface PlateField {+ cols: number;+ rows: number;+ /** Displacement w at each grid point. */+ w: Float32Array;+ /** ∂|w|/∂x and ∂|w|/∂y — the slope a thrown grain drifts down. */+ gx: Float32Array;+ gy: Float32Array;+ /** sin(nπx/a) per mode index per column, and the same down the rows. */+ sx: Float32Array;+ sy: Float32Array;+ /** How many modes the tables were built for. */+ tabled: number;+}++/** λ = (n/a)² + (m/b)², the eigenvalue of mode (n, m) on a plate a×b. */+export function modeEigenvalue(n: number, m: number, a: number, b: number): number {+ const u = n / a;+ const v = m / b;+ return u * u + v * v;+}++/**+ * Every mode up to `maxIndex` in each direction, cheapest first. A plate has+ * infinitely many; the ones far above the drive answer with nothing, so the+ * list is cut where it stops mattering.+ */+export function plateModes(a: number, b: number, maxIndex = 9): PlateMode[] {+ const out: PlateMode[] = [];+ for (let n = 1; n <= maxIndex; n++) {+ for (let m = 1; m <= maxIndex; m++) {+ out.push({ n, m, lambda: modeEigenvalue(n, m, a, b) });+ }+ }+ out.sort((p, q) => p.lambda - q.lambda);+ return out;+}++/**+ * How hard a mode answers a drive at `f`. A damped oscillator's response is+ * Lorentzian around its own frequency, with width f/Q: 1 on resonance, and+ * falling away as the drive moves off it. Q is the plate's quality — a high Q+ * is a bell that answers one frequency, a low Q a damped sheet that answers a+ * band of them at once.+ */+export function resonance(lambda: number, f: number, q: number): number {+ if (f <= 0) return 0;+ const detune = (lambda - f) / f;+ return 1 / (1 + q * q * detune * detune);+}++/**+ * The phase of that answer. A driven oscillator moves WITH the driver below+ * its own frequency and AGAINST it above — the π flip through resonance.+ * Without the flip, neighbouring modes only ever add, and the figure fills in+ * instead of cancelling into lines.+ */+export function resonancePhase(lambda: number, f: number): number {+ return lambda <= f ? 1 : -1;+}++/** A mode's shape at a point, both coordinates 0…1 across the plate. */+export function modeShape(mode: PlateMode, x: number, y: number): number {+ return Math.sin(mode.n * Math.PI * x) * Math.sin(mode.m * Math.PI * y);+}++/**+ * Which modes are actually ringing, and how strongly, for a plate struck at+ * (strikeX, strikeY) and driven at f.+ *+ * The weight carries all three effects at once: Lorentzian magnitude, the π+ * phase flip, and the coupling to the striking point. Modes that answer with+ * almost nothing are dropped — carrying forty modes that contribute 0.1 %+ * each costs the frame and changes no pixel. The result is normalised, so the+ * plate's displacement stays in a fixed range whatever it is driven at.+ */+export function excitedModes(+ modes: PlateMode[],+ f: number,+ q: number,+ strikeX: number,+ strikeY: number,+ limit = 8,+): ExcitedMode[] {+ const scored: ExcitedMode[] = [];+ for (const mode of modes) {+ const r = resonance(mode.lambda, f, q);+ if (r < 0.02) continue;+ const coupling = modeShape(mode, strikeX, strikeY);+ const weight = r * resonancePhase(mode.lambda, f) * coupling;+ if (Math.abs(weight) < 0.01) continue;+ scored.push({ mode, weight });+ }+ scored.sort((p, o) => Math.abs(o.weight) - Math.abs(p.weight));+ const kept = scored.slice(0, limit);+ const peak = kept.reduce((s, e) => s + Math.abs(e.weight), 0);+ if (peak <= 0) return kept;+ return kept.map((e) => ({ mode: e.mode, weight: e.weight / peak }));+}++export function createField(cols: number, rows: number, maxModes = 8): PlateField {+ return {+ cols,+ rows,+ w: new Float32Array(cols * rows),+ gx: new Float32Array(cols * rows),+ gy: new Float32Array(cols * rows),+ sx: new Float32Array(maxModes * cols),+ sy: new Float32Array(maxModes * rows),+ tabled: maxModes,+ };+}++/**+ * Evaluate the plate on its grid, then the slope of |w|.+ *+ * The mode shapes are separable — sin(nπx)·sin(mπy) — so each mode's sine is+ * tabulated once per column and once per row, and the field itself is a+ * multiply-add over those tables. A 160×90 grid across eight modes is 115k+ * multiplications and not one call to Math.sin.+ */+export function fillField(field: PlateField, excited: ExcitedMode[]): void {+ const { cols, rows, w, gx, gy, sx, sy } = field;+ const count = Math.min(excited.length, field.tabled);++ for (let e = 0; e < count; e++) {+ const { n, m } = excited[e].mode;+ const rowOff = e * cols;+ for (let i = 0; i < cols; i++) {+ sx[rowOff + i] = Math.sin(n * Math.PI * (i / (cols - 1)));+ }+ const colOff = e * rows;+ for (let j = 0; j < rows; j++) {+ sy[colOff + j] = Math.sin(m * Math.PI * (j / (rows - 1)));+ }+ }++ w.fill(0);+ for (let e = 0; e < count; e++) {+ const weight = excited[e].weight;+ const xOff = e * cols;+ const yOff = e * rows;+ for (let j = 0; j < rows; j++) {+ const wy = weight * sy[yOff + j];+ if (wy === 0) continue;+ const row = j * cols;+ for (let i = 0; i < cols; i++) {+ w[row + i] += wy * sx[xOff + i];+ }+ }+ }++ // Scale the shape to a peak of 1. The plate's SHAPE is what the modes+ // decide; how hard it is being hit is a separate number the caller owns+ // (the throw step). Without this the threshold below would mean something+ // different at every drive frequency, and the figure would dissolve+ // whenever the modes happened to cancel.+ let peak = 0;+ for (let i = 0; i < w.length; i++) {+ const v = w[i] < 0 ? -w[i] : w[i];+ if (v > peak) peak = v;+ }+ if (peak > 1e-6) {+ const scale = 1 / peak;+ for (let i = 0; i < w.length; i++) w[i] *= scale;+ }++ // Central differences of |w|. The grain drifts down this, so it is the+ // slope of the MAGNITUDE — a grain does not care which way the plate is+ // bending, only how hard it is being thrown.+ for (let j = 0; j < rows; j++) {+ const row = j * cols;+ const up = (j > 0 ? j - 1 : j) * cols;+ const down = (j < rows - 1 ? j + 1 : j) * cols;+ for (let i = 0; i < cols; i++) {+ const left = i > 0 ? i - 1 : i;+ const right = i < cols - 1 ? i + 1 : i;+ gx[row + i] = Math.abs(w[row + right]) - Math.abs(w[row + left]);+ gy[row + i] = Math.abs(w[down + i]) - Math.abs(w[up + i]);+ }+ }+}++/** Bilinear read of one plane of the field at (x, y), both 0…1. */+export function sampleField(+ plane: Float32Array,+ cols: number,+ rows: number,+ x: number,+ y: number,+): number {+ const fx = Math.min(cols - 1.0001, Math.max(0, x * (cols - 1)));+ const fy = Math.min(rows - 1.0001, Math.max(0, y * (rows - 1)));+ const i = fx | 0;+ const j = fy | 0;+ const tx = fx - i;+ const ty = fy - j;+ const a = plane[j * cols + i];+ const b = plane[j * cols + i + 1];+ const c = plane[(j + 1) * cols + i];+ const d = plane[(j + 1) * cols + i + 1];+ return a + (b - a) * tx + (c - a) * ty + (a - b - c + d) * tx * ty;+}++/**+ * How much of the plate's motion it takes to throw a grain off it. Below+ * this the grain is never airborne and never moves — which is exactly why a+ * node line stays a line instead of blurring away.+ */+export const THROW_THRESHOLD = 0.055;++/**+ * Where a grain goes this frame.+ *+ * It is thrown only while |w| beats the threshold; the harder it is thrown,+ * the further it travels. Airborne it drifts DOWN the slope of |w| — toward+ * the quiet — with a random component, because a bouncing grain does not+ * choose its direction, it is merely biased. The randoms are passed in+ * rather than drawn here so the physics stays deterministic under test.+ *+ * The displacement is written into `out` (plate coordinates, 0…1 across the+ * plate) and the return says whether the grain moved at all. Returning a+ * fresh `[dx, dy]` cost 19,000 array allocations per frame at the maintainer's+ * window size, which the garbage collector then had to clean up sixty times a+ * second — measured at 22.9 ms per walk before this was changed.+ */+export function grainThrow(+ w: number,+ gx: number,+ gy: number,+ step: number,+ rndX: number,+ rndY: number,+ out: Float32Array,+): boolean {+ const mag = w < 0 ? -w : w;+ const excess = mag - THROW_THRESHOLD;+ if (excess <= 0) {+ out[0] = 0;+ out[1] = 0;+ return false;+ }+ const energy = (excess < 1 ? excess : 1) * step;+ // Downhill on |w|, normalised so a shallow slope still points somewhere.+ // Math.hypot is correct and slow; the magnitudes here cannot overflow, so+ // the plain square root is the right tool.+ const slope = Math.sqrt(gx * gx + gy * gy);+ const dirX = slope > 1e-6 ? -gx / slope : 0;+ const dirY = slope > 1e-6 ? -gy / slope : 0;+ out[0] = (dirX * 0.62 + (rndX - 0.5) * 1.5) * energy;+ out[1] = (dirY * 0.62 + (rndY - 0.5) * 1.5) * energy;+ return true;+}++/** The plate has edges: a grain that walks off one comes back on. */+export function reflect(v: number): number {+ if (v < 0) return -v;+ if (v > 1) return 2 - v;+ return v;+}++/**+ * Grains scale with the area, so a small window does less work than a big one+ * and a huge one does not run away with the frame.+ *+ * One grain per ~110 square pixels. Denser was tried (1 per 70) and measured:+ * it costs a third more per frame and the extra sand lands on node lines that+ * are already drawn, so it buys weight, not detail.+ */+export function grainCountFor(width: number, height: number): number {+ return Math.min(16000, Math.max(2500, Math.round((width * height) / 110)));+}++/**+ * What the conversation does to the plate.+ *+ * The voice sets the drive frequency, and the frequency picks the modes — the+ * figure is never chosen directly. Resting is a low drive and a coarse+ * figure; speaking drives it high and fine. `q` loosens while the assistant+ * talks so several modes ring at once and the figure churns rather than+ * holding one shape.+ */+export function driveFor(state: VoiceState, level: number): { f: number; q: number } {+ switch (state) {+ case "listening":+ return { f: 34 + level * 46, q: 15 };+ case "thinking":+ return { f: 52 + level * 30, q: 22 };+ case "speaking":+ return { f: 62 + level * 92, q: 9 };+ default:+ return { f: 19 + level * 8, q: 20 };+ }+}