Moves the controller, bridge and led-driver default ESP-NOW channel to 11 and updates the led-driver and led-tool submodule pointers. Includes the rest of the working tree: web UI, desktop and sim-controller changes, API and bridge code, graphify output, and the .gitea and fixture-driver folders. Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
538 lines
17 KiB
JavaScript
538 lines
17 KiB
JavaScript
/* 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: {}, view: 'list' };
|
|
|
|
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;
|
|
if (card.tile) card.tile.querySelector('.t-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' };
|
|
|
|
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.tile.querySelector('.t-name').textContent = card.name;
|
|
card.applied = JSON.parse(JSON.stringify(card.preset));
|
|
apply(card, false);
|
|
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);
|
|
makeTile(card);
|
|
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 =
|
|
'<div class="card-head"><span class="card-name"></span><span class="btns">' +
|
|
'<button type="button" class="secondary" data-a="restart" title="Restart the pattern">↺</button>' +
|
|
'<button type="button" data-a="save" title="Save this preset to the controller">Save</button>' +
|
|
'<button type="button" class="secondary" data-a="close" title="Close the preset editor">Close</button></span></div>' +
|
|
'<span class="save-status" aria-live="polite"></span>' +
|
|
'<canvas></canvas>';
|
|
el.querySelector('.card-name').textContent = name;
|
|
const card = {
|
|
mod,
|
|
index,
|
|
id: saved.id,
|
|
pattern: saved.pattern,
|
|
maxColors: defFor(saved.pattern).max_colors ?? 8,
|
|
name,
|
|
preset,
|
|
applied: JSON.parse(JSON.stringify(preset)),
|
|
el,
|
|
canvas: el.querySelector('canvas'),
|
|
clock: 0,
|
|
next: 0,
|
|
framePtr: mod._malloc(LED_CAP * 3),
|
|
last: null,
|
|
};
|
|
const form = document.createElement('form');
|
|
form.onsubmit = (ev) => ev.preventDefault();
|
|
const def = defFor(saved.pattern);
|
|
const colours = colourList(card);
|
|
colours.hidden = card.maxColors === 0; // as the controller: no colour list for a pattern that takes none
|
|
const reverse = checkField(card, 'reverse', 'reverse', false);
|
|
reverse.hidden = !def.supports_reverse; // as the controller: only for patterns that support it
|
|
form.append(
|
|
nameField(card),
|
|
colours,
|
|
bgField(card),
|
|
numField(card, 'delay', 'Delay d (ms)', { min: def.min_delay ?? 10, max: def.max_delay ?? 10000 }),
|
|
numField(card, 'brightness', 'Bright b', { min: 0, max: 255 }),
|
|
numField(card, 'fade', 'Fade (ms)', { min: 0, max: 10000, step: 50 }),
|
|
...numFields(card),
|
|
reverse,
|
|
checkField(card, 'auto', 'auto a', true),
|
|
);
|
|
el.append(form);
|
|
el.querySelector('[data-a=save]').onclick = () => save(card);
|
|
el.querySelector('[data-a=close]').onclick = () => closeEditor();
|
|
el.querySelector('[data-a=restart]').onclick = () => apply(card, true);
|
|
applySpec(card);
|
|
apply(card, true);
|
|
return card;
|
|
}
|
|
|
|
function draw(card, c = card.canvas) {
|
|
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 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);
|
|
}
|
|
}
|
|
|
|
// Show one pattern card at a time (index wraps at the ends)
|
|
function show(index) {
|
|
const n = state.cards.length;
|
|
if (!n) return;
|
|
state.view = 'editor';
|
|
document.body.classList.remove('list');
|
|
state.current = (index + n) % n;
|
|
state.cards.forEach((c, i) => {
|
|
c.el.hidden = i !== state.current;
|
|
});
|
|
}
|
|
|
|
// Close the editor: in the controller's split pane that closes the pane; in its own window or tab, the window
|
|
function closeEditor() {
|
|
const split = window.parent && window.parent !== window ? window.parent.simSplit : null;
|
|
if (split && split.close) {
|
|
split.close();
|
|
return;
|
|
}
|
|
window.close();
|
|
// A tab that the page did not open stays open: go back to the controller instead
|
|
setTimeout(() => {
|
|
location.href = '/';
|
|
}, 150);
|
|
}
|
|
|
|
// The tile grid: every preset as a live tile; clicking one opens its editor
|
|
function showList() {
|
|
state.view = 'list';
|
|
document.body.classList.add('list');
|
|
}
|
|
|
|
function makeTile(card) {
|
|
const t = document.createElement('button');
|
|
t.type = 'button';
|
|
t.className = 'tile';
|
|
t.innerHTML = '<span class="t-name"></span><span class="t-pattern"></span><canvas></canvas>';
|
|
t.querySelector('.t-name').textContent = card.name;
|
|
t.querySelector('.t-pattern').textContent = card.pattern;
|
|
t.onclick = () => show(state.cards.indexOf(card));
|
|
card.tile = t;
|
|
card.thumb = t.querySelector('canvas');
|
|
$('tiles').append(t);
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|
|
const shown = state.cards[state.current];
|
|
const status = shown.el.querySelector('.save-status');
|
|
const dirty = JSON.stringify(shown.preset) !== JSON.stringify(shown.applied);
|
|
if (dirty) status.textContent = 'Unsaved changes (press Save to keep them)';
|
|
else if (status.textContent.startsWith('Unsaved')) status.textContent = '';
|
|
if (state.view === 'list') {
|
|
for (const c of state.cards) if (!c.tile.hidden) draw(c, c.thumb);
|
|
} else {
|
|
draw(shown);
|
|
}
|
|
}
|
|
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;
|
|
}
|
|
try {
|
|
const r = await fetch('/patterns/definitions', { headers: { Accept: 'application/json' } });
|
|
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
|
state.defs = await r.json();
|
|
} catch (err) {
|
|
banner(`Could not load the pattern definitions from the controller: ${err}. Field labels are missing.`);
|
|
}
|
|
const first = await instantiate(wasmModule);
|
|
const count = first._fx_count();
|
|
const patternNames = [];
|
|
for (let i = 0; i < count; i += 1) patternNames.push(first.UTF8ToString(first._fx_name(i)));
|
|
state.wasm = wasmModule;
|
|
|
|
let saved = [];
|
|
try {
|
|
const r = await fetch('/presets', { headers: { Accept: 'application/json' } });
|
|
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
|
saved = Object.values(await r.json());
|
|
} catch (err) {
|
|
banner(`Could not load the presets from the controller: ${err}`);
|
|
}
|
|
const list = saved
|
|
.map((p) => ({ p, index: patternNames.indexOf(p.pattern) }))
|
|
.filter((x) => x.index >= 0);
|
|
const skipped = saved.length - list.length;
|
|
if (skipped) banner(`${skipped} preset(s) use a pattern this build does not have and are not shown.`);
|
|
|
|
const grid = $('gallery');
|
|
for (let i = 0; i < list.length; i += 1) {
|
|
const mod = i === 0 ? first : await instantiate(wasmModule);
|
|
const card = buildCard(mod, list[i].index, list[i].p);
|
|
state.cards.push(card);
|
|
grid.append(card.el);
|
|
makeTile(card);
|
|
}
|
|
$('g-search').oninput = () => {
|
|
const q = $('g-search').value.trim().toLowerCase();
|
|
for (const c of state.cards) {
|
|
c.tile.hidden = Boolean(q) && !(c.name.toLowerCase().includes(q) || c.pattern.toLowerCase().includes(q));
|
|
}
|
|
};
|
|
$('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-add').onclick = () => addPreset();
|
|
show(0);
|
|
showList();
|
|
requestAnimationFrame(tick);
|
|
}
|
|
|
|
main();
|