/* Pattern gallery: every led-driver pattern side by side, from the C++ engine built to WebAssembly * (wasm/led_fx.mjs: led-driver/main/patterns.cpp and the effects, no threads). * * One module instance per pattern, so each has its own engine state; the wasm is compiled once and shared. * Each instance has its own clock and runs patterns_frame() every 10 ms of it (FRAME_MS on the board). */ import LedFx from './wasm/led_fx.mjs'; const FRAME_MS = 10; const MAX_STEPS = 25; // per animation frame, after the tab was in the background const LED_CAP = 512; const $ = (id) => document.getElementById(id); const state = { leds: 119, speed: 1, paused: false, cards: [] }; function banner(text) { const el = $('banner'); el.textContent = text; el.hidden = !text; } function hex(c) { return `#${c.map((v) => Number(v).toString(16).padStart(2, '0')).join('')}`; } function rgb(h) { const v = parseInt(h.slice(1), 16); return [(v >> 16) & 255, (v >> 8) & 255, v & 255]; } async function instantiate(wasmModule) { return LedFx({ print: () => {}, printErr: (t) => console.warn('[fx]', t), instantiateWasm(imports, receive) { WebAssembly.instantiate(wasmModule, imports).then((inst) => receive(inst, wasmModule)); return {}; }, }); } function presetJson(card) { return JSON.stringify(card.preset); } function apply(card, restart) { const p = card.mod.stringToNewUTF8(presetJson(card)); const ok = card.mod._fx_select_json(p, restart ? 1 : 0); card.mod._free(p); if (restart) { card.clock = 0; card.next = 0; } return ok; } function numField(card, key, label, opts = {}) { const l = document.createElement('label'); if (opts.cls) l.className = opts.cls; l.textContent = label; const i = document.createElement('input'); i.type = 'number'; i.step = opts.step ?? 1; if (opts.min !== undefined) i.min = opts.min; if (opts.max !== undefined) i.max = opts.max; i.value = card.preset[key] ?? 0; i.onchange = () => { const v = Number(i.value); if (Number.isFinite(v)) { card.preset[key] = Math.round(v); apply(card, opts.restart); } }; l.append(i); return l; } function checkField(card, key, label, restart) { const l = document.createElement('label'); l.className = 'check'; const i = document.createElement('input'); i.type = 'checkbox'; i.checked = Boolean(card.preset[key]); i.onchange = () => { card.preset[key] = i.checked; apply(card, restart); }; l.append(i, label); return l; } function colourList(card) { const l = document.createElement('label'); l.className = 'full'; l.textContent = 'Colours'; const box = document.createElement('div'); box.className = 'colours'; const render = () => { const items = card.preset.colors.map((c, k) => { const i = document.createElement('input'); i.type = 'color'; i.value = hex(c); i.title = 'Click to change; right-click to remove'; i.oninput = () => { card.preset.colors[k] = rgb(i.value); apply(card, false); }; i.oncontextmenu = (ev) => { ev.preventDefault(); card.preset.colors.splice(k, 1); apply(card, false); render(); }; return i; }); const add = document.createElement('button'); add.type = 'button'; add.className = 'secondary'; add.textContent = '+'; add.title = 'Add a colour'; add.disabled = card.preset.colors.length >= 8; add.onclick = () => { const last = card.preset.colors[card.preset.colors.length - 1]; card.preset.colors.push(last ? [last[2], last[0], last[1]] : [255, 0, 0]); apply(card, false); render(); }; const clear = document.createElement('button'); clear.type = 'button'; clear.className = 'link'; clear.textContent = card.preset.colors.length ? 'use defaults' : 'pattern defaults'; clear.disabled = !card.preset.colors.length; clear.onclick = () => { card.preset.colors = []; apply(card, false); render(); }; box.replaceChildren(...items, add, clear); }; render(); l.append(box); return l; } function bgField(card) { const l = document.createElement('label'); l.textContent = 'Background'; const i = document.createElement('input'); i.type = 'color'; i.value = hex(card.preset.background || [0, 0, 0]); i.oninput = () => { card.preset.background = rgb(i.value); apply(card, false); }; l.append(i); return l; } function buildCard(mod, index) { mod._fx_init(state.leds); const name = mod.UTF8ToString(mod._fx_name(index)); const ptr = mod._fx_defaults_json(index); const preset = JSON.parse(mod.UTF8ToString(ptr)); mod._free(ptr); preset.n5 = preset.n5 ?? 0; const el = document.createElement('section'); el.className = 'card'; el.innerHTML = '
' + '' + '
' + ''; el.querySelector('.card-name').textContent = name; const card = { mod, index, name, preset, el, canvas: el.querySelector('canvas'), clock: 0, next: 0, framePtr: mod._malloc(LED_CAP * 3), last: null, }; const form = document.createElement('form'); form.hidden = true; form.onsubmit = (ev) => ev.preventDefault(); form.append( colourList(card), bgField(card), numField(card, 'delay', 'Delay d (ms)', { min: 10, max: 10000 }), numField(card, 'brightness', 'Bright b', { min: 0, max: 255 }), numField(card, 'mode', 'Style n6', { min: 0 }), numField(card, 'n1', 'n1'), numField(card, 'n2', 'n2'), numField(card, 'n3', 'n3'), numField(card, 'n4', 'n4'), numField(card, 'n5', 'n5'), checkField(card, 'reverse', 'reverse', false), checkField(card, 'auto', 'auto a', true), checkField(card, 'beat_time', 'beat time', false), ); el.append(form); el.querySelector('[data-a=edit]').onclick = (ev) => { form.hidden = !form.hidden; ev.currentTarget.setAttribute('aria-expanded', String(!form.hidden)); ev.currentTarget.textContent = form.hidden ? 'Edit' : 'Close'; }; el.querySelector('[data-a=restart]').onclick = () => apply(card, true); apply(card, true); return card; } function draw(card) { const mod = card.mod; const n = mod._sim_frame(card.framePtr, LED_CAP * 3); const px = mod.HEAPU8.subarray(card.framePtr, card.framePtr + n * 3); const c = card.canvas; const dpr = window.devicePixelRatio || 1; const w = Math.max(1, Math.round(c.clientWidth * dpr)); const h = Math.max(1, Math.round(c.clientHeight * dpr)); if (c.width !== w || c.height !== h) { c.width = w; c.height = h; } const ctx = c.getContext('2d'); ctx.fillStyle = '#0b0c0f'; ctx.fillRect(0, 0, w, h); if (!n) return; const pitch = w / n; const gap = pitch >= 3 ? 1 : 0; for (let i = 0; i < n; i += 1) { const r = px[i * 3]; const g = px[i * 3 + 1]; const b = px[i * 3 + 2]; ctx.fillStyle = r | g | b ? `rgb(${r},${g},${b})` : '#1d1f24'; ctx.fillRect(Math.floor(i * pitch), 2 * dpr, Math.max(1, Math.ceil(pitch) - gap), h - 4 * dpr); } } let lastT = 0; function tick(t) { const dt = lastT ? Math.min(250, t - lastT) : 0; lastT = t; if (!state.paused) { for (const card of state.cards) { card.clock += dt * state.speed; let steps = 0; while (card.next <= card.clock && steps < MAX_STEPS) { card.mod._fx_step(card.next); card.next += FRAME_MS; steps += 1; } if (card.next <= card.clock) { card.next = Math.ceil(card.clock / FRAME_MS) * FRAME_MS; // fell behind: skip ahead } draw(card); } } requestAnimationFrame(tick); } async function main() { let wasmModule; try { wasmModule = await WebAssembly.compileStreaming(fetch('/sim/wasm/led_fx.wasm')); } catch (err) { banner(`Could not load the pattern engine (web/wasm/led_fx.wasm): ${err}. Build it with make sim-wasm, then rebuild the controller.`); return; } const first = await instantiate(wasmModule); const count = first._fx_count(); $('g-count').textContent = `${count} patterns`; const grid = $('gallery'); for (let i = 0; i < count; i += 1) { const mod = i === 0 ? first : await instantiate(wasmModule); const card = buildCard(mod, i); state.cards.push(card); grid.append(card.el); } $('g-leds').onchange = () => { const n = Math.max(1, Math.min(LED_CAP, Math.round(Number($('g-leds').value)) || 119)); $('g-leds').value = n; state.leds = n; for (const card of state.cards) { card.mod._fx_init(n); apply(card, true); } }; $('g-speed').onchange = () => { state.speed = Number($('g-speed').value) || 1; }; $('g-pause').onclick = () => { state.paused = !state.paused; $('g-pause').textContent = state.paused ? 'Play' : 'Pause'; }; $('g-restart').onclick = () => state.cards.forEach((c) => apply(c, true)); requestAnimationFrame(tick); } main();