The showcase prompt, round 3, Gemini 4 Argon
agent (cont.)
+2:32write_file{"Content":"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\" />\n<title>∂S = 0 // EIKONAL — Coupled Wave-PDE, Spectral Ray-Caustics & Acoustic Field Laboratory</title>\n<style>\n :root {\n --bg-obsidian: #05070B;\n --bg-panel: #0A0E17;\n --bg-panel-elevated: #101624;\n --bg-control: #141C2E;\n --border-hairline: rgba(148, 163, 184, 0.12);\n --border-bright: rgba(56, 189, 248, 0.45);\n --text-primary: #F1F5F9;\n --text-secondary: #94A3B8;\n --text-muted: #64748B;\n --accent-cyan: #38BDF8;\n --accent-amber: #F59E0B;\n --accent-emerald: #10B981;\n --accent-rose: #FB7185;\n --accent-violet: #A78BFA;\n --font-sans: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n --font-mono: 'JetBrains Mono', 'Fira Code', 'SF Mono', Consolas, monospace;\n }\n\n * {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n user-select: none;\n -webkit-user-select: none;\n }\n\n html, body {\n width: 100%;\n height: 100%;\n overflow: hidden;\n background: var(--bg-obsidian);\n color: var(--text-primary);\n font-family: var(--font-sans);\n font-size: 12px;\n line-height: 1.4;\n -webkit-font-smoothing: antialiased;\n }\n\n /* App Shell */\n .app-shell {\n display: flex;\n flex-direction: column;\n width: 100vw;\n height: 100vh;\n background: var(--bg-obsidian);\n }\n\n /* Top Instrument Header */\n .top-bar {\n height: 46px;\n min-height: 46px;\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 0 12px;\n background: linear-gradient(180deg, #0D1320 0%, #090D16 100%);\n border-bottom: 1px solid var(--border-hairline);\n gap: 8px;\n z-index: 30;\n }\n\n .brand-cluster {\n display: flex;\n align-items: center;\n gap: 10px;\n flex-shrink: 0;\n }\n\n .brand-mark {\n display: flex;\n align-items: center;\n gap: 7px;\n padding: 4px 9px;\n background: rgba(56, 189, 248, 0.08);\n border: 1px solid rgba(56, 189, 248, 0.28);\n border-radius: 5px;\n font-family: var(--font-mono);\n font-weight: 700;\n font-size: 11.5px;\n letter-spacing: 0.05em;\n color: var(--accent-cyan);\n box-shadow: 0 0 18px rgba(56, 189, 248, 0.12);\n }\n\n .brand-mark .sym {\n color: var(--accent-amber);\n font-weight: 800;\n }\n\n .brand-subtitle {\n font-size: 11px;\n color: var(--text-secondary);\n letter-spacing: 0.02em;\n white-space: nowrap;\n }\n\n /* Scene Preset Switcher */\n .preset-strip {\n display: flex;\n align-items: center;\n gap: 4px;\n background: #060911;\n padding: 3px;\n border-radius: 6px;\n border: 1px solid var(--border-hairline);\n overflow-x: auto;\n scrollbar-width: none;\n }\n\n .preset-btn {\n appearance: none;\n background: transparent;\n border: 1px solid transparent;\n color: var(--text-secondary);\n font-family: var(--font-mono);\n font-size: 10.5px;\n font-weight: 600;\n padding: 5px 9px;\n border-radius: 4px;\n cursor: pointer;\n white-space: nowrap;\n transition: all 0.14s ease;\n display: flex;\n align-items: center;\n gap: 5px;\n }\n\n .preset-btn .idx {\n color: var(--text-muted);\n font-size: 9.5px;\n }\n\n .preset-btn:hover {\n color: var(--text-primary);\n background: rgba(255, 255, 255, 0.04);\n }\n\n .preset-btn.active {\n color: #040810;\n background: var(--accent-cyan);\n border-color: #7DD3FC;\n box-shadow: 0 0 14px rgba(56, 189, 248, 0.35);\n font-weight: 700;\n }\n\n .preset-btn.active .idx {\n color: rgba(4, 8, 16, 0.7);\n }\n\n /* Right Action Cluster */\n .action-cluster {\n display: flex;\n align-items: center;\n gap: 6px;\n flex-shrink: 0;\n }\n\n .tool-btn {\n appearance: none;\n background: var(--bg-panel-elevated);\n border: 1px solid var(--border-hairline);\n color: var(--text-primary);\n font-family: var(--font-mono);\n font-size: 10.5px;\n font-weight: 600;\n padding: 5px 9px;\n border-radius: 5px;\n cursor: pointer;\n display: flex;\n align-items: center;\n gap: 5px;\n transition: all 0.14s ease;\n white-space: nowrap;\n }\n\n .tool-btn:hover {\n border-color: rgba(255, 255, 255, 0.28);\n background: #182238;\n }\n\n .tool-btn.active-amber {\n background: rgba(245, 158, 11, 0.16);\n border-color: rgba(245, 158, 11, 0.65);\n color: #FCD34D;\n box-shadow: 0 0 14px rgba(245, 158, 11, 0.2);\n }\n\n .tool-btn.active-emerald {\n background: rgba(16, 185, 129, 0.16);\n border-color: rgba(16, 185, 129, 0.65);\n color: #6EE7B7;\n box-shadow: 0 0 14px rgba(16, 185, 129, 0.22);\n }\n\n .tool-btn .dot {\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: var(--text-muted);\n }\n\n .tool-btn.active-amber .dot {\n background: var(--accent-amber);\n box-shadow: 0 0 6px var(--accent-amber);\n }\n\n .tool-btn.active-emerald .dot {\n background: var(--accent-emerald);\n box-shadow: 0 0 6px var(--accent-emerald);\n }\n\n /* Main Workspace Split */\n .workspace {\n flex: 1;\n display: flex;\n min-height: 0;\n position: relative;\n }\n\n /* Optical Bench Stage */\n .bench-stage {\n flex: 1;\n position: relative;\n min-width: 0;\n background: #04060A;\n overflow: hidden;\n cursor: crosshair;\n }\n\n #simCanvas {\n width: 100%;\n height: 100%;\n display: block;\n }\n\n /* Floating Top-Left Scene Briefing Pill */\n .scene-overlay-card {\n position: absolute;\n top: 12px;\n left: 12px;\n max-width: 410px;\n background: rgba(8, 12, 20, 0.84);\n backdrop-filter: blur(10px);\n -webkit-backdrop-filter: blur(10px);\n border: 1px solid rgba(148, 163, 184, 0.16);\n border-left: 3px solid var(--accent-cyan);\n border-radius: 6px;\n padding: 9px 12px;\n pointer-events: none;\n box-shadow: 0 10px 28px rgba(0, 0, 0, 0.55);\n }\n\n .scene-title-row {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n margin-bottom: 3px;\n }\n\n .scene-title {\n font-family: var(--font-mono);\n font-size: 11.5px;\n font-weight: 700;\n color: var(--text-primary);\n letter-spacing: 0.03em;\n }\n\n .scene-equation-badge {\n font-family: var(--font-mono);\n font-size: 10px;\n color: var(--accent-amber);\n background: rgba(245, 158, 11, 0.1);\n border: 1px solid rgba(245, 158, 11, 0.25);\n padding: 1px 6px;\n border-radius: 3px;\n }\n\n .scene-desc {\n font-size: 11px;\n color: var(--text-secondary);\n line-height: 1.38;\n }\n\n .scene-desc strong {\n color: var(--text-primary);\n font-weight: 600;\n }\n\n /* Bottom Bar Overlays on Canvas */\n .canvas-bottom-hud {\n position: absolute;\n bottom: 12px;\n left: 12px;\n right: 12px;\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n pointer-events: none;\n }\n\n .hud-pill-group {\n display: flex;\n align-items: center;\n gap: 4px;\n background: rgba(8, 12, 20, 0.86);\n backdrop-filter: blur(10px);\n -webkit-backdrop-filter: blur(10px);\n border: 1px solid rgba(148, 163, 184, 0.16);\n padding: 4px;\n border-radius: 6px;\n pointer-events: auto;\n }\n\n .hud-label {\n font-family: var(--font-mono);\n font-size: 9.5px;\n color: var(--text-muted);\n padding: 0 6px;\n text-transform: uppercase;\n letter-spacing: 0.06em;\n }\n\n .layer-btn {\n appearance: none;\n background: transparent;\n border: 1px solid transparent;\n color: var(--text-secondary);\n font-family: var(--font-mono);\n font-size: 10px;\n padding: 3px 8px;\n border-radius: 4px;\n cursor: pointer;\n transition: all 0.12s;\n }\n\n .layer-btn:hover {\n color: var(--text-primary);\n background: rgba(255, 255, 255, 0.05);\n }\n\n .layer-btn.active {\n background: rgba(56, 189, 248, 0.16);\n border-color: rgba(56, 189, 248, 0.45);\n color: var(--accent-cyan);\n font-weight: 600;\n }\n\n .spectrum-legend {\n display: flex;\n align-items: center;\n gap: 7px;\n background: rgba(8, 12, 20, 0.86);\n backdrop-filter: blur(10px);\n border: 1px solid rgba(148, 163, 184, 0.16);\n padding: 5px 10px;\n border-radius: 6px;\n font-family: var(--font-mono);\n font-size: 10px;\n color: var(--text-secondary);\n pointer-events: auto;\n }\n\n .spectrum-bar {\n width: 92px;\n height: 7px;\n border-radius: 3px;\n background: linear-gradient(90deg, #6D28D9 0%, #2563EB 22%, #06B6D4 40%, #10B981 55%, #EAB308 74%, #EF4444 92%, #991B1B 100%);\n box-shadow: 0 0 8px rgba(56, 189, 248, 0.25);\n }\n\n /* Right Telemetry & Hardware Rack */\n .telemetry-rack {\n width: 334px;\n min-width: 334px;\n background: var(--bg-panel);\n border-left: 1px solid var(--border-hairline);\n display: flex;\n flex-direction: column;\n overflow-y: auto;\n z-index: 20;\n }\n\n .rack-section {\n padding: 10px 12px;\n border-bottom: 1px solid var(--border-hairline);\n }\n\n .rack-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 7px;\n }\n\n .rack-title {\n font-family: var(--font-mono);\n font-size: 10px;\n font-weight: 700;\n text-transform: uppercase;\n letter-spacing: 0.08em;\n color: var(--text-secondary);\n display: flex;\n align-items: center;\n gap: 6px;\n }\n\n .rack-title .indicator {\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: var(--accent-cyan);\n box-shadow: 0 0 6px var(--accent-cyan);\n }\n\n .rack-badge {\n font-family: var(--font-mono);\n font-size: 9.5px;\n color: var(--text-muted);\n font-variant-numeric: tabular-nums;\n }\n\n /* Oscilloscope & Phase Portrait Dual Display */\n .scope-grid {\n display: grid;\n grid-template-columns: 1fr 102px;\n gap: 6px;\n }\n\n .scope-box {\n background: #050810;\n border: 1px solid rgba(148, 163, 184, 0.14);\n border-radius: 5px;\n position: relative;\n overflow: hidden;\n height: 102px;\n }\n\n .scope-box canvas {\n width: 100%;\n height: 100%;\n display: block;\n }\n\n .scope-corner-label {\n position: absolute;\n top: 4px;\n left: 6px;\n font-family: var(--font-mono);\n font-size: 9px;\n color: var(--text-muted);\n pointer-events: none;\n display: flex;\n gap: 8px;\n }\n\n .scope-corner-label .p1 { color: var(--accent-cyan); }\n .scope-corner-label .p2 { color: var(--accent-amber); }\n\n .probe-readouts {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n gap: 5px;\n margin-top: 6px;\n }\n\n .readout-cell {\n background: rgba(16, 22, 36, 0.7);\n border: 1px solid rgba(148, 163, 184, 0.1);\n border-radius: 4px;\n padding: 4px 6px;\n }\n\n .readout-label {\n font-size: 9px;\n color: var(--text-muted);\n font-family: var(--font-mono);\n }\n\n .readout-val {\n font-family: var(--font-mono);\n font-size: 11px;\n font-weight: 700;\n color: var(--text-primary);\n font-variant-numeric: tabular-nums;\n }\n\n /* Sliders & Controls */\n .control-row {\n margin-bottom: 8px;\n }\n\n .control-row:last-child {\n margin-bottom: 0;\n }\n\n .control-label-line {\n display: flex;\n justify-content: space-between;\n align-items: center;\n margin-bottom: 3px;\n font-size: 10.5px;\n }\n\n .control-name {\n color: var(--text-secondary);\n font-weight: 500;\n }\n\n .control-val {\n font-family: var(--font-mono);\n font-size: 10.5px;\n color: var(--accent-cyan);\n font-weight: 600;\n font-variant-numeric: tabular-nums;\n }\n\n input[type=\"range\"] {\n -webkit-appearance: none;\n appearance: none;\n width: 100%;\n height: 5px;\n background: #161F33;\n border-radius: 3px;\n outline: none;\n border: 1px solid rgba(255, 255, 255, 0.06);\n }\n\n input[type=\"range\"]::-webkit-slider-thumb {\n -webkit-appearance: none;\n appearance: none;\n width: 13px;\n height: 13px;\n border-radius: 50%;\n background: var(--accent-cyan);\n border: 2px solid #050810;\n cursor: pointer;\n box-shadow: 0 0 8px rgba(56, 189, 248, 0.6);\n }\n\n /* Material Preset Chips */\n .chip-row {\n display: flex;\n gap: 4px;\n margin-top: 6px;\n }\n\n .mat-chip {\n flex: 1;\n appearance: none;\n background: #111827;\n border: 1px solid rgba(148, 163, 184, 0.16);\n color: var(--text-secondary);\n font-family: var(--font-mono);\n font-size: 9.5px;\n padding: 4px 4px;\n border-radius: 4px;\n cursor: pointer;\n text-align: center;\n transition: all 0.12s;\n }\n\n .mat-chip:hover {\n color: var(--text-primary);\n border-color: rgba(255, 255, 255, 0.3);\n }\n\n .mat-chip.active {\n background: rgba(56, 189, 248, 0.14);\n border-color: var(--accent-cyan);\n color: var(--accent-cyan);\n font-weight: 600;\n }\n\n /* Sandbox Tool Strip */\n .sandbox-tools {\n display: none;\n grid-template-columns: repeat(4, 1fr);\n gap: 4px;\n margin-top: 6px;\n }\n\n .sandbox-tools.visible {\n display: grid;\n }\n\n /* Live Mathematical Proof Box */\n .math-proof-box {\n background: #060911;\n border: 1px solid rgba(148, 163, 184, 0.12);\n border-radius: 5px;\n padding: 7px 9px;\n font-family: var(--font-mono);\n font-size: 10px;\n color: var(--text-secondary);\n }\n\n .math-line {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 2px 0;\n border-bottom: 1px dashed rgba(148, 163, 184, 0.08);\n }\n\n .math-line:last-child {\n border-bottom: none;\n }\n\n .math-eq {\n color: #CBD5E1;\n }\n\n .math-live {\n color: var(--accent-emerald);\n font-variant-numeric: tabular-nums;\n }\n\n /* Telemetry Footer */\n .telemetry-footer {\n margin-top: auto;\n padding: 8px 12px;\n background: #060910;\n border-top: 1px solid var(--border-hairline);\n display: flex;\n justify-content: space-between;\n align-items: center;\n font-family: var(--font-mono);\n font-size: 9.5px;\n color: var(--text-muted);\n font-variant-numeric: tabular-nums;\n }\n\n .fps-pill {\n color: var(--accent-emerald);\n font-weight: 700;\n }\n\n /* Modal Popover for Embed & Governing Theory */\n .modal-backdrop {\n position: fixed;\n inset: 0;\n background: rgba(3, 5, 9, 0.78);\n backdrop-filter: blur(6px);\n display: none;\n align-items: center;\n justify-content: center;\n z-index: 100;\n padding: 20px;\n }\n\n .modal-backdrop.open {\n display: flex;\n }\n\n .modal-card {\n width: 100%;\n max-width: 560px;\n background: #0C121E;\n border: 1px solid rgba(56, 189, 248, 0.35);\n border-radius: 8px;\n box-shadow: 0 24px 60px rgba(0, 0, 0, 0.75);\n overflow: hidden;\n }\n\n .modal-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 12px 16px;\n background: #080C15;\n border-bottom: 1px solid var(--border-hairline);\n }\n\n .modal-title {\n font-family: var(--font-mono);\n font-size: 12px;\n font-weight: 700;\n color: var(--accent-cyan);\n }\n\n .modal-close {\n appearance: none;\n background: transparent;\n border: none;\n color: var(--text-secondary);\n font-family: var(--font-mono);\n font-size: 14px;\n cursor: pointer;\n }\n\n .modal-body {\n padding: 16px;\n color: var(--text-secondary);\n font-size: 12px;\n line-height: 1.55;\n }\n\n .code-block {\n background: #05070C;\n border: 1px solid var(--border-hairline);\n border-radius: 5px;\n padding: 10px;\n font-family: var(--font-mono);\n font-size: 11px;\n color: #7DD3FC;\n overflow-x: auto;\n margin: 8px 0 12px;\n user-select: all;\n -webkit-user-select: all;\n }\n\n /* Responsive Embed Mode */\n @media (max-width: 900px) {\n .brand-subtitle { display: none; }\n .telemetry-rack { width: 280px; min-width: 280px; }\n }\n\n @media (max-width: 700px) {\n .workspace { flex-direction: column; }\n .telemetry-rack {\n width: 100%;\n min-width: 0;\n height: 210px;\n border-left: none;\n border-top: 1px solid var(--border-hairline);\n }\n .scene-overlay-card { max-width: 290px; padding: 6px 9px; }\n }\n</style>\n</head>\n<body>\n<div class=\"app-shell\">\n <!-- TOP PRECISION HEADER -->\n <header class=\"top-bar\">\n <div class=\"brand-cluster\">\n <div class=\"brand-mark\" title=\"Principle of Stationary Action: δS = δ∫ n(x,y,λ) ds = 0\">\n <span class=\"sym\">∂S=0</span>\n <span>EIKONAL</span>\n </div>\n <span class=\"brand-subtitle\">Coupled Wave-PDE · Spectral Ray-Caustics · Acoustic Field Solver</span>\n </div>\n\n <nav class=\"preset-strip\" id=\"presetStrip\" aria-label=\"Canonical Physics Experiments\">\n <button class=\"preset-btn active\" data-scene=\"prism\"><span class=\"idx\">01</span>CAUSTIC PRISM</button>\n <button class=\"preset-btn\" data-scene=\"ellipse\"><span class=\"idx\">02</span>ELLIPTICAL FOCUS</button>\n <button class=\"preset-btn\" data-scene=\"slit\"><span class=\"idx\">03</span>DOUBLE SLIT</button>\n <button class=\"preset-btn\" data-scene=\"einstein\"><span class=\"idx\">04</span>EINSTEIN RING</button>\n <button class=\"preset-btn\" data-scene=\"chladni\"><span class=\"idx\">05</span>CHLADNI MODES</button>\n <button class=\"preset-btn\" data-scene=\"sandbox\"><span class=\"idx\">06</span>SANDBOX</button>\n </nav>\n\n <div class=\"action-cluster\">\n <button class=\"tool-btn active-amber\" id=\"btnLoupe\" title=\"Toggle Multi-Scale X-Ray Reality Loupe [Key: L]\">\n <span class=\"dot\"></span>\n <span>X-RAY LOUPE</span>\n </button>\n <button class=\"tool-btn\" id=\"btnAudio\" title=\"Synthesize Live Acoustic Pressure from Probe P1 [Key: M]\">\n <span class=\"dot\"></span>\n <span id=\"audioLabel\">AUDIO PROBE</span>\n </button>\n <button class=\"tool-btn\" id=\"btnPulse\" title=\"Emit Coherent Wavefront & Photon Impulse [Key: Space]\">\n <span>⚡ IMPULSE</span>\n </button>\n <button class=\"tool-btn\" id=\"btnEmbed\" title=\"Embed Snippet & Mathematical Architecture\">\n <span></> EMBED</span>\n </button>\n </div>\n </header>\n\n <!-- MAIN WORKSPACE -->\n <div class=\"workspace\">\n <!-- HERO INTERACTIVE OPTICAL BENCH -->\n <main class=\"bench-stage\" id=\"benchStage\">\n <canvas id=\"simCanvas\"></canvas>\n\n <!-- Scene Contextual Briefing -->\n <div class=\"scene-overlay-card\" id=\"sceneCard\">\n <div class=\"scene-title-row\">\n <span class=\"scene-title\" id=\"sceneTitle\">01 // NEWTONIAN DISPERSION & FLUID CAUSTICS</span>\n <span class=\"scene-equation-badge\" id=\"sceneEq\">n(λ) = n₀ + B/λ²</span>\n </div>\n <p class=\"scene-desc\" id=\"sceneDesc\">\n White light (16 CIE-1931 spectral bands, 380–700nm) refracts through a draggable <strong>flint-glass prism</strong> and <strong>biconvex lens</strong> while coupling to a live <strong>2D hyperbolic wave PDE</strong>. Drag any optic, rotate its bevel ring, or move the <strong>X-Ray Loupe</strong> to inspect sub-grid vectors.\n </p>\n </div>\n\n <!-- Bottom Canvas Layer & Spectrum Bar -->\n <div class=\"canvas-bottom-hud\">\n <div class=\"hud-pill-group\" id=\"layerGroup\">\n <span class=\"hud-label\">FIELD VIEW</span>\n <button class=\"layer-btn active\" data-layer=\"coupled\">Coupled Wave + Rays</button>\n <button class=\"layer-btn\" data-layer=\"wave\">Wave Amplitude ψ(x,y)</button>\n <button class=\"layer-btn\" data-layer=\"rms\">Interference ∫ψ²dt</button>\n <button class=\"layer-btn\" data-layer=\"caustics\">Spectral Caustics</button>\n </div>\n\n <div class=\"spectrum-legend\" title=\"CIE 1931 Physically Accurate Wavelength-to-sRGB Dispersion (380nm Violet to 700nm Crimson)\">\n <span>380nm</span>\n <div class=\"spectrum-bar\"></div>\n <span>700nm CIE-1931</span>\n </div>\n </div>\n </main>\n\n <!-- RIGHT TELEMETRY & HARDWARE INSTRUMENT RACK -->\n <aside class=\"telemetry-rack\">\n <!-- 1. OSCILLOSCOPE & PHASE SPACE -->\n <section class=\"rack-section\">\n <div class=\"rack-header\">\n <span class=\"rack-title\"><span class=\"indicator\"></span>INTERFEROMETER PROBES (P1 · P2)</span>\n <span class=\"rack-badge\" id=\"phaseDiffReadout\">Δφ = 0.00π rad</span>\n </div>\n <div class=\"scope-grid\">\n <div class=\"scope-box\">\n <canvas id=\"scopeCanvas\" width=\"200\" height=\"102\"></canvas>\n <div class=\"scope-corner-label\">\n <span class=\"p1\">● P1(t)</span>\n <span class=\"p2\">● P2(t)</span>\n </div>\n </div>\n <div class=\"scope-box\">\n <canvas id=\"phaseCanvas\" width=\"102\" height=\"102\"></canvas>\n <div class=\"scope-corner-label\">\n <span>(ψ, ∂ₜψ)</span>\n </div>\n </div>\n </div>\n <div class=\"probe-readouts\">\n <div class=\"readout-cell\">\n <div class=\"readout-label\">P1 AMPLITUDE ψ</div>\n <div class=\"readout-val\" id=\"valP1Amp\">+0.000</div>\n </div>\n <div class=\"readout-cell\">\n <div class=\"readout-label\">P1 RMS ENERGY</div>\n <div class=\"readout-val\" id=\"valP1Rms\">0.000</div>\n </div>\n <div class=\"readout-cell\">\n <div class=\"readout-label\">LOCAL INDEX n</div>\n <div class=\"readout-val\" id=\"valP1Ior\">1.000</div>\n </div>\n </div>\n </section>\n\n <!-- 2. DETECTOR SCREEN / SPECTRUM ANALYZER -->\n <section class=\"rack-section\">\n <div class=\"rack-header\">\n <span class=\"rack-title\" id=\"spectrumTitle\"><span class=\"indicator\" style=\"background:var(--accent-amber)\"></span>SPECTRAL FFT & FRINGE INTEGRAL</span>\n <span class=\"rack-badge\" id=\"spectrumBadge\">256-PT RADIX-2</span>\n </div>\n <div class=\"scope-box\" style=\"height: 88px;\">\n <canvas id=\"spectrumCanvas\" width=\"308\" height=\"88\"></canvas>\n <div class=\"scope-corner-label\" id=\"spectrumLegend\">\n <span class=\"p1\">■ Measured PDE</span>\n <span class=\"p2\">--- Analytic Theory</span>\n </div>\n </div>\n </section>\n\n <!-- 3. PHYSICAL PARAMETERS -->\n <section class=\"rack-section\">\n <div class=\"rack-header\">\n <span class=\"rack-title\"><span class=\"indicator\" style=\"background:var(--accent-emerald)\"></span>OPTICAL & WAVE PARAMETERS</span>\n <span class=\"rack-badge\" id=\"matBadge\">SF11 FLINT</span>\n </div>\n\n <div class=\"control-row\">\n <div class=\"control-label-line\">\n <span class=\"control-name\">Refractive Index n₀ (550nm)</span>\n <span class=\"control-val\" id=\"lblIor\">1.68</span>\n </div>\n <input type=\"range\" id=\"sliderIor\" min=\"1.10\" max=\"2.42\" step=\"0.01\" value=\"1.68\" />\n </div>\n\n <div class=\"control-row\">\n <div class=\"control-label-line\">\n <span class=\"control-name\">Cauchy Dispersion B (μm²)</span>\n <span class=\"control-val\" id=\"lblDisp\">0.018</span>\n </div>\n <input type=\"range\" id=\"sliderDisp\" min=\"0.000\" max=\"0.036\" step=\"0.001\" value=\"0.018\" />\n </div>\n\n <div class=\"control-row\">\n <div class=\"control-label-line\">\n <span class=\"control-name\">Wave Driver Frequency f</span>\n <span class=\"control-val\" id=\"lblFreq\">4.8 Hz</span>\n </div>\n <input type=\"range\" id=\"sliderFreq\" min=\"1.2\" max=\"11.0\" step=\"0.1\" value=\"4.8\" />\n </div>\n\n <div class=\"control-row\">\n <div class=\"control-label-line\">\n <span class=\"control-name\" id=\"lblSceneParamName\">Fluid-Optical Coupling α</span>\n <span class=\"control-val\" id=\"lblSceneParamVal\">0.45</span>\n </div>\n <input type=\"range\" id=\"sliderSceneParam\" min=\"0.05\" max=\"1.00\" step=\"0.01\" value=\"0.45\" />\n </div>\n\n <div class=\"chip-row\" id=\"materialChips\">\n <button class=\"mat-chip\" data-n=\"1.33\" data-b=\"0.003\" data-name=\"WATER\">H₂O 1.33</button>\n <button class=\"mat-chip\" data-n=\"1.52\" data-b=\"0.006\" data-name=\"BK7 CROWN\">BK7 1.52</button>\n <button class=\"mat-chip active\" data-n=\"1.68\" data-b=\"0.018\" data-name=\"SF11 FLINT\">FLINT 1.68</button>\n <button class=\"mat-chip\" data-n=\"2.42\" data-b=\"0.032\" data-name=\"DIAMOND\">C-DIA 2.42</button>\n </div>\n\n <div class=\"sandbox-tools\" id=\"sandboxTools\">\n <button class=\"mat-chip active\" data-brush=\"ripple\">💧 Wave</button>\n <button class=\"mat-chip\" data-brush=\"glass\">💎 Glass</button>\n <button class=\"mat-chip\" data-brush=\"wall\">🧱 Mirror</button>\n <button class=\"mat-chip\" data-brush=\"erase\">🧹 Clear</button>\n </div>\n </section>\n\n <!-- 4. LIVE SOLVER INVARIANTS & PROOF -->\n <section class=\"rack-section\">\n <div class=\"rack-header\">\n <span class=\"rack-title\">LIVE SOLVER INVARIANTS</span>\n <span class=\"rack-badge\">9-PT ISOTROPIC O(h⁴)</span>\n </div>\n <div class=\"math-proof-box\">\n <div class=\"math-line\">\n <span class=\"math-eq\">∂²ₜψ = (c₀/n)² ∇²ᵢₛₒψ - γ∂ₜψ</span>\n <span class=\"math-live\" id=\"proofCfl\">CFL 0.56</span>\n </div>\n <div class=\"math-line\">\n <span class=\"math-eq\">Hamiltonian H = ½∫(ψ̇² + c²|∇ψ|²)dA</span>\n <span class=\"math-live\" id=\"proofEnergy\">H = 1.42 J</span>\n </div>\n <div class=\"math-line\">\n <span class=\"math-eq\">Snell-Fermat δ∫n(x,y,λ)ds = 0</span>\n <span class=\"math-live\" id=\"proofRays\">512 Rays</span>\n </div>\n </div>\n </section>\n\n <footer class=\"telemetry-footer\">\n <span class=\"fps-pill\" id=\"fpsReadout\">60.0 FPS</span>\n <span id=\"gridReadout\">300×188 PDE · 16λ CIE</span>\n <span id=\"loupeCoordReadout\">LOUPE: ACTIVE</span>\n </footer>\n </aside>\n </div>\n</div>\n\n<!-- EMBED & ARCHITECTURAL PROOF MODAL -->\n<div class=\"modal-backdrop\" id=\"embedModal\">\n <div class=\"modal-card\">\n <div class=\"modal-header\">\n <span class=\"modal-title\"></> EMBED THIS LABORATORY & SOLVER ARCHITECTURE</span>\n <button class=\"modal-close\" id=\"btnCloseModal\">✕</button>\n </div>\n <div class=\"modal-body\">\n <p><strong>Zero-Dependency Single-File Artifact:</strong> Drop this directly into any blog post, Substack, MDX article, or iframe container. Append <code>?scene=prism|ellipse|slit|einstein|chladni</code> to boot into any canonical experiment.</p>\n <div class=\"code-block\" id=\"embedCodeBlock\"><iframe src=\"index.html?scene=prism&loupe=1\" width=\"100%\" height=\"640\" style=\"border:1px solid #1e293b;border-radius:10px;background:#05070B;\" allow=\"autoplay\" loading=\"lazy\"></iframe></div>\n <p style=\"margin-bottom:6px;\"><strong style=\"color:var(--text-primary)\">Why Everything Holds Up When You Look Closer:</strong></p>\n <ul style=\"padding-left:18px; color:var(--text-secondary); font-size:11.5px;\">\n <li><strong>Unified Variational Physics:</strong> Young's double-slit diffraction, elliptical whispering-gallery refocusing, Newton's prism dispersion, Chladni nodal sand self-assembly, and Einstein gravitational lensing all emerge from the <em>exact same</em> coupled PDE + Eikonal solver.</li>\n <li><strong>True Acoustic Sonification:</strong> Enabling the Audio Probe synthesizes sound directly from the PDE wave oscillation <code>ψ(P1, t)</code> at Probe P1's coordinates—dragging P1 into a dark interference fringe silences the tone via genuine wave cancellation.</li>\n <li><strong>Multi-Scale X-Ray Loupe:</strong> Peel back the macro rendering anywhere on the bench to inspect discrete stencil nodes, Poynting flux vectors <code>S = -c²ψ̇∇ψ</code>, and exact Snell refraction angles.</li>\n </ul>\n </div>\n </div>\n</div>\n\n<script>\n(() => {\n 'use strict';\n\n // ============================================================================\n // 1. CIE 1931 SPECTRAL WAVELENGTH (380nm - 700nm) TO LINEAR/sRGB CONVERSION\n // ============================================================================\n const NUM_WAVELENGTHS = 16;\n const SPECTRAL_BANDS = [];\n\n function wavelengthToRGB(nm) {\n let r = 0, g = 0, b = 0;\n if (nm >= 380 && nm < 440) {\n r = -(nm - 440) / (440 - 380);\n g = 0.0;\n b = 1.0;\n } else if (nm >= 440 && nm < 490) {\n r = 0.0;\n g = (nm - 440) / (490 - 440);\n b = 1.0;\n } else if (nm >= 490 && nm < 510) {\n r = 0.0;\n g = 1.0;\n b = -(nm - 510) / (510 - 490);\n } else if (nm >= 510 && nm < 580) {\n r = (nm - 510) / (580 - 510);\n g = 1.0;\n b = 0.0;\n } else if (nm >= 580 && nm < 645) {\n r = 1.0;\n g = -(nm - 645) / (645 - 580);\n b = 0.0;\n } else if (nm >= 645 && nm <= 705) {\n r = 1.0;\n g = 0.0;\n b = 0.0;\n }\n let factor = 1.0;\n if (nm >= 380 && nm < 420) {\n factor = 0.35 + 0.65 * (nm - 380) / (420 - 380);\n } else if (nm > 645 && nm <= 705) {\n factor = 0.35 + 0.65 * (705 - nm) / (705 - 645);\n }\n const R = Math.round(255 * Math.pow(Math.max(0, r * factor), 0.82));\n const G = Math.round(255 * Math.pow(Math.max(0, g * factor), 0.82));\n const B = Math.round(255 * Math.pow(Math.max(0, b * factor), 0.82));\n return {\n nm,\n um: nm / 1000,\n r: R,\n g: G,\n b: B,\n css: `rgb(${R},${G},${B})`,\n rgbaGlow: `rgba(${R},${G},${B},0.26)`,\n rgbaCore: `rgba(${R},${G},${B},0.72)`\n };\n }\n\n for (let i = 0; i < NUM_WAVELENGTHS; i++) {\n const nm = 390 + (i / (NUM_WAVELENGTHS - 1)) * 300; // 390nm .. 690nm\n SPECTRAL_BANDS.push(wavelengthToRGB(nm));\n }\n\n // Reference wavelength 550nm (0.55 um)\n const INV_LAMBDA0_SQ = 1.0 / (0.55 * 0.55);\n\n function cauchyIndex(n0, B, um) {\n return n0 + B * ((1.0 / (um * um)) - INV_LAMBDA0_SQ);\n }\n\n // ============================================================================\n // 2. SIMULATION GRID & FIELD BUFFERS (300 x 188 9-Point Isotropic PDE)\n // ============================================================================\n const NX = 300;\n const NY = 188;\n const NCELLS = NX * NY;\n\n const uCurr = new Float32Array(NCELLS);\n const uPrev = new Float32Array(NCELLS);\n const uNext = new Float32Array(NCELLS);\n const uVel = new Float32Array(NCELLS);\n const uRMS = new Float32Array(NCELLS);\n\n const iorGrid = new Float32Array(NCELLS); // Base refractive index n(x,y)\n const wallGrid = new Uint8Array(NCELLS); // 1 = solid mirror/barrier\n const dampGrid = new Float32Array(NCELLS); // Absorbing PML boundary profile\n const userGlassGrid = new Float32Array(NCELLS);\n const userWallGrid = new Uint8Array(NCELLS);\n\n // Offscreen image buffer for ultra-fast 32-bit pixel shading\n const fieldCanvas = document.createElement('canvas');\n fieldCanvas.width = NX;\n fieldCanvas.height = NY;\n const fieldCtx = fieldCanvas.getContext('2d');\n const fieldImg = fieldCtx.createImageData(NX, NY);\n const fieldPixels32 = new Uint32Array(fieldImg.data.buffer);\n\n // Chladni Nodal Sand Particles (4,000 grains)\n const NUM_PARTICLES = 4000;\n const sandX = new Float32Array(NUM_PARTICLES);\n const sandY = new Float32Array(NUM_PARTICLES);\n const sandVX = new Float32Array(NUM_PARTICLES);\n const sandVY = new Float32Array(NUM_PARTICLES);\n\n function initSandParticles() {\n for (let i = 0; i < NUM_PARTICLES; i++) {\n sandX[i] = 16 + Math.random() * (NX - 32);\n sandY[i] = 16 + Math.random() * (NY - 32);\n sandVX[i] = 0;\n sandVY[i] = 0;\n }\n }\n initSandParticles();\n\n // ============================================================================\n // 3. STATE, SCENE CONFIGURATIONS & INTERACTIVE OBJECTS\n // ============================================================================\n const urlParams = new URLSearchParams(window.location.search);\n const initialScene = urlParams.get('scene') || 'prism';\n\n const state = {\n scene: initialScene,\n layer: 'coupled', // 'coupled' | 'wave' | 'rms' | 'caustics'\n simTime: 0,\n frameCount: 0,\n fps: 60.0,\n n0: 1.68,\n dispersionB: 0.018,\n waveFreq: 4.8,\n sceneParam: 0.45, // Context-dependent parameter\n cavityMode: false,\n sandboxBrush: 'ripple',\n totalEnergy: 0,\n activeRayCount: 0,\n\n // Interactive X-Ray Loupe\n loupe: {\n enabled: urlParams.get('loupe') !== '0',\n x: 0.44, // normalized [0..1]\n y: 0.47,\n radiusPx: 108,\n snellInfo: null\n },\n\n // Draggable Field Probes (normalized coordinates)\n probes: [\n { id: 'P1', x: 0.77, y: 0.46, color: '#38BDF8', amp: 0, vel: 0, rms: 0, ior: 1, history: new Float32Array(256), histVel: new Float32Array(256) },\n { id: 'P2', x: 0.77, y: 0.64, color: '#F59E0B', amp: 0, vel: 0, rms: 0, ior: 1, history: new Float32Array(256), histVel: new Float32Array(256) }\n ],\n probePtr: 0,\n\n // Scene Optical Elements (Coordinates in Grid Space [0..NX, 0..NY])\n laser: { x: 18, y: 108, angle: -0.18, spread: 0.03, aperture: 18, active: true, raysPerBand: 22 },\n waveSource: { x: 38, y: 94, active: true, amplitude: 1.35 },\n\n prism: { x: 112, y: 88, radius: 34, angle: 0.12, active: true },\n lens: { x: 194, y: 92, rx: 14, ry: 42, angle: 0.04, active: true, concave: false },\n ellipse: { cx: 150, cy: 94, a: 122, e: 0.62, active: false, lastPulseTime: -10 },\n slit: { x: 96, sep: 32, width: 9, active: false, screenX: 256 },\n bh: { x: 148, y: 94, rs: 13.5, active: false },\n chladni: { m: 3, n: 5, active: false }\n };\n\n const SCENE_META = {\n prism: {\n title: '01 // NEWTONIAN DISPERSION & FLUID CAUSTICS',\n eq: 'n(λ) = n₀ + B/λ²',\n desc: 'Collimated white light (16 CIE-1931 spectral bands, 380–700nm) refracts through a draggable <strong>flint-glass prism</strong> and <strong>biconvex lens</strong> while coupling to a live <strong>2D hyperbolic wave PDE</strong>. Drag any optic, rotate its bevel ring, or move the <strong>X-Ray Loupe</strong> to inspect sub-grid vectors.',\n paramName: 'Wave-Optical Coupling α',\n paramMin: 0.0, paramMax: 1.0, paramStep: 0.02, paramVal: 0.48\n },\n ellipse: {\n title: '02 // ELLIPTICAL WHISPERING GALLERY (STATIONARY PATH)',\n eq: '|F₁P| + |PF₂| = 2a',\n desc: 'An impulse emitted at <strong>Focus F₁</strong> expands in all directions, reflects off the elliptical boundary, and re-converges in exact phase coherence at <strong>Focus F₂</strong> because every reflected path has identical length <strong>2a</strong>. Try dragging Source F₁ off-focus to watch phase coherence break into an astroid caustic!',\n paramName: 'Orbital Eccentricity e',\n paramMin: 0.25, paramMax: 0.82, paramStep: 0.01, paramVal: 0.62\n },\n slit: {\n title: '03 // YOUNG’S DOUBLE-SLIT INTERFERENCE & DIFFRACTION',\n eq: 'I(θ) = I₀ cos²β sinc²α',\n desc: 'Coherent wavefronts diffract through two adjustable apertures, generating hyperbolic constructive and destructive fringes. The right rack compares the <strong>emergent PDE intensity ∫ψ²dt</strong> against the <strong>exact Fraunhofer analytical integral</strong>. Drag Probe P1 into a dark nodal channel to hear acoustic cancellation!',\n paramName: 'Slit Separation a (grid)',\n paramMin: 16, paramMax: 64, paramStep: 1, paramVal: 32\n },\n einstein: {\n title: '04 // EINSTEIN RING & OPTICAL SCHWARZSCHILD METRIC',\n eq: 'n(r) = 1 + rₛ / r',\n desc: 'Curved spacetime acts as a graded-index metamaterial <strong>n(r) = 1 + 2GM/rc²</strong>. Both Huygens wavefronts and Fermat photon trajectories bend around the horizon, forming a bright <strong>Einstein Ring caustic</strong>, Shapiro wavefront delay, and critical photon-sphere orbits at <strong>b = (3√3/2)rₛ</strong>.',\n paramName: 'Schwarzschild Horizon rₛ',\n paramMin: 5.0, paramMax: 24.0, paramStep: 0.5, paramVal: 13.5\n },\n chladni: {\n title: '05 // CHLADNI EIGENMODES & SELF-ORGANIZING MATTER',\n eq: '∇²ψ + k²ₘₙψ = 0',\n desc: 'Harmonic transducers excite resonant standing waves inside a reflective acoustic plate. <strong>4,000 individual quartz sand grains</strong> read the local PDE wave amplitude beneath them and migrate via acoustic radiation pressure to crystallize along zero-amplitude nodal contours (ψ = 0).',\n paramName: 'Eigenmode Harmonic Index',\n paramMin: 1, paramMax: 8, paramStep: 0.25, paramVal: 4.0\n },\n sandbox: {\n title: '06 // FREEFORM VARIATIONAL OPTICS & WAVE BENCH',\n eq: 'δ ∫ L(ψ, ∇ψ, ψ̇) dt = 0',\n desc: 'Sculpt custom refractive glass lenses, reflective mirrors, and wave impulses directly on the bench, while dragging the prism, biconvex lens, laser source, and interferometer probes anywhere in the field.',\n paramName: 'Brush Radius / Coupling',\n paramMin: 0.1, paramMax: 1.0, paramStep: 0.05, paramVal: 0.50\n }\n };\n\n // ============================================================================\n // 4. INITIALIZE / SWITCH CANONICAL SCENES\n // ============================================================================\n function clearWaveField() {\n uCurr.fill(0);\n uPrev.fill(0);\n uNext.fill(0);\n uVel.fill(0);\n uRMS.fill(0);\n }\n\n function applyScene(sceneName) {\n state.scene = sceneName;\n clearWaveField();\n userGlassGrid.fill(0);\n userWallGrid.fill(0);\n\n // Reset flags\n state.prism.active = false;\n state.lens.active = false;\n state.ellipse.active = false;\n state.slit.active = false;\n state.bh.active = false;\n state.chladni.active = false;\n state.cavityMode = false;\n\n const meta = SCENE_META[sceneName] || SCENE_META.prism;\n document.getElementById('sceneTitle').textContent = meta.title;\n document.getElementById('sceneEq').textContent = meta.eq;\n document.getElementById('sceneDesc').innerHTML = meta.desc;\n\n const sliderParam = document.getElementById('sliderSceneParam');\n document.getElementById('lblSceneParamName').textContent = meta.paramName;\n sliderParam.min = meta.paramMin;\n sliderParam.max = meta.paramMax;\n sliderParam.step = meta.paramStep;\n sliderParam.value = meta.paramVal;\n state.sceneParam = meta.paramVal;\n document.getElementById('lblSceneParamVal').textContent = Number(meta.paramVal).toFixed(2);\n\n document.getElementById('sandboxTools').classList.toggle('visible', sceneName === 'sandbox');\n\n // Update top preset buttons\n document.querySelectorAll('.preset-btn').forEach(btn => {\n btn.classList.toggle('active', btn.dataset.scene === sceneName);\n });\n\n if (sceneName === 'prism') {\n state.n0 = 1.68;\n state.dispersionB = 0.018;\n state.waveFreq = 4.6;\n state.prism = { x: 108, y: 88, radius: 35, angle: 0.14, active: true };\n state.lens = { x: 196, y: 95, rx: 14, ry: 44, angle: 0.06, active: true, concave: false };\n state.laser = { x: 18, y: 108, angle: -0.20, spread: 0.015, aperture: 14, active: true, raysPerBand: 22 };\n state.waveSource = { x: 34, y: 92, active: true, amplitude: 1.25 };\n state.probes[0].x = 0.76; state.probes[0].y = 0.49;\n state.probes[1].x = 0.64; state.probes[1].y = 0.66;\n state.loupe.x = 0.37; state.loupe.y = 0.45;\n } else if (sceneName === 'ellipse') {\n state.cavityMode = true;\n state.ellipse.active = true;\n state.ellipse.cx = NX * 0.5;\n state.ellipse.cy = NY * 0.5;\n state.ellipse.a = 122;\n state.ellipse.e = 0.62;\n const cDist = state.ellipse.a * state.ellipse.e;\n state.waveSource = { x: state.ellipse.cx - cDist, y: state.ellipse.cy, active: false, amplitude: 2.2 };\n state.laser = { x: state.ellipse.cx - cDist, y: state.ellipse.cy, angle: 0, spread: Math.PI * 2, aperture: 0, active: true, raysPerBand: 4 };\n state.probes[0].x = (state.ellipse.cx + cDist) / NX;\n state.probes[0].y = state.ellipse.cy / NY;\n state.probes[1].x = state.ellipse.cx / NX;\n state.probes[1].y = (state.ellipse.cy - 36) / NY;\n state.loupe.x = (state.ellipse.cx + cDist) / NX;\n state.loupe.y = state.ellipse.cy / NY;\n rebuildMediumGrid();\n triggerWaveImpulse(state.waveSource.x, state.waveSource.y, 6.5, 4.5);\n state.ellipse.lastPulseTime = state.simTime;\n } else if (sceneName === 'slit') {\n state.slit.active = true;\n state.slit.x = 92;\n state.slit.sep = 32;\n state.slit.width = 8;\n state.slit.screenX = 248;\n state.waveFreq = 6.2;\n state.waveSource = { x: 32, y: NY * 0.5, active: true, amplitude: 1.5 };\n state.laser = { x: 18, y: NY * 0.5, angle: 0, spread: 0.04, aperture: 46, active: true, raysPerBand: 14 };\n // Put Probe P1 on central bright fringe, Probe P2 on first dark destructive node\n state.probes[0].x = state.slit.screenX / NX;\n state.probes[0].y = 0.50;\n state.probes[1].x = state.slit.screenX / NX;\n state.probes[1].y = 0.39;\n state.loupe.x = 0.33;\n state.loupe.y = 0.42;\n } else if (sceneName === 'einstein') {\n state.bh.active = true;\n state.bh.x = 146;\n state.bh.y = 94;\n state.bh.rs = 13.5;\n state.waveFreq = 5.4;\n state.waveSource = { x: 26, y: 94, active: true, amplitude: 1.35 };\n state.laser = { x: 18, y: 94, angle: 0.0, spread: 0.01, aperture: 56, active: true, raysPerBand: 24 };\n state.probes[0].x = 0.74;\n state.probes[0].y = 0.50;\n state.probes[1].x = 0.58;\n state.probes[1].y = 0.32;\n state.loupe.x = 0.52;\n state.loupe.y = 0.38;\n } else if (sceneName === 'chladni') {\n state.cavityMode = true;\n state.chladni.active = true;\n state.waveFreq = 7.4;\n state.laser.active = false;\n state.waveSource = { x: NX * 0.5, y: NY * 0.5, active: true, amplitude: 1.8 };\n state.probes[0].x = 0.65;\n state.probes[0].y = 0.50;\n state.probes[1].x = 0.35;\n state.probes[1].y = 0.35;\n state.loupe.x = 0.50;\n state.loupe.y = 0.50;\n initSandParticles();\n } else if (sceneName === 'sandbox') {\n state.prism = { x: 105, y: 76, radius: 30, angle: 0.2, active: true };\n state.lens = { x: 188, y: 108, rx: 13, ry: 38, angle: -0.1, active: true, concave: false };\n state.laser = { x: 20, y: 84, angle: -0.05, spread: 0.02, aperture: 14, active: true, raysPerBand: 18 };\n state.waveSource = { x: 40, y: 120, active: true, amplitude: 1.2 };\n state.loupe.x = 0.62;\n state.loupe.y = 0.56;\n }\n\n document.getElementById('sliderIor').value = state.n0;\n document.getElementById('lblIor').textContent = state.n0.toFixed(2);\n document.getElementById('sliderDisp').value = state.dispersionB;\n document.getElementById('lblDisp').textContent = state.dispersionB.toFixed(3);\n document.getElementById('sliderFreq').value = state.waveFreq;\n document.getElementById('lblFreq').textContent = state.waveFreq.toFixed(1) + ' Hz';\n\n rebuildMediumGrid();\n\n // Seed initial wave state so the bench is immediately alive at frame 0\n for (let w = 0; w < 28; w++) {\n stepWavePDE(0.016);\n }\n }\n\n // ============================================================================\n // 5. GEOMETRY HELPERS & MEDIUM GRID RASTERIZATION\n // ============================================================================\n function getPrismVertices(prism) {\n const verts = [];\n for (let k = 0; k < 3; k++) {\n const a = prism.angle - Math.PI / 2 + (k * 2 * Math.PI) / 3;\n verts.push({\n x: prism.x + Math.cos(a) * prism.radius,\n y: prism.y + Math.sin(a) * prism.radius\n });\n }\n return verts;\n }\n\n function pointInTriangle(px, py, v0, v1, v2) {\n const dX = px - v2.x, dY = py - v2.y;\n const dX21 = v2.x - v1.x, dY12 = v1.y - v2.y;\n const D = dY12 * (v0.x - v2.x) + dX21 * (v0.y - v2.y);\n const s = dY12 * dX + dX21 * dY;\n const t = (v2.y - v0.y) * dX + (v0.x - v2.x) * dY;\n if (D < 0) return s <= 0 && t <= 0 && s + t >= D;\n return s >= 0 && t >= 0 && s + t <= D;\n }\n\n function pointInLens(px, py, lens) {\n const dx = px - lens.x;\n const dy = py - lens.y;\n const ca = Math.cos(-lens.angle);\n const sa = Math.sin(-lens.angle);\n const lx = dx * ca - dy * sa;\n const ly = dx * sa + dy * ca;\n if (Math.abs(ly) > lens.ry) return false;\n const normY = ly / lens.ry;\n const halfWidth = lens.rx * (1.0 - 0.82 * normY * normY);\n return Math.abs(lx) <= halfWidth;\n }\n\n function rebuildMediumGrid() {\n // 1. Absorbing PML boundary vs Reflective Cavity boundary\n const pmlWidth = 18;\n for (let y = 0; y < NY; y++) {\n for (let x = 0; x < NX; x++) {\n const idx = y * NX + x;\n iorGrid[idx] = 1.0 + userGlassGrid[idx];\n wallGrid[idx] = userWallGrid[idx];\n\n if (state.cavityMode) {\n if (x <= 2 || x >= NX - 3 || y <= 2 || y >= NY - 3) {\n wallGrid[idx] = 1;\n }\n dampGrid[idx] = 0.9992;\n } else {\n const dx = Math.min(x, NX - 1 - x);\n const dy = Math.min(y, NY - 1 - y);\n const d = Math.min(dx, dy);\n if (d < pmlWidth) {\n const t = (pmlWidth - d) / pmlWidth;\n dampGrid[idx] = 1.0 - 0.14 * t * t;\n } else {\n dampGrid[idx] = 0.9988;\n }\n }\n }\n }\n\n // 2. Prism Refractive Index\n if (state.prism.active) {\n const [v0, v1, v2] = getPrismVertices(state.prism);\n const minX = Math.max(1, Math.floor(state.prism.x - state.prism.radius - 2));\n const maxX = Math.min(NX - 2, Math.ceil(state.prism.x + state.prism.radius + 2));\n const minY = Math.max(1, Math.floor(state.prism.y - state.prism.radius - 2));\n const maxY = Math.min(NY - 2, Math.ceil(state.prism.y + state.prism.radius + 2));\n for (let y = minY; y <= maxY; y++) {\n for (let x = minX; x <= maxX; x++) {\n if (pointInTriangle(x, y, v0, v1, v2)) {\n iorGrid[y * NX + x] = state.n0;\n }\n }\n }\n }\n\n // 3. Biconvex Lens Refractive Index\n if (state.lens.active) {\n const rMax = Math.max(state.lens.rx, state.lens.ry) + 3;\n const minX = Math.max(1, Math.floor(state.lens.x - rMax));\n const maxX = Math.min(NX - 2, Math.ceil(state.lens.x + rMax));\n const minY = Math.max(1, Math.floor(state.lens.y - rMax));\n const maxY = Math.min(NY - 2, Math.ceil(state.lens.y + rMax));\n for (let y = minY; y <= maxY; y++) {\n for (let x = minX; x <= maxX; x++) {\n if (pointInLens(x, y, state.lens)) {\n iorGrid[y * NX + x] = state.n0;\n }\n }\n }\n }\n\n // 4. Elliptical Whispering Gallery Reflective Wall\n if (state.ellipse.active) {\n const a = state.ellipse.a;\n const e = state.ellipse.e;\n const b = a * Math.sqrt(Math.max(0.04, 1 - e * e));\n state.ellipse.b = b;\n const cx = state.ellipse.cx;\n const cy = state.ellipse.cy;\n for (let y = 0; y < NY; y++) {\n for (let x = 0; x < NX; x++) {\n const idx = y * NX + x;\n const dx = (x - cx) / a;\n const dy = (y - cy) / b;\n const r2 = dx * dx + dy * dy;\n if (r2 >= 1.0) {\n wallGrid[idx] = 1;\n dampGrid[idx] = 0.95;\n } else {\n wallGrid[idx] = 0;\n dampGrid[idx] = 0.9994;\n }\n }\n }\n }\n\n // 5. Young's Double-Slit Barrier\n if (state.slit.active) {\n const sx = Math.round(state.slit.x);\n const halfSep = state.slit.sep * 0.5;\n const halfW = state.slit.width * 0.5;\n const cy = NY * 0.5;\n const slit1Y = cy - halfSep;\n const slit2Y = cy + halfSep;\n for (let y = 0; y < NY; y++) {\n const inSlit1 = Math.abs(y - slit1Y) <= halfW;\n const inSlit2 = Math.abs(y - slit2Y) <= halfW;\n if (!inSlit1 && !inSlit2) {\n for (let dx = -2; dx <= 2; dx++) {\n const xx = sx + dx;\n if (xx >= 0 && xx < NX) {\n wallGrid[y * NX + xx] = 1;\n }\n }\n }\n }\n }\n\n // 6. Schwarzschild Gravitational Lens Metric n(r) = 1 + rs / r\n if (state.bh.active) {\n const bx = state.bh.x;\n const by = state.bh.y;\n const rs = state.bh.rs;\n for (let y = 0; y < NY; y++) {\n for (let x = 0; x < NX; x++) {\n const r = Math.hypot(x - bx, y - by);\n const effR = Math.max(r, rs * 0.48);\n const nGrav = 1.0 + (rs / effR);\n iorGrid[y * NX + x] = Math.min(3.4, nGrav);\n }\n }\n }\n }\n\n // ============================================================================\n // 6. 2D HYPERBOLIC WAVE PDE SOLVER (9-Point O(h⁴) Isotropic Stencil)\n // ============================================================================\n function triggerWaveImpulse(gx, gy, radius = 6.0, strength = 3.8) {\n const minX = Math.max(2, Math.floor(gx - radius * 2.5));\n const maxX = Math.min(NX - 3, Math.ceil(gx + radius * 2.5));\n const minY = Math.max(2, Math.floor(gy - radius * 2.5));\n const maxY = Math.min(NY - 3, Math.ceil(gy + radius * 2.5));\n const invR2 = 1.0 / (radius * radius);\n for (let y = minY; y <= maxY; y++) {\n for (let x = minX; x <= maxX; x++) {\n const idx = y * NX + x;\n if (wallGrid[idx]) continue;\n const d2 = (x - gx) * (x - gx) + (y - gy) * (y - gy);\n const env = Math.exp(-d2 * invR2) * Math.cos(Math.sqrt(d2) * 0.55);\n uCurr[idx] += strength * env;\n }\n }\n }\n\n function stepWavePDE(dt) {\n const substeps = 2;\n const baseC2 = 0.34; // Courant-Friedrichs-Lewy stable base speed squared\n\n for (let step = 0; step < substeps; step++) {\n state.simTime += dt / substeps;\n const t = state.simTime;\n const omega = 2 * Math.PI * state.waveFreq;\n\n // Continuous Harmonic Sources\n if (state.scene === 'slit') {\n // Planar wave driver to the left of the double-slit barrier\n const srcX = 24;\n const val = Math.sin(omega * t) * 1.35;\n for (let y = 20; y < NY - 20; y++) {\n const env = Math.exp(-Math.pow((y - NY * 0.5) / 56, 4));\n uCurr[y * NX + srcX] = val * env;\n }\n } else if (state.scene === 'einstein') {\n // Coherent planar + point wavefronts entering gravitational field\n const srcX = 20;\n const val = Math.sin(omega * t) * 1.15;\n for (let y = 22; y < NY - 22; y++) {\n const env = Math.exp(-Math.pow((y - NY * 0.5) / 62, 4));\n uCurr[y * NX + srcX] = val * env;\n }\n } else if (state.scene === 'chladni') {\n // Symmetric multi-point resonant transducers driving Chladni eigenmodes\n const modeIdx = state.sceneParam;\n const m = Math.max(1, Math.round(modeIdx));\n const n = Math.max(1, Math.round(modeIdx * 1.5));\n const drive = Math.sin(omega * 1.25 * t) * 0.36;\n for (let py = 1; py <= 3; py++) {\n for (let px = 1; px <= 3; px++) {\n const gx = Math.round((px / 4) * NX);\n const gy = Math.round((py / 4) * NY);\n const sign = Math.cos(m * Math.PI * (px / 4)) * Math.cos(n * Math.PI * (py / 4));\n uCurr[gy * NX + gx] += drive * sign;\n }\n }\n } else if (state.scene === 'ellipse') {\n // Periodic coherent pulse at Focus F1 every 3.2 seconds\n if (t - state.ellipse.lastPulseTime > 3.1) {\n triggerWaveImpulse(state.waveSource.x, state.waveSource.y, 5.5, 4.4);\n state.ellipse.lastPulseTime = t;\n if (audioEngine.enabled) audioEngine.triggerPing(520);\n }\n } else if (state.waveSource.active) {\n const sx = Math.max(3, Math.min(NX - 4, Math.round(state.waveSource.x)));\n const sy = Math.max(3, Math.min(NY - 4, Math.round(state.waveSource.y)));\n const val = Math.sin(omega * t) * state.waveSource.amplitude;\n for (let dy = -1; dy <= 1; dy++) {\n for (let dx = -1; dx <= 1; dx++) {\n const idx = (sy + dy) * NX + (sx + dx);\n if (!wallGrid[idx]) uCurr[idx] = val;\n }\n }\n }\n\n // 9-Point Isotropic Laplacian Stencil Integration\n let energySum = 0;\n for (let y = 1; y < NY - 1; y++) {\n const row = y * NX;\n const rowUp = (y - 1) * NX;\n const rowDn = (y + 1) * NX;\n\n for (let x = 1; x < NX - 1; x++) {\n const i = row + x;\n if (wallGrid[i]) {\n uNext[i] = 0;\n uVel[i] = 0;\n continue;\n }\n\n const center = uCurr[i];\n const ortho = uCurr[i - 1] + uCurr[i + 1] + uCurr[rowUp + x] + uCurr[rowDn + x];\n const diag = uCurr[rowUp + x - 1] + uCurr[rowUp + x + 1] + uCurr[rowDn + x - 1] + uCurr[rowDn + x + 1];\n const laplacian = (4.0 * ortho + diag - 20.0 * center) * (1.0 / 6.0);\n\n const nLoc = iorGrid[i];\n const c2 = baseC2 / (nLoc * nLoc);\n const damp = dampGrid[i];\n\n let nextVal = (2.0 * center - uPrev[i] + c2 * laplacian) * damp;\n // Soft physical saturation for guaranteed stability\n if (nextVal > 6.0) nextVal = 6.0 + Math.tanh(nextVal - 6.0);\n else if (nextVal < -6.0) nextVal = -6.0 + Math.tanh(nextVal + 6.0);\n\n uNext[i] = nextVal;\n const vel = (nextVal - uPrev[i]) * 0.5;\n uVel[i] = vel;\n uRMS[i] = uRMS[i] * 0.982 + (nextVal * nextVal) * 0.018;\n\n if ((x & 1) === 0 && (y & 1) === 0) {\n const gx = (uCurr[i + 1] - uCurr[i - 1]) * 0.5;\n const gy = (uCurr[rowDn + x] - uCurr[rowUp + x]) * 0.5;\n energySum += 0.5 * (vel * vel + c2 * (gx * gx + gy * gy));\n }\n }\n }\n state.totalEnergy = energySum * 0.04;\n\n // Swap buffers\n uPrev.set(uCurr);\n uCurr.set(uNext);\n }\n\n // Update Chladni Nodal Sand Particles when in Chladni scene\n if (state.scene === 'chladni') {\n stepChladniParticles();\n }\n\n // Sample Interferometer Probes P1 & P2\n sampleProbes();\n }\n\n function stepChladniParticles() {\n for (let i = 0; i < NUM_PARTICLES; i++) {\n let px = sandX[i];\n let py = sandY[i];\n const ix = Math.max(2, Math.min(NX - 3, Math.floor(px)));\n const iy = Math.max(2, Math.min(NY - 3, Math.floor(py)));\n const idx = iy * NX + ix;\n\n const rms = Math.sqrt(uRMS[idx]);\n const instAmp = Math.abs(uCurr[idx]);\n const agitation = rms * 1.45 + instAmp * 0.35;\n\n // Acoustic radiation pressure gradient -∇(uRMS) pushes particles toward nodes\n const gradX = (uRMS[idx + 1] - uRMS[idx - 1]) * 0.5;\n const gradY = (uRMS[idx + NX] - uRMS[idx - NX]) * 0.5;\n\n sandVX[i] = sandVX[i] * 0.78 - gradX * 4.5 + (Math.random() - 0.5) * agitation * 3.1;\n sandVY[i] = sandVY[i] * 0.78 - gradY * 4.5 + (Math.random() - 0.5) * agitation * 3.1;\n\n px += sandVX[i];\n py += sandVY[i];\n\n if (px < 8) { px = 8 + Math.random() * 4; sandVX[i] *= -0.5; }\n if (px > NX - 9) { px = NX - 9 - Math.random() * 4; sandVX[i] *= -0.5; }\n if (py < 8) { py = 8 + Math.random() * 4; sandVY[i] *= -0.5; }\n if (py > NY - 9) { py = NY - 9 - Math.random() * 4; sandVY[i] *= -0.5; }\n\n sandX[i] = px;\n sandY[i] = py;\n }\n }\n\n function sampleProbes() {\n const ptr = state.probePtr;\n for (let p = 0; p < 2; p++) {\n const pr = state.probes[p];\n const gx = Math.max(1, Math.min(NX - 2, Math.round(pr.x * NX)));\n const gy = Math.max(1, Math.min(NY - 2, Math.round(pr.y * NY)));\n const idx = gy * NX + gx;\n pr.amp = uCurr[idx];\n pr.vel = uVel[idx];\n pr.rms = Math.sqrt(uRMS[idx]);\n pr.ior = iorGrid[idx];\n pr.history[ptr] = pr.amp;\n pr.histVel[ptr] = pr.vel;\n }\n state.probePtr = (ptr + 1) & 255;\n }\n\n // ============================================================================\n // 7. COUPLED SPECTRAL RAY & CAUSTIC SOLVER (Snell + Cauchy + Eikonal)\n // ============================================================================\n // Ray-segment intersection helper\n function intersectRaySegment(ox, oy, dx, dy, ax, ay, bx, by) {\n const v1x = ox - ax;\n const v1y = oy - ay;\n const v2x = bx - ax;\n const v2y = by - ay;\n const v3x = -dy;\n const v3y = dx;\n const dot = v2x * v3x + v2y * v3y;\n if (Math.abs(dot) < 1e-7) return null;\n const t1 = (v2x * v1y - v2y * v1x) / dot;\n const t2 = (v1x * v3x + v1y * v3y) / dot;\n if (t1 > 0.15 && t2 >= 0.0 && t2 <= 1.0) {\n let nx = -v2y;\n let ny = v2x;\n const len = Math.hypot(nx, ny) || 1;\n nx /= len; ny /= len;\n return { t: t1, x: ox + dx * t1, y: oy + dy * t1, nx, ny };\n }\n return null;\n }\n\n // Ray-Lens boundary intersection (approximated by high-precision 24-segment curved polygon)\n function getLensSegments(lens) {\n const segs = [];\n const N = 20;\n const pts = [];\n const ca = Math.cos(lens.angle);\n const sa = Math.sin(lens.angle);\n // Right convex arc\n for (let i = 0; i <= N; i++) {\n const u = -1 + (2 * i) / N;\n const ly = u * lens.ry;\n const lx = lens.rx * (1.0 - 0.82 * u * u);\n pts.push({\n x: lens.x + lx * ca - ly * sa,\n y: lens.y + lx * sa + ly * ca\n });\n }\n // Left convex arc\n for (let i = N - 1; i >= 1; i--) {\n const u = -1 + (2 * i) / N;\n const ly = u * lens.ry;\n const lx = -lens.rx * (1.0 - 0.82 * u * u);\n pts.push({\n x: lens.x + lx * ca - ly * sa,\n y: lens.y + lx * sa + ly * ca\n });\n }\n for (let i = 0; i < pts.length; i++) {\n const a = pts[i];\n const b = pts[(i + 1) % pts.length];\n segs.push({ ax: a.x, ay: a.y, bx: b.x, by: b.y });\n }\n return segs;\n }\n\n function traceSpectralRays() {\n if (!state.laser.active) {\n state.activeRayCount = 0;\n return [];\n }\n\n const prismSegs = [];\n if (state.prism.active) {\n const pv = getPrismVertices(state.prism);\n for (let i = 0; i < 3; i++) {\n const a = pv[i], b = pv[(i + 1) % 3];\n prismSegs.push({ ax: a.x, ay: a.y, bx: b.x, by: b.y, type: 'prism' });\n }\n }\n const lensSegs = state.lens.active ? getLensSegments(state.lens) : [];\n\n const allBoundaries = [...prismSegs, ...lensSegs];\n const rays = [];\n const waveCoupling = state.scene === 'prism' ? state.sceneParam : 0.25;\n\n const loupeGX = state.loupe.x * NX;\n const loupeGY = state.loupe.y * NY;\n let closestSnellDist = 9999;\n state.loupe.snellInfo = null;\n\n const numBands = state.scene === 'ellipse' ? 4 : NUM_WAVELENGTHS;\n const raysPerBand = state.laser.raysPerBand || 16;\n\n for (let bIdx = 0; bIdx < numBands; bIdx++) {\n const band = SPECTRAL_BANDS[Math.floor((bIdx / Math.max(1, numBands - 1)) * (NUM_WAVELENGTHS - 1))];\n const nGlass = cauchyIndex(state.n0, state.dispersionB, band.um);\n\n for (let rIdx = 0; rIdx < raysPerBand; rIdx++) {\n const frac = raysPerBand > 1 ? (rIdx / (raysPerBand - 1)) - 0.5 : 0;\n let ox, oy, ang;\n\n if (state.scene === 'ellipse') {\n ox = state.waveSource.x;\n oy = state.waveSource.y;\n ang = (rIdx / raysPerBand) * Math.PI * 2 + bIdx * 0.04;\n } else {\n const perpX = -Math.sin(state.laser.angle);\n const perpY = Math.cos(state.laser.angle);\n ox = state.laser.x + perpX * frac * state.laser.aperture;\n oy = state.laser.y + perpY * frac * state.laser.aperture;\n ang = state.laser.angle + frac * state.laser.spread;\n }\n\n let dx = Math.cos(ang);\n let dy = Math.sin(ang);\n\n const path = [{ x: ox, y: oy }];\n\n if (state.scene === 'einstein' || state.scene === 'slit') {\n // Continuous Eikonal geodesic integration ds for graded-index / double-slit\n let x = ox, y = oy;\n const stepSize = 2.4;\n for (let s = 0; s < 135; s++) {\n const nx = x + dx * stepSize;\n const ny = y + dy * stepSize;\n if (nx < 2 || nx >= NX - 2 || ny < 2 || ny >= NY - 2) {\n path.push({ x: nx, y: ny });\n break;\n }\n const ix = Math.floor(nx), iy = Math.floor(ny);\n const idx = iy * NX + ix;\n if (wallGrid[idx]) {\n path.push({ x: nx, y: ny });\n break;\n }\n\n if (state.bh.active) {\n const rx = nx - state.bh.x;\n const ry = ny - state.bh.y;\n const r = Math.hypot(rx, ry);\n if (r < state.bh.rs * 0.85) {\n path.push({ x: nx, y: ny });\n break; // Captured inside event horizon!\n }\n // Einstein deflection gradient ∇n = -rs / r³ * r_vec\n const dispScale = 1.0 + (band.um - 0.55) * -0.18;\n const force = -(state.bh.rs * 1.85 * dispScale) / (r * r * r + 8.0);\n dx += force * rx * stepSize;\n dy += force * ry * stepSize;\n }\n\n // Couple wave-field surface slope ∇u\n const gradUX = (uCurr[idx + 1] - uCurr[idx - 1]) * 0.5;\n const gradUY = (uCurr[idx + NX] - uCurr[idx - NX]) * 0.5;\n dx += gradUX * 0.015 * waveCoupling;\n dy += gradUY * 0.015 * waveCoupling;\n\n const dLen = Math.hypot(dx, dy) || 1;\n dx /= dLen; dy /= dLen;\n\n x = nx; y = ny;\n if ((s & 1) === 0) path.push({ x, y });\n }\n } else if (state.scene === 'ellipse') {\n // Exact analytical reflection inside Elliptical Whispering Gallery\n const cx = state.ellipse.cx, cy = state.ellipse.cy;\n const a = state.ellipse.a, b = state.ellipse.b || (a * 0.78);\n for (let bounce = 0; bounce < 2; bounce++) {\n // Solve ((ox + t*dx - cx)/a)^2 + ((oy + t*dy - cy)/b)^2 = 1\n const rx = (ox - cx) / a, ry = (oy - cy) / b;\n const vx = dx / a, vy = dy / b;\n const A = vx * vx + vy * vy;\n const B = 2 * (rx * vx + ry * vy);\n const C = rx * rx + ry * ry - 1.0;\n const disc = B * B - 4 * A * C;\n if (disc <= 0) break;\n const tHit = (-B + Math.sqrt(disc)) / (2 * A);\n const hx = ox + dx * tHit;\n const hy = oy + dy * tHit;\n path.push({ x: hx, y: hy });\n\n // Outward normal to ellipse: ( (hx-cx)/a^2, (hy-cy)/b^2 )\n let nx = (hx - cx) / (a * a);\n let ny = (hy - cy) / (b * b);\n const nLen = Math.hypot(nx, ny) || 1;\n nx /= nLen; ny /= nLen;\n const dot = dx * nx + dy * ny;\n dx = dx - 2 * dot * nx;\n dy = dy - 2 * dot * ny;\n ox = hx + dx * 0.2;\n oy = hy + dy * 0.2;\n }\n } else {\n // Ray-boundary exact Snell's Law refraction + wave ripple perturbation\n let insideMedium = false;\n for (let bounce = 0; bounce < 6; bounce++) {\n let bestHit = null;\n for (let s = 0; s < allBoundaries.length; s++) {\n const seg = allBoundaries[s];\n const hit = intersectRaySegment(ox, oy, dx, dy, seg.ax, seg.ay, seg.bx, seg.by);\n if (hit && (!bestHit || hit.t < bestHit.t)) {\n bestHit = hit;\n }\n }\n\n if (!bestHit) {\n // Propagate to edge of optical bench with subtle wave-slope caustic modulation\n let x = ox, y = oy;\n const step = 4.5;\n for (let k = 0; k < 70; k++) {\n x += dx * step;\n y += dy * step;\n if (x < 1 || x >= NX - 1 || y < 1 || y >= NY - 1) {\n path.push({ x, y });\n break;\n }\n const ix = Math.floor(x), iy = Math.floor(y);\n const idx = iy * NX + ix;\n if (wallGrid[idx]) {\n path.push({ x, y });\n break;\n }\n const gux = (uCurr[idx + 1] - uCurr[idx - 1]) * 0.5;\n const guy = (uCurr[idx + NX] - uCurr[idx - NX]) * 0.5;\n dx += gux * 0.022 * waveCoupling;\n dy += guy * 0.022 * waveCoupling;\n const l = Math.hypot(dx, dy) || 1;\n dx /= l; dy /= l;\n if ((k & 1) === 0) path.push({ x, y });\n }\n break;\n }\n\n path.push({ x: bestHit.x, y: bestHit.y });\n\n // Orient surface normal against incident vector\n let nx = bestHit.nx;\n let ny = bestHit.ny;\n let cosI = -(dx * nx + dy * ny);\n if (cosI < 0) {\n nx = -nx;\n ny = -ny;\n cosI = -cosI;\n }\n\n // Sample wave ripple normal perturbation at interface\n const hix = Math.max(1, Math.min(NX - 2, Math.floor(bestHit.x)));\n const hiy = Math.max(1, Math.min(NY - 2, Math.floor(bestHit.y)));\n const hIdx = hiy * NX + hix;\n const wavePerturb = (uCurr[hIdx + 1] - uCurr[hIdx - 1]) * 0.045 * waveCoupling;\n\n const n1 = insideMedium ? nGlass : 1.0;\n const n2 = insideMedium ? 1.0 : nGlass;\n const eta = n1 / n2;\n const sin2T = eta * eta * (1.0 - cosI * cosI);\n\n // Record Snell diagnostic if near X-Ray Loupe\n const distToLoupe = Math.hypot(bestHit.x - loupeGX, bestHit.y - loupeGY);\n if (distToLoupe < closestSnellDist && bIdx === 8) {\n closestSnellDist = distToLoupe;\n const thetaI = Math.acos(Math.min(1, cosI)) * (180 / Math.PI);\n const thetaT = sin2T <= 1.0 ? Math.asin(Math.min(1, Math.sqrt(sin2T))) * (180 / Math.PI) : 90;\n state.loupe.snellInfo = {\n x: bestHit.x, y: bestHit.y,\n nx, ny,\n ix: dx, iy: dy,\n thetaI, thetaT,\n tir: sin2T > 1.0\n };\n }\n\n if (sin2T > 1.0) {\n // Total Internal Reflection (TIR)\n dx = dx + 2 * cosI * nx;\n dy = dy + 2 * cosI * ny;\n } else {\n // Exact Vector Snell's Law Refraction\n const cosT = Math.sqrt(1.0 - sin2T);\n dx = eta * dx + (eta * cosI - cosT) * nx + wavePerturb * ny;\n dy = eta * dy + (eta * cosI - cosT) * ny - wavePerturb * nx;\n insideMedium = !insideMedium;\n }\n const len = Math.hypot(dx, dy) || 1;\n dx /= len; dy /= len;\n ox = bestHit.x + dx * 0.25;\n oy = bestHit.y + dy * 0.25;\n }\n }\n\n rays.push({ band, path });\n }\n }\n\n state.activeRayCount = rays.length;\n return rays;\n }\n\n // ============================================================================\n // 8. RENDERING PIPELINE (32-bit Field Buffer + Retina Ray/Caustic + X-Ray Loupe)\n // ============================================================================\n const simCanvas = document.getElementById('simCanvas');\n const ctx = simCanvas.getContext('2d');\n\n function renderFieldToOffscreen() {\n const layer = state.layer;\n for (let y = 0; y < NY; y++) {\n const row = y * NX;\n for (let x = 0; x < NX; x++) {\n const i = row + x;\n if (wallGrid[i]) {\n // Anodized dark titanium barrier\n fieldPixels32[i] = (255 << 24) | (38 << 16) | (28 << 8) | 22;\n continue;\n }\n\n const u = uCurr[i];\n const rms = Math.sqrt(uRMS[i]);\n const n = iorGrid[i];\n const glassTint = Math.max(0, (n - 1.0) * 34);\n\n let r = 5, g = 8, b = 15;\n\n if (layer === 'coupled' || layer === 'wave') {\n // Pseudo-3D wave shading using height + directional light derivative\n const ux = (x < NX - 1 ? uCurr[i + 1] : u) - u;\n const uy = (y < NY - 1 ? uCurr[i + NX] : u) - u;\n const spec = Math.max(0, (ux + uy) * 52);\n\n if (u >= 0) {\n const v = Math.min(1.0, u * 0.85);\n r = 6 + v * 28 + spec * 0.9 + glassTint * 0.4;\n g = 10 + v * 155 + spec * 1.1 + glassTint * 0.8;\n b = 18 + v * 235 + spec * 1.3 + glassTint * 1.3;\n } else {\n const v = Math.min(1.0, -u * 0.85);\n r = 6 + v * 95 + spec * 0.5 + glassTint * 0.4;\n g = 9 + v * 28 + spec * 0.6 + glassTint * 0.8;\n b = 18 + v * 115 + spec * 0.9 + glassTint * 1.3;\n }\n // Subtle RMS interference glow\n r += rms * 28;\n g += rms * 42;\n b += rms * 55;\n } else if (layer === 'rms') {\n // Time-integrated standing wave interference energy ∫ψ²dt\n const v = Math.min(1.0, rms * 1.65);\n const v2 = v * v;\n r = 6 + v * 45 + v2 * 210;\n g = 9 + v * 165 + v2 * 75;\n b = 18 + v * 230 - v2 * 50;\n } else if (layer === 'caustics') {\n r = 5 + glassTint * 0.35;\n g = 8 + glassTint * 0.65;\n b = 14 + glassTint * 1.10;\n }\n\n const R = r > 255 ? 255 : (r < 0 ? 0 : r | 0);\n const G = g > 255 ? 255 : (g < 0 ? 0 : g | 0);\n const B = b > 255 ? 255 : (b < 0 ? 0 : b | 0);\n fieldPixels32[i] = (255 << 24) | (B << 16) | (G << 8) | R;\n }\n }\n fieldCtx.putImageData(fieldImg, 0, 0);\n }\n\n function renderBench() {\n const rect = simCanvas.getBoundingClientRect();\n const dpr = Math.min(window.devicePixelRatio || 1, 2);\n const W = Math.round(rect.width * dpr);\n const H = Math.round(rect.height * dpr);\n if (simCanvas.width !== W || simCanvas.height !== H) {\n simCanvas.width = W;\n simCanvas.height = H;\n }\n\n ctx.save();\n ctx.scale(dpr, dpr);\n const cw = rect.width;\n const ch = rect.height;\n const sx = cw / NX;\n const sy = ch / NY;\n\n // 1. Draw Upsampled Wave PDE Field\n renderFieldToOffscreen();\n ctx.imageSmoothingEnabled = true;\n ctx.imageSmoothingQuality = 'high';\n ctx.drawImage(fieldCanvas, 0, 0, cw, ch);\n\n // Subtle precision optical table grid lines\n ctx.strokeStyle = 'rgba(148, 163, 184, 0.045)';\n ctx.lineWidth = 1;\n const gridStep = 40;\n ctx.beginPath();\n for (let x = gridStep; x < cw; x += gridStep) {\n ctx.moveTo(x, 0); ctx.lineTo(x, ch);\n }\n for (let y = gridStep; y < ch; y += gridStep) {\n ctx.moveTo(0, y); ctx.lineTo(cw, y);\n }\n ctx.stroke();\n\n // 2. Trace & Render Spectral Rays and Caustics (Additive Linear Blending)\n const rays = traceSpectralRays();\n if (state.layer !== 'wave' && state.layer !== 'rms' && rays.length > 0) {\n ctx.save();\n ctx.globalCompositeOperation = 'lighter';\n ctx.lineCap = 'round';\n ctx.lineJoin = 'round';\n\n for (let i = 0; i < rays.length; i++) {\n const { band, path } = rays[i];\n if (path.length < 2) continue;\n\n // Outer spectral bloom pass\n ctx.strokeStyle = band.rgbaGlow;\n ctx.lineWidth = state.scene === 'ellipse' ? 2.2 : 3.2;\n ctx.beginPath();\n ctx.moveTo(path[0].x * sx, path[0].y * sy);\n for (let k = 1; k < path.length; k++) {\n ctx.lineTo(path[k].x * sx, path[k].y * sy);\n }\n ctx.stroke();\n\n // Inner high-intensity photon filament\n ctx.strokeStyle = band.rgbaCore;\n ctx.lineWidth = 1.05;\n ctx.stroke();\n }\n ctx.restore();\n }\n\n // 3. Draw Optical Bench Hardware & Geometries\n drawOpticalElements(ctx, sx, sy, cw, ch);\n\n // 4. Draw Chladni Quartz Sand Grains (Scene 05)\n if (state.scene === 'chladni') {\n ctx.fillStyle = '#FDE68A';\n for (let i = 0; i < NUM_PARTICLES; i++) {\n const px = sandX[i] * sx;\n const py = sandY[i] * sy;\n ctx.fillRect(px - 1.1, py - 1.1, 2.2, 2.2);\n }\n }\n\n // 5. Draw Interferometer Probes P1 & P2\n drawProbes(ctx, sx, sy);\n\n // 6. Draw Multi-Scale X-Ray Reality Loupe\n if (state.loupe.enabled) {\n drawXRayLoupe(ctx, sx, sy, cw, ch);\n }\n\n ctx.restore();\n }\n\n function drawOpticalElements(ctx, sx, sy, cw, ch) {\n // A. Equilateral Flint-Glass Prism\n if (state.prism.active) {\n const pv = getPrismVertices(state.prism);\n ctx.save();\n ctx.beginPath();\n ctx.moveTo(pv[0].x * sx, pv[0].y * sy);\n ctx.lineTo(pv[1].x * sx, pv[1].y * sy);\n ctx.lineTo(pv[2].x * sx, pv[2].y * sy);\n ctx.closePath();\n\n const grad = ctx.createLinearGradient(\n (state.prism.x - 30) * sx, (state.prism.y - 30) * sy,\n (state.prism.x + 30) * sx, (state.prism.y + 30) * sy\n );\n grad.addColorStop(0, 'rgba(125, 211, 252, 0.18)');\n grad.addColorStop(0.5, 'rgba(56, 189, 248, 0.07)');\n grad.addColorStop(1, 'rgba(167, 139, 250, 0.20)');\n ctx.fillStyle = grad;\n ctx.fill();\n\n ctx.strokeStyle = 'rgba(186, 230, 253, 0.82)';\n ctx.lineWidth = 1.6;\n ctx.stroke();\n\n // Rotation dial ring & label\n const cx = state.prism.x * sx;\n const cy = state.prism.y * sy;\n ctx.strokeStyle = 'rgba(56, 189, 248, 0.24)';\n ctx.setLineDash([3, 4]);\n ctx.beginPath();\n ctx.arc(cx, cy, state.prism.radius * sx * 1.08, 0, Math.PI * 2);\n ctx.stroke();\n ctx.setLineDash([]);\n\n // Rotation handle knob at vertex 0\n ctx.fillStyle = '#38BDF8';\n ctx.beginPath();\n ctx.arc(pv[0].x * sx, pv[0].y * sy, 4.5, 0, Math.PI * 2);\n ctx.fill();\n\n ctx.fillStyle = 'rgba(241, 245, 249, 0.85)';\n ctx.font = '600 10px \"JetBrains Mono\", monospace';\n ctx.fillText(`PRISM n=${state.n0.toFixed(2)}`, cx - 34, cy + state.prism.radius * sy + 16);\n ctx.restore();\n }\n\n // B. Biconvex Crystal Lens\n if (state.lens.active) {\n const segs = getLensSegments(state.lens);\n ctx.save();\n ctx.beginPath();\n ctx.moveTo(segs[0].ax * sx, segs[0].ay * sy);\n for (let i = 0; i < segs.length; i++) {\n ctx.lineTo(segs[i].bx * sx, segs[i].by * sy);\n }\n ctx.closePath();\n\n const lx = state.lens.x * sx;\n const ly = state.lens.y * sy;\n const lGrad = ctx.createLinearGradient(lx - 20, ly - 50, lx + 20, ly + 50);\n lGrad.addColorStop(0, 'rgba(56, 189, 248, 0.22)');\n lGrad.addColorStop(0.5, 'rgba(255, 255, 255, 0.08)');\n lGrad.addColorStop(1, 'rgba(56, 189, 248, 0.22)');\n ctx.fillStyle = lGrad;\n ctx.fill();\n\n ctx.strokeStyle = 'rgba(125, 211, 252, 0.88)';\n ctx.lineWidth = 1.6;\n ctx.stroke();\n\n // Optical axis & handle\n const topX = lx - Math.sin(state.lens.angle) * state.lens.ry * sy;\n const topY = ly - Math.cos(state.lens.angle) * state.lens.ry * sy;\n ctx.fillStyle = '#38BDF8';\n ctx.beginPath();\n ctx.arc(topX, topY, 4.5, 0, Math.PI * 2);\n ctx.fill();\n\n ctx.fillStyle = 'rgba(241, 245, 249, 0.85)';\n ctx.font = '600 10px \"JetBrains Mono\", monospace';\n ctx.fillText(`LENS f=${Math.round(48 / (state.n0 - 1))}mm`, lx - 34, ly + state.lens.ry * sy + 16);\n ctx.restore();\n }\n\n // C. Elliptical Whispering Gallery Overlay\n if (state.ellipse.active) {\n const cx = state.ellipse.cx * sx;\n const cy = state.ellipse.cy * sy;\n const rx = state.ellipse.a * sx;\n const ry = (state.ellipse.b || state.ellipse.a * 0.78) * sy;\n const cDist = state.ellipse.a * state.ellipse.e;\n const f1x = (state.ellipse.cx - cDist) * sx;\n const f2x = (state.ellipse.cx + cDist) * sx;\n\n ctx.save();\n ctx.strokeStyle = '#38BDF8';\n ctx.lineWidth = 2.2;\n ctx.beginPath();\n ctx.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2);\n ctx.stroke();\n\n // Sample Stationary Path Verification Triangle: Source -> Wall -> F2\n const sampleAng = state.simTime * 0.45;\n const wx = cx + Math.cos(sampleAng) * rx;\n const wy = cy + Math.sin(sampleAng) * ry;\n ctx.strokeStyle = 'rgba(245, 158, 11, 0.55)';\n ctx.setLineDash([4, 4]);\n ctx.lineWidth = 1.3;\n ctx.beginPath();\n ctx.moveTo(f1x, cy);\n ctx.lineTo(wx, wy);\n ctx.lineTo(f2x, cy);\n ctx.stroke();\n ctx.setLineDash([]);\n\n // Focus markers F1 and F2\n ctx.strokeStyle = '#F59E0B';\n ctx.lineWidth = 1.5;\n ctx.beginPath();\n ctx.arc(f1x, cy, 8, 0, Math.PI * 2);\n ctx.moveTo(f2x - 10, cy); ctx.lineTo(f2x + 10, cy);\n ctx.moveTo(f2x, cy - 10); ctx.lineTo(f2x, cy + 10);\n ctx.stroke();\n\n ctx.fillStyle = '#FCD34D';\n ctx.font = '700 10.5px \"JetBrains Mono\", monospace';\n ctx.fillText('FOCUS F₁ (Source)', f1x - 42, cy - 14);\n ctx.fillText('FOCUS F₂ (Conjugate)', f2x - 48, cy - 14);\n ctx.fillText(`|F₁P| + |PF₂| = ${(2 * state.ellipse.a).toFixed(1)} (Stationary)`, (wx - 58), wy + (wy < cy ? -10 : 16));\n ctx.restore();\n }\n\n // D. Young's Double-Slit Detector Screen & Live Intensity Curve Overlay\n if (state.slit.active) {\n const scrX = state.slit.screenX * sx;\n ctx.save();\n ctx.strokeStyle = 'rgba(245, 158, 11, 0.45)';\n ctx.setLineDash([4, 4]);\n ctx.beginPath();\n ctx.moveTo(scrX, 16);\n ctx.lineTo(scrX, ch - 16);\n ctx.stroke();\n ctx.setLineDash([]);\n\n // Draw live emergent intensity profile I(y) right along the detector screen!\n ctx.strokeStyle = '#38BDF8';\n ctx.lineWidth = 2.0;\n ctx.beginPath();\n const gx = Math.min(NX - 3, Math.round(state.slit.screenX));\n for (let y = 12; y < NY - 12; y++) {\n const rms = Math.sqrt(uRMS[y * NX + gx]);\n const plotX = scrX + Math.min(68, rms * 52);\n const plotY = y * sy;\n if (y === 12) ctx.moveTo(plotX, plotY);\n else ctx.lineTo(plotX, plotY);\n }\n ctx.stroke();\n\n ctx.fillStyle = '#38BDF8';\n ctx.font = '700 10px \"JetBrains Mono\", monospace';\n ctx.fillText('DETECTOR I(y)', scrX + 6, 26);\n ctx.restore();\n }\n\n // E. Schwarzschild Black Hole / Einstein Ring Horizons\n if (state.bh.active) {\n const bx = state.bh.x * sx;\n const by = state.bh.y * sy;\n const rsPx = state.bh.rs * sx;\n\n ctx.save();\n // Event Horizon (r = rs)\n const bhGrad = ctx.createRadialGradient(bx, by, rsPx * 0.2, bx, by, rsPx * 2.6);\n bhGrad.addColorStop(0, '#000000');\n bhGrad.addColorStop(0.38, '#020409');\n bhGrad.addColorStop(0.65, 'rgba(245, 158, 11, 0.22)');\n bhGrad.addColorStop(1, 'rgba(56, 189, 248, 0.0)');\n ctx.fillStyle = bhGrad;\n ctx.beginPath();\n ctx.arc(bx, by, rsPx * 2.6, 0, Math.PI * 2);\n ctx.fill();\n\n // Photon Sphere (r = 1.5 rs)\n ctx.strokeStyle = 'rgba(245, 158, 11, 0.75)';\n ctx.setLineDash([3, 3]);\n ctx.lineWidth = 1.4;\n ctx.beginPath();\n ctx.arc(bx, by, rsPx * 1.5, 0, Math.PI * 2);\n ctx.stroke();\n ctx.setLineDash([]);\n\n ctx.fillStyle = '#FCD34D';\n ctx.font = '700 10px \"JetBrains Mono\", monospace';\n ctx.fillText(`PHOTON SPHERE 1.5rₛ`, bx - 52, by - rsPx * 1.5 - 8);\n ctx.restore();\n }\n\n // F. Laser Emitter & Wave Source Markers\n if (state.laser.active && state.scene !== 'ellipse') {\n const lx = state.laser.x * sx;\n const ly = state.laser.y * sy;\n ctx.save();\n ctx.translate(lx, ly);\n ctx.rotate(state.laser.angle);\n ctx.fillStyle = '#1E293B';\n ctx.strokeStyle = '#38BDF8';\n ctx.lineWidth = 1.5;\n ctx.beginPath();\n ctx.roundRect(-14, -9, 24, 18, 4);\n ctx.fill();\n ctx.stroke();\n ctx.fillStyle = '#F8FAFC';\n ctx.beginPath();\n ctx.arc(8, 0, 3, 0, Math.PI * 2);\n ctx.fill();\n ctx.restore();\n }\n\n if (state.waveSource.active || state.scene === 'ellipse') {\n const wx = state.waveSource.x * sx;\n const wy = state.waveSource.y * sy;\n ctx.save();\n ctx.strokeStyle = '#38BDF8';\n ctx.fillStyle = 'rgba(56, 189, 248, 0.25)';\n ctx.lineWidth = 1.6;\n ctx.beginPath();\n ctx.arc(wx, wy, 6.5, 0, Math.PI * 2);\n ctx.fill();\n ctx.stroke();\n ctx.restore();\n }\n }\n\n function drawProbes(ctx, sx, sy) {\n for (let i = 0; i < 2; i++) {\n const p = state.probes[i];\n const px = p.x * NX * sx;\n const py = p.y * NY * sy;\n\n ctx.save();\n // Outer pulsing ring proportional to instantaneous wave amplitude\n const pulseR = 11 + Math.min(8, Math.abs(p.amp) * 5);\n ctx.strokeStyle = p.color;\n ctx.globalAlpha = 0.45;\n ctx.lineWidth = 1.5;\n ctx.beginPath();\n ctx.arc(px, py, pulseR, 0, Math.PI * 2);\n ctx.stroke();\n\n ctx.globalAlpha = 1.0;\n ctx.fillStyle = '#090D16';\n ctx.beginPath();\n ctx.arc(px, py, 8, 0, Math.PI * 2);\n ctx.fill();\n ctx.stroke();\n\n ctx.fillStyle = p.color;\n ctx.font = '700 9.5px \"JetBrains Mono\", monospace';\n ctx.textAlign = 'center';\n ctx.textBaseline = 'middle';\n ctx.fillText(p.id, px, py);\n ctx.restore();\n }\n }\n\n // ============================================================================\n // 9. THE MULTI-SCALE X-RAY REALITY LOUPE (\"Hold Up When They Look Closer\")\n // ============================================================================\n function drawXRayLoupe(ctx, sx, sy, cw, ch) {\n const lx = state.loupe.x * cw;\n const ly = state.loupe.y * ch;\n const R = state.loupe.radiusPx;\n const gxCenter = Math.round(state.loupe.x * NX);\n const gyCenter = Math.round(state.loupe.y * NY);\n\n ctx.save();\n\n // 1. Clip circular optical doublet interior\n ctx.beginPath();\n ctx.arc(lx, ly, R, 0, Math.PI * 2);\n ctx.clip();\n\n // Dark blueprint X-Ray background\n ctx.fillStyle = 'rgba(4, 8, 17, 0.92)';\n ctx.fillRect(lx - R, ly - R, R * 2, R * 2);\n\n // 2. Render Magnified Sub-Grid Finite-Difference Stencil & Poynting Flux Vectors\n const spanX = 14;\n const spanY = 14;\n const zoom = 2.15;\n\n // Fine blueprint lattice lines\n ctx.strokeStyle = 'rgba(56, 189, 248, 0.12)';\n ctx.lineWidth = 0.7;\n for (let dy = -spanY; dy <= spanY; dy++) {\n const gy = gyCenter + dy;\n if (gy < 1 || gy >= NY - 1) continue;\n const py = ly + (gy - state.loupe.y * NY) * sy * zoom;\n ctx.beginPath();\n ctx.moveTo(lx - R, py);\n ctx.lineTo(lx + R, py);\n ctx.stroke();\n }\n for (let dx = -spanX; dx <= spanX; dx++) {\n const gx = gxCenter + dx;\n if (gx < 1 || gx >= NX - 1) continue;\n const px = lx + (gx - state.loupe.x * NX) * sx * zoom;\n ctx.beginPath();\n ctx.moveTo(px, ly - R);\n ctx.lineTo(px, ly + R);\n ctx.stroke();\n }\n\n // Discrete PDE nodes + Poynting Energy Flux Vectors S = -c² (∂ₜu) ∇u\n for (let dy = -spanY; dy <= spanY; dy++) {\n const gy = gyCenter + dy;\n if (gy < 2 || gy >= NY - 2) continue;\n for (let dx = -spanX; dx <= spanX; dx++) {\n const gx = gxCenter + dx;\n if (gx < 2 || gx >= NX - 2) continue;\n\n const px = lx + (gx - state.loupe.x * NX) * sx * zoom;\n const py = ly + (gy - state.loupe.y * NY) * sy * zoom;\n if ((px - lx) * (px - lx) + (py - ly) * (py - ly) > R * R) continue;\n\n const idx = gy * NX + gx;\n const u = uCurr[idx];\n const vel = uVel[idx];\n const nLoc = iorGrid[idx];\n\n if (wallGrid[idx]) {\n ctx.fillStyle = 'rgba(244, 63, 94, 0.65)';\n ctx.fillRect(px - 2.5, py - 2.5, 5, 5);\n continue;\n }\n\n // Dielectric glass tint inside loupe\n if (nLoc > 1.03) {\n ctx.fillStyle = 'rgba(56, 189, 248, 0.14)';\n ctx.fillRect(px - sx * zoom * 0.5, py - sy * zoom * 0.5, sx * zoom, sy * zoom);\n }\n\n // Gradient ∇u & Poynting vector S = -vel * ∇u\n const gradX = (uCurr[idx + 1] - uCurr[idx - 1]) * 0.5;\n const gradY = (uCurr[idx + NX] - uCurr[idx - NX]) * 0.5;\n const sxVec = -vel * gradX * 26;\n const syVec = -vel * gradY * 26;\n const vecMag = Math.hypot(sxVec, syVec);\n\n if (vecMag > 0.4) {\n const clampMag = Math.min(13, vecMag * 4.5);\n const vx = (sxVec / vecMag) * clampMag;\n const vy = (syVec / vecMag) * clampMag;\n ctx.strokeStyle = u >= 0 ? 'rgba(56, 189, 248, 0.85)' : 'rgba(245, 158, 11, 0.85)';\n ctx.lineWidth = 1.15;\n ctx.beginPath();\n ctx.moveTo(px, py);\n ctx.lineTo(px + vx, py + vy);\n ctx.stroke();\n }\n\n // Lattice Node Dot\n const nodeR = 1.4 + Math.min(2.6, Math.abs(u) * 1.4);\n ctx.fillStyle = u >= 0 ? '#38BDF8' : '#F59E0B';\n ctx.beginPath();\n ctx.arc(px, py, nodeR, 0, Math.PI * 2);\n ctx.fill();\n }\n }\n\n // 3. If Snell Refraction occurs near Loupe, draw Exact Normal & Angle Arcs!\n const sn = state.loupe.snellInfo;\n if (sn) {\n const snPx = lx + (sn.x - state.loupe.x * NX) * sx * zoom;\n const snPy = ly + (sn.y - state.loupe.y * NY) * sy * zoom;\n if (Math.hypot(snPx - lx, snPy - ly) < R * 0.85) {\n ctx.strokeStyle = '#10B981';\n ctx.setLineDash([3, 3]);\n ctx.lineWidth = 1.4;\n ctx.beginPath();\n ctx.moveTo(snPx - sn.nx * 38, snPy - sn.ny * 38);\n ctx.lineTo(snPx + sn.nx * 38, snPy + sn.ny * 38);\n ctx.stroke();\n ctx.setLineDash([]);\n\n ctx.fillStyle = '#6EE7B7';\n ctx.font = '700 9.5px \"JetBrains Mono\", monospace';\n ctx.fillText(\n sn.tir ? `TIR θᵢ=${sn.thetaI.toFixed(1)}°` : `θᵢ=${sn.thetaI.toFixed(1)}° → θₜ=${sn.thetaT.toFixed(1)}°`,\n snPx + 8,\n snPy - 8\n );\n }\n }\n\n // 4. Internal HUD Telemetry inside X-Ray Loupe\n const cIdx = Math.max(0, Math.min(NCELLS - 1, gyCenter * NX + gxCenter));\n const localU = uCurr[cIdx];\n const localN = iorGrid[cIdx];\n ctx.fillStyle = 'rgba(8, 13, 24, 0.86)';\n ctx.fillRect(lx - R, ly + R - 28, R * 2, 28);\n ctx.fillStyle = '#FCD34D';\n ctx.font = '700 9.5px \"JetBrains Mono\", monospace';\n ctx.textAlign = 'center';\n ctx.fillText(\n `ψ=${localU >= 0 ? '+' : ''}${localU.toFixed(3)} · n=${localN.toFixed(2)} · v=${(1 / localN).toFixed(2)}c₀`,\n lx,\n ly + R - 11\n );\n\n ctx.restore();\n\n // 5. Outer Precision Achromatic Doublet Bevel Ring & Degree Protractor\n ctx.save();\n ctx.strokeStyle = '#F59E0B';\n ctx.lineWidth = 2.2;\n ctx.shadowColor = 'rgba(245, 158, 11, 0.35)';\n ctx.shadowBlur = 14;\n ctx.beginPath();\n ctx.arc(lx, ly, R, 0, Math.PI * 2);\n ctx.stroke();\n ctx.shadowBlur = 0;\n\n // Protractor degree ticks around loupe rim\n ctx.strokeStyle = 'rgba(245, 158, 11, 0.55)';\n ctx.lineWidth = 1;\n for (let deg = 0; deg < 360; deg += 15) {\n const rad = (deg * Math.PI) / 180;\n const rIn = (deg % 45 === 0) ? R - 7 : R - 4;\n ctx.beginPath();\n ctx.moveTo(lx + Math.cos(rad) * rIn, ly + Math.sin(rad) * rIn);\n ctx.lineTo(lx + Math.cos(rad) * R, ly + Math.sin(rad) * R);\n ctx.stroke();\n }\n\n // Top Loupe Header Pill\n ctx.fillStyle = '#0A0E17';\n ctx.strokeStyle = '#F59E0B';\n ctx.lineWidth = 1.2;\n ctx.beginPath();\n ctx.roundRect(lx - 66, ly - R - 11, 132, 18, 9);\n ctx.fill();\n ctx.stroke();\n\n ctx.fillStyle = '#FCD34D';\n ctx.font = '700 9px \"JetBrains Mono\", monospace';\n ctx.textAlign = 'center';\n ctx.textBaseline = 'middle';\n ctx.fillText('2.2× EIKONAL X-RAY', lx, ly - R - 2);\n ctx.restore();\n }\n\n // ============================================================================\n // 10. RIGHT RACK TELEMETRY RENDERING (OSCILLOSCOPE, PHASE SPACE & FFT/FRINGES)\n // ============================================================================\n const scopeCanvas = document.getElementById('scopeCanvas');\n const scopeCtx = scopeCanvas.getContext('2d');\n const phaseCanvas = document.getElementById('phaseCanvas');\n const phaseCtx = phaseCanvas.getContext('2d');\n const spectrumCanvas = document.getElementById('spectrumCanvas');\n const specCtx = spectrumCanvas.getContext('2d');\n\n function renderTelemetryCanvases() {\n const p1 = state.probes[0];\n const p2 = state.probes[1];\n const ptr = state.probePtr;\n\n // 1. Dual-Trace Oscilloscope\n const sw = scopeCanvas.width;\n const sh = scopeCanvas.height;\n scopeCtx.fillStyle = '#050810';\n scopeCtx.fillRect(0, 0, sw, sh);\n\n // Graticule\n scopeCtx.strokeStyle = 'rgba(148, 163, 184, 0.08)';\n scopeCtx.lineWidth = 1;\n scopeCtx.beginPath();\n scopeCtx.moveTo(0, sh * 0.5); scopeCtx.lineTo(sw, sh * 0.5);\n scopeCtx.moveTo(sw * 0.5, 0); scopeCtx.lineTo(sw * 0.5, sh);\n scopeCtx.stroke();\n\n for (let pIdx = 1; pIdx >= 0; pIdx--) {\n const pr = state.probes[pIdx];\n scopeCtx.strokeStyle = pr.color;\n scopeCtx.lineWidth = 1.5;\n scopeCtx.beginPath();\n for (let i = 0; i < 256; i++) {\n const sampleIdx = (ptr + i) & 255;\n const val = pr.history[sampleIdx];\n const x = (i / 255) * sw;\n const y = sh * 0.5 - val * (sh * 0.28);\n if (i === 0) scopeCtx.moveTo(x, y);\n else scopeCtx.lineTo(x, y);\n }\n scopeCtx.stroke();\n }\n\n // 2. Phase Space Portrait (ψ, ∂ₜψ)\n const pw = phaseCanvas.width;\n const ph = phaseCanvas.height;\n phaseCtx.fillStyle = '#050810';\n phaseCtx.fillRect(0, 0, pw, ph);\n phaseCtx.strokeStyle = 'rgba(148, 163, 184, 0.08)';\n phaseCtx.beginPath();\n phaseCtx.moveTo(0, ph * 0.5); phaseCtx.lineTo(pw, ph * 0.5);\n phaseCtx.moveTo(pw * 0.5, 0); phaseCtx.lineTo(pw * 0.5, ph);\n phaseCtx.stroke();\n\n phaseCtx.strokeStyle = '#38BDF8';\n phaseCtx.lineWidth = 1.3;\n phaseCtx.beginPath();\n for (let i = 0; i < 128; i++) {\n const sampleIdx = (ptr + 128 + i) & 255;\n const u = p1.history[sampleIdx];\n const v = p1.histVel[sampleIdx];\n const x = pw * 0.5 + u * 26;\n const y = ph * 0.5 - v * 65;\n if (i === 0) phaseCtx.moveTo(x, y);\n else phaseCtx.lineTo(x, y);\n }\n phaseCtx.stroke();\n\n // 3. Detector Screen Fringe Integral (Double Slit) OR Live Frequency Spectrum\n const kw = spectrumCanvas.width;\n const kh = spectrumCanvas.height;\n specCtx.fillStyle = '#050810';\n specCtx.fillRect(0, 0, kw, kh);\n\n if (state.scene === 'slit') {\n document.getElementById('spectrumTitle').innerHTML = '<span class=\"indicator\" style=\"background:var(--accent-amber)\"></span>FRAUNHOFER FRINGE INTEGRAL I(y)';\n document.getElementById('spectrumBadge').textContent = 'PDE vs THEORY';\n const gx = Math.min(NX - 3, Math.round(state.slit.screenX));\n const L = Math.max(20, state.slit.screenX - state.slit.x);\n const lambdaGrid = 28.0 / Math.max(1.5, state.waveFreq); // Effective PDE wavelength\n\n // Analytical Fraunhofer curve: cos²(π a sinθ / λ) sinc²(π d sinθ / λ)\n specCtx.strokeStyle = '#F59E0B';\n specCtx.setLineDash([3, 3]);\n specCtx.lineWidth = 1.4;\n specCtx.beginPath();\n for (let x = 0; x < kw; x++) {\n const gy = (x / kw) * NY;\n const dy = gy - NY * 0.5;\n const sinTheta = dy / Math.hypot(L, dy);\n const alpha = (Math.PI * state.slit.width * sinTheta) / lambdaGrid;\n const beta = (Math.PI * state.slit.sep * sinTheta) / lambdaGrid;\n const sinc = Math.abs(alpha) < 1e-4 ? 1.0 : Math.sin(alpha) / alpha;\n const theoryI = Math.cos(beta) * Math.cos(beta) * sinc * sinc;\n const py = kh - 8 - theoryI * (kh - 20);\n if (x === 0) specCtx.moveTo(x, py);\n else specCtx.lineTo(x, py);\n }\n specCtx.stroke();\n specCtx.setLineDash([]);\n\n // Measured PDE RMS Intensity along Detector Screen\n specCtx.strokeStyle = '#38BDF8';\n specCtx.lineWidth = 1.8;\n specCtx.beginPath();\n let maxRms = 0.01;\n for (let y = 10; y < NY - 10; y++) {\n const r = Math.sqrt(uRMS[y * NX + gx]);\n if (r > maxRms) maxRms = r;\n }\n for (let x = 0; x < kw; x++) {\n const gy = Math.max(1, Math.min(NY - 2, Math.round((x / kw) * NY)));\n const r = Math.sqrt(uRMS[gy * NX + gx]) / maxRms;\n const py = kh - 8 - r * (kh - 20);\n if (x === 0) specCtx.moveTo(x, py);\n else specCtx.lineTo(x, py);\n }\n specCtx.stroke();\n } else {\n document.getElementById('spectrumTitle').innerHTML = '<span class=\"indicator\" style=\"background:var(--accent-amber)\"></span>DFT HARMONIC SPECTRUM (P1)';\n document.getElementById('spectrumBadge').textContent = '48-BIN DISCRETE FT';\n const numBins = 44;\n const barW = (kw - 16) / numBins;\n for (let k = 1; k <= numBins; k++) {\n let re = 0, im = 0;\n const freqK = k * 0.45;\n for (let n = 0; n < 128; n++) {\n const sample = p1.history[(ptr + 128 + n) & 255];\n const ang = (2 * Math.PI * freqK * n) / 128;\n re += sample * Math.cos(ang);\n im -= sample * Math.sin(ang);\n }\n const mag = Math.min(1.0, Math.hypot(re, im) / 26);\n const bh = Math.max(2, mag * (kh - 18));\n const bx = 8 + (k - 1) * barW;\n specCtx.fillStyle = mag > 0.45 ? '#F59E0B' : '#38BDF8';\n specCtx.fillRect(bx, kh - 6 - bh, barW - 2, bh);\n }\n }\n\n // 4. Numerical Readouts (every 3rd frame to keep DOM crisp)\n if (state.frameCount % 3 === 0) {\n document.getElementById('valP1Amp').textContent = (p1.amp >= 0 ? '+' : '') + p1.amp.toFixed(3);\n document.getElementById('valP1Rms').textContent = p1.rms.toFixed(3);\n document.getElementById('valP1Ior').textContent = p1.ior.toFixed(3);\n document.getElementById('proofEnergy').textContent = `H = ${state.totalEnergy.toFixed(2)} J`;\n document.getElementById('proofRays').textContent = `${state.activeRayCount} Rays`;\n document.getElementById('fpsReadout').textContent = `${state.fps.toFixed(1)} FPS`;\n document.getElementById('loupeCoordReadout').textContent =\n `LOUPE (${Math.round(state.loupe.x * NX)},${Math.round(state.loupe.y * NY)})`;\n\n // Compute instantaneous cross-correlation phase difference Δφ between P1 and P2\n let dot = 0, n1 = 0, n2 = 0;\n for (let i = 0; i < 64; i++) {\n const idx = (ptr + 192 + i) & 255;\n const a = p1.history[idx], b = p2.history[idx];\n dot += a * b; n1 += a * a; n2 += b * b;\n }\n const cosPhi = (n1 > 1e-5 && n2 > 1e-5) ? Math.max(-1, Math.min(1, dot / Math.sqrt(n1 * n2))) : 1;\n const dPhiPi = Math.acos(cosPhi) / Math.PI;\n document.getElementById('phaseDiffReadout').textContent = `Δφ = ${dPhiPi.toFixed(2)}π rad`;\n }\n }\n\n // ============================================================================\n // 11. REAL-TIME WEB AUDIO PHYSICAL SONIFICATION (Coupled to Probe P1)\n // ============================================================================\n const audioEngine = {\n ctx: null,\n enabled: false,\n osc1: null,\n osc2: null,\n oscSub: null,\n gainNode: null,\n filterNode: null,\n\n toggle() {\n if (!this.ctx) {\n const AudioCtx = window.AudioContext || window.webkitAudioContext;\n this.ctx = new AudioCtx();\n this.osc1 = this.ctx.createOscillator();\n this.osc2 = this.ctx.createOscillator();\n this.oscSub = this.ctx.createOscillator();\n this.gainNode = this.ctx.createGain();\n this.filterNode = this.ctx.createBiquadFilter();\n\n this.osc1.type = 'sine';\n this.osc2.type = 'triangle';\n this.oscSub.type = 'sine';\n\n this.filterNode.type = 'lowpass';\n this.filterNode.frequency.value = 1100;\n this.filterNode.Q.value = 3.5;\n\n this.gainNode.gain.value = 0.0;\n\n this.osc1.connect(this.filterNode);\n this.osc2.connect(this.filterNode);\n this.oscSub.connect(this.filterNode);\n this.filterNode.connect(this.gainNode);\n this.gainNode.connect(this.ctx.destination);\n\n this.osc1.start();\n this.osc2.start();\n this.oscSub.start();\n }\n\n if (this.ctx.state === 'suspended') {\n this.ctx.resume();\n }\n\n this.enabled = !this.enabled;\n const btn = document.getElementById('btnAudio');\n btn.classList.toggle('active-emerald', this.enabled);\n document.getElementById('audioLabel').textContent = this.enabled ? 'AUDIO: LIVE' : 'AUDIO PROBE';\n\n if (!this.enabled && this.gainNode) {\n this.gainNode.gain.setTargetAtTime(0.0, this.ctx.currentTime, 0.04);\n } else {\n this.triggerPing(440);\n }\n },\n\n updateFromField() {\n if (!this.enabled || !this.ctx) return;\n const p1 = state.probes[0];\n const p2 = state.probes[1];\n const now = this.ctx.currentTime;\n\n const baseFreq = 110 + state.waveFreq * 36;\n const fmMod = p1.amp * 28;\n this.osc1.frequency.setTargetAtTime(baseFreq + fmMod, now, 0.015);\n this.osc2.frequency.setTargetAtTime(baseFreq * 1.498 + p2.amp * 18, now, 0.015);\n this.oscSub.frequency.setTargetAtTime(baseFreq * 0.5, now, 0.02);\n\n // Gain is directly driven by local RMS wave energy at Probe P1!\n // In a dark destructive interference fringe, p1.rms -> 0, silencing the tone!\n const targetGain = Math.min(0.18, p1.rms * 0.14 + Math.abs(p1.amp) * 0.04);\n this.gainNode.gain.setTargetAtTime(targetGain, now, 0.025);\n this.filterNode.frequency.setTargetAtTime(380 + p1.rms * 1600, now, 0.03);\n },\n\n triggerPing(freq = 528) {\n if (!this.enabled || !this.ctx) return;\n const osc = this.ctx.createOscillator();\n const g = this.ctx.createGain();\n osc.type = 'sine';\n osc.frequency.value = freq;\n g.gain.setValueAtTime(0.11, this.ctx.currentTime);\n g.gain.exponentialRampToValueAtTime(0.0001, this.ctx.currentTime + 0.38);\n osc.connect(g);\n g.connect(this.ctx.destination);\n osc.start();\n osc.stop(this.ctx.currentTime + 0.4);\n }\n };\n\n // ============================================================================\n // 12. DIRECT MANIPULATION & INTERACTION CONTROLLER\n // ============================================================================\n let dragTarget = null;\n let isPointerDown = false;\n\n function canvasToGrid(clientX, clientY) {\n const rect = simCanvas.getBoundingClientRect();\n const nx = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));\n const ny = Math.max(0, Math.min(1, (clientY - rect.top) / rect.height));\n return { nx, ny, gx: nx * NX, gy: ny * NY, px: clientX - rect.left, py: clientY - rect.top, rect };\n }\n\n simCanvas.addEventListener('pointerdown', (e) => {\n isPointerDown = true;\n simCanvas.setPointerCapture(e.pointerId);\n const pos = canvasToGrid(e.clientX, e.clientY);\n const sx = pos.rect.width / NX;\n const sy = pos.rect.height / NY;\n\n // 1. Check Probes P1 & P2\n for (let i = 0; i < 2; i++) {\n const p = state.probes[i];\n if (Math.hypot(pos.gx - p.x * NX, pos.gy - p.y * NY) < 8) {\n dragTarget = { type: 'probe', index: i };\n return;\n }\n }\n\n // 2. Check X-Ray Loupe Rim or Header\n if (state.loupe.enabled) {\n const lx = state.loupe.x * pos.rect.width;\n const ly = state.loupe.y * pos.rect.height;\n const distPx = Math.hypot(pos.px - lx, pos.py - ly);\n if (Math.abs(distPx - state.loupe.radiusPx) < 18 || (Math.abs(pos.px - lx) < 68 && Math.abs(pos.py - (ly - state.loupe.radiusPx)) < 16)) {\n dragTarget = { type: 'loupe' };\n return;\n }\n }\n\n // 3. Check Prism Vertex Handle (Rotate) or Body (Translate)\n if (state.prism.active) {\n const pv = getPrismVertices(state.prism);\n if (Math.hypot(pos.gx - pv[0].x, pos.gy - pv[0].y) < 9) {\n dragTarget = { type: 'prismRotate' };\n return;\n }\n if (Math.hypot(pos.gx - state.prism.x, pos.gy - state.prism.y) < state.prism.radius) {\n dragTarget = { type: 'prismMove', dx: pos.gx - state.prism.x, dy: pos.gy - state.prism.y };\n return;\n }\n }\n\n // 4. Check Lens Top Handle (Rotate) or Body (Translate)\n if (state.lens.active) {\n const topGX = state.lens.x - Math.sin(state.lens.angle) * state.lens.ry;\n const topGY = state.lens.y - Math.cos(state.lens.angle) * state.lens.ry;\n if (Math.hypot(pos.gx - topGX, pos.gy - topGY) < 9) {\n dragTarget = { type: 'lensRotate' };\n return;\n }\n if (pointInLens(pos.gx, pos.gy, state.lens) || Math.hypot(pos.gx - state.lens.x, pos.gy - state.lens.y) < 18) {\n dragTarget = { type: 'lensMove', dx: pos.gx - state.lens.x, dy: pos.gy - state.lens.y };\n return;\n }\n }\n\n // 5. Check Black Hole Singularity\n if (state.bh.active && Math.hypot(pos.gx - state.bh.x, pos.gy - state.bh.y) < 22) {\n dragTarget = { type: 'bhMove' };\n return;\n }\n\n // 6. Check Wave Source / Focus F1\n if ((state.waveSource.active || state.scene === 'ellipse') && Math.hypot(pos.gx - state.waveSource.x, pos.gy - state.waveSource.y) < 11) {\n dragTarget = { type: 'waveSource' };\n return;\n }\n\n // 7. Check Laser Emitter\n if (state.laser.active && state.scene !== 'ellipse' && Math.hypot(pos.gx - state.laser.x, pos.gy - state.laser.y) < 13) {\n dragTarget = { type: 'laserMove' };\n return;\n }\n\n // 8. Check Double-Slit Barrier\n if (state.slit.active && Math.abs(pos.gx - state.slit.x) < 9) {\n dragTarget = { type: 'slitAdjust' };\n return;\n }\n\n // 9. Otherwise: Apply Sandbox Brush or Drop Coherent Wave Impulse\n dragTarget = { type: 'fieldBrush' };\n applyFieldBrush(pos.gx, pos.gy);\n });\n\n simCanvas.addEventListener('pointermove', (e) => {\n const pos = canvasToGrid(e.clientX, e.clientY);\n if (!isPointerDown || !dragTarget) {\n if (e.shiftKey && state.loupe.enabled) {\n state.loupe.x = pos.nx;\n state.loupe.y = pos.ny;\n }\n return;\n }\n\n const t = dragTarget.type;\n if (t === 'probe') {\n state.probes[dragTarget.index].x = Math.max(0.04, Math.min(0.96, pos.nx));\n state.probes[dragTarget.index].y = Math.max(0.05, Math.min(0.95, pos.ny));\n } else if (t === 'loupe') {\n state.loupe.x = Math.max(0.08, Math.min(0.92, pos.nx));\n state.loupe.y = Math.max(0.10, Math.min(0.90, pos.ny));\n } else if (t === 'prismMove') {\n state.prism.x = Math.max(36, Math.min(NX - 36, pos.gx - dragTarget.dx));\n state.prism.y = Math.max(36, Math.min(NY - 36, pos.gy - dragTarget.dy));\n rebuildMediumGrid();\n } else if (t === 'prismRotate') {\n state.prism.angle = Math.atan2(pos.gy - state.prism.y, pos.gx - state.prism.x) + Math.PI / 2;\n rebuildMediumGrid();\n } else if (t === 'lensMove') {\n state.lens.x = Math.max(30, Math.min(NX - 30, pos.gx - dragTarget.dx));\n state.lens.y = Math.max(36, Math.min(NY - 36, pos.gy - dragTarget.dy));\n rebuildMediumGrid();\n } else if (t === 'lensRotate') {\n state.lens.angle = Math.atan2(state.lens.x - pos.gx, state.lens.y - pos.gy);\n rebuildMediumGrid();\n } else if (t === 'bhMove') {\n state.bh.x = Math.max(35, Math.min(NX - 35, pos.gx));\n state.bh.y = Math.max(35, Math.min(NY - 35, pos.gy));\n rebuildMediumGrid();\n } else if (t === 'waveSource') {\n state.waveSource.x = Math.max(12, Math.min(NX - 12, pos.gx));\n state.waveSource.y = Math.max(12, Math.min(NY - 12, pos.gy));\n if (state.scene === 'ellipse') {\n triggerWaveImpulse(state.waveSource.x, state.waveSource.y, 5.5, 3.8);\n }\n } else if (t === 'laserMove') {\n state.laser.y = Math.max(20, Math.min(NY - 20, pos.gy));\n state.laser.angle = Math.max(-0.55, Math.min(0.55, (pos.gx - state.laser.x) * 0.012 - 0.15));\n } else if (t === 'slitAdjust') {\n state.slit.sep = Math.max(14, Math.min(68, Math.abs(pos.gy - NY * 0.5) * 2));\n document.getElementById('sliderSceneParam').value = state.slit.sep;\n document.getElementById('lblSceneParamVal').textContent = state.slit.sep.toFixed(0);\n rebuildMediumGrid();\n } else if (t === 'fieldBrush') {\n applyFieldBrush(pos.gx, pos.gy);\n }\n });\n\n window.addEventListener('pointerup', () => {\n isPointerDown = false;\n dragTarget = null;\n });\n\n function applyFieldBrush(gx, gy) {\n if (state.scene === 'sandbox' && state.sandboxBrush !== 'ripple') {\n const r = Math.round(6 + state.sceneParam * 10);\n const minX = Math.max(2, Math.floor(gx - r));\n const maxX = Math.min(NX - 3, Math.ceil(gx + r));\n const minY = Math.max(2, Math.floor(gy - r));\n const maxY = Math.min(NY - 3, Math.ceil(gy + r));\n for (let y = minY; y <= maxY; y++) {\n for (let x = minX; x <= maxX; x++) {\n if ((x - gx) * (x - gx) + (y - gy) * (y - gy) <= r * r) {\n const idx = y * NX + x;\n if (state.sandboxBrush === 'glass') {\n userGlassGrid[idx] = state.n0 - 1.0;\n userWallGrid[idx] = 0;\n } else if (state.sandboxBrush === 'wall') {\n userWallGrid[idx] = 1;\n } else if (state.sandboxBrush === 'erase') {\n userGlassGrid[idx] = 0;\n userWallGrid[idx] = 0;\n }\n }\n }\n }\n rebuildMediumGrid();\n } else {\n triggerWaveImpulse(gx, gy, 5.2, 3.2);\n if (audioEngine.enabled) audioEngine.triggerPing(480 + (1 - gy / NY) * 240);\n }\n }\n\n // ============================================================================\n // 13. UI CONTROLS, PRESETS & KEYBOARD SHORTCUTS\n // ============================================================================\n document.getElementById('presetStrip').addEventListener('click', (e) => {\n const btn = e.target.closest('.preset-btn');\n if (btn && btn.dataset.scene) {\n applyScene(btn.dataset.scene);\n }\n });\n\n document.getElementById('layerGroup').addEventListener('click', (e) => {\n const btn = e.target.closest('.layer-btn');\n if (btn && btn.dataset.layer) {\n state.layer = btn.dataset.layer;\n document.querySelectorAll('.layer-btn').forEach(b => b.classList.toggle('active', b === btn));\n }\n });\n\n document.getElementById('btnLoupe').addEventListener('click', () => {\n state.loupe.enabled = !state.loupe.enabled;\n document.getElementById('btnLoupe').classList.toggle('active-amber', state.loupe.enabled);\n });\n\n document.getElementById('btnAudio').addEventListener('click', () => {\n audioEngine.toggle();\n });\n\n document.getElementById('btnPulse').addEventListener('click', () => {\n triggerWaveImpulse(state.waveSource.x, state.waveSource.y, 6.5, 4.8);\n if (audioEngine.enabled) audioEngine.triggerPing(587.33);\n });\n\n document.getElementById('btnEmbed').addEventListener('click', () => {\n const code = `<iframe src=\"index.html?scene=${state.scene}&loupe=${state.loupe.enabled ? 1 : 0}\" width=\"100%\" height=\"640\" style=\"border:1px solid #1e293b;border-radius:10px;background:#05070B;\" allow=\"autoplay\" loading=\"lazy\"></iframe>`;\n document.getElementById('embedCodeBlock').textContent = code;\n document.getElementById('embedModal').classList.add('open');\n });\n\n document.getElementById('btnCloseModal').addEventListener('click', () => {\n document.getElementById('embedModal').classList.remove('open');\n });\n\n document.getElementById('sliderIor').addEventListener('input', (e) => {\n state.n0 = parseFloat(e.target.value);\n document.getElementById('lblIor').textContent = state.n0.toFixed(2);\n rebuildMediumGrid();\n });\n\n document.getElementById('sliderDisp').addEventListener('input', (e) => {\n state.dispersionB = parseFloat(e.target.value);\n document.getElementById('lblDisp').textContent = state.dispersionB.toFixed(3);\n });\n\n document.getElementById('sliderFreq').addEventListener('input', (e) => {\n state.waveFreq = parseFloat(e.target.value);\n document.getElementById('lblFreq').textContent = state.waveFreq.toFixed(1) + ' Hz';\n });\n\n document.getElementById('sliderSceneParam').addEventListener('input', (e) => {\n const val = parseFloat(e.target.value);\n state.sceneParam = val;\n document.getElementById('lblSceneParamVal').textContent = val.toFixed(2);\n if (state.scene === 'ellipse') {\n state.ellipse.e = val;\n const cDist = state.ellipse.a * state.ellipse.e;\n state.waveSource.x = state.ellipse.cx - cDist;\n state.probes[0].x = (state.ellipse.cx + cDist) / NX;\n rebuildMediumGrid();\n } else if (state.scene === 'slit') {\n state.slit.sep = val;\n rebuildMediumGrid();\n } else if (state.scene === 'einstein') {\n state.bh.rs = val;\n rebuildMediumGrid();\n }\n });\n\n document.getElementById('materialChips').addEventListener('click', (e) => {\n const chip = e.target.closest('.mat-chip');\n if (!chip) return;\n document.querySelectorAll('#materialChips .mat-chip').forEach(c => c.classList.toggle('active', c === chip));\n state.n0 = parseFloat(chip.dataset.n);\n state.dispersionB = parseFloat(chip.dataset.b);\n document.getElementById('matBadge').textContent = chip.dataset.name;\n document.getElementById('sliderIor').value = state.n0;\n document.getElementById('lblIor').textContent = state.n0.toFixed(2);\n document.getElementById('sliderDisp').value = state.dispersionB;\n document.getElementById('lblDisp').textContent = state.dispersionB.toFixed(3);\n rebuildMediumGrid();\n });\n\n document.getElementById('sandboxTools').addEventListener('click', (e) => {\n const chip = e.target.closest('.mat-chip');\n if (!chip) return;\n document.querySelectorAll('#sandboxTools .mat-chip').forEach(c => c.classList.toggle('active', c === chip));\n state.sandboxBrush = chip.dataset.brush;\n if (state.sandboxBrush === 'erase') {\n userGlassGrid.fill(0);\n userWallGrid.fill(0);\n clearWaveField();\n rebuildMediumGrid();\n }\n });\n\n window.addEventListener('keydown', (e) => {\n if (e.key === 'l' || e.key === 'L') {\n document.getElementById('btnLoupe').click();\n } else if (e.key === 'm' || e.key === 'M') {\n document.getElementById('btnAudio').click();\n } else if (e.code === 'Space') {\n e.preventDefault();\n document.getElementById('btnPulse').click();\n } else if (e.key >= '1' && e.key <= '6') {\n const scenes = ['prism', 'ellipse', 'slit', 'einstein', 'chladni', 'sandbox'];\n applyScene(scenes[parseInt(e.key, 10) - 1]);\n }\n });\n\n // ============================================================================\n // 14. MAIN REAL-TIME SIMULATION LOOP\n // ============================================================================\n let lastFrameTime = performance.now();\n\n function animate(now) {\n const dtMs = now - lastFrameTime;\n lastFrameTime = now;\n if (dtMs > 0 && dtMs < 200) {\n const instFps = 1000 / dtMs;\n state.fps = state.fps * 0.92 + instFps * 0.08;\n }\n\n state.frameCount++;\n stepWavePDE(0.016);\n audioEngine.updateFromField();\n renderBench();\n renderTelemetryCanvases();\n\n requestAnimationFrame(animate);\n }\n\n // Initialize Scene & Start 60 FPS Loop\n applyScene(initialScene);\n requestAnimationFrame(animate);\n})();\n</script>\n</body>\n</html>\n","Overwrite":true,"Path":"~/run/index.html"}
input
{ "Content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\" />\n<title>∂S = 0 // EIKONAL — Coupled Wave-PDE, Spectral Ray-Caustics & Acoustic Field Laboratory</title>\n<style>\n :root {\n --bg-obsidian: #05070B;\n --bg-panel: #0A0E17;\n --bg-panel-elevated: #101624;\n --bg-control: #141C2E;\n --border-hairline: rgba(148, 163, 184, 0.12);\n --border-bright: rgba(56, 189, 248, 0.45);\n --text-primary: #F1F5F9;\n --text-secondary: #94A3B8;\n --text-muted: #64748B;\n --accent-cyan: #38BDF8;\n --accent-amber: #F59E0B;\n --accent-emerald: #10B981;\n --accent-rose: #FB7185;\n --accent-violet: #A78BFA;\n --font-sans: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n --font-mono: 'JetBrains Mono', 'Fira Code', 'SF Mono', Consolas, monospace;\n }\n\n * {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n user-select: none;\n -webkit-user-select: none;\n }\n\n html, body {\n width: 100%;\n height: 100%;\n overflow: hidden;\n background: var(--bg-obsidian);\n color: var(--text-primary);\n font-family: var(--font-sans);\n font-size: 12px;\n line-height: 1.4;\n -webkit-font-smoothing: antialiased;\n }\n\n /* App Shell */\n .app-shell {\n display: flex;\n flex-direction: column;\n width: 100vw;\n height: 100vh;\n background: var(--bg-obsidian);\n }\n\n /* Top Instrument Header */\n .top-bar {\n height: 46px;\n min-height: 46px;\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 0 12px;\n background: linear-gradient(180deg, #0D1320 0%, #090D16 100%);\n border-bottom: 1px solid var(--border-hairline);\n gap: 8px;\n z-index: 30;\n }\n\n .brand-cluster {\n display: flex;\n align-items: center;\n gap: 10px;\n flex-shrink: 0;\n }\n\n .brand-mark {\n display: flex;\n align-items: center;\n gap: 7px;\n padding: 4px 9px;\n background: rgba(56, 189, 248, 0.08);\n border: 1px solid rgba(56, 189, 248, 0.28);\n border-radius: 5px;\n font-family: var(--font-mono);\n font-weight: 700;\n font-size: 11.5px;\n letter-spacing: 0.05em;\n color: var(--accent-cyan);\n box-shadow: 0 0 18px rgba(56, 189, 248, 0.12);\n }\n\n .brand-mark .sym {\n color: var(--accent-amber);\n font-weight: 800;\n }\n\n .brand-subtitle {\n font-size: 11px;\n color: var(--text-secondary);\n letter-spacing: 0.02em;\n white-space: nowrap;\n }\n\n /* Scene Preset Switcher */\n .preset-strip {\n display: flex;\n align-items: center;\n gap: 4px;\n background: #060911;\n padding: 3px;\n border-radius: 6px;\n border: 1px solid var(--border-hairline);\n overflow-x: auto;\n scrollbar-width: none;\n }\n\n .preset-btn {\n appearance: none;\n background: transparent;\n border: 1px solid transparent;\n color: var(--text-secondary);\n font-family: var(--font-mono);\n font-size: 10.5px;\n font-weight: 600;\n padding: 5px 9px;\n border-radius: 4px;\n cursor: pointer;\n white-space: nowrap;\n transition: all 0.14s ease;\n display: flex;\n align-items: center;\n gap: 5px;\n }\n\n .preset-btn .idx {\n color: var(--text-muted);\n font-size: 9.5px;\n }\n\n .preset-btn:hover {\n color: var(--text-primary);\n background: rgba(255, 255, 255, 0.04);\n }\n\n .preset-btn.active {\n color: #040810;\n background: var(--accent-cyan);\n border-color: #7DD3FC;\n box-shadow: 0 0 14px rgba(56, 189, 248, 0.35);\n font-weight: 700;\n }\n\n .preset-btn.active .idx {\n color: rgba(4, 8, 16, 0.7);\n }\n\n /* Right Action Cluster */\n .action-cluster {\n display: flex;\n align-items: center;\n gap: 6px;\n flex-shrink: 0;\n }\n\n .tool-btn {\n appearance: none;\n background: var(--bg-panel-elevated);\n border: 1px solid var(--border-hairline);\n color: var(--text-primary);\n font-family: var(--font-mono);\n font-size: 10.5px;\n font-weight: 600;\n padding: 5px 9px;\n border-radius: 5px;\n cursor: pointer;\n display: flex;\n align-items: center;\n gap: 5px;\n transition: all 0.14s ease;\n white-space: nowrap;\n }\n\n .tool-btn:hover {\n border-color: rgba(255, 255, 255, 0.28);\n background: #182238;\n }\n\n .tool-btn.active-amber {\n background: rgba(245, 158, 11, 0.16);\n border-color: rgba(245, 158, 11, 0.65);\n color: #FCD34D;\n box-shadow: 0 0 14px rgba(245, 158, 11, 0.2);\n }\n\n .tool-btn.active-emerald {\n background: rgba(16, 185, 129, 0.16);\n border-color: rgba(16, 185, 129, 0.65);\n color: #6EE7B7;\n box-shadow: 0 0 14px rgba(16, 185, 129, 0.22);\n }\n\n .tool-btn .dot {\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: var(--text-muted);\n }\n\n .tool-btn.active-amber .dot {\n background: var(--accent-amber);\n box-shadow: 0 0 6px var(--accent-amber);\n }\n\n .tool-btn.active-emerald .dot {\n background: var(--accent-emerald);\n box-shadow: 0 0 6px var(--accent-emerald);\n }\n\n /* Main Workspace Split */\n .workspace {\n flex: 1;\n display: flex;\n min-height: 0;\n position: relative;\n }\n\n /* Optical Bench Stage */\n .bench-stage {\n flex: 1;\n position: relative;\n min-width: 0;\n background: #04060A;\n overflow: hidden;\n cursor: crosshair;\n }\n\n #simCanvas {\n width: 100%;\n height: 100%;\n display: block;\n }\n\n /* Floating Top-Left Scene Briefing Pill */\n .scene-overlay-card {\n position: absolute;\n top: 12px;\n left: 12px;\n max-width: 410px;\n background: rgba(8, 12, 20, 0.84);\n backdrop-filter: blur(10px);\n -webkit-backdrop-filter: blur(10px);\n border: 1px solid rgba(148, 163, 184, 0.16);\n border-left: 3px solid var(--accent-cyan);\n border-radius: 6px;\n padding: 9px 12px;\n pointer-events: none;\n box-shadow: 0 10px 28px rgba(0, 0, 0, 0.55);\n }\n\n .scene-title-row {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n margin-bottom: 3px;\n }\n\n .scene-title {\n font-family: var(--font-mono);\n font-size: 11.5px;\n font-weight: 700;\n color: var(--text-primary);\n letter-spacing: 0.03em;\n }\n\n .scene-equation-badge {\n font-family: var(--font-mono);\n font-size: 10px;\n color: var(--accent-amber);\n background: rgba(245, 158, 11, 0.1);\n border: 1px solid rgba(245, 158, 11, 0.25);\n padding: 1px 6px;\n border-radius: 3px;\n }\n\n .scene-desc {\n font-size: 11px;\n color: var(--text-secondary);\n line-height: 1.38;\n }\n\n .scene-desc strong {\n color: var(--text-primary);\n font-weight: 600;\n }\n\n /* Bottom Bar Overlays on Canvas */\n .canvas-bottom-hud {\n position: absolute;\n bottom: 12px;\n left: 12px;\n right: 12px;\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n pointer-events: none;\n }\n\n .hud-pill-group {\n display: flex;\n align-items: center;\n gap: 4px;\n background: rgba(8, 12, 20, 0.86);\n backdrop-filter: blur(10px);\n -webkit-backdrop-filter: blur(10px);\n border: 1px solid rgba(148, 163, 184, 0.16);\n padding: 4px;\n border-radius: 6px;\n pointer-events: auto;\n }\n\n .hud-label {\n font-family: var(--font-mono);\n font-size: 9.5px;\n color: var(--text-muted);\n padding: 0 6px;\n text-transform: uppercase;\n letter-spacing: 0.06em;\n }\n\n .layer-btn {\n appearance: none;\n background: transparent;\n border: 1px solid transparent;\n color: var(--text-secondary);\n font-family: var(--font-mono);\n font-size: 10px;\n padding: 3px 8px;\n border-radius: 4px;\n cursor: pointer;\n transition: all 0.12s;\n }\n\n .layer-btn:hover {\n color: var(--text-primary);\n background: rgba(255, 255, 255, 0.05);\n }\n\n .layer-btn.active {\n background: rgba(56, 189, 248, 0.16);\n border-color: rgba(56, 189, 248, 0.45);\n color: var(--accent-cyan);\n font-weight: 600;\n }\n\n .spectrum-legend {\n display: flex;\n align-items: center;\n gap: 7px;\n background: rgba(8, 12, 20, 0.86);\n backdrop-filter: blur(10px);\n border: 1px solid rgba(148, 163, 184, 0.16);\n padding: 5px 10px;\n border-radius: 6px;\n font-family: var(--font-mono);\n font-size: 10px;\n color: var(--text-secondary);\n pointer-events: auto;\n }\n\n .spectrum-bar {\n width: 92px;\n height: 7px;\n border-radius: 3px;\n background: linear-gradient(90deg, #6D28D9 0%, #2563EB 22%, #06B6D4 40%, #10B981 55%, #EAB308 74%, #EF4444 92%, #991B1B 100%);\n box-shadow: 0 0 8px rgba(56, 189, 248, 0.25);\n }\n\n /* Right Telemetry & Hardware Rack */\n .telemetry-rack {\n width: 334px;\n min-width: 334px;\n background: var(--bg-panel);\n border-left: 1px solid var(--border-hairline);\n display: flex;\n flex-direction: column;\n overflow-y: auto;\n z-index: 20;\n }\n\n .rack-section {\n padding: 10px 12px;\n border-bottom: 1px solid var(--border-hairline);\n }\n\n .rack-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 7px;\n }\n\n .rack-title {\n font-family: var(--font-mono);\n font-size: 10px;\n font-weight: 700;\n text-transform: uppercase;\n letter-spacing: 0.08em;\n color: var(--text-secondary);\n display: flex;\n align-items: center;\n gap: 6px;\n }\n\n .rack-title .indicator {\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: var(--accent-cyan);\n box-shadow: 0 0 6px var(--accent-cyan);\n }\n\n .rack-badge {\n font-family: var(--font-mono);\n font-size: 9.5px;\n color: var(--text-muted);\n font-variant-numeric: tabular-nums;\n }\n\n /* Oscilloscope & Phase Portrait Dual Display */\n .scope-grid {\n display: grid;\n grid-template-columns: 1fr 102px;\n gap: 6px;\n }\n\n .scope-box {\n background: #050810;\n border: 1px solid rgba(148, 163, 184, 0.14);\n border-radius: 5px;\n position: relative;\n overflow: hidden;\n height: 102px;\n }\n\n .scope-box canvas {\n width: 100%;\n height: 100%;\n display: block;\n }\n\n .scope-corner-label {\n position: absolute;\n top: 4px;\n left: 6px;\n font-family: var(--font-mono);\n font-size: 9px;\n color: var(--text-muted);\n pointer-events: none;\n display: flex;\n gap: 8px;\n }\n\n .scope-corner-label .p1 { color: var(--accent-cyan); }\n .scope-corner-label .p2 { color: var(--accent-amber); }\n\n .probe-readouts {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n gap: 5px;\n margin-top: 6px;\n }\n\n .readout-cell {\n background: rgba(16, 22, 36, 0.7);\n border: 1px solid rgba(148, 163, 184, 0.1);\n border-radius: 4px;\n padding: 4px 6px;\n }\n\n .readout-label {\n font-size: 9px;\n color: var(--text-muted);\n font-family: var(--font-mono);\n }\n\n .readout-val {\n font-family: var(--font-mono);\n font-size: 11px;\n font-weight: 700;\n color: var(--text-primary);\n font-variant-numeric: tabular-nums;\n }\n\n /* Sliders & Controls */\n .control-row {\n margin-bottom: 8px;\n }\n\n .control-row:last-child {\n margin-bottom: 0;\n }\n\n .control-label-line {\n display: flex;\n justify-content: space-between;\n align-items: center;\n margin-bottom: 3px;\n font-size: 10.5px;\n }\n\n .control-name {\n color: var(--text-secondary);\n font-weight: 500;\n }\n\n .control-val {\n font-family: var(--font-mono);\n font-size: 10.5px;\n color: var(--accent-cyan);\n font-weight: 600;\n font-variant-numeric: tabular-nums;\n }\n\n input[type=\"range\"] {\n -webkit-appearance: none;\n appearance: none;\n width: 100%;\n height: 5px;\n background: #161F33;\n border-radius: 3px;\n outline: none;\n border: 1px solid rgba(255, 255, 255, 0.06);\n }\n\n input[type=\"range\"]::-webkit-slider-thumb {\n -webkit-appearance: none;\n appearance: none;\n width: 13px;\n height: 13px;\n border-radius: 50%;\n background: var(--accent-cyan);\n border: 2px solid #050810;\n cursor: pointer;\n box-shadow: 0 0 8px rgba(56, 189, 248, 0.6);\n }\n\n /* Material Preset Chips */\n .chip-row {\n display: flex;\n gap: 4px;\n margin-top: 6px;\n }\n\n .mat-chip {\n flex: 1;\n appearance: none;\n background: #111827;\n border: 1px solid rgba(148, 163, 184, 0.16);\n color: var(--text-secondary);\n font-family: var(--font-mono);\n font-size: 9.5px;\n padding: 4px 4px;\n border-radius: 4px;\n cursor: pointer;\n text-align: center;\n transition: all 0.12s;\n }\n\n .mat-chip:hover {\n color: var(--text-primary);\n border-color: rgba(255, 255, 255, 0.3);\n }\n\n .mat-chip.active {\n background: rgba(56, 189, 248, 0.14);\n border-color: var(--accent-cyan);\n color: var(--accent-cyan);\n font-weight: 600;\n }\n\n /* Sandbox Tool Strip */\n .sandbox-tools {\n display: none;\n grid-template-columns: repeat(4, 1fr);\n gap: 4px;\n margin-top: 6px;\n }\n\n .sandbox-tools.visible {\n display: grid;\n }\n\n /* Live Mathematical Proof Box */\n .math-proof-box {\n background: #060911;\n border: 1px solid rgba(148, 163, 184, 0.12);\n border-radius: 5px;\n padding: 7px 9px;\n font-family: var(--font-mono);\n font-size: 10px;\n color: var(--text-secondary);\n }\n\n .math-line {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 2px 0;\n border-bottom: 1px dashed rgba(148, 163, 184, 0.08);\n }\n\n .math-line:last-child {\n border-bottom: none;\n }\n\n .math-eq {\n color: #CBD5E1;\n }\n\n .math-live {\n color: var(--accent-emerald);\n font-variant-numeric: tabular-nums;\n }\n\n /* Telemetry Footer */\n .telemetry-footer {\n margin-top: auto;\n padding: 8px 12px;\n background: #060910;\n border-top: 1px solid var(--border-hairline);\n display: flex;\n justify-content: space-between;\n align-items: center;\n font-family: var(--font-mono);\n font-size: 9.5px;\n color: var(--text-muted);\n font-variant-numeric: tabular-nums;\n }\n\n .fps-pill {\n color: var(--accent-emerald);\n font-weight: 700;\n }\n\n /* Modal Popover for Embed & Governing Theory */\n .modal-backdrop {\n position: fixed;\n inset: 0;\n background: rgba(3, 5, 9, 0.78);\n backdrop-filter: blur(6px);\n display: none;\n align-items: center;\n justify-content: center;\n z-index: 100;\n padding: 20px;\n }\n\n .modal-backdrop.open {\n display: flex;\n }\n\n .modal-card {\n width: 100%;\n max-width: 560px;\n background: #0C121E;\n border: 1px solid rgba(56, 189, 248, 0.35);\n border-radius: 8px;\n box-shadow: 0 24px 60px rgba(0, 0, 0, 0.75);\n overflow: hidden;\n }\n\n .modal-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 12px 16px;\n background: #080C15;\n border-bottom: 1px solid var(--border-hairline);\n }\n\n .modal-title {\n font-family: var(--font-mono);\n font-size: 12px;\n font-weight: 700;\n color: var(--accent-cyan);\n }\n\n .modal-close {\n appearance: none;\n background: transparent;\n border: none;\n color: var(--text-secondary);\n font-family: var(--font-mono);\n font-size: 14px;\n cursor: pointer;\n }\n\n .modal-body {\n padding: 16px;\n color: var(--text-secondary);\n font-size: 12px;\n line-height: 1.55;\n }\n\n .code-block {\n background: #05070C;\n border: 1px solid var(--border-hairline);\n border-radius: 5px;\n padding: 10px;\n font-family: var(--font-mono);\n font-size: 11px;\n color: #7DD3FC;\n overflow-x: auto;\n margin: 8px 0 12px;\n user-select: all;\n -webkit-user-select: all;\n }\n\n /* Responsive Embed Mode */\n @media (max-width: 900px) {\n .brand-subtitle { display: none; }\n .telemetry-rack { width: 280px; min-width: 280px; }\n }\n\n @media (max-width: 700px) {\n .workspace { flex-direction: column; }\n .telemetry-rack {\n width: 100%;\n min-width: 0;\n height: 210px;\n border-left: none;\n border-top: 1px solid var(--border-hairline);\n }\n .scene-overlay-card { max-width: 290px; padding: 6px 9px; }\n }\n</style>\n</head>\n<body>\n<div class=\"app-shell\">\n <!-- TOP PRECISION HEADER -->\n <header class=\"top-bar\">\n <div class=\"brand-cluster\">\n <div class=\"brand-mark\" title=\"Principle of Stationary Action: δS = δ∫ n(x,y,λ) ds = 0\">\n <span class=\"sym\">∂S=0</span>\n <span>EIKONAL</span>\n </div>\n <span class=\"brand-subtitle\">Coupled Wave-PDE · Spectral Ray-Caustics · Acoustic Field Solver</span>\n </div>\n\n <nav class=\"preset-strip\" id=\"presetStrip\" aria-label=\"Canonical Physics Experiments\">\n <button class=\"preset-btn active\" data-scene=\"prism\"><span class=\"idx\">01</span>CAUSTIC PRISM</button>\n <button class=\"preset-btn\" data-scene=\"ellipse\"><span class=\"idx\">02</span>ELLIPTICAL FOCUS</button>\n <button class=\"preset-btn\" data-scene=\"slit\"><span class=\"idx\">03</span>DOUBLE SLIT</button>\n <button class=\"preset-btn\" data-scene=\"einstein\"><span class=\"idx\">04</span>EINSTEIN RING</button>\n <button class=\"preset-btn\" data-scene=\"chladni\"><span class=\"idx\">05</span>CHLADNI MODES</button>\n <button class=\"preset-btn\" data-scene=\"sandbox\"><span class=\"idx\">06</span>SANDBOX</button>\n </nav>\n\n <div class=\"action-cluster\">\n <button class=\"tool-btn active-amber\" id=\"btnLoupe\" title=\"Toggle Multi-Scale X-Ray Reality Loupe [Key: L]\">\n <span class=\"dot\"></span>\n <span>X-RAY LOUPE</span>\n </button>\n <button class=\"tool-btn\" id=\"btnAudio\" title=\"Synthesize Live Acoustic Pressure from Probe P1 [Key: M]\">\n <span class=\"dot\"></span>\n <span id=\"audioLabel\">AUDIO PROBE</span>\n </button>\n <button class=\"tool-btn\" id=\"btnPulse\" title=\"Emit Coherent Wavefront & Photon Impulse [Key: Space]\">\n <span>⚡ IMPULSE</span>\n </button>\n <button class=\"tool-btn\" id=\"btnEmbed\" title=\"Embed Snippet & Mathematical Architecture\">\n <span></> EMBED</span>\n </button>\n </div>\n </header>\n\n <!-- MAIN WORKSPACE -->\n <div class=\"workspace\">\n <!-- HERO INTERACTIVE OPTICAL BENCH -->\n <main class=\"bench-stage\" id=\"benchStage\">\n <canvas id=\"simCanvas\"></canvas>\n\n <!-- Scene Contextual Briefing -->\n <div class=\"scene-overlay-card\" id=\"sceneCard\">\n <div class=\"scene-title-row\">\n <span class=\"scene-title\" id=\"sceneTitle\">01 // NEWTONIAN DISPERSION & FLUID CAUSTICS</span>\n <span class=\"scene-equation-badge\" id=\"sceneEq\">n(λ) = n₀ + B/λ²</span>\n </div>\n <p class=\"scene-desc\" id=\"sceneDesc\">\n White light (16 CIE-1931 spectral bands, 380–700nm) refracts through a draggable <strong>flint-glass prism</strong> and <strong>biconvex lens</strong> while coupling to a live <strong>2D hyperbolic wave PDE</strong>. Drag any optic, rotate its bevel ring, or move the <strong>X-Ray Loupe</strong> to inspect sub-grid vectors.\n </p>\n </div>\n\n <!-- Bottom Canvas Layer & Spectrum Bar -->\n <div class=\"canvas-bottom-hud\">\n <div class=\"hud-pill-group\" id=\"layerGroup\">\n <span class=\"hud-label\">FIELD VIEW</span>\n <button class=\"layer-btn active\" data-layer=\"coupled\">Coupled Wave + Rays</button>\n <button class=\"layer-btn\" data-layer=\"wave\">Wave Amplitude ψ(x,y)</button>\n <button class=\"layer-btn\" data-layer=\"rms\">Interference ∫ψ²dt</button>\n <button class=\"layer-btn\" data-layer=\"caustics\">Spectral Caustics</button>\n </div>\n\n <div class=\"spectrum-legend\" title=\"CIE 1931 Physically Accurate Wavelength-to-sRGB Dispersion (380nm Violet to 700nm Crimson)\">\n <span>380nm</span>\n <div class=\"spectrum-bar\"></div>\n <span>700nm CIE-1931</span>\n </div>\n </div>\n </main>\n\n <!-- RIGHT TELEMETRY & HARDWARE INSTRUMENT RACK -->\n <aside class=\"telemetry-rack\">\n <!-- 1. OSCILLOSCOPE & PHASE SPACE -->\n <section class=\"rack-section\">\n <div class=\"rack-header\">\n <span class=\"rack-title\"><span class=\"indicator\"></span>INTERFEROMETER PROBES (P1 · P2)</span>\n <span class=\"rack-badge\" id=\"phaseDiffReadout\">Δφ = 0.00π rad</span>\n </div>\n <div class=\"scope-grid\">\n <div class=\"scope-box\">\n <canvas id=\"scopeCanvas\" width=\"200\" height=\"102\"></canvas>\n <div class=\"scope-corner-label\">\n <span class=\"p1\">● P1(t)</span>\n <span class=\"p2\">● P2(t)</span>\n </div>\n </div>\n <div class=\"scope-box\">\n <canvas id=\"phaseCanvas\" width=\"102\" height=\"102\"></canvas>\n <div class=\"scope-corner-label\">\n <span>(ψ, ∂ₜψ)</span>\n </div>\n </div>\n </div>\n <div class=\"probe-readouts\">\n <div class=\"readout-cell\">\n <div class=\"readout-label\">P1 AMPLITUDE ψ</div>\n <div class=\"readout-val\" id=\"valP1Amp\">+0.000</div>\n </div>\n <div class=\"readout-cell\">\n <div class=\"readout-label\">P1 RMS ENERGY</div>\n <div class=\"readout-val\" id=\"valP1Rms\">0.000</div>\n </div>\n <div class=\"readout-cell\">\n <div class=\"readout-label\">LOCAL INDEX n</div>\n <div class=\"readout-val\" id=\"valP1Ior\">1.000</div>\n </div>\n </div>\n </section>\n\n <!-- 2. DETECTOR SCREEN / SPECTRUM ANALYZER -->\n <section class=\"rack-section\">\n <div class=\"rack-header\">\n <span class=\"rack-title\" id=\"spectrumTitle\"><span class=\"indicator\" style=\"background:var(--accent-amber)\"></span>SPECTRAL FFT & FRINGE INTEGRAL</span>\n <span class=\"rack-badge\" id=\"spectrumBadge\">256-PT RADIX-2</span>\n </div>\n <div class=\"scope-box\" style=\"height: 88px;\">\n <canvas id=\"spectrumCanvas\" width=\"308\" height=\"88\"></canvas>\n <div class=\"scope-corner-label\" id=\"spectrumLegend\">\n <span class=\"p1\">■ Measured PDE</span>\n <span class=\"p2\">--- Analytic Theory</span>\n </div>\n </div>\n </section>\n\n <!-- 3. PHYSICAL PARAMETERS -->\n <section class=\"rack-section\">\n <div class=\"rack-header\">\n <span class=\"rack-title\"><span class=\"indicator\" style=\"background:var(--accent-emerald)\"></span>OPTICAL & WAVE PARAMETERS</span>\n <span class=\"rack-badge\" id=\"matBadge\">SF11 FLINT</span>\n </div>\n\n <div class=\"control-row\">\n <div class=\"control-label-line\">\n <span class=\"control-name\">Refractive Index n₀ (550nm)</span>\n <span class=\"control-val\" id=\"lblIor\">1.68</span>\n </div>\n <input type=\"range\" id=\"sliderIor\" min=\"1.10\" max=\"2.42\" step=\"0.01\" value=\"1.68\" />\n </div>\n\n <div class=\"control-row\">\n <div class=\"control-label-line\">\n <span class=\"control-name\">Cauchy Dispersion B (μm²)</span>\n <span class=\"control-val\" id=\"lblDisp\">0.018</span>\n </div>\n <input type=\"range\" id=\"sliderDisp\" min=\"0.000\" max=\"0.036\" step=\"0.001\" value=\"0.018\" />\n </div>\n\n <div class=\"control-row\">\n <div class=\"control-label-line\">\n <span class=\"control-name\">Wave Driver Frequency f</span>\n <span class=\"control-val\" id=\"lblFreq\">4.8 Hz</span>\n </div>\n <input type=\"range\" id=\"sliderFreq\" min=\"1.2\" max=\"11.0\" step=\"0.1\" value=\"4.8\" />\n </div>\n\n <div class=\"control-row\">\n <div class=\"control-label-line\">\n <span class=\"control-name\" id=\"lblSceneParamName\">Fluid-Optical Coupling α</span>\n <span class=\"control-val\" id=\"lblSceneParamVal\">0.45</span>\n </div>\n <input type=\"range\" id=\"sliderSceneParam\" min=\"0.05\" max=\"1.00\" step=\"0.01\" value=\"0.45\" />\n </div>\n\n <div class=\"chip-row\" id=\"materialChips\">\n <button class=\"mat-chip\" data-n=\"1.33\" data-b=\"0.003\" data-name=\"WATER\">H₂O 1.33</button>\n <button class=\"mat-chip\" data-n=\"1.52\" data-b=\"0.006\" data-name=\"BK7 CROWN\">BK7 1.52</button>\n <button class=\"mat-chip active\" data-n=\"1.68\" data-b=\"0.018\" data-name=\"SF11 FLINT\">FLINT 1.68</button>\n <button class=\"mat-chip\" data-n=\"2.42\" data-b=\"0.032\" data-name=\"DIAMOND\">C-DIA 2.42</button>\n </div>\n\n <div class=\"sandbox-tools\" id=\"sandboxTools\">\n <button class=\"mat-chip active\" data-brush=\"ripple\">💧 Wave</button>\n <button class=\"mat-chip\" data-brush=\"glass\">💎 Glass</button>\n <button class=\"mat-chip\" data-brush=\"wall\">🧱 Mirror</button>\n <button class=\"mat-chip\" data-brush=\"erase\">🧹 Clear</button>\n </div>\n </section>\n\n <!-- 4. LIVE SOLVER INVARIANTS & PROOF -->\n <section class=\"rack-section\">\n <div class=\"rack-header\">\n <span class=\"rack-title\">LIVE SOLVER INVARIANTS</span>\n <span class=\"rack-badge\">9-PT ISOTROPIC O(h⁴)</span>\n </div>\n <div class=\"math-proof-box\">\n <div class=\"math-line\">\n <span class=\"math-eq\">∂²ₜψ = (c₀/n)² ∇²ᵢₛₒψ - γ∂ₜψ</span>\n <span class=\"math-live\" id=\"proofCfl\">CFL 0.56</span>\n </div>\n <div class=\"math-line\">\n <span class=\"math-eq\">Hamiltonian H = ½∫(ψ̇² + c²|∇ψ|²)dA</span>\n <span class=\"math-live\" id=\"proofEnergy\">H = 1.42 J</span>\n </div>\n <div class=\"math-line\">\n <span class=\"math-eq\">Snell-Fermat δ∫n(x,y,λ)ds = 0</span>\n <span class=\"math-live\" id=\"proofRays\">512 Rays</span>\n </div>\n </div>\n </section>\n\n <footer class=\"telemetry-footer\">\n <span class=\"fps-pill\" id=\"fpsReadout\">60.0 FPS</span>\n <span id=\"gridReadout\">300×188 PDE · 16λ CIE</span>\n <span id=\"loupeCoordReadout\">LOUPE: ACTIVE</span>\n </footer>\n </aside>\n </div>\n</div>\n\n<!-- EMBED & ARCHITECTURAL PROOF MODAL -->\n<div class=\"modal-backdrop\" id=\"embedModal\">\n <div class=\"modal-card\">\n <div class=\"modal-header\">\n <span class=\"modal-title\"></> EMBED THIS LABORATORY & SOLVER ARCHITECTURE</span>\n <button class=\"modal-close\" id=\"btnCloseModal\">✕</button>\n </div>\n <div class=\"modal-body\">\n <p><strong>Zero-Dependency Single-File Artifact:</strong> Drop this directly into any blog post, Substack, MDX article, or iframe container. Append <code>?scene=prism|ellipse|slit|einstein|chladni</code> to boot into any canonical experiment.</p>\n <div class=\"code-block\" id=\"embedCodeBlock\"><iframe src=\"index.html?scene=prism&loupe=1\" width=\"100%\" height=\"640\" style=\"border:1px solid #1e293b;border-radius:10px;background:#05070B;\" allow=\"autoplay\" loading=\"lazy\"></iframe></div>\n <p style=\"margin-bottom:6px;\"><strong style=\"color:var(--text-primary)\">Why Everything Holds Up When You Look Closer:</strong></p>\n <ul style=\"padding-left:18px; color:var(--text-secondary); font-size:11.5px;\">\n <li><strong>Unified Variational Physics:</strong> Young's double-slit diffraction, elliptical whispering-gallery refocusing, Newton's prism dispersion, Chladni nodal sand self-assembly, and Einstein gravitational lensing all emerge from the <em>exact same</em> coupled PDE + Eikonal solver.</li>\n <li><strong>True Acoustic Sonification:</strong> Enabling the Audio Probe synthesizes sound directly from the PDE wave oscillation <code>ψ(P1, t)</code> at Probe P1's coordinates—dragging P1 into a dark interference fringe silences the tone via genuine wave cancellation.</li>\n <li><strong>Multi-Scale X-Ray Loupe:</strong> Peel back the macro rendering anywhere on the bench to inspect discrete stencil nodes, Poynting flux vectors <code>S = -c²ψ̇∇ψ</code>, and exact Snell refraction angles.</li>\n </ul>\n </div>\n </div>\n</div>\n\n<script>\n(() => {\n 'use strict';\n\n // ============================================================================\n // 1. CIE 1931 SPECTRAL WAVELENGTH (380nm - 700nm) TO LINEAR/sRGB CONVERSION\n // ============================================================================\n const NUM_WAVELENGTHS = 16;\n const SPECTRAL_BANDS = [];\n\n function wavelengthToRGB(nm) {\n let r = 0, g = 0, b = 0;\n if (nm >= 380 && nm < 440) {\n r = -(nm - 440) / (440 - 380);\n g = 0.0;\n b = 1.0;\n } else if (nm >= 440 && nm < 490) {\n r = 0.0;\n g = (nm - 440) / (490 - 440);\n b = 1.0;\n } else if (nm >= 490 && nm < 510) {\n r = 0.0;\n g = 1.0;\n b = -(nm - 510) / (510 - 490);\n } else if (nm >= 510 && nm < 580) {\n r = (nm - 510) / (580 - 510);\n g = 1.0;\n b = 0.0;\n } else if (nm >= 580 && nm < 645) {\n r = 1.0;\n g = -(nm - 645) / (645 - 580);\n b = 0.0;\n } else if (nm >= 645 && nm <= 705) {\n r = 1.0;\n g = 0.0;\n b = 0.0;\n }\n let factor = 1.0;\n if (nm >= 380 && nm < 420) {\n factor = 0.35 + 0.65 * (nm - 380) / (420 - 380);\n } else if (nm > 645 && nm <= 705) {\n factor = 0.35 + 0.65 * (705 - nm) / (705 - 645);\n }\n const R = Math.round(255 * Math.pow(Math.max(0, r * factor), 0.82));\n const G = Math.round(255 * Math.pow(Math.max(0, g * factor), 0.82));\n const B = Math.round(255 * Math.pow(Math.max(0, b * factor), 0.82));\n return {\n nm,\n um: nm / 1000,\n r: R,\n g: G,\n b: B,\n css: `rgb(${R},${G},${B})`,\n rgbaGlow: `rgba(${R},${G},${B},0.26)`,\n rgbaCore: `rgba(${R},${G},${B},0.72)`\n };\n }\n\n for (let i = 0; i < NUM_WAVELENGTHS; i++) {\n const nm = 390 + (i / (NUM_WAVELENGTHS - 1)) * 300; // 390nm .. 690nm\n SPECTRAL_BANDS.push(wavelengthToRGB(nm));\n }\n\n // Reference wavelength 550nm (0.55 um)\n const INV_LAMBDA0_SQ = 1.0 / (0.55 * 0.55);\n\n function cauchyIndex(n0, B, um) {\n return n0 + B * ((1.0 / (um * um)) - INV_LAMBDA0_SQ);\n }\n\n // ============================================================================\n // 2. SIMULATION GRID & FIELD BUFFERS (300 x 188 9-Point Isotropic PDE)\n // ============================================================================\n const NX = 300;\n const NY = 188;\n const NCELLS = NX * NY;\n\n const uCurr = new Float32Array(NCELLS);\n const uPrev = new Float32Array(NCELLS);\n const uNext = new Float32Array(NCELLS);\n const uVel = new Float32Array(NCELLS);\n const uRMS = new Float32Array(NCELLS);\n\n const iorGrid = new Float32Array(NCELLS); // Base refractive index n(x,y)\n const wallGrid = new Uint8Array(NCELLS); // 1 = solid mirror/barrier\n const dampGrid = new Float32Array(NCELLS); // Absorbing PML boundary profile\n const userGlassGrid = new Float32Array(NCELLS);\n const userWallGrid = new Uint8Array(NCELLS);\n\n // Offscreen image buffer for ultra-fast 32-bit pixel shading\n const fieldCanvas = document.createElement('canvas');\n fieldCanvas.width = NX;\n fieldCanvas.height = NY;\n const fieldCtx = fieldCanvas.getContext('2d');\n const fieldImg = fieldCtx.createImageData(NX, NY);\n const fieldPixels32 = new Uint32Array(fieldImg.data.buffer);\n\n // Chladni Nodal Sand Particles (4,000 grains)\n const NUM_PARTICLES = 4000;\n const sandX = new Float32Array(NUM_PARTICLES);\n const sandY = new Float32Array(NUM_PARTICLES);\n const sandVX = new Float32Array(NUM_PARTICLES);\n const sandVY = new Float32Array(NUM_PARTICLES);\n\n function initSandParticles() {\n for (let i = 0; i < NUM_PARTICLES; i++) {\n sandX[i] = 16 + Math.random() * (NX - 32);\n sandY[i] = 16 + Math.random() * (NY - 32);\n sandVX[i] = 0;\n sandVY[i] = 0;\n }\n }\n initSandParticles();\n\n // ============================================================================\n // 3. STATE, SCENE CONFIGURATIONS & INTERACTIVE OBJECTS\n // ============================================================================\n const urlParams = new URLSearchParams(window.location.search);\n const initialScene = urlParams.get('scene') || 'prism';\n\n const state = {\n scene: initialScene,\n layer: 'coupled', // 'coupled' | 'wave' | 'rms' | 'caustics'\n simTime: 0,\n frameCount: 0,\n fps: 60.0,\n n0: 1.68,\n dispersionB: 0.018,\n waveFreq: 4.8,\n sceneParam: 0.45, // Context-dependent parameter\n cavityMode: false,\n sandboxBrush: 'ripple',\n totalEnergy: 0,\n activeRayCount: 0,\n\n // Interactive X-Ray Loupe\n loupe: {\n enabled: urlParams.get('loupe') !== '0',\n x: 0.44, // normalized [0..1]\n y: 0.47,\n radiusPx: 108,\n snellInfo: null\n },\n\n // Draggable Field Probes (normalized coordinates)\n probes: [\n { id: 'P1', x: 0.77, y: 0.46, color: '#38BDF8', amp: 0, vel: 0, rms: 0, ior: 1, history: new Float32Array(256), histVel: new Float32Array(256) },\n { id: 'P2', x: 0.77, y: 0.64, color: '#F59E0B', amp: 0, vel: 0, rms: 0, ior: 1, history: new Float32Array(256), histVel: new Float32Array(256) }\n ],\n probePtr: 0,\n\n // Scene Optical Elements (Coordinates in Grid Space [0..NX, 0..NY])\n laser: { x: 18, y: 108, angle: -0.18, spread: 0.03, aperture: 18, active: true, raysPerBand: 22 },\n waveSource: { x: 38, y: 94, active: true, amplitude: 1.35 },\n\n prism: { x: 112, y: 88, radius: 34, angle: 0.12, active: true },\n lens: { x: 194, y: 92, rx: 14, ry: 42, angle: 0.04, active: true, concave: false },\n ellipse: { cx: 150, cy: 94, a: 122, e: 0.62, active: false, lastPulseTime: -10 },\n slit: { x: 96, sep: 32, width: 9, active: false, screenX: 256 },\n bh: { x: 148, y: 94, rs: 13.5, active: false },\n chladni: { m: 3, n: 5, active: false }\n };\n\n const SCENE_META = {\n prism: {\n title: '01 // NEWTONIAN DISPERSION & FLUID CAUSTICS',\n eq: 'n(λ) = n₀ + B/λ²',\n desc: 'Collimated white light (16 CIE-1931 spectral bands, 380–700nm) refracts through a draggable <strong>flint-glass prism</strong> and <strong>biconvex lens</strong> while coupling to a live <strong>2D hyperbolic wave PDE</strong>. Drag any optic, rotate its bevel ring, or move the <strong>X-Ray Loupe</strong> to inspect sub-grid vectors.',\n paramName: 'Wave-Optical Coupling α',\n paramMin: 0.0, paramMax: 1.0, paramStep: 0.02, paramVal: 0.48\n },\n ellipse: {\n title: '02 // ELLIPTICAL WHISPERING GALLERY (STATIONARY PATH)',\n eq: '|F₁P| + |PF₂| = 2a',\n desc: 'An impulse emitted at <strong>Focus F₁</strong> expands in all directions, reflects off the elliptical boundary, and re-converges in exact phase coherence at <strong>Focus F₂</strong> because every reflected path has identical length <strong>2a</strong>. Try dragging Source F₁ off-focus to watch phase coherence break into an astroid caustic!',\n paramName: 'Orbital Eccentricity e',\n paramMin: 0.25, paramMax: 0.82, paramStep: 0.01, paramVal: 0.62\n },\n slit: {\n title: '03 // YOUNG’S DOUBLE-SLIT INTERFERENCE & DIFFRACTION',\n eq: 'I(θ) = I₀ cos²β sinc²α',\n desc: 'Coherent wavefronts diffract through two adjustable apertures, generating hyperbolic constructive and destructive fringes. The right rack compares the <strong>emergent PDE intensity ∫ψ²dt</strong> against the <strong>exact Fraunhofer analytical integral</strong>. Drag Probe P1 into a dark nodal channel to hear acoustic cancellation!',\n paramName: 'Slit Separation a (grid)',\n paramMin: 16, paramMax: 64, paramStep: 1, paramVal: 32\n },\n einstein: {\n title: '04 // EINSTEIN RING & OPTICAL SCHWARZSCHILD METRIC',\n eq: 'n(r) = 1 + rₛ / r',\n desc: 'Curved spacetime acts as a graded-index metamaterial <strong>n(r) = 1 + 2GM/rc²</strong>. Both Huygens wavefronts and Fermat photon trajectories bend around the horizon, forming a bright <strong>Einstein Ring caustic</strong>, Shapiro wavefront delay, and critical photon-sphere orbits at <strong>b = (3√3/2)rₛ</strong>.',\n paramName: 'Schwarzschild Horizon rₛ',\n paramMin: 5.0, paramMax: 24.0, paramStep: 0.5, paramVal: 13.5\n },\n chladni: {\n title: '05 // CHLADNI EIGENMODES & SELF-ORGANIZING MATTER',\n eq: '∇²ψ + k²ₘₙψ = 0',\n desc: 'Harmonic transducers excite resonant standing waves inside a reflective acoustic plate. <strong>4,000 individual quartz sand grains</strong> read the local PDE wave amplitude beneath them and migrate via acoustic radiation pressure to crystallize along zero-amplitude nodal contours (ψ = 0).',\n paramName: 'Eigenmode Harmonic Index',\n paramMin: 1, paramMax: 8, paramStep: 0.25, paramVal: 4.0\n },\n sandbox: {\n title: '06 // FREEFORM VARIATIONAL OPTICS & WAVE BENCH',\n eq: 'δ ∫ L(ψ, ∇ψ, ψ̇) dt = 0',\n desc: 'Sculpt custom refractive glass lenses, reflective mirrors, and wave impulses directly on the bench, while dragging the prism, biconvex lens, laser source, and interferometer probes anywhere in the field.',\n paramName: 'Brush Radius / Coupling',\n paramMin: 0.1, paramMax: 1.0, paramStep: 0.05, paramVal: 0.50\n }\n };\n\n // ============================================================================\n // 4. INITIALIZE / SWITCH CANONICAL SCENES\n // ============================================================================\n function clearWaveField() {\n uCurr.fill(0);\n uPrev.fill(0);\n uNext.fill(0);\n uVel.fill(0);\n uRMS.fill(0);\n }\n\n function applyScene(sceneName) {\n state.scene = sceneName;\n clearWaveField();\n userGlassGrid.fill(0);\n userWallGrid.fill(0);\n\n // Reset flags\n state.prism.active = false;\n state.lens.active = false;\n state.ellipse.active = false;\n state.slit.active = false;\n state.bh.active = false;\n state.chladni.active = false;\n state.cavityMode = false;\n\n const meta = SCENE_META[sceneName] || SCENE_META.prism;\n document.getElementById('sceneTitle').textContent = meta.title;\n document.getElementById('sceneEq').textContent = meta.eq;\n document.getElementById('sceneDesc').innerHTML = meta.desc;\n\n const sliderParam = document.getElementById('sliderSceneParam');\n document.getElementById('lblSceneParamName').textContent = meta.paramName;\n sliderParam.min = meta.paramMin;\n sliderParam.max = meta.paramMax;\n sliderParam.step = meta.paramStep;\n sliderParam.value = meta.paramVal;\n state.sceneParam = meta.paramVal;\n document.getElementById('lblSceneParamVal').textContent = Number(meta.paramVal).toFixed(2);\n\n document.getElementById('sandboxTools').classList.toggle('visible', sceneName === 'sandbox');\n\n // Update top preset buttons\n document.querySelectorAll('.preset-btn').forEach(btn => {\n btn.classList.toggle('active', btn.dataset.scene === sceneName);\n });\n\n if (sceneName === 'prism') {\n state.n0 = 1.68;\n state.dispersionB = 0.018;\n state.waveFreq = 4.6;\n state.prism = { x: 108, y: 88, radius: 35, angle: 0.14, active: true };\n state.lens = { x: 196, y: 95, rx: 14, ry: 44, angle: 0.06, active: true, concave: false };\n state.laser = { x: 18, y: 108, angle: -0.20, spread: 0.015, aperture: 14, active: true, raysPerBand: 22 };\n state.waveSource = { x: 34, y: 92, active: true, amplitude: 1.25 };\n state.probes[0].x = 0.76; state.probes[0].y = 0.49;\n state.probes[1].x = 0.64; state.probes[1].y = 0.66;\n state.loupe.x = 0.37; state.loupe.y = 0.45;\n } else if (sceneName === 'ellipse') {\n state.cavityMode = true;\n state.ellipse.active = true;\n state.ellipse.cx = NX * 0.5;\n state.ellipse.cy = NY * 0.5;\n state.ellipse.a = 122;\n state.ellipse.e = 0.62;\n const cDist = state.ellipse.a * state.ellipse.e;\n state.waveSource = { x: state.ellipse.cx - cDist, y: state.ellipse.cy, active: false, amplitude: 2.2 };\n state.laser = { x: state.ellipse.cx - cDist, y: state.ellipse.cy, angle: 0, spread: Math.PI * 2, aperture: 0, active: true, raysPerBand: 4 };\n state.probes[0].x = (state.ellipse.cx + cDist) / NX;\n state.probes[0].y = state.ellipse.cy / NY;\n state.probes[1].x = state.ellipse.cx / NX;\n state.probes[1].y = (state.ellipse.cy - 36) / NY;\n state.loupe.x = (state.ellipse.cx + cDist) / NX;\n state.loupe.y = state.ellipse.cy / NY;\n rebuildMediumGrid();\n triggerWaveImpulse(state.waveSource.x, state.waveSource.y, 6.5, 4.5);\n state.ellipse.lastPulseTime = state.simTime;\n } else if (sceneName === 'slit') {\n state.slit.active = true;\n state.slit.x = 92;\n state.slit.sep = 32;\n state.slit.width = 8;\n state.slit.screenX = 248;\n state.waveFreq = 6.2;\n state.waveSource = { x: 32, y: NY * 0.5, active: true, amplitude: 1.5 };\n state.laser = { x: 18, y: NY * 0.5, angle: 0, spread: 0.04, aperture: 46, active: true, raysPerBand: 14 };\n // Put Probe P1 on central bright fringe, Probe P2 on first dark destructive node\n state.probes[0].x = state.slit.screenX / NX;\n state.probes[0].y = 0.50;\n state.probes[1].x = state.slit.screenX / NX;\n state.probes[1].y = 0.39;\n state.loupe.x = 0.33;\n state.loupe.y = 0.42;\n } else if (sceneName === 'einstein') {\n state.bh.active = true;\n state.bh.x = 146;\n state.bh.y = 94;\n state.bh.rs = 13.5;\n state.waveFreq = 5.4;\n state.waveSource = { x: 26, y: 94, active: true, amplitude: 1.35 };\n state.laser = { x: 18, y: 94, angle: 0.0, spread: 0.01, aperture: 56, active: true, raysPerBand: 24 };\n state.probes[0].x = 0.74;\n state.probes[0].y = 0.50;\n state.probes[1].x = 0.58;\n state.probes[1].y = 0.32;\n state.loupe.x = 0.52;\n state.loupe.y = 0.38;\n } else if (sceneName === 'chladni') {\n state.cavityMode = true;\n state.chladni.active = true;\n state.waveFreq = 7.4;\n state.laser.active = false;\n state.waveSource = { x: NX * 0.5, y: NY * 0.5, active: true, amplitude: 1.8 };\n state.probes[0].x = 0.65;\n state.probes[0].y = 0.50;\n state.probes[1].x = 0.35;\n state.probes[1].y = 0.35;\n state.loupe.x = 0.50;\n state.loupe.y = 0.50;\n initSandParticles();\n } else if (sceneName === 'sandbox') {\n state.prism = { x: 105, y: 76, radius: 30, angle: 0.2, active: true };\n state.lens = { x: 188, y: 108, rx: 13, ry: 38, angle: -0.1, active: true, concave: false };\n state.laser = { x: 20, y: 84, angle: -0.05, spread: 0.02, aperture: 14, active: true, raysPerBand: 18 };\n state.waveSource = { x: 40, y: 120, active: true, amplitude: 1.2 };\n state.loupe.x = 0.62;\n state.loupe.y = 0.56;\n }\n\n document.getElementById('sliderIor').value = state.n0;\n document.getElementById('lblIor').textContent = state.n0.toFixed(2);\n document.getElementById('sliderDisp').value = state.dispersionB;\n document.getElementById('lblDisp').textContent = state.dispersionB.toFixed(3);\n document.getElementById('sliderFreq').value = state.waveFreq;\n document.getElementById('lblFreq').textContent = state.waveFreq.toFixed(1) + ' Hz';\n\n rebuildMediumGrid();\n\n // Seed initial wave state so the bench is immediately alive at frame 0\n for (let w = 0; w < 28; w++) {\n stepWavePDE(0.016);\n }\n }\n\n // ============================================================================\n // 5. GEOMETRY HELPERS & MEDIUM GRID RASTERIZATION\n // ============================================================================\n function getPrismVertices(prism) {\n const verts = [];\n for (let k = 0; k < 3; k++) {\n const a = prism.angle - Math.PI / 2 + (k * 2 * Math.PI) / 3;\n verts.push({\n x: prism.x + Math.cos(a) * prism.radius,\n y: prism.y + Math.sin(a) * prism.radius\n });\n }\n return verts;\n }\n\n function pointInTriangle(px, py, v0, v1, v2) {\n const dX = px - v2.x, dY = py - v2.y;\n const dX21 = v2.x - v1.x, dY12 = v1.y - v2.y;\n const D = dY12 * (v0.x - v2.x) + dX21 * (v0.y - v2.y);\n const s = dY12 * dX + dX21 * dY;\n const t = (v2.y - v0.y) * dX + (v0.x - v2.x) * dY;\n if (D < 0) return s <= 0 && t <= 0 && s + t >= D;\n return s >= 0 && t >= 0 && s + t <= D;\n }\n\n function pointInLens(px, py, lens) {\n const dx = px - lens.x;\n const dy = py - lens.y;\n const ca = Math.cos(-lens.angle);\n const sa = Math.sin(-lens.angle);\n const lx = dx * ca - dy * sa;\n const ly = dx * sa + dy * ca;\n if (Math.abs(ly) > lens.ry) return false;\n const normY = ly / lens.ry;\n const halfWidth = lens.rx * (1.0 - 0.82 * normY * normY);\n return Math.abs(lx) <= halfWidth;\n }\n\n function rebuildMediumGrid() {\n // 1. Absorbing PML boundary vs Reflective Cavity boundary\n const pmlWidth = 18;\n for (let y = 0; y < NY; y++) {\n for (let x = 0; x < NX; x++) {\n const idx = y * NX + x;\n iorGrid[idx] = 1.0 + userGlassGrid[idx];\n wallGrid[idx] = userWallGrid[idx];\n\n if (state.cavityMode) {\n if (x <= 2 || x >= NX - 3 || y <= 2 || y >= NY - 3) {\n wallGrid[idx] = 1;\n }\n dampGrid[idx] = 0.9992;\n } else {\n const dx = Math.min(x, NX - 1 - x);\n const dy = Math.min(y, NY - 1 - y);\n const d = Math.min(dx, dy);\n if (d < pmlWidth) {\n const t = (pmlWidth - d) / pmlWidth;\n dampGrid[idx] = 1.0 - 0.14 * t * t;\n } else {\n dampGrid[idx] = 0.9988;\n }\n }\n }\n }\n\n // 2. Prism Refractive Index\n if (state.prism.active) {\n const [v0, v1, v2] = getPrismVertices(state.prism);\n const minX = Math.max(1, Math.floor(state.prism.x - state.prism.radius - 2));\n const maxX = Math.min(NX - 2, Math.ceil(state.prism.x + state.prism.radius + 2));\n const minY = Math.max(1, Math.floor(state.prism.y - state.prism.radius - 2));\n const maxY = Math.min(NY - 2, Math.ceil(state.prism.y + state.prism.radius + 2));\n for (let y = minY; y <= maxY; y++) {\n for (let x = minX; x <= maxX; x++) {\n if (pointInTriangle(x, y, v0, v1, v2)) {\n iorGrid[y * NX + x] = state.n0;\n }\n }\n }\n }\n\n // 3. Biconvex Lens Refractive Index\n if (state.lens.active) {\n const rMax = Math.max(state.lens.rx, state.lens.ry) + 3;\n const minX = Math.max(1, Math.floor(state.lens.x - rMax));\n const maxX = Math.min(NX - 2, Math.ceil(state.lens.x + rMax));\n const minY = Math.max(1, Math.floor(state.lens.y - rMax));\n const maxY = Math.min(NY - 2, Math.ceil(state.lens.y + rMax));\n for (let y = minY; y <= maxY; y++) {\n for (let x = minX; x <= maxX; x++) {\n if (pointInLens(x, y, state.lens)) {\n iorGrid[y * NX + x] = state.n0;\n }\n }\n }\n }\n\n // 4. Elliptical Whispering Gallery Reflective Wall\n if (state.ellipse.active) {\n const a = state.ellipse.a;\n const e = state.ellipse.e;\n const b = a * Math.sqrt(Math.max(0.04, 1 - e * e));\n state.ellipse.b = b;\n const cx = state.ellipse.cx;\n const cy = state.ellipse.cy;\n for (let y = 0; y < NY; y++) {\n for (let x = 0; x < NX; x++) {\n const idx = y * NX + x;\n const dx = (x - cx) / a;\n const dy = (y - cy) / b;\n const r2 = dx * dx + dy * dy;\n if (r2 >= 1.0) {\n wallGrid[idx] = 1;\n dampGrid[idx] = 0.95;\n } else {\n wallGrid[idx] = 0;\n dampGrid[idx] = 0.9994;\n }\n }\n }\n }\n\n // 5. Young's Double-Slit Barrier\n if (state.slit.active) {\n const sx = Math.round(state.slit.x);\n const halfSep = state.slit.sep * 0.5;\n const halfW = state.slit.width * 0.5;\n const cy = NY * 0.5;\n const slit1Y = cy - halfSep;\n const slit2Y = cy + halfSep;\n for (let y = 0; y < NY; y++) {\n const inSlit1 = Math.abs(y - slit1Y) <= halfW;\n const inSlit2 = Math.abs(y - slit2Y) <= halfW;\n if (!inSlit1 && !inSlit2) {\n for (let dx = -2; dx <= 2; dx++) {\n const xx = sx + dx;\n if (xx >= 0 && xx < NX) {\n wallGrid[y * NX + xx] = 1;\n }\n }\n }\n }\n }\n\n // 6. Schwarzschild Gravitational Lens Metric n(r) = 1 + rs / r\n if (state.bh.active) {\n const bx = state.bh.x;\n const by = state.bh.y;\n const rs = state.bh.rs;\n for (let y = 0; y < NY; y++) {\n for (let x = 0; x < NX; x++) {\n const r = Math.hypot(x - bx, y - by);\n const effR = Math.max(r, rs * 0.48);\n const nGrav = 1.0 + (rs / effR);\n iorGrid[y * NX + x] = Math.min(3.4, nGrav);\n }\n }\n }\n }\n\n // ============================================================================\n // 6. 2D HYPERBOLIC WAVE PDE SOLVER (9-Point O(h⁴) Isotropic Stencil)\n // ============================================================================\n function triggerWaveImpulse(gx, gy, radius = 6.0, strength = 3.8) {\n const minX = Math.max(2, Math.floor(gx - radius * 2.5));\n const maxX = Math.min(NX - 3, Math.ceil(gx + radius * 2.5));\n const minY = Math.max(2, Math.floor(gy - radius * 2.5));\n const maxY = Math.min(NY - 3, Math.ceil(gy + radius * 2.5));\n const invR2 = 1.0 / (radius * radius);\n for (let y = minY; y <= maxY; y++) {\n for (let x = minX; x <= maxX; x++) {\n const idx = y * NX + x;\n if (wallGrid[idx]) continue;\n const d2 = (x - gx) * (x - gx) + (y - gy) * (y - gy);\n const env = Math.exp(-d2 * invR2) * Math.cos(Math.sqrt(d2) * 0.55);\n uCurr[idx] += strength * env;\n }\n }\n }\n\n function stepWavePDE(dt) {\n const substeps = 2;\n const baseC2 = 0.34; // Courant-Friedrichs-Lewy stable base speed squared\n\n for (let step = 0; step < substeps; step++) {\n state.simTime += dt / substeps;\n const t = state.simTime;\n const omega = 2 * Math.PI * state.waveFreq;\n\n // Continuous Harmonic Sources\n if (state.scene === 'slit') {\n // Planar wave driver to the left of the double-slit barrier\n const srcX = 24;\n const val = Math.sin(omega * t) * 1.35;\n for (let y = 20; y < NY - 20; y++) {\n const env = Math.exp(-Math.pow((y - NY * 0.5) / 56, 4));\n uCurr[y * NX + srcX] = val * env;\n }\n } else if (state.scene === 'einstein') {\n // Coherent planar + point wavefronts entering gravitational field\n const srcX = 20;\n const val = Math.sin(omega * t) * 1.15;\n for (let y = 22; y < NY - 22; y++) {\n const env = Math.exp(-Math.pow((y - NY * 0.5) / 62, 4));\n uCurr[y * NX + srcX] = val * env;\n }\n } else if (state.scene === 'chladni') {\n // Symmetric multi-point resonant transducers driving Chladni eigenmodes\n const modeIdx = state.sceneParam;\n const m = Math.max(1, Math.round(modeIdx));\n const n = Math.max(1, Math.round(modeIdx * 1.5));\n const drive = Math.sin(omega * 1.25 * t) * 0.36;\n for (let py = 1; py <= 3; py++) {\n for (let px = 1; px <= 3; px++) {\n const gx = Math.round((px / 4) * NX);\n const gy = Math.round((py / 4) * NY);\n const sign = Math.cos(m * Math.PI * (px / 4)) * Math.cos(n * Math.PI * (py / 4));\n uCurr[gy * NX + gx] += drive * sign;\n }\n }\n } else if (state.scene === 'ellipse') {\n // Periodic coherent pulse at Focus F1 every 3.2 seconds\n if (t - state.ellipse.lastPulseTime > 3.1) {\n triggerWaveImpulse(state.waveSource.x, state.waveSource.y, 5.5, 4.4);\n state.ellipse.lastPulseTime = t;\n if (audioEngine.enabled) audioEngine.triggerPing(520);\n }\n } else if (state.waveSource.active) {\n const sx = Math.max(3, Math.min(NX - 4, Math.round(state.waveSource.x)));\n const sy = Math.max(3, Math.min(NY - 4, Math.round(state.waveSource.y)));\n const val = Math.sin(omega * t) * state.waveSource.amplitude;\n for (let dy = -1; dy <= 1; dy++) {\n for (let dx = -1; dx <= 1; dx++) {\n const idx = (sy + dy) * NX + (sx + dx);\n if (!wallGrid[idx]) uCurr[idx] = val;\n }\n }\n }\n\n // 9-Point Isotropic Laplacian Stencil Integration\n let energySum = 0;\n for (let y = 1; y < NY - 1; y++) {\n const row = y * NX;\n const rowUp = (y - 1) * NX;\n const rowDn = (y + 1) * NX;\n\n for (let x = 1; x < NX - 1; x++) {\n const i = row + x;\n if (wallGrid[i]) {\n uNext[i] = 0;\n uVel[i] = 0;\n continue;\n }\n\n const center = uCurr[i];\n const ortho = uCurr[i - 1] + uCurr[i + 1] + uCurr[rowUp + x] + uCurr[rowDn + x];\n const diag = uCurr[rowUp + x - 1] + uCurr[rowUp + x + 1] + uCurr[rowDn + x - 1] + uCurr[rowDn + x + 1];\n const laplacian = (4.0 * ortho + diag - 20.0 * center) * (1.0 / 6.0);\n\n const nLoc = iorGrid[i];\n const c2 = baseC2 / (nLoc * nLoc);\n const damp = dampGrid[i];\n\n let nextVal = (2.0 * center - uPrev[i] + c2 * laplacian) * damp;\n // Soft physical saturation for guaranteed stability\n if (nextVal > 6.0) nextVal = 6.0 + Math.tanh(nextVal - 6.0);\n else if (nextVal < -6.0) nextVal = -6.0 + Math.tanh(nextVal + 6.0);\n\n uNext[i] = nextVal;\n const vel = (nextVal - uPrev[i]) * 0.5;\n uVel[i] = vel;\n uRMS[i] = uRMS[i] * 0.982 + (nextVal * nextVal) * 0.018;\n\n if ((x & 1) === 0 && (y & 1) === 0) {\n const gx = (uCurr[i + 1] - uCurr[i - 1]) * 0.5;\n const gy = (uCurr[rowDn + x] - uCurr[rowUp + x]) * 0.5;\n energySum += 0.5 * (vel * vel + c2 * (gx * gx + gy * gy));\n }\n }\n }\n state.totalEnergy = energySum * 0.04;\n\n // Swap buffers\n uPrev.set(uCurr);\n uCurr.set(uNext);\n }\n\n // Update Chladni Nodal Sand Particles when in Chladni scene\n if (state.scene === 'chladni') {\n stepChladniParticles();\n }\n\n // Sample Interferometer Probes P1 & P2\n sampleProbes();\n }\n\n function stepChladniParticles() {\n for (let i = 0; i < NUM_PARTICLES; i++) {\n let px = sandX[i];\n let py = sandY[i];\n const ix = Math.max(2, Math.min(NX - 3, Math.floor(px)));\n const iy = Math.max(2, Math.min(NY - 3, Math.floor(py)));\n const idx = iy * NX + ix;\n\n const rms = Math.sqrt(uRMS[idx]);\n const instAmp = Math.abs(uCurr[idx]);\n const agitation = rms * 1.45 + instAmp * 0.35;\n\n // Acoustic radiation pressure gradient -∇(uRMS) pushes particles toward nodes\n const gradX = (uRMS[idx + 1] - uRMS[idx - 1]) * 0.5;\n const gradY = (uRMS[idx + NX] - uRMS[idx - NX]) * 0.5;\n\n sandVX[i] = sandVX[i] * 0.78 - gradX * 4.5 + (Math.random() - 0.5) * agitation * 3.1;\n sandVY[i] = sandVY[i] * 0.78 - gradY * 4.5 + (Math.random() - 0.5) * agitation * 3.1;\n\n px += sandVX[i];\n py += sandVY[i];\n\n if (px < 8) { px = 8 + Math.random() * 4; sandVX[i] *= -0.5; }\n if (px > NX - 9) { px = NX - 9 - Math.random() * 4; sandVX[i] *= -0.5; }\n if (py < 8) { py = 8 + Math.random() * 4; sandVY[i] *= -0.5; }\n if (py > NY - 9) { py = NY - 9 - Math.random() * 4; sandVY[i] *= -0.5; }\n\n sandX[i] = px;\n sandY[i] = py;\n }\n }\n\n function sampleProbes() {\n const ptr = state.probePtr;\n for (let p = 0; p < 2; p++) {\n const pr = state.probes[p];\n const gx = Math.max(1, Math.min(NX - 2, Math.round(pr.x * NX)));\n const gy = Math.max(1, Math.min(NY - 2, Math.round(pr.y * NY)));\n const idx = gy * NX + gx;\n pr.amp = uCurr[idx];\n pr.vel = uVel[idx];\n pr.rms = Math.sqrt(uRMS[idx]);\n pr.ior = iorGrid[idx];\n pr.history[ptr] = pr.amp;\n pr.histVel[ptr] = pr.vel;\n }\n state.probePtr = (ptr + 1) & 255;\n }\n\n // ============================================================================\n // 7. COUPLED SPECTRAL RAY & CAUSTIC SOLVER (Snell + Cauchy + Eikonal)\n // ============================================================================\n // Ray-segment intersection helper\n function intersectRaySegment(ox, oy, dx, dy, ax, ay, bx, by) {\n const v1x = ox - ax;\n const v1y = oy - ay;\n const v2x = bx - ax;\n const v2y = by - ay;\n const v3x = -dy;\n const v3y = dx;\n const dot = v2x * v3x + v2y * v3y;\n if (Math.abs(dot) < 1e-7) return null;\n const t1 = (v2x * v1y - v2y * v1x) / dot;\n const t2 = (v1x * v3x + v1y * v3y) / dot;\n if (t1 > 0.15 && t2 >= 0.0 && t2 <= 1.0) {\n let nx = -v2y;\n let ny = v2x;\n const len = Math.hypot(nx, ny) || 1;\n nx /= len; ny /= len;\n return { t: t1, x: ox + dx * t1, y: oy + dy * t1, nx, ny };\n }\n return null;\n }\n\n // Ray-Lens boundary intersection (approximated by high-precision 24-segment curved polygon)\n function getLensSegments(lens) {\n const segs = [];\n const N = 20;\n const pts = [];\n const ca = Math.cos(lens.angle);\n const sa = Math.sin(lens.angle);\n // Right convex arc\n for (let i = 0; i <= N; i++) {\n const u = -1 + (2 * i) / N;\n const ly = u * lens.ry;\n const lx = lens.rx * (1.0 - 0.82 * u * u);\n pts.push({\n x: lens.x + lx * ca - ly * sa,\n y: lens.y + lx * sa + ly * ca\n });\n }\n // Left convex arc\n for (let i = N - 1; i >= 1; i--) {\n const u = -1 + (2 * i) / N;\n const ly = u * lens.ry;\n const lx = -lens.rx * (1.0 - 0.82 * u * u);\n pts.push({\n x: lens.x + lx * ca - ly * sa,\n y: lens.y + lx * sa + ly * ca\n });\n }\n for (let i = 0; i < pts.length; i++) {\n const a = pts[i];\n const b = pts[(i + 1) % pts.length];\n segs.push({ ax: a.x, ay: a.y, bx: b.x, by: b.y });\n }\n return segs;\n }\n\n function traceSpectralRays() {\n if (!state.laser.active) {\n state.activeRayCount = 0;\n return [];\n }\n\n const prismSegs = [];\n if (state.prism.active) {\n const pv = getPrismVertices(state.prism);\n for (let i = 0; i < 3; i++) {\n const a = pv[i], b = pv[(i + 1) % 3];\n prismSegs.push({ ax: a.x, ay: a.y, bx: b.x, by: b.y, type: 'prism' });\n }\n }\n const lensSegs = state.lens.active ? getLensSegments(state.lens) : [];\n\n const allBoundaries = [...prismSegs, ...lensSegs];\n const rays = [];\n const waveCoupling = state.scene === 'prism' ? state.sceneParam : 0.25;\n\n const loupeGX = state.loupe.x * NX;\n const loupeGY = state.loupe.y * NY;\n let closestSnellDist = 9999;\n state.loupe.snellInfo = null;\n\n const numBands = state.scene === 'ellipse' ? 4 : NUM_WAVELENGTHS;\n const raysPerBand = state.laser.raysPerBand || 16;\n\n for (let bIdx = 0; bIdx < numBands; bIdx++) {\n const band = SPECTRAL_BANDS[Math.floor((bIdx / Math.max(1, numBands - 1)) * (NUM_WAVELENGTHS - 1))];\n const nGlass = cauchyIndex(state.n0, state.dispersionB, band.um);\n\n for (let rIdx = 0; rIdx < raysPerBand; rIdx++) {\n const frac = raysPerBand > 1 ? (rIdx / (raysPerBand - 1)) - 0.5 : 0;\n let ox, oy, ang;\n\n if (state.scene === 'ellipse') {\n ox = state.waveSource.x;\n oy = state.waveSource.y;\n ang = (rIdx / raysPerBand) * Math.PI * 2 + bIdx * 0.04;\n } else {\n const perpX = -Math.sin(state.laser.angle);\n const perpY = Math.cos(state.laser.angle);\n ox = state.laser.x + perpX * frac * state.laser.aperture;\n oy = state.laser.y + perpY * frac * state.laser.aperture;\n ang = state.laser.angle + frac * state.laser.spread;\n }\n\n let dx = Math.cos(ang);\n let dy = Math.sin(ang);\n\n const path = [{ x: ox, y: oy }];\n\n if (state.scene === 'einstein' || state.scene === 'slit') {\n // Continuous Eikonal geodesic integration ds for graded-index / double-slit\n let x = ox, y = oy;\n const stepSize = 2.4;\n for (let s = 0; s < 135; s++) {\n const nx = x + dx * stepSize;\n const ny = y + dy * stepSize;\n if (nx < 2 || nx >= NX - 2 || ny < 2 || ny >= NY - 2) {\n path.push({ x: nx, y: ny });\n break;\n }\n const ix = Math.floor(nx), iy = Math.floor(ny);\n const idx = iy * NX + ix;\n if (wallGrid[idx]) {\n path.push({ x: nx, y: ny });\n break;\n }\n\n if (state.bh.active) {\n const rx = nx - state.bh.x;\n const ry = ny - state.bh.y;\n const r = Math.hypot(rx, ry);\n if (r < state.bh.rs * 0.85) {\n path.push({ x: nx, y: ny });\n break; // Captured inside event horizon!\n }\n // Einstein deflection gradient ∇n = -rs / r³ * r_vec\n const dispScale = 1.0 + (band.um - 0.55) * -0.18;\n const force = -(state.bh.rs * 1.85 * dispScale) / (r * r * r + 8.0);\n dx += force * rx * stepSize;\n dy += force * ry * stepSize;\n }\n\n // Couple wave-field surface slope ∇u\n const gradUX = (uCurr[idx + 1] - uCurr[idx - 1]) * 0.5;\n const gradUY = (uCurr[idx + NX] - uCurr[idx - NX]) * 0.5;\n dx += gradUX * 0.015 * waveCoupling;\n dy += gradUY * 0.015 * waveCoupling;\n\n const dLen = Math.hypot(dx, dy) || 1;\n dx /= dLen; dy /= dLen;\n\n x = nx; y = ny;\n if ((s & 1) === 0) path.push({ x, y });\n }\n } else if (state.scene === 'ellipse') {\n // Exact analytical reflection inside Elliptical Whispering Gallery\n const cx = state.ellipse.cx, cy = state.ellipse.cy;\n const a = state.ellipse.a, b = state.ellipse.b || (a * 0.78);\n for (let bounce = 0; bounce < 2; bounce++) {\n // Solve ((ox + t*dx - cx)/a)^2 + ((oy + t*dy - cy)/b)^2 = 1\n const rx = (ox - cx) / a, ry = (oy - cy) / b;\n const vx = dx / a, vy = dy / b;\n const A = vx * vx + vy * vy;\n const B = 2 * (rx * vx + ry * vy);\n const C = rx * rx + ry * ry - 1.0;\n const disc = B * B - 4 * A * C;\n if (disc <= 0) break;\n const tHit = (-B + Math.sqrt(disc)) / (2 * A);\n const hx = ox + dx * tHit;\n const hy = oy + dy * tHit;\n path.push({ x: hx, y: hy });\n\n // Outward normal to ellipse: ( (hx-cx)/a^2, (hy-cy)/b^2 )\n let nx = (hx - cx) / (a * a);\n let ny = (hy - cy) / (b * b);\n const nLen = Math.hypot(nx, ny) || 1;\n nx /= nLen; ny /= nLen;\n const dot = dx * nx + dy * ny;\n dx = dx - 2 * dot * nx;\n dy = dy - 2 * dot * ny;\n ox = hx + dx * 0.2;\n oy = hy + dy * 0.2;\n }\n } else {\n // Ray-boundary exact Snell's Law refraction + wave ripple perturbation\n let insideMedium = false;\n for (let bounce = 0; bounce < 6; bounce++) {\n let bestHit = null;\n for (let s = 0; s < allBoundaries.length; s++) {\n const seg = allBoundaries[s];\n const hit = intersectRaySegment(ox, oy, dx, dy, seg.ax, seg.ay, seg.bx, seg.by);\n if (hit && (!bestHit || hit.t < bestHit.t)) {\n bestHit = hit;\n }\n }\n\n if (!bestHit) {\n // Propagate to edge of optical bench with subtle wave-slope caustic modulation\n let x = ox, y = oy;\n const step = 4.5;\n for (let k = 0; k < 70; k++) {\n x += dx * step;\n y += dy * step;\n if (x < 1 || x >= NX - 1 || y < 1 || y >= NY - 1) {\n path.push({ x, y });\n break;\n }\n const ix = Math.floor(x), iy = Math.floor(y);\n const idx = iy * NX + ix;\n if (wallGrid[idx]) {\n path.push({ x, y });\n break;\n }\n const gux = (uCurr[idx + 1] - uCurr[idx - 1]) * 0.5;\n const guy = (uCurr[idx + NX] - uCurr[idx - NX]) * 0.5;\n dx += gux * 0.022 * waveCoupling;\n dy += guy * 0.022 * waveCoupling;\n const l = Math.hypot(dx, dy) || 1;\n dx /= l; dy /= l;\n if ((k & 1) === 0) path.push({ x, y });\n }\n break;\n }\n\n path.push({ x: bestHit.x, y: bestHit.y });\n\n // Orient surface normal against incident vector\n let nx = bestHit.nx;\n let ny = bestHit.ny;\n let cosI = -(dx * nx + dy * ny);\n if (cosI < 0) {\n nx = -nx;\n ny = -ny;\n cosI = -cosI;\n }\n\n // Sample wave ripple normal perturbation at interface\n const hix = Math.max(1, Math.min(NX - 2, Math.floor(bestHit.x)));\n const hiy = Math.max(1, Math.min(NY - 2, Math.floor(bestHit.y)));\n const hIdx = hiy * NX + hix;\n const wavePerturb = (uCurr[hIdx + 1] - uCurr[hIdx - 1]) * 0.045 * waveCoupling;\n\n const n1 = insideMedium ? nGlass : 1.0;\n const n2 = insideMedium ? 1.0 : nGlass;\n const eta = n1 / n2;\n const sin2T = eta * eta * (1.0 - cosI * cosI);\n\n // Record Snell diagnostic if near X-Ray Loupe\n const distToLoupe = Math.hypot(bestHit.x - loupeGX, bestHit.y - loupeGY);\n if (distToLoupe < closestSnellDist && bIdx === 8) {\n closestSnellDist = distToLoupe;\n const thetaI = Math.acos(Math.min(1, cosI)) * (180 / Math.PI);\n const thetaT = sin2T <= 1.0 ? Math.asin(Math.min(1, Math.sqrt(sin2T))) * (180 / Math.PI) : 90;\n state.loupe.snellInfo = {\n x: bestHit.x, y: bestHit.y,\n nx, ny,\n ix: dx, iy: dy,\n thetaI, thetaT,\n tir: sin2T > 1.0\n };\n }\n\n if (sin2T > 1.0) {\n // Total Internal Reflection (TIR)\n dx = dx + 2 * cosI * nx;\n dy = dy + 2 * cosI * ny;\n } else {\n // Exact Vector Snell's Law Refraction\n const cosT = Math.sqrt(1.0 - sin2T);\n dx = eta * dx + (eta * cosI - cosT) * nx + wavePerturb * ny;\n dy = eta * dy + (eta * cosI - cosT) * ny - wavePerturb * nx;\n insideMedium = !insideMedium;\n }\n const len = Math.hypot(dx, dy) || 1;\n dx /= len; dy /= len;\n ox = bestHit.x + dx * 0.25;\n oy = bestHit.y + dy * 0.25;\n }\n }\n\n rays.push({ band, path });\n }\n }\n\n state.activeRayCount = rays.length;\n return rays;\n }\n\n // ============================================================================\n // 8. RENDERING PIPELINE (32-bit Field Buffer + Retina Ray/Caustic + X-Ray Loupe)\n // ============================================================================\n const simCanvas = document.getElementById('simCanvas');\n const ctx = simCanvas.getContext('2d');\n\n function renderFieldToOffscreen() {\n const layer = state.layer;\n for (let y = 0; y < NY; y++) {\n const row = y * NX;\n for (let x = 0; x < NX; x++) {\n const i = row + x;\n if (wallGrid[i]) {\n // Anodized dark titanium barrier\n fieldPixels32[i] = (255 << 24) | (38 << 16) | (28 << 8) | 22;\n continue;\n }\n\n const u = uCurr[i];\n const rms = Math.sqrt(uRMS[i]);\n const n = iorGrid[i];\n const glassTint = Math.max(0, (n - 1.0) * 34);\n\n let r = 5, g = 8, b = 15;\n\n if (layer === 'coupled' || layer === 'wave') {\n // Pseudo-3D wave shading using height + directional light derivative\n const ux = (x < NX - 1 ? uCurr[i + 1] : u) - u;\n const uy = (y < NY - 1 ? uCurr[i + NX] : u) - u;\n const spec = Math.max(0, (ux + uy) * 52);\n\n if (u >= 0) {\n const v = Math.min(1.0, u * 0.85);\n r = 6 + v * 28 + spec * 0.9 + glassTint * 0.4;\n g = 10 + v * 155 + spec * 1.1 + glassTint * 0.8;\n b = 18 + v * 235 + spec * 1.3 + glassTint * 1.3;\n } else {\n const v = Math.min(1.0, -u * 0.85);\n r = 6 + v * 95 + spec * 0.5 + glassTint * 0.4;\n g = 9 + v * 28 + spec * 0.6 + glassTint * 0.8;\n b = 18 + v * 115 + spec * 0.9 + glassTint * 1.3;\n }\n // Subtle RMS interference glow\n r += rms * 28;\n g += rms * 42;\n b += rms * 55;\n } else if (layer === 'rms') {\n // Time-integrated standing wave interference energy ∫ψ²dt\n const v = Math.min(1.0, rms * 1.65);\n const v2 = v * v;\n r = 6 + v * 45 + v2 * 210;\n g = 9 + v * 165 + v2 * 75;\n b = 18 + v * 230 - v2 * 50;\n } else if (layer === 'caustics') {\n r = 5 + glassTint * 0.35;\n g = 8 + glassTint * 0.65;\n b = 14 + glassTint * 1.10;\n }\n\n const R = r > 255 ? 255 : (r < 0 ? 0 : r | 0);\n const G = g > 255 ? 255 : (g < 0 ? 0 : g | 0);\n const B = b > 255 ? 255 : (b < 0 ? 0 : b | 0);\n fieldPixels32[i] = (255 << 24) | (B << 16) | (G << 8) | R;\n }\n }\n fieldCtx.putImageData(fieldImg, 0, 0);\n }\n\n function renderBench() {\n const rect = simCanvas.getBoundingClientRect();\n const dpr = Math.min(window.devicePixelRatio || 1, 2);\n const W = Math.round(rect.width * dpr);\n const H = Math.round(rect.height * dpr);\n if (simCanvas.width !== W || simCanvas.height !== H) {\n simCanvas.width = W;\n simCanvas.height = H;\n }\n\n ctx.save();\n ctx.scale(dpr, dpr);\n const cw = rect.width;\n const ch = rect.height;\n const sx = cw / NX;\n const sy = ch / NY;\n\n // 1. Draw Upsampled Wave PDE Field\n renderFieldToOffscreen();\n ctx.imageSmoothingEnabled = true;\n ctx.imageSmoothingQuality = 'high';\n ctx.drawImage(fieldCanvas, 0, 0, cw, ch);\n\n // Subtle precision optical table grid lines\n ctx.strokeStyle = 'rgba(148, 163, 184, 0.045)';\n ctx.lineWidth = 1;\n const gridStep = 40;\n ctx.beginPath();\n for (let x = gridStep; x < cw; x += gridStep) {\n ctx.moveTo(x, 0); ctx.lineTo(x, ch);\n }\n for (let y = gridStep; y < ch; y += gridStep) {\n ctx.moveTo(0, y); ctx.lineTo(cw, y);\n }\n ctx.stroke();\n\n // 2. Trace & Render Spectral Rays and Caustics (Additive Linear Blending)\n const rays = traceSpectralRays();\n if (state.layer !== 'wave' && state.layer !== 'rms' && rays.length > 0) {\n ctx.save();\n ctx.globalCompositeOperation = 'lighter';\n ctx.lineCap = 'round';\n ctx.lineJoin = 'round';\n\n for (let i = 0; i < rays.length; i++) {\n const { band, path } = rays[i];\n if (path.length < 2) continue;\n\n // Outer spectral bloom pass\n ctx.strokeStyle = band.rgbaGlow;\n ctx.lineWidth = state.scene === 'ellipse' ? 2.2 : 3.2;\n ctx.beginPath();\n ctx.moveTo(path[0].x * sx, path[0].y * sy);\n for (let k = 1; k < path.length; k++) {\n ctx.lineTo(path[k].x * sx, path[k].y * sy);\n }\n ctx.stroke();\n\n // Inner high-intensity photon filament\n ctx.strokeStyle = band.rgbaCore;\n ctx.lineWidth = 1.05;\n ctx.stroke();\n }\n ctx.restore();\n }\n\n // 3. Draw Optical Bench Hardware & Geometries\n drawOpticalElements(ctx, sx, sy, cw, ch);\n\n // 4. Draw Chladni Quartz Sand Grains (Scene 05)\n if (state.scene === 'chladni') {\n ctx.fillStyle = '#FDE68A';\n for (let i = 0; i < NUM_PARTICLES; i++) {\n const px = sandX[i] * sx;\n const py = sandY[i] * sy;\n ctx.fillRect(px - 1.1, py - 1.1, 2.2, 2.2);\n }\n }\n\n // 5. Draw Interferometer Probes P1 & P2\n drawProbes(ctx, sx, sy);\n\n // 6. Draw Multi-Scale X-Ray Reality Loupe\n if (state.loupe.enabled) {\n drawXRayLoupe(ctx, sx, sy, cw, ch);\n }\n\n ctx.restore();\n }\n\n function drawOpticalElements(ctx, sx, sy, cw, ch) {\n // A. Equilateral Flint-Glass Prism\n if (state.prism.active) {\n const pv = getPrismVertices(state.prism);\n ctx.save();\n ctx.beginPath();\n ctx.moveTo(pv[0].x * sx, pv[0].y * sy);\n ctx.lineTo(pv[1].x * sx, pv[1].y * sy);\n ctx.lineTo(pv[2].x * sx, pv[2].y * sy);\n ctx.closePath();\n\n const grad = ctx.createLinearGradient(\n (state.prism.x - 30) * sx, (state.prism.y - 30) * sy,\n (state.prism.x + 30) * sx, (state.prism.y + 30) * sy\n );\n grad.addColorStop(0, 'rgba(125, 211, 252, 0.18)');\n grad.addColorStop(0.5, 'rgba(56, 189, 248, 0.07)');\n grad.addColorStop(1, 'rgba(167, 139, 250, 0.20)');\n ctx.fillStyle = grad;\n ctx.fill();\n\n ctx.strokeStyle = 'rgba(186, 230, 253, 0.82)';\n ctx.lineWidth = 1.6;\n ctx.stroke();\n\n // Rotation dial ring & label\n const cx = state.prism.x * sx;\n const cy = state.prism.y * sy;\n ctx.strokeStyle = 'rgba(56, 189, 248, 0.24)';\n ctx.setLineDash([3, 4]);\n ctx.beginPath();\n ctx.arc(cx, cy, state.prism.radius * sx * 1.08, 0, Math.PI * 2);\n ctx.stroke();\n ctx.setLineDash([]);\n\n // Rotation handle knob at vertex 0\n ctx.fillStyle = '#38BDF8';\n ctx.beginPath();\n ctx.arc(pv[0].x * sx, pv[0].y * sy, 4.5, 0, Math.PI * 2);\n ctx.fill();\n\n ctx.fillStyle = 'rgba(241, 245, 249, 0.85)';\n ctx.font = '600 10px \"JetBrains Mono\", monospace';\n ctx.fillText(`PRISM n=${state.n0.toFixed(2)}`, cx - 34, cy + state.prism.radius * sy + 16);\n ctx.restore();\n }\n\n // B. Biconvex Crystal Lens\n if (state.lens.active) {\n const segs = getLensSegments(state.lens);\n ctx.save();\n ctx.beginPath();\n ctx.moveTo(segs[0].ax * sx, segs[0].ay * sy);\n for (let i = 0; i < segs.length; i++) {\n ctx.lineTo(segs[i].bx * sx, segs[i].by * sy);\n }\n ctx.closePath();\n\n const lx = state.lens.x * sx;\n const ly = state.lens.y * sy;\n const lGrad = ctx.createLinearGradient(lx - 20, ly - 50, lx + 20, ly + 50);\n lGrad.addColorStop(0, 'rgba(56, 189, 248, 0.22)');\n lGrad.addColorStop(0.5, 'rgba(255, 255, 255, 0.08)');\n lGrad.addColorStop(1, 'rgba(56, 189, 248, 0.22)');\n ctx.fillStyle = lGrad;\n ctx.fill();\n\n ctx.strokeStyle = 'rgba(125, 211, 252, 0.88)';\n ctx.lineWidth = 1.6;\n ctx.stroke();\n\n // Optical axis & handle\n const topX = lx - Math.sin(state.lens.angle) * state.lens.ry * sy;\n const topY = ly - Math.cos(state.lens.angle) * state.lens.ry * sy;\n ctx.fillStyle = '#38BDF8';\n ctx.beginPath();\n ctx.arc(topX, topY, 4.5, 0, Math.PI * 2);\n ctx.fill();\n\n ctx.fillStyle = 'rgba(241, 245, 249, 0.85)';\n ctx.font = '600 10px \"JetBrains Mono\", monospace';\n ctx.fillText(`LENS f=${Math.round(48 / (state.n0 - 1))}mm`, lx - 34, ly + state.lens.ry * sy + 16);\n ctx.restore();\n }\n\n // C. Elliptical Whispering Gallery Overlay\n if (state.ellipse.active) {\n const cx = state.ellipse.cx * sx;\n const cy = state.ellipse.cy * sy;\n const rx = state.ellipse.a * sx;\n const ry = (state.ellipse.b || state.ellipse.a * 0.78) * sy;\n const cDist = state.ellipse.a * state.ellipse.e;\n const f1x = (state.ellipse.cx - cDist) * sx;\n const f2x = (state.ellipse.cx + cDist) * sx;\n\n ctx.save();\n ctx.strokeStyle = '#38BDF8';\n ctx.lineWidth = 2.2;\n ctx.beginPath();\n ctx.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2);\n ctx.stroke();\n\n // Sample Stationary Path Verification Triangle: Source -> Wall -> F2\n const sampleAng = state.simTime * 0.45;\n const wx = cx + Math.cos(sampleAng) * rx;\n const wy = cy + Math.sin(sampleAng) * ry;\n ctx.strokeStyle = 'rgba(245, 158, 11, 0.55)';\n ctx.setLineDash([4, 4]);\n ctx.lineWidth = 1.3;\n ctx.beginPath();\n ctx.moveTo(f1x, cy);\n ctx.lineTo(wx, wy);\n ctx.lineTo(f2x, cy);\n ctx.stroke();\n ctx.setLineDash([]);\n\n // Focus markers F1 and F2\n ctx.strokeStyle = '#F59E0B';\n ctx.lineWidth = 1.5;\n ctx.beginPath();\n ctx.arc(f1x, cy, 8, 0, Math.PI * 2);\n ctx.moveTo(f2x - 10, cy); ctx.lineTo(f2x + 10, cy);\n ctx.moveTo(f2x, cy - 10); ctx.lineTo(f2x, cy + 10);\n ctx.stroke();\n\n ctx.fillStyle = '#FCD34D';\n ctx.font = '700 10.5px \"JetBrains Mono\", monospace';\n ctx.fillText('FOCUS F₁ (Source)', f1x - 42, cy - 14);\n ctx.fillText('FOCUS F₂ (Conjugate)', f2x - 48, cy - 14);\n ctx.fillText(`|F₁P| + |PF₂| = ${(2 * state.ellipse.a).toFixed(1)} (Stationary)`, (wx - 58), wy + (wy < cy ? -10 : 16));\n ctx.restore();\n }\n\n // D. Young's Double-Slit Detector Screen & Live Intensity Curve Overlay\n if (state.slit.active) {\n const scrX = state.slit.screenX * sx;\n ctx.save();\n ctx.strokeStyle = 'rgba(245, 158, 11, 0.45)';\n ctx.setLineDash([4, 4]);\n ctx.beginPath();\n ctx.moveTo(scrX, 16);\n ctx.lineTo(scrX, ch - 16);\n ctx.stroke();\n ctx.setLineDash([]);\n\n // Draw live emergent intensity profile I(y) right along the detector screen!\n ctx.strokeStyle = '#38BDF8';\n ctx.lineWidth = 2.0;\n ctx.beginPath();\n const gx = Math.min(NX - 3, Math.round(state.slit.screenX));\n for (let y = 12; y < NY - 12; y++) {\n const rms = Math.sqrt(uRMS[y * NX + gx]);\n const plotX = scrX + Math.min(68, rms * 52);\n const plotY = y * sy;\n if (y === 12) ctx.moveTo(plotX, plotY);\n else ctx.lineTo(plotX, plotY);\n }\n ctx.stroke();\n\n ctx.fillStyle = '#38BDF8';\n ctx.font = '700 10px \"JetBrains Mono\", monospace';\n ctx.fillText('DETECTOR I(y)', scrX + 6, 26);\n ctx.restore();\n }\n\n // E. Schwarzschild Black Hole / Einstein Ring Horizons\n if (state.bh.active) {\n const bx = state.bh.x * sx;\n const by = state.bh.y * sy;\n const rsPx = state.bh.rs * sx;\n\n ctx.save();\n // Event Horizon (r = rs)\n const bhGrad = ctx.createRadialGradient(bx, by, rsPx * 0.2, bx, by, rsPx * 2.6);\n bhGrad.addColorStop(0, '#000000');\n bhGrad.addColorStop(0.38, '#020409');\n bhGrad.addColorStop(0.65, 'rgba(245, 158, 11, 0.22)');\n bhGrad.addColorStop(1, 'rgba(56, 189, 248, 0.0)');\n ctx.fillStyle = bhGrad;\n ctx.beginPath();\n ctx.arc(bx, by, rsPx * 2.6, 0, Math.PI * 2);\n ctx.fill();\n\n // Photon Sphere (r = 1.5 rs)\n ctx.strokeStyle = 'rgba(245, 158, 11, 0.75)';\n ctx.setLineDash([3, 3]);\n ctx.lineWidth = 1.4;\n ctx.beginPath();\n ctx.arc(bx, by, rsPx * 1.5, 0, Math.PI * 2);\n ctx.stroke();\n ctx.setLineDash([]);\n\n ctx.fillStyle = '#FCD34D';\n ctx.font = '700 10px \"JetBrains Mono\", monospace';\n ctx.fillText(`PHOTON SPHERE 1.5rₛ`, bx - 52, by - rsPx * 1.5 - 8);\n ctx.restore();\n }\n\n // F. Laser Emitter & Wave Source Markers\n if (state.laser.active && state.scene !== 'ellipse') {\n const lx = state.laser.x * sx;\n const ly = state.laser.y * sy;\n ctx.save();\n ctx.translate(lx, ly);\n ctx.rotate(state.laser.angle);\n ctx.fillStyle = '#1E293B';\n ctx.strokeStyle = '#38BDF8';\n ctx.lineWidth = 1.5;\n ctx.beginPath();\n ctx.roundRect(-14, -9, 24, 18, 4);\n ctx.fill();\n ctx.stroke();\n ctx.fillStyle = '#F8FAFC';\n ctx.beginPath();\n ctx.arc(8, 0, 3, 0, Math.PI * 2);\n ctx.fill();\n ctx.restore();\n }\n\n if (state.waveSource.active || state.scene === 'ellipse') {\n const wx = state.waveSource.x * sx;\n const wy = state.waveSource.y * sy;\n ctx.save();\n ctx.strokeStyle = '#38BDF8';\n ctx.fillStyle = 'rgba(56, 189, 248, 0.25)';\n ctx.lineWidth = 1.6;\n ctx.beginPath();\n ctx.arc(wx, wy, 6.5, 0, Math.PI * 2);\n ctx.fill();\n ctx.stroke();\n ctx.restore();\n }\n }\n\n function drawProbes(ctx, sx, sy) {\n for (let i = 0; i < 2; i++) {\n const p = state.probes[i];\n const px = p.x * NX * sx;\n const py = p.y * NY * sy;\n\n ctx.save();\n // Outer pulsing ring proportional to instantaneous wave amplitude\n const pulseR = 11 + Math.min(8, Math.abs(p.amp) * 5);\n ctx.strokeStyle = p.color;\n ctx.globalAlpha = 0.45;\n ctx.lineWidth = 1.5;\n ctx.beginPath();\n ctx.arc(px, py, pulseR, 0, Math.PI * 2);\n ctx.stroke();\n\n ctx.globalAlpha = 1.0;\n ctx.fillStyle = '#090D16';\n ctx.beginPath();\n ctx.arc(px, py, 8, 0, Math.PI * 2);\n ctx.fill();\n ctx.stroke();\n\n ctx.fillStyle = p.color;\n ctx.font = '700 9.5px \"JetBrains Mono\", monospace';\n ctx.textAlign = 'center';\n ctx.textBaseline = 'middle';\n ctx.fillText(p.id, px, py);\n ctx.restore();\n }\n }\n\n // ============================================================================\n // 9. THE MULTI-SCALE X-RAY REALITY LOUPE (\"Hold Up When They Look Closer\")\n // ============================================================================\n function drawXRayLoupe(ctx, sx, sy, cw, ch) {\n const lx = state.loupe.x * cw;\n const ly = state.loupe.y * ch;\n const R = state.loupe.radiusPx;\n const gxCenter = Math.round(state.loupe.x * NX);\n const gyCenter = Math.round(state.loupe.y * NY);\n\n ctx.save();\n\n // 1. Clip circular optical doublet interior\n ctx.beginPath();\n ctx.arc(lx, ly, R, 0, Math.PI * 2);\n ctx.clip();\n\n // Dark blueprint X-Ray background\n ctx.fillStyle = 'rgba(4, 8, 17, 0.92)';\n ctx.fillRect(lx - R, ly - R, R * 2, R * 2);\n\n // 2. Render Magnified Sub-Grid Finite-Difference Stencil & Poynting Flux Vectors\n const spanX = 14;\n const spanY = 14;\n const zoom = 2.15;\n\n // Fine blueprint lattice lines\n ctx.strokeStyle = 'rgba(56, 189, 248, 0.12)';\n ctx.lineWidth = 0.7;\n for (let dy = -spanY; dy <= spanY; dy++) {\n const gy = gyCenter + dy;\n if (gy < 1 || gy >= NY - 1) continue;\n const py = ly + (gy - state.loupe.y * NY) * sy * zoom;\n ctx.beginPath();\n ctx.moveTo(lx - R, py);\n ctx.lineTo(lx + R, py);\n ctx.stroke();\n }\n for (let dx = -spanX; dx <= spanX; dx++) {\n const gx = gxCenter + dx;\n if (gx < 1 || gx >= NX - 1) continue;\n const px = lx + (gx - state.loupe.x * NX) * sx * zoom;\n ctx.beginPath();\n ctx.moveTo(px, ly - R);\n ctx.lineTo(px, ly + R);\n ctx.stroke();\n }\n\n // Discrete PDE nodes + Poynting Energy Flux Vectors S = -c² (∂ₜu) ∇u\n for (let dy = -spanY; dy <= spanY; dy++) {\n const gy = gyCenter + dy;\n if (gy < 2 || gy >= NY - 2) continue;\n for (let dx = -spanX; dx <= spanX; dx++) {\n const gx = gxCenter + dx;\n if (gx < 2 || gx >= NX - 2) continue;\n\n const px = lx + (gx - state.loupe.x * NX) * sx * zoom;\n const py = ly + (gy - state.loupe.y * NY) * sy * zoom;\n if ((px - lx) * (px - lx) + (py - ly) * (py - ly) > R * R) continue;\n\n const idx = gy * NX + gx;\n const u = uCurr[idx];\n const vel = uVel[idx];\n const nLoc = iorGrid[idx];\n\n if (wallGrid[idx]) {\n ctx.fillStyle = 'rgba(244, 63, 94, 0.65)';\n ctx.fillRect(px - 2.5, py - 2.5, 5, 5);\n continue;\n }\n\n // Dielectric glass tint inside loupe\n if (nLoc > 1.03) {\n ctx.fillStyle = 'rgba(56, 189, 248, 0.14)';\n ctx.fillRect(px - sx * zoom * 0.5, py - sy * zoom * 0.5, sx * zoom, sy * zoom);\n }\n\n // Gradient ∇u & Poynting vector S = -vel * ∇u\n const gradX = (uCurr[idx + 1] - uCurr[idx - 1]) * 0.5;\n const gradY = (uCurr[idx + NX] - uCurr[idx - NX]) * 0.5;\n const sxVec = -vel * gradX * 26;\n const syVec = -vel * gradY * 26;\n const vecMag = Math.hypot(sxVec, syVec);\n\n if (vecMag > 0.4) {\n const clampMag = Math.min(13, vecMag * 4.5);\n const vx = (sxVec / vecMag) * clampMag;\n const vy = (syVec / vecMag) * clampMag;\n ctx.strokeStyle = u >= 0 ? 'rgba(56, 189, 248, 0.85)' : 'rgba(245, 158, 11, 0.85)';\n ctx.lineWidth = 1.15;\n ctx.beginPath();\n ctx.moveTo(px, py);\n ctx.lineTo(px + vx, py + vy);\n ctx.stroke();\n }\n\n // Lattice Node Dot\n const nodeR = 1.4 + Math.min(2.6, Math.abs(u) * 1.4);\n ctx.fillStyle = u >= 0 ? '#38BDF8' : '#F59E0B';\n ctx.beginPath();\n ctx.arc(px, py, nodeR, 0, Math.PI * 2);\n ctx.fill();\n }\n }\n\n // 3. If Snell Refraction occurs near Loupe, draw Exact Normal & Angle Arcs!\n const sn = state.loupe.snellInfo;\n if (sn) {\n const snPx = lx + (sn.x - state.loupe.x * NX) * sx * zoom;\n const snPy = ly + (sn.y - state.loupe.y * NY) * sy * zoom;\n if (Math.hypot(snPx - lx, snPy - ly) < R * 0.85) {\n ctx.strokeStyle = '#10B981';\n ctx.setLineDash([3, 3]);\n ctx.lineWidth = 1.4;\n ctx.beginPath();\n ctx.moveTo(snPx - sn.nx * 38, snPy - sn.ny * 38);\n ctx.lineTo(snPx + sn.nx * 38, snPy + sn.ny * 38);\n ctx.stroke();\n ctx.setLineDash([]);\n\n ctx.fillStyle = '#6EE7B7';\n ctx.font = '700 9.5px \"JetBrains Mono\", monospace';\n ctx.fillText(\n sn.tir ? `TIR θᵢ=${sn.thetaI.toFixed(1)}°` : `θᵢ=${sn.thetaI.toFixed(1)}° → θₜ=${sn.thetaT.toFixed(1)}°`,\n snPx + 8,\n snPy - 8\n );\n }\n }\n\n // 4. Internal HUD Telemetry inside X-Ray Loupe\n const cIdx = Math.max(0, Math.min(NCELLS - 1, gyCenter * NX + gxCenter));\n const localU = uCurr[cIdx];\n const localN = iorGrid[cIdx];\n ctx.fillStyle = 'rgba(8, 13, 24, 0.86)';\n ctx.fillRect(lx - R, ly + R - 28, R * 2, 28);\n ctx.fillStyle = '#FCD34D';\n ctx.font = '700 9.5px \"JetBrains Mono\", monospace';\n ctx.textAlign = 'center';\n ctx.fillText(\n `ψ=${localU >= 0 ? '+' : ''}${localU.toFixed(3)} · n=${localN.toFixed(2)} · v=${(1 / localN).toFixed(2)}c₀`,\n lx,\n ly + R - 11\n );\n\n ctx.restore();\n\n // 5. Outer Precision Achromatic Doublet Bevel Ring & Degree Protractor\n ctx.save();\n ctx.strokeStyle = '#F59E0B';\n ctx.lineWidth = 2.2;\n ctx.shadowColor = 'rgba(245, 158, 11, 0.35)';\n ctx.shadowBlur = 14;\n ctx.beginPath();\n ctx.arc(lx, ly, R, 0, Math.PI * 2);\n ctx.stroke();\n ctx.shadowBlur = 0;\n\n // Protractor degree ticks around loupe rim\n ctx.strokeStyle = 'rgba(245, 158, 11, 0.55)';\n ctx.lineWidth = 1;\n for (let deg = 0; deg < 360; deg += 15) {\n const rad = (deg * Math.PI) / 180;\n const rIn = (deg % 45 === 0) ? R - 7 : R - 4;\n ctx.beginPath();\n ctx.moveTo(lx + Math.cos(rad) * rIn, ly + Math.sin(rad) * rIn);\n ctx.lineTo(lx + Math.cos(rad) * R, ly + Math.sin(rad) * R);\n ctx.stroke();\n }\n\n // Top Loupe Header Pill\n ctx.fillStyle = '#0A0E17';\n ctx.strokeStyle = '#F59E0B';\n ctx.lineWidth = 1.2;\n ctx.beginPath();\n ctx.roundRect(lx - 66, ly - R - 11, 132, 18, 9);\n ctx.fill();\n ctx.stroke();\n\n ctx.fillStyle = '#FCD34D';\n ctx.font = '700 9px \"JetBrains Mono\", monospace';\n ctx.textAlign = 'center';\n ctx.textBaseline = 'middle';\n ctx.fillText('2.2× EIKONAL X-RAY', lx, ly - R - 2);\n ctx.restore();\n }\n\n // ============================================================================\n // 10. RIGHT RACK TELEMETRY RENDERING (OSCILLOSCOPE, PHASE SPACE & FFT/FRINGES)\n // ============================================================================\n const scopeCanvas = document.getElementById('scopeCanvas');\n const scopeCtx = scopeCanvas.getContext('2d');\n const phaseCanvas = document.getElementById('phaseCanvas');\n const phaseCtx = phaseCanvas.getContext('2d');\n const spectrumCanvas = document.getElementById('spectrumCanvas');\n const specCtx = spectrumCanvas.getContext('2d');\n\n function renderTelemetryCanvases() {\n const p1 = state.probes[0];\n const p2 = state.probes[1];\n const ptr = state.probePtr;\n\n // 1. Dual-Trace Oscilloscope\n const sw = scopeCanvas.width;\n const sh = scopeCanvas.height;\n scopeCtx.fillStyle = '#050810';\n scopeCtx.fillRect(0, 0, sw, sh);\n\n // Graticule\n scopeCtx.strokeStyle = 'rgba(148, 163, 184, 0.08)';\n scopeCtx.lineWidth = 1;\n scopeCtx.beginPath();\n scopeCtx.moveTo(0, sh * 0.5); scopeCtx.lineTo(sw, sh * 0.5);\n scopeCtx.moveTo(sw * 0.5, 0); scopeCtx.lineTo(sw * 0.5, sh);\n scopeCtx.stroke();\n\n for (let pIdx = 1; pIdx >= 0; pIdx--) {\n const pr = state.probes[pIdx];\n scopeCtx.strokeStyle = pr.color;\n scopeCtx.lineWidth = 1.5;\n scopeCtx.beginPath();\n for (let i = 0; i < 256; i++) {\n const sampleIdx = (ptr + i) & 255;\n const val = pr.history[sampleIdx];\n const x = (i / 255) * sw;\n const y = sh * 0.5 - val * (sh * 0.28);\n if (i === 0) scopeCtx.moveTo(x, y);\n else scopeCtx.lineTo(x, y);\n }\n scopeCtx.stroke();\n }\n\n // 2. Phase Space Portrait (ψ, ∂ₜψ)\n const pw = phaseCanvas.width;\n const ph = phaseCanvas.height;\n phaseCtx.fillStyle = '#050810';\n phaseCtx.fillRect(0, 0, pw, ph);\n phaseCtx.strokeStyle = 'rgba(148, 163, 184, 0.08)';\n phaseCtx.beginPath();\n phaseCtx.moveTo(0, ph * 0.5); phaseCtx.lineTo(pw, ph * 0.5);\n phaseCtx.moveTo(pw * 0.5, 0); phaseCtx.lineTo(pw * 0.5, ph);\n phaseCtx.stroke();\n\n phaseCtx.strokeStyle = '#38BDF8';\n phaseCtx.lineWidth = 1.3;\n phaseCtx.beginPath();\n for (let i = 0; i < 128; i++) {\n const sampleIdx = (ptr + 128 + i) & 255;\n const u = p1.history[sampleIdx];\n const v = p1.histVel[sampleIdx];\n const x = pw * 0.5 + u * 26;\n const y = ph * 0.5 - v * 65;\n if (i === 0) phaseCtx.moveTo(x, y);\n else phaseCtx.lineTo(x, y);\n }\n phaseCtx.stroke();\n\n // 3. Detector Screen Fringe Integral (Double Slit) OR Live Frequency Spectrum\n const kw = spectrumCanvas.width;\n const kh = spectrumCanvas.height;\n specCtx.fillStyle = '#050810';\n specCtx.fillRect(0, 0, kw, kh);\n\n if (state.scene === 'slit') {\n document.getElementById('spectrumTitle').innerHTML = '<span class=\"indicator\" style=\"background:var(--accent-amber)\"></span>FRAUNHOFER FRINGE INTEGRAL I(y)';\n document.getElementById('spectrumBadge').textContent = 'PDE vs THEORY';\n const gx = Math.min(NX - 3, Math.round(state.slit.screenX));\n const L = Math.max(20, state.slit.screenX - state.slit.x);\n const lambdaGrid = 28.0 / Math.max(1.5, state.waveFreq); // Effective PDE wavelength\n\n // Analytical Fraunhofer curve: cos²(π a sinθ / λ) sinc²(π d sinθ / λ)\n specCtx.strokeStyle = '#F59E0B';\n specCtx.setLineDash([3, 3]);\n specCtx.lineWidth = 1.4;\n specCtx.beginPath();\n for (let x = 0; x < kw; x++) {\n const gy = (x / kw) * NY;\n const dy = gy - NY * 0.5;\n const sinTheta = dy / Math.hypot(L, dy);\n const alpha = (Math.PI * state.slit.width * sinTheta) / lambdaGrid;\n const beta = (Math.PI * state.slit.sep * sinTheta) / lambdaGrid;\n const sinc = Math.abs(alpha) < 1e-4 ? 1.0 : Math.sin(alpha) / alpha;\n const theoryI = Math.cos(beta) * Math.cos(beta) * sinc * sinc;\n const py = kh - 8 - theoryI * (kh - 20);\n if (x === 0) specCtx.moveTo(x, py);\n else specCtx.lineTo(x, py);\n }\n specCtx.stroke();\n specCtx.setLineDash([]);\n\n // Measured PDE RMS Intensity along Detector Screen\n specCtx.strokeStyle = '#38BDF8';\n specCtx.lineWidth = 1.8;\n specCtx.beginPath();\n let maxRms = 0.01;\n for (let y = 10; y < NY - 10; y++) {\n const r = Math.sqrt(uRMS[y * NX + gx]);\n if (r > maxRms) maxRms = r;\n }\n for (let x = 0; x < kw; x++) {\n const gy = Math.max(1, Math.min(NY - 2, Math.round((x / kw) * NY)));\n const r = Math.sqrt(uRMS[gy * NX + gx]) / maxRms;\n const py = kh - 8 - r * (kh - 20);\n if (x === 0) specCtx.moveTo(x, py);\n else specCtx.lineTo(x, py);\n }\n specCtx.stroke();\n } else {\n document.getElementById('spectrumTitle').innerHTML = '<span class=\"indicator\" style=\"background:var(--accent-amber)\"></span>DFT HARMONIC SPECTRUM (P1)';\n document.getElementById('spectrumBadge').textContent = '48-BIN DISCRETE FT';\n const numBins = 44;\n const barW = (kw - 16) / numBins;\n for (let k = 1; k <= numBins; k++) {\n let re = 0, im = 0;\n const freqK = k * 0.45;\n for (let n = 0; n < 128; n++) {\n const sample = p1.history[(ptr + 128 + n) & 255];\n const ang = (2 * Math.PI * freqK * n) / 128;\n re += sample * Math.cos(ang);\n im -= sample * Math.sin(ang);\n }\n const mag = Math.min(1.0, Math.hypot(re, im) / 26);\n const bh = Math.max(2, mag * (kh - 18));\n const bx = 8 + (k - 1) * barW;\n specCtx.fillStyle = mag > 0.45 ? '#F59E0B' : '#38BDF8';\n specCtx.fillRect(bx, kh - 6 - bh, barW - 2, bh);\n }\n }\n\n // 4. Numerical Readouts (every 3rd frame to keep DOM crisp)\n if (state.frameCount % 3 === 0) {\n document.getElementById('valP1Amp').textContent = (p1.amp >= 0 ? '+' : '') + p1.amp.toFixed(3);\n document.getElementById('valP1Rms').textContent = p1.rms.toFixed(3);\n document.getElementById('valP1Ior').textContent = p1.ior.toFixed(3);\n document.getElementById('proofEnergy').textContent = `H = ${state.totalEnergy.toFixed(2)} J`;\n document.getElementById('proofRays').textContent = `${state.activeRayCount} Rays`;\n document.getElementById('fpsReadout').textContent = `${state.fps.toFixed(1)} FPS`;\n document.getElementById('loupeCoordReadout').textContent =\n `LOUPE (${Math.round(state.loupe.x * NX)},${Math.round(state.loupe.y * NY)})`;\n\n // Compute instantaneous cross-correlation phase difference Δφ between P1 and P2\n let dot = 0, n1 = 0, n2 = 0;\n for (let i = 0; i < 64; i++) {\n const idx = (ptr + 192 + i) & 255;\n const a = p1.history[idx], b = p2.history[idx];\n dot += a * b; n1 += a * a; n2 += b * b;\n }\n const cosPhi = (n1 > 1e-5 && n2 > 1e-5) ? Math.max(-1, Math.min(1, dot / Math.sqrt(n1 * n2))) : 1;\n const dPhiPi = Math.acos(cosPhi) / Math.PI;\n document.getElementById('phaseDiffReadout').textContent = `Δφ = ${dPhiPi.toFixed(2)}π rad`;\n }\n }\n\n // ============================================================================\n // 11. REAL-TIME WEB AUDIO PHYSICAL SONIFICATION (Coupled to Probe P1)\n // ============================================================================\n const audioEngine = {\n ctx: null,\n enabled: false,\n osc1: null,\n osc2: null,\n oscSub: null,\n gainNode: null,\n filterNode: null,\n\n toggle() {\n if (!this.ctx) {\n const AudioCtx = window.AudioContext || window.webkitAudioContext;\n this.ctx = new AudioCtx();\n this.osc1 = this.ctx.createOscillator();\n this.osc2 = this.ctx.createOscillator();\n this.oscSub = this.ctx.createOscillator();\n this.gainNode = this.ctx.createGain();\n this.filterNode = this.ctx.createBiquadFilter();\n\n this.osc1.type = 'sine';\n this.osc2.type = 'triangle';\n this.oscSub.type = 'sine';\n\n this.filterNode.type = 'lowpass';\n this.filterNode.frequency.value = 1100;\n this.filterNode.Q.value = 3.5;\n\n this.gainNode.gain.value = 0.0;\n\n this.osc1.connect(this.filterNode);\n this.osc2.connect(this.filterNode);\n this.oscSub.connect(this.filterNode);\n this.filterNode.connect(this.gainNode);\n this.gainNode.connect(this.ctx.destination);\n\n this.osc1.start();\n this.osc2.start();\n this.oscSub.start();\n }\n\n if (this.ctx.state === 'suspended') {\n this.ctx.resume();\n }\n\n this.enabled = !this.enabled;\n const btn = document.getElementById('btnAudio');\n btn.classList.toggle('active-emerald', this.enabled);\n document.getElementById('audioLabel').textContent = this.enabled ? 'AUDIO: LIVE' : 'AUDIO PROBE';\n\n if (!this.enabled && this.gainNode) {\n this.gainNode.gain.setTargetAtTime(0.0, this.ctx.currentTime, 0.04);\n } else {\n this.triggerPing(440);\n }\n },\n\n updateFromField() {\n if (!this.enabled || !this.ctx) return;\n const p1 = state.probes[0];\n const p2 = state.probes[1];\n const now = this.ctx.currentTime;\n\n const baseFreq = 110 + state.waveFreq * 36;\n const fmMod = p1.amp * 28;\n this.osc1.frequency.setTargetAtTime(baseFreq + fmMod, now, 0.015);\n this.osc2.frequency.setTargetAtTime(baseFreq * 1.498 + p2.amp * 18, now, 0.015);\n this.oscSub.frequency.setTargetAtTime(baseFreq * 0.5, now, 0.02);\n\n // Gain is directly driven by local RMS wave energy at Probe P1!\n // In a dark destructive interference fringe, p1.rms -> 0, silencing the tone!\n const targetGain = Math.min(0.18, p1.rms * 0.14 + Math.abs(p1.amp) * 0.04);\n this.gainNode.gain.setTargetAtTime(targetGain, now, 0.025);\n this.filterNode.frequency.setTargetAtTime(380 + p1.rms * 1600, now, 0.03);\n },\n\n triggerPing(freq = 528) {\n if (!this.enabled || !this.ctx) return;\n const osc = this.ctx.createOscillator();\n const g = this.ctx.createGain();\n osc.type = 'sine';\n osc.frequency.value = freq;\n g.gain.setValueAtTime(0.11, this.ctx.currentTime);\n g.gain.exponentialRampToValueAtTime(0.0001, this.ctx.currentTime + 0.38);\n osc.connect(g);\n g.connect(this.ctx.destination);\n osc.start();\n osc.stop(this.ctx.currentTime + 0.4);\n }\n };\n\n // ============================================================================\n // 12. DIRECT MANIPULATION & INTERACTION CONTROLLER\n // ============================================================================\n let dragTarget = null;\n let isPointerDown = false;\n\n function canvasToGrid(clientX, clientY) {\n const rect = simCanvas.getBoundingClientRect();\n const nx = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));\n const ny = Math.max(0, Math.min(1, (clientY - rect.top) / rect.height));\n return { nx, ny, gx: nx * NX, gy: ny * NY, px: clientX - rect.left, py: clientY - rect.top, rect };\n }\n\n simCanvas.addEventListener('pointerdown', (e) => {\n isPointerDown = true;\n simCanvas.setPointerCapture(e.pointerId);\n const pos = canvasToGrid(e.clientX, e.clientY);\n const sx = pos.rect.width / NX;\n const sy = pos.rect.height / NY;\n\n // 1. Check Probes P1 & P2\n for (let i = 0; i < 2; i++) {\n const p = state.probes[i];\n if (Math.hypot(pos.gx - p.x * NX, pos.gy - p.y * NY) < 8) {\n dragTarget = { type: 'probe', index: i };\n return;\n }\n }\n\n // 2. Check X-Ray Loupe Rim or Header\n if (state.loupe.enabled) {\n const lx = state.loupe.x * pos.rect.width;\n const ly = state.loupe.y * pos.rect.height;\n const distPx = Math.hypot(pos.px - lx, pos.py - ly);\n if (Math.abs(distPx - state.loupe.radiusPx) < 18 || (Math.abs(pos.px - lx) < 68 && Math.abs(pos.py - (ly - state.loupe.radiusPx)) < 16)) {\n dragTarget = { type: 'loupe' };\n return;\n }\n }\n\n // 3. Check Prism Vertex Handle (Rotate) or Body (Translate)\n if (state.prism.active) {\n const pv = getPrismVertices(state.prism);\n if (Math.hypot(pos.gx - pv[0].x, pos.gy - pv[0].y) < 9) {\n dragTarget = { type: 'prismRotate' };\n return;\n }\n if (Math.hypot(pos.gx - state.prism.x, pos.gy - state.prism.y) < state.prism.radius) {\n dragTarget = { type: 'prismMove', dx: pos.gx - state.prism.x, dy: pos.gy - state.prism.y };\n return;\n }\n }\n\n // 4. Check Lens Top Handle (Rotate) or Body (Translate)\n if (state.lens.active) {\n const topGX = state.lens.x - Math.sin(state.lens.angle) * state.lens.ry;\n const topGY = state.lens.y - Math.cos(state.lens.angle) * state.lens.ry;\n if (Math.hypot(pos.gx - topGX, pos.gy - topGY) < 9) {\n dragTarget = { type: 'lensRotate' };\n return;\n }\n if (pointInLens(pos.gx, pos.gy, state.lens) || Math.hypot(pos.gx - state.lens.x, pos.gy - state.lens.y) < 18) {\n dragTarget = { type: 'lensMove', dx: pos.gx - state.lens.x, dy: pos.gy - state.lens.y };\n return;\n }\n }\n\n // 5. Check Black Hole Singularity\n if (state.bh.active && Math.hypot(pos.gx - state.bh.x, pos.gy - state.bh.y) < 22) {\n dragTarget = { type: 'bhMove' };\n return;\n }\n\n // 6. Check Wave Source / Focus F1\n if ((state.waveSource.active || state.scene === 'ellipse') && Math.hypot(pos.gx - state.waveSource.x, pos.gy - state.waveSource.y) < 11) {\n dragTarget = { type: 'waveSource' };\n return;\n }\n\n // 7. Check Laser Emitter\n if (state.laser.active && state.scene !== 'ellipse' && Math.hypot(pos.gx - state.laser.x, pos.gy - state.laser.y) < 13) {\n dragTarget = { type: 'laserMove' };\n return;\n }\n\n // 8. Check Double-Slit Barrier\n if (state.slit.active && Math.abs(pos.gx - state.slit.x) < 9) {\n dragTarget = { type: 'slitAdjust' };\n return;\n }\n\n // 9. Otherwise: Apply Sandbox Brush or Drop Coherent Wave Impulse\n dragTarget = { type: 'fieldBrush' };\n applyFieldBrush(pos.gx, pos.gy);\n });\n\n simCanvas.addEventListener('pointermove', (e) => {\n const pos = canvasToGrid(e.clientX, e.clientY);\n if (!isPointerDown || !dragTarget) {\n if (e.shiftKey && state.loupe.enabled) {\n state.loupe.x = pos.nx;\n state.loupe.y = pos.ny;\n }\n return;\n }\n\n const t = dragTarget.type;\n if (t === 'probe') {\n state.probes[dragTarget.index].x = Math.max(0.04, Math.min(0.96, pos.nx));\n state.probes[dragTarget.index].y = Math.max(0.05, Math.min(0.95, pos.ny));\n } else if (t === 'loupe') {\n state.loupe.x = Math.max(0.08, Math.min(0.92, pos.nx));\n state.loupe.y = Math.max(0.10, Math.min(0.90, pos.ny));\n } else if (t === 'prismMove') {\n state.prism.x = Math.max(36, Math.min(NX - 36, pos.gx - dragTarget.dx));\n state.prism.y = Math.max(36, Math.min(NY - 36, pos.gy - dragTarget.dy));\n rebuildMediumGrid();\n } else if (t === 'prismRotate') {\n state.prism.angle = Math.atan2(pos.gy - state.prism.y, pos.gx - state.prism.x) + Math.PI / 2;\n rebuildMediumGrid();\n } else if (t === 'lensMove') {\n state.lens.x = Math.max(30, Math.min(NX - 30, pos.gx - dragTarget.dx));\n state.lens.y = Math.max(36, Math.min(NY - 36, pos.gy - dragTarget.dy));\n rebuildMediumGrid();\n } else if (t === 'lensRotate') {\n state.lens.angle = Math.atan2(state.lens.x - pos.gx, state.lens.y - pos.gy);\n rebuildMediumGrid();\n } else if (t === 'bhMove') {\n state.bh.x = Math.max(35, Math.min(NX - 35, pos.gx));\n state.bh.y = Math.max(35, Math.min(NY - 35, pos.gy));\n rebuildMediumGrid();\n } else if (t === 'waveSource') {\n state.waveSource.x = Math.max(12, Math.min(NX - 12, pos.gx));\n state.waveSource.y = Math.max(12, Math.min(NY - 12, pos.gy));\n if (state.scene === 'ellipse') {\n triggerWaveImpulse(state.waveSource.x, state.waveSource.y, 5.5, 3.8);\n }\n } else if (t === 'laserMove') {\n state.laser.y = Math.max(20, Math.min(NY - 20, pos.gy));\n state.laser.angle = Math.max(-0.55, Math.min(0.55, (pos.gx - state.laser.x) * 0.012 - 0.15));\n } else if (t === 'slitAdjust') {\n state.slit.sep = Math.max(14, Math.min(68, Math.abs(pos.gy - NY * 0.5) * 2));\n document.getElementById('sliderSceneParam').value = state.slit.sep;\n document.getElementById('lblSceneParamVal').textContent = state.slit.sep.toFixed(0);\n rebuildMediumGrid();\n } else if (t === 'fieldBrush') {\n applyFieldBrush(pos.gx, pos.gy);\n }\n });\n\n window.addEventListener('pointerup', () => {\n isPointerDown = false;\n dragTarget = null;\n });\n\n function applyFieldBrush(gx, gy) {\n if (state.scene === 'sandbox' && state.sandboxBrush !== 'ripple') {\n const r = Math.round(6 + state.sceneParam * 10);\n const minX = Math.max(2, Math.floor(gx - r));\n const maxX = Math.min(NX - 3, Math.ceil(gx + r));\n const minY = Math.max(2, Math.floor(gy - r));\n const maxY = Math.min(NY - 3, Math.ceil(gy + r));\n for (let y = minY; y <= maxY; y++) {\n for (let x = minX; x <= maxX; x++) {\n if ((x - gx) * (x - gx) + (y - gy) * (y - gy) <= r * r) {\n const idx = y * NX + x;\n if (state.sandboxBrush === 'glass') {\n userGlassGrid[idx] = state.n0 - 1.0;\n userWallGrid[idx] = 0;\n } else if (state.sandboxBrush === 'wall') {\n userWallGrid[idx] = 1;\n } else if (state.sandboxBrush === 'erase') {\n userGlassGrid[idx] = 0;\n userWallGrid[idx] = 0;\n }\n }\n }\n }\n rebuildMediumGrid();\n } else {\n triggerWaveImpulse(gx, gy, 5.2, 3.2);\n if (audioEngine.enabled) audioEngine.triggerPing(480 + (1 - gy / NY) * 240);\n }\n }\n\n // ============================================================================\n // 13. UI CONTROLS, PRESETS & KEYBOARD SHORTCUTS\n // ============================================================================\n document.getElementById('presetStrip').addEventListener('click', (e) => {\n const btn = e.target.closest('.preset-btn');\n if (btn && btn.dataset.scene) {\n applyScene(btn.dataset.scene);\n }\n });\n\n document.getElementById('layerGroup').addEventListener('click', (e) => {\n const btn = e.target.closest('.layer-btn');\n if (btn && btn.dataset.layer) {\n state.layer = btn.dataset.layer;\n document.querySelectorAll('.layer-btn').forEach(b => b.classList.toggle('active', b === btn));\n }\n });\n\n document.getElementById('btnLoupe').addEventListener('click', () => {\n state.loupe.enabled = !state.loupe.enabled;\n document.getElementById('btnLoupe').classList.toggle('active-amber', state.loupe.enabled);\n });\n\n document.getElementById('btnAudio').addEventListener('click', () => {\n audioEngine.toggle();\n });\n\n document.getElementById('btnPulse').addEventListener('click', () => {\n triggerWaveImpulse(state.waveSource.x, state.waveSource.y, 6.5, 4.8);\n if (audioEngine.enabled) audioEngine.triggerPing(587.33);\n });\n\n document.getElementById('btnEmbed').addEventListener('click', () => {\n const code = `<iframe src=\"index.html?scene=${state.scene}&loupe=${state.loupe.enabled ? 1 : 0}\" width=\"100%\" height=\"640\" style=\"border:1px solid #1e293b;border-radius:10px;background:#05070B;\" allow=\"autoplay\" loading=\"lazy\"></iframe>`;\n document.getElementById('embedCodeBlock').textContent = code;\n document.getElementById('embedModal').classList.add('open');\n });\n\n document.getElementById('btnCloseModal').addEventListener('click', () => {\n document.getElementById('embedModal').classList.remove('open');\n });\n\n document.getElementById('sliderIor').addEventListener('input', (e) => {\n state.n0 = parseFloat(e.target.value);\n document.getElementById('lblIor').textContent = state.n0.toFixed(2);\n rebuildMediumGrid();\n });\n\n document.getElementById('sliderDisp').addEventListener('input', (e) => {\n state.dispersionB = parseFloat(e.target.value);\n document.getElementById('lblDisp').textContent = state.dispersionB.toFixed(3);\n });\n\n document.getElementById('sliderFreq').addEventListener('input', (e) => {\n state.waveFreq = parseFloat(e.target.value);\n document.getElementById('lblFreq').textContent = state.waveFreq.toFixed(1) + ' Hz';\n });\n\n document.getElementById('sliderSceneParam').addEventListener('input', (e) => {\n const val = parseFloat(e.target.value);\n state.sceneParam = val;\n document.getElementById('lblSceneParamVal').textContent = val.toFixed(2);\n if (state.scene === 'ellipse') {\n state.ellipse.e = val;\n const cDist = state.ellipse.a * state.ellipse.e;\n state.waveSource.x = state.ellipse.cx - cDist;\n state.probes[0].x = (state.ellipse.cx + cDist) / NX;\n rebuildMediumGrid();\n } else if (state.scene === 'slit') {\n state.slit.sep = val;\n rebuildMediumGrid();\n } else if (state.scene === 'einstein') {\n state.bh.rs = val;\n rebuildMediumGrid();\n }\n });\n\n document.getElementById('materialChips').addEventListener('click', (e) => {\n const chip = e.target.closest('.mat-chip');\n if (!chip) return;\n document.querySelectorAll('#materialChips .mat-chip').forEach(c => c.classList.toggle('active', c === chip));\n state.n0 = parseFloat(chip.dataset.n);\n state.dispersionB = parseFloat(chip.dataset.b);\n document.getElementById('matBadge').textContent = chip.dataset.name;\n document.getElementById('sliderIor').value = state.n0;\n document.getElementById('lblIor').textContent = state.n0.toFixed(2);\n document.getElementById('sliderDisp').value = state.dispersionB;\n document.getElementById('lblDisp').textContent = state.dispersionB.toFixed(3);\n rebuildMediumGrid();\n });\n\n document.getElementById('sandboxTools').addEventListener('click', (e) => {\n const chip = e.target.closest('.mat-chip');\n if (!chip) return;\n document.querySelectorAll('#sandboxTools .mat-chip').forEach(c => c.classList.toggle('active', c === chip));\n state.sandboxBrush = chip.dataset.brush;\n if (state.sandboxBrush === 'erase') {\n userGlassGrid.fill(0);\n userWallGrid.fill(0);\n clearWaveField();\n rebuildMediumGrid();\n }\n });\n\n window.addEventListener('keydown', (e) => {\n if (e.key === 'l' || e.key === 'L') {\n document.getElementById('btnLoupe').click();\n } else if (e.key === 'm' || e.key === 'M') {\n document.getElementById('btnAudio').click();\n } else if (e.code === 'Space') {\n e.preventDefault();\n document.getElementById('btnPulse').click();\n } else if (e.key >= '1' && e.key <= '6') {\n const scenes = ['prism', 'ellipse', 'slit', 'einstein', 'chladni', 'sandbox'];\n applyScene(scenes[parseInt(e.key, 10) - 1]);\n }\n });\n\n // ============================================================================\n // 14. MAIN REAL-TIME SIMULATION LOOP\n // ============================================================================\n let lastFrameTime = performance.now();\n\n function animate(now) {\n const dtMs = now - lastFrameTime;\n lastFrameTime = now;\n if (dtMs > 0 && dtMs < 200) {\n const instFps = 1000 / dtMs;\n state.fps = state.fps * 0.92 + instFps * 0.08;\n }\n\n state.frameCount++;\n stepWavePDE(0.016);\n audioEngine.updateFromField();\n renderBench();\n renderTelemetryCanvases();\n\n requestAnimationFrame(animate);\n }\n\n // Initialize Scene & Start 60 FPS Loop\n applyScene(initialScene);\n requestAnimationFrame(animate);\n})();\n</script>\n</body>\n</html>\n", "Overwrite": true, "Path": "~/run/index.html" }result, 1 line
Created file.