/* 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: [], current: 0, wasm: null, defs: {} }; 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 {}; }, }); } // The preview runs the card's current values, so edits show at once. Save writes them to the controller only. 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 >= card.maxColors; 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 nameField(card) { const l = document.createElement('label'); l.className = 'full'; l.textContent = 'Name'; const i = document.createElement('input'); i.type = 'text'; i.maxLength = 32; i.value = card.name; i.oninput = () => { card.name = i.value.trim() || card.name; card.el.querySelector('.card-name').textContent = card.name; }; l.append(i); 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; } // The controller's pattern definitions (GET /patterns/definitions, as its preset editor reads them): the n-field // labels, the style options (n6 "Style: 0 a, 1 b"), delay limits and how many colours a pattern takes. function parseStyles(text) { if (typeof text !== 'string') return null; const out = {}; for (const part of text.replace(/^\s*Style:\s*/i, '').split(',')) { const m = part.trim().match(/^(\d+)\s+(.*)$/); if (m) out[Number(m[1])] = m[2]; } return Object.keys(out).length ? out : null; } function defFor(pattern) { return (state.defs && state.defs[pattern]) || {}; } // Show only the n fields this pattern reads, with the controller's labels function applySpec(card) { const def = defFor(card.pattern); for (const k of ['n1', 'n2', 'n3', 'n4']) { const el = card.fields[k]; el.hidden = !def[k]; if (def[k]) el.firstChild.textContent = def[k]; } card.fields.style.hidden = !parseStyles(def.n6); } function numFields(card) { const fields = {}; for (const k of ['n1', 'n2', 'n3', 'n4']) fields[k] = numField(card, k, k); fields.style = styleField(card); card.fields = fields; return Object.values(fields); } function styleField(card) { const l = document.createElement('label'); l.textContent = 'Mode'; const sel = document.createElement('select'); const styles = parseStyles(defFor(card.pattern).n6) || {}; const values = Object.keys(styles).map(Number); if (!values.includes(card.preset.mode)) values.push(card.preset.mode); for (const v of values) { sel.append(new Option(styles[v] ? `${v} ${styles[v]}` : `${v} (unknown)`, String(v))); } sel.value = String(card.preset.mode); sel.onchange = () => { card.preset.mode = Number(sel.value); applySpec(card); }; l.append(sel); return l; } // A controller preset (GET /presets: "#RRGGBB" colours, n1..n6) as the gallery's fields function fromSaved(s) { const out = {}; out.colors = (s.colors || []).filter((c) => typeof c === 'string').map(rgb); out.background = typeof s.background === 'string' ? rgb(s.background) : [0, 0, 0]; for (const k of ['delay', 'brightness', 'auto', 'reverse', 'fade', 'n1', 'n2', 'n3', 'n4', 'n5']) { if (s[k] !== undefined && s[k] !== null) out[k] = s[k]; } out.mode = s.n6 ?? s.mode ?? 0; return out; } // The controller's preset fields for a card (colours and background as "#RRGGBB") function payloadFor(card) { const p = card.preset; return { name: card.name, pattern: card.pattern, colors: p.colors.map((c) => hex(c).toUpperCase()), background: hex(p.background || [0, 0, 0]).toUpperCase(), brightness: p.brightness, delay: p.delay, auto: p.auto, reverse: p.reverse, n1: p.n1, n2: p.n2, n3: p.n3, n4: p.n4, n5: p.n5, n6: p.mode, }; } const JSON_HEADERS = { 'Content-Type': 'application/json', Accept: 'application/json' }; // Rebuild the dropdown from the cards (keeps the shown one selected) function refreshPick() { const sel = $('g-pick'); sel.replaceChildren(...state.cards.map((c, i) => new Option(`${i + 1}. ${c.name} (${c.pattern})`, String(i)))); sel.value = String(state.current); } async function save(card) { const status = card.el.querySelector('.save-status'); status.textContent = 'Saving…'; try { const r = await fetch(`/presets/${card.id}`, { method: 'PUT', headers: JSON_HEADERS, body: JSON.stringify(payloadFor(card)), }); if (!r.ok) throw new Error(`HTTP ${r.status}`); card.el.querySelector('.card-name').textContent = card.name; card.applied = JSON.parse(JSON.stringify(card.preset)); apply(card, false); refreshPick(); status.textContent = 'Saved'; } catch (err) { status.textContent = `Save failed: ${err.message}`; } } // A new preset on the controller, copied from the shown card async function addPreset() { const src = state.cards[state.current]; if (!src) return; try { const r = await fetch('/presets', { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify({ ...payloadFor(src), name: `${src.name} copy` }), }); if (!r.ok) throw new Error(`HTTP ${r.status}`); const out = await r.json(); const id = Object.keys(out)[0]; const mod = await instantiate(state.wasm); const card = buildCard(mod, src.index, { ...out[id], id }); state.cards.push(card); $('gallery').append(card.el); $('g-count').textContent = `${state.cards.length} presets`; refreshPick(); show(state.cards.length - 1); } catch (err) { banner(`Could not add the preset: ${err.message}`); } } function buildCard(mod, index, saved) { mod._fx_init(state.leds); const name = saved.name || mod.UTF8ToString(mod._fx_name(index)); const ptr = mod._fx_defaults_json(index); const preset = { ...JSON.parse(mod.UTF8ToString(ptr)), ...fromSaved(saved) }; mod._free(ptr); preset.n5 = preset.n5 ?? 0; const el = document.createElement('section'); el.className = 'card'; el.innerHTML = '