// The Fluodditylike v0 substrate as a WebGL2 engine. Pure imperative TS — owns the GL // context, the ping-pong float textures, and the rAF loop. NEVER imported by Svelte's // reactive layer; the orchestrator pushes a plain {rule, params} snapshot in. // // Pipeline per step (docs/v0_normalization.md §1, world_size = 1): // 1. particle_update : sample 2 sensors, eval the rule, integrate vel/pos -> particle tex // 2. deposit : additive gl.POINTS gaussian splat of velocity -> deposit tex // 3. field_update : 5-tap diffuse(prev field) + persist, mix in deposit -> field tex // render(): field -> HSV to the canvas. import { createContext, Program, PingPong, createFloatTarget, createColorTarget, type GL, type Target, } from "./gl/glutil"; import type { Rule } from "./rule"; import type { SubstrateParams } from "./params"; import fullscreenVert from "./shaders/fullscreen.vert?raw"; import particleFrag from "./shaders/particle_update.frag?raw"; import depositVert from "./shaders/deposit.vert?raw"; import depositFrag from "./shaders/deposit.frag?raw"; import fieldFrag from "./shaders/field_update.frag?raw"; import displayFrag from "./shaders/display.frag?raw"; import blitVert from "./shaders/blit.vert?raw"; import blitFrag from "./shaders/blit.frag?raw"; /** A breeder-grid candidate: a compiled rule plus the substrate it runs in. */ export interface GenSpec { /** The compiled rule, or a thunk to compile it lazily. A thunk is only invoked when the tile is * actually warmed (built or hovered), so cached thumbnails never pay the compile cost. */ rule: Rule | (() => Rule); params: SubstrateParams; depositGain: number; /** √(world_size) for this organism's world. 1.0 = the old fixed-ws=1 frame; the desktop * ran at √0.40≈0.632. An environment property (one per world) — it rides per-spec only * because the grid/forest render many independent worlds, each pinning its own environment. */ worldScale: number; /** Edge behaviour code (uBoundary): 0 bounce · 1 reset · 2 wrap. Like worldScale, an environment * property carried per-spec so the grid/forest can render worlds with different boundaries. */ boundary: number; /** Stable organism id (overview/DAG). Captured thumbnails are cached + reused under it, so * revisiting the forest only warms NEW organisms. Omit for transient breeder candidates. */ id?: string; } /** Thumbnail capture resolution (square). The field downscales into this; LINEAR-upscaled to * the on-screen tile. 384² × ~9 RGBA8 ≈ 5 MB — cheap. */ const THUMB_RES = 384; /** Steps run before a thumbnail/preview is captured (and the focus view's initial burst). Higher = * slow-starting organisms reach a visible state before capture, at a linear build-time cost. Tune * here; it's also reported as the SimPins `warmup` on saved records. */ const WARMUP_STEPS = 120; const SIGMA = 0.163; const GAUSS_NORM = 1.0 / (2.0 * Math.PI * SIGMA * SIGMA); // ≈ 5.99 // Desktop splat half-size is 0.0015 in world units (v0_normalization.md §1d). World width is // 2, so the sprite spans (2·0.0015 / 2)·fieldRes ≈ 1.5px at 1024² — derived, not arbitrary. const SPLAT_WORLD_HALF = 0.0015; export interface EngineOptions { rule: Rule; params: SubstrateParams; seed?: number; /** particle count = particleTexSize²; 512 → ~262k (spec target ~250k live). */ particleTexSize?: number; /** field/canvas-state resolution (spec: 1024 live). */ fieldRes?: number; } export class Engine { private gl: GL; private canvas: HTMLCanvasElement; private particleProg: Program; private depositProg: Program; private fieldProg: Program; private displayProg: Program; private blitProg: Program; private particles: PingPong; private field: PingPong; private deposit: Target; private vao: WebGLVertexArrayObject; // --- breeder grid (mode === "grid") --------------------------------------------------- // The single full-res sim above is the one resident sim; the grid is rendered by time- // slicing it across candidates and caching each converged frame as a coloured thumbnail. // Fidelity: thumbnails are the SAME sim at the SAME pins as the focus/single view, just // displayed smaller — so preview == actual by construction (no separate low-res preview). private mode: "single" | "grid" = "single"; private specs: GenSpec[] = []; private cols = 3; // Thumbnail textures. `thumbCache` keys captured frames by organism id, so revisiting the forest // (DAG ↔ viewer ↔ breed ↔ back) reuses them and only warms NEW organisms; un-id'd specs (transient // breeder candidates) recycle `thumbPool` by slot instead. No eviction yet — bounded by the // session's organism count; the LRU is the lazy-loading milestone's job. private thumbCache = new Map(); private thumbPool: Target[] = []; private thumbs: Target[] = []; // current generation: index i -> the texture to composite for spec i // When set, the composite lays each thumbnail at an explicit CSS-pixel rect (the DAG/overview // home) instead of the regular cols×rows grid (the breeder). Same thumbnail machinery either way. private placements: { x: number; y: number; size: number }[] | null = null; private buildQueue: number[] = []; // spec indices still needing a warm+capture (cached ones skipped) private buildIndex = 0; // cursor into buildQueue private buildDoneFired = false; // onBuildDone fires once per generation, deferred to a frame private hoverIndex: number | null = null; // candidate to animate live (null = all frozen) private residentTile = -1; // which candidate the resident sim currently holds (-1 = none/stale) private onBuildDone?: () => void; private pSize: number; private fieldRes: number; private particleCount: number; private rule: Rule; private params: SubstrateParams; private seed: number; private exposure = 10.0; private debug = false; // diagnostic display mode (red=NaN, blue=zero, log-mag otherwise) private depositGain = 30.0; // behavioral energy knob; sweep via setDepositGain() private worldScale = 1.0; // √(world_size); 1.0 = the v0 fixed frame. setWorldScale() / per-spec. private boundary = 2; // edge mode (uBoundary): 2 = wrap (v0 default). setBoundary() / per-spec. private steps = 0; private running = false; private raf = 0; private stepsPerFrame = 1; private warmupSteps = WARMUP_STEPS; private resizeObserver?: ResizeObserver; constructor(canvas: HTMLCanvasElement, opts: EngineOptions) { this.canvas = canvas; this.gl = createContext(canvas); const gl = this.gl; // Blending into RGBA32F (the deposit accumulation) needs EXT_float_blend. if (!gl.getExtension("EXT_float_blend")) { console.warn("EXT_float_blend missing — additive deposit into RGBA32F may not accumulate."); } this.pSize = opts.particleTexSize ?? 512; this.fieldRes = opts.fieldRes ?? 1024; this.particleCount = this.pSize * this.pSize; this.rule = opts.rule; this.params = opts.params; this.seed = opts.seed ?? 1; this.particleProg = new Program(gl, fullscreenVert, particleFrag, "particle_update"); this.depositProg = new Program(gl, depositVert, depositFrag, "deposit"); this.fieldProg = new Program(gl, fullscreenVert, fieldFrag, "field_update"); this.displayProg = new Program(gl, fullscreenVert, displayFrag, "display"); this.blitProg = new Program(gl, blitVert, blitFrag, "blit"); // Particle state: NEAREST/CLAMP, fetched by texel; never filtered or wrapped in-sampler. const initData = this.makeInitialParticles(this.seed); this.particles = new PingPong( createFloatTarget(gl, this.pSize, this.pSize, { data: initData }), createFloatTarget(gl, this.pSize, this.pSize), ); // Field + deposit are RGBA16F: the deposit pass blends additively into them, and 16F // blending is core WebGL2 (32F blending would need EXT_float_blend — see glutil). // REPEAT wrap on the field so the diffuse neighbour taps are toroidal. this.field = new PingPong( createFloatTarget(gl, this.fieldRes, this.fieldRes, { wrap: gl.REPEAT, half: true }), createFloatTarget(gl, this.fieldRes, this.fieldRes, { wrap: gl.REPEAT, half: true }), ); this.deposit = createFloatTarget(gl, this.fieldRes, this.fieldRes, { half: true }); // One empty VAO, bound for the engine's lifetime: all draws are attribute-less // (fullscreen triangle and deposit points both use gl_VertexID). this.vao = gl.createVertexArray()!; gl.bindVertexArray(this.vao); gl.disable(gl.DEPTH_TEST); gl.disable(gl.BLEND); // Textures are zero-filled at creation (see glutil — drivers don't reliably honour the // null-init spec); this clear is belt-and-suspenders and the reset path. this.clearFields(); this.resize(); } // --- public API (the orchestrator seam) ------------------------------------------------- setRule(rule: Rule) { this.rule = rule; } setParams(params: SubstrateParams) { this.params = params; } setExposure(e: number) { this.exposure = e; } // --- breeder grid seam ------------------------------------------------------------------ /** Callback fired once the whole grid has finished warming up + capturing thumbnails. */ setOnBuildDone(fn: () => void) { this.onBuildDone = fn; } /** Switch between the full-screen single sim (focus/editor) and the thumbnail grid. Cached * thumbnails survive the switch; the resident sim is considered stale (focus clobbers it). */ setMode(mode: "single" | "grid") { this.mode = mode; this.residentTile = -1; if (mode === "grid") this.hoverIndex = null; } /** Load a new generation of candidates and (re)build their thumbnails over the next frames. */ setGeneration(specs: GenSpec[], cols: number) { this.specs = specs; this.cols = Math.max(1, cols); this.thumbs = new Array(specs.length); this.buildQueue = []; let poolUsed = 0; for (let i = 0; i < specs.length; i++) { const id = specs[i].id; const cached = id ? this.thumbCache.get(id) : undefined; if (cached) { this.thumbs[i] = cached; // reuse a previously captured frame — no re-warm continue; } // Needs a capture: id'd organisms get a cache-owned texture; transient candidates a pooled one. let tex: Target; if (id) { tex = createColorTarget(this.gl, THUMB_RES, THUMB_RES); this.thumbCache.set(id, tex); } else { tex = this.thumbPool[poolUsed] ?? (this.thumbPool[poolUsed] = createColorTarget(this.gl, THUMB_RES, THUMB_RES)); poolUsed++; } this.thumbs[i] = tex; this.buildQueue.push(i); } this.buildIndex = 0; this.buildDoneFired = false; this.hoverIndex = null; this.residentTile = -1; this.mode = "grid"; } /** Drop the current composite (specs + placements) and show blank — used when leaving a view so a * stale grid/forest isn't composited during an async reload. Keeps the thumbnail cache, and does * NOT fire onBuildDone (there's nothing to build). */ clearComposite() { this.specs = []; this.thumbs = []; this.buildQueue = []; this.buildIndex = 0; this.buildDoneFired = true; this.placements = null; this.hoverIndex = null; this.residentTile = -1; this.mode = "grid"; } /** Lay the thumbnails at explicit CSS-pixel rects (the overview/DAG), or pass null to fall back * to the regular cols×rows grid (the breeder). Cheap — it only changes where cached thumbnails * are composited, never the sim, so panning/zooming the DAG never rebuilds a thumbnail. */ setPlacements(placements: { x: number; y: number; size: number }[] | null) { this.placements = placements; } /** Animate candidate `i` (null = freeze all). Switching tiles re-warms the resident sim. */ setHover(i: number | null) { this.hoverIndex = i !== null && i >= 0 && i < this.specs.length ? i : null; } /** Grid build progress, for an "evolving…" indicator. */ gridProgress(): { done: number; total: number } { return { done: Math.min(this.buildIndex, this.buildQueue.length), total: this.buildQueue.length }; } /** Run the warmup burst on the resident sim so structure is on screen immediately (focus). */ warmup() { for (let i = 0; i < this.warmupSteps; i++) this.step(); } /** Repro-relevant engine settings as plain data (for the SimPins of a saved record). */ config(): { seed: number; warmup: number; fieldRes: number; particleCount: number } { return { seed: this.seed, warmup: this.warmupSteps, fieldRes: this.fieldRes, particleCount: this.particleCount, }; } setStepsPerFrame(n: number) { this.stepsPerFrame = Math.max(1, Math.floor(n)); } /** Toggle the diagnostic display (true) vs normal HSV exposure view (false). */ setDebug(on: boolean) { this.debug = on; } /** Scale how much energy each particle deposits into the field (drives the substrate). */ setDepositGain(g: number) { this.depositGain = g; } /** √(world_size) for the single (focus) sim. Grid/forest tiles set it per-spec in buildTile. */ setWorldScale(s: number) { this.worldScale = s; } /** Boundary mode (uBoundary code) for the single (focus) sim. Tiles set it per-spec in buildTile. */ setBoundary(b: number) { this.boundary = b; } /** * Diagnostics for the console (dev only). Deliberately no readPixels: it's blocked/ * randomized by Firefox's anti-fingerprinting, so the field can't be measured CPU-side — * use the diagnostic display (setDebug(true)) to inspect the field instead. */ debugStats() { const gl = this.gl; return { steps: this.steps, exposure: this.exposure, depositGain: this.depositGain, glError: gl.getError(), floatBlend: !!gl.getExtension("EXT_float_blend"), colorBufferFloat: !!gl.getExtension("EXT_color_buffer_float"), }; } /** Re-seed and clear all state (genome/param changes restart the stochastic sim). */ reset(seed = this.seed) { const gl = this.gl; this.seed = seed; this.steps = 0; gl.bindTexture(gl.TEXTURE_2D, this.particles.read.tex); gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.pSize, this.pSize, gl.RGBA, gl.FLOAT, this.makeInitialParticles(seed)); this.clearFields(); } /** Zero the field (both ping-pong halves) and deposit textures. */ private clearFields() { const gl = this.gl; for (const t of [this.field.read, this.field.write, this.deposit]) { gl.bindFramebuffer(gl.FRAMEBUFFER, t.fbo); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); } gl.bindFramebuffer(gl.FRAMEBUFFER, null); } start() { if (this.running) return; this.running = true; this.resize(); // Warm up so structure is on screen immediately instead of building over a few seconds. for (let i = 0; i < this.warmupSteps; i++) this.step(); this.render(); this.raf = requestAnimationFrame(this.loop); this.resizeObserver = new ResizeObserver(() => this.resize()); this.resizeObserver.observe(this.canvas); } stop() { this.running = false; if (this.raf) cancelAnimationFrame(this.raf); this.resizeObserver?.disconnect(); this.resizeObserver = undefined; } /** Size the drawing buffer to the canvas's CSS size × devicePixelRatio. */ resize() { const dpr = Math.min(window.devicePixelRatio || 1, 2); const w = Math.max(1, Math.round(this.canvas.clientWidth * dpr)); const h = Math.max(1, Math.round(this.canvas.clientHeight * dpr)); if (this.canvas.width !== w || this.canvas.height !== h) { this.canvas.width = w; this.canvas.height = h; } } dispose() { this.stop(); // Browser reclaims GL objects when the context is dropped; explicit deletion omitted // for the spike. } // --- frame loop ------------------------------------------------------------------------- private loop = () => { if (!this.running) return; if (this.mode === "grid") { this.gridFrame(); } else { for (let i = 0; i < this.stepsPerFrame; i++) this.step(); this.render(); } this.raf = requestAnimationFrame(this.loop); }; // --- grid frame: build thumbnails, animate the hovered tile, composite ------------------- private gridFrame() { if (this.buildIndex < this.buildQueue.length) { // Warm up + capture one un-cached candidate per frame (a brief reveal, keeps the tab responsive). this.buildTile(this.buildQueue[this.buildIndex]); this.buildIndex++; } else if (!this.buildDoneFired && this.specs.length > 0) { // All un-cached tiles built (or everything was already cached) -> signal once, the frame after. // Guard on specs.length so a transient empty generation never fires it (which would clear a // loading flag before the real generation arrives). this.buildDoneFired = true; this.onBuildDone?.(); } else if (this.hoverIndex !== null) { if (this.residentTile !== this.hoverIndex) { this.buildTile(this.hoverIndex); // catch the resident sim up to this tile's frozen frame } else { this.step(); // already resident -> advance it live this.captureThumb(this.hoverIndex); } } this.renderGrid(); } /** Point the resident sim at candidate `i`, warm it to convergence, capture its thumbnail. */ private buildTile(i: number) { const s = this.specs[i]; this.rule = typeof s.rule === "function" ? s.rule() : s.rule; // compile lazily, only when warmed this.params = s.params; this.depositGain = s.depositGain; this.worldScale = s.worldScale; this.boundary = s.boundary; this.reset(this.seed); // same seed for every candidate -> a fair comparison this.warmup(); this.captureThumb(i); this.residentTile = i; } /** Render the resident sim's field (HSV display) into thumbnail `i`'s cached texture. */ private captureThumb(i: number) { const gl = this.gl; const t = this.thumbs[i]; gl.bindFramebuffer(gl.FRAMEBUFFER, t.fbo); gl.viewport(0, 0, t.width, t.height); this.displayProg.use(); const sp = this.displayProg; this.bindTex(0, this.field.read.tex); gl.uniform1i(sp.loc("uField"), 0); gl.uniform2f(sp.loc("uViewport"), t.width, t.height); // viewport fills the FBO -> uv in [0,1] gl.uniform1f(sp.loc("uExposure"), this.exposure); gl.uniform1f(sp.loc("uDebug"), this.debug ? 1 : 0); gl.drawArrays(gl.TRIANGLES, 0, 3); } /** Composite the cached thumbnails: at explicit placements (overview/DAG) when set, otherwise as * a regular cols×rows grid (breeder). */ private renderGrid() { const gl = this.gl; gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.viewport(0, 0, this.canvas.width, this.canvas.height); gl.clearColor(0.02, 0.02, 0.03, 1); gl.clear(gl.COLOR_BUFFER_BIT); this.blitProg.use(); if (this.placements && this.placements.length === this.specs.length) { // CSS-pixel rects from the UI (top-left origin) -> device-pixel GL viewports (bottom-left). const dpr = this.canvas.width / Math.max(1, this.canvas.clientWidth); for (let i = 0; i < this.specs.length; i++) { const p = this.placements[i]; const side = p.size * dpr; const x = p.x * dpr; const y = this.canvas.height - (p.y * dpr + side); // flip Y if (x + side < 0 || x > this.canvas.width || y + side < 0 || y > this.canvas.height) continue; // cull gl.viewport(x, y, side, side); this.bindTex(0, this.thumbs[i].tex); gl.uniform1i(this.blitProg.loc("uSrc"), 0); gl.drawArrays(gl.TRIANGLES, 0, 3); } return; } const rows = Math.ceil(this.specs.length / this.cols); const cellW = this.canvas.width / this.cols; const cellH = this.canvas.height / rows; const side = Math.min(cellW, cellH) * 0.94; // letterbox to a centred square (no stretch) for (let i = 0; i < this.specs.length; i++) { const col = i % this.cols; const row = Math.floor(i / this.cols); const cx = col * cellW + (cellW - side) / 2; // GL viewport origin is bottom-left; lay rows out top-to-bottom. const cy = this.canvas.height - (row * cellH + (cellH - side) / 2 + side); gl.viewport(cx, cy, side, side); this.bindTex(0, this.thumbs[i].tex); gl.uniform1i(this.blitProg.loc("uSrc"), 0); gl.drawArrays(gl.TRIANGLES, 0, 3); } } step() { const gl = this.gl; // 1. particle_update -> particles.write gl.bindFramebuffer(gl.FRAMEBUFFER, this.particles.write.fbo); gl.viewport(0, 0, this.pSize, this.pSize); this.particleProg.use(); const pp = this.particleProg; this.bindTex(0, this.particles.read.tex); gl.uniform1i(pp.loc("uParticles"), 0); this.bindTex(1, this.field.read.tex); gl.uniform1i(pp.loc("uField"), 1); gl.uniform4fv(pp.loc("uRule[0]"), this.rule); gl.uniform2f(pp.loc("uFieldRes"), this.fieldRes, this.fieldRes); const p = this.params; gl.uniform1f(pp.loc("uSensorGain"), p.sensorGain); gl.uniform1f(pp.loc("uSensorAngle"), p.sensorAngle); gl.uniform1f(pp.loc("uSensorDistance"), p.sensorDistance); gl.uniform1f(pp.loc("uForceGain"), p.forceGain); gl.uniform1f(pp.loc("uDrag"), p.drag); gl.uniform1f(pp.loc("uStrafePower"), p.strafePower); gl.uniform1f(pp.loc("uAxialForce"), p.axialForce); gl.uniform1f(pp.loc("uLateralForce"), p.lateralForce); gl.uniform1f(pp.loc("uWorldScale"), this.worldScale); gl.uniform1i(pp.loc("uBoundary"), this.boundary); gl.drawArrays(gl.TRIANGLES, 0, 3); this.particles.swap(); // particles.read is now the updated state // 2. deposit -> deposit (additive gl.POINTS) gl.bindFramebuffer(gl.FRAMEBUFFER, this.deposit.fbo); gl.viewport(0, 0, this.fieldRes, this.fieldRes); gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE); this.depositProg.use(); const dp = this.depositProg; this.bindTex(0, this.particles.read.tex); gl.uniform1i(dp.loc("uParticles"), 0); gl.uniform1i(dp.loc("uTexW"), this.pSize); // Desktop splat half-size is 0.0015/√ws world units (the same √ws factor as the dynamics). const splatPx = Math.max(1, (SPLAT_WORLD_HALF / this.worldScale) * this.fieldRes); gl.uniform1f(dp.loc("uSplatPx"), splatPx); gl.uniform1f(dp.loc("uGaussNorm"), GAUSS_NORM); gl.uniform1f(dp.loc("uSigma"), SIGMA); gl.uniform1f(dp.loc("uDepositGain"), this.depositGain); gl.drawArrays(gl.POINTS, 0, this.particleCount); gl.disable(gl.BLEND); // 3. field_update -> field.write gl.bindFramebuffer(gl.FRAMEBUFFER, this.field.write.fbo); gl.viewport(0, 0, this.fieldRes, this.fieldRes); this.fieldProg.use(); const fp = this.fieldProg; this.bindTex(0, this.field.read.tex); gl.uniform1i(fp.loc("uField"), 0); this.bindTex(1, this.deposit.tex); gl.uniform1i(fp.loc("uDeposit"), 1); gl.uniform2f(fp.loc("uFieldRes"), this.fieldRes, this.fieldRes); gl.uniform1f(fp.loc("uPersistence"), p.trailPersistence); gl.uniform1f(fp.loc("uDiffusion"), p.trailDiffusion); gl.drawArrays(gl.TRIANGLES, 0, 3); this.field.swap(); this.steps++; // NOTE: CPU readback (readPixels FLOAT from a 16F buffer) is unreliable on some drivers // (seen on Firefox: returns impossible values), so auto-calibration is disabled. Use the // diagnostic display (setDebug(true)) or manual setExposure() instead. } render() { const gl = this.gl; gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.viewport(0, 0, this.canvas.width, this.canvas.height); this.displayProg.use(); const sp = this.displayProg; this.bindTex(0, this.field.read.tex); gl.uniform1i(sp.loc("uField"), 0); gl.uniform2f(sp.loc("uViewport"), this.canvas.width, this.canvas.height); gl.uniform1f(sp.loc("uExposure"), this.exposure); gl.uniform1f(sp.loc("uDebug"), this.debug ? 1 : 0); gl.drawArrays(gl.TRIANGLES, 0, 3); } // --- internals -------------------------------------------------------------------------- private bindTex(unit: number, tex: WebGLTexture) { const gl = this.gl; gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, tex); } /** Seeded uniform init: pos ~ U(-1,1)², vel ~ 1e-3·N(0,1) (docs/v0_normalization.md §1). */ private makeInitialParticles(seed: number): Float32Array { const n = this.particleCount; const data = new Float32Array(n * 4); const rand = mulberry32(seed); for (let i = 0; i < n; i++) { const o = i * 4; data[o] = rand() * 2 - 1; data[o + 1] = rand() * 2 - 1; data[o + 2] = gaussian(rand) * 1e-3; data[o + 3] = gaussian(rand) * 1e-3; } return data; } } function mulberry32(seed: number): () => number { let a = seed >>> 0; return () => { a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } /** Box-Muller standard normal from a uniform [0,1) generator. */ function gaussian(rand: () => number): number { const u = Math.max(rand(), 1e-12); const v = rand(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v); }