Files
led-controller/led-simulator/web/app.js
T
jimmyandClaude Haiku 5.5 cb51a726bc feat: pattern gallery as a preset editor; chase steps; sim split with the preset editor
- Pattern gallery shows the controller's presets, one at a time, with a dropdown, Save, Add preset, and
  the controller's field labels, delay limits and colour counts. Edits show in the preview; Save writes to
  the controller only.
- Presets are always timed in ms (beat_time is no longer sent to drivers); beats stay in sequences.
- Chase steps of 0 hold still; the marquee style is removed from the controller, the gallery and the
  driver (submodule commit 12a8e22).
- The rig's split pane opens the preset editor too (Rig / Presets switch and a Preset editor menu entry).
- Sequence editor, room layout and simulator controls from earlier work are included.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-17 07:16:51 +13:00

1471 lines
45 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* The simulated rig, served by led-controller's host build at /sim/ (sim-controller/components/sim/sim_rig.c).
*
* Each bar is a module worker running the C++ led-driver built to WebAssembly (driver-worker.js). The page is
* the radio between them and the controller's "browser" bridge (WebSocket /sim/ws):
* controller -> page binary dest_mac(6) + ESP-NOW packet (the controller transmits)
* page -> controller binary src_mac(6) + ESP-NOW packet (a driver transmits)
* controller -> page text {"t":"takeover"} (another page opened the rig)
* page -> controller text {"t":"flash","mac":..,"data":..} (a driver committed its NVS store)
*
* Where the bars are is the active room. In Edit mode the room can be changed: add bars by clicking the floor,
* drag to move, drag the end handle to turn, Delete to remove. Every change is saved (PUT /sim/api/rooms/<name>)
* and the bars' places go to the controller's rig layout (POST /devices/layout).
*/
/* global RigLayout */
(function () {
'use strict';
const BG = '#0e0f12';
const FLOOR = '#121419';
const GRID = '#1b1e25';
const WALL = '#2f3440';
const OFF_COLOUR = '#1d1f24';
const LABEL = '#8a909c';
const LABEL_LIT = '#d6dae2';
const SELECT = '#5aa9ff';
const STATE_COLOUR = {
off: '#4b505b',
queued: '#f2b84b',
loading: '#f2b84b',
running: '#3ecf8e',
crashed: '#ff6b6b',
};
const LOG_LINES = 600;
const BROADCAST = 'ff:ff:ff:ff:ff:ff';
const AUTO_KEY = 'ledsim.autoPower';
const LED_H = 9;
const HANDLE_R = 6;
const SNAP_M = 0.05;
const SNAP_DEG = 15;
const $ = (id) => document.getElementById(id);
const params = new URLSearchParams(location.search);
// Test hook: a stand-in worker script under /sim/.
const workerUrl = /^\/sim\/[\w.-]+\.js$/.test(params.get('worker') || '')
? params.get('worker')
: '/sim/driver-worker.js';
const app = {
cfg: null,
room: null,
roomName: '',
bridgeMac: null,
strips: [],
byMac: new Map(),
ws: null,
wsOpen: false,
takenOver: false,
seedTimer: 0,
queue: [],
booting: 0,
view: null,
sel: new Set(), // the selected strips; app.selected is the one the drawer shows (when exactly one)
marquee: null, // the box being dragged on the floor, canvas px
zoom: 1, // the room's view: z about its fitted size, pan x/y in canvas px (view only, never saved)
pan: { x: 0, y: 0 },
spaceDown: false,
geo: [],
dirty: true,
selected: null,
canvas: null,
ctx: null,
dpr: 1,
edit: false,
drag: null,
saveTimer: 0,
lastDef: '',
};
// ----- helpers -----------------------------------------------------------
function macBytes(s) {
return new Uint8Array(s.split(':').map((h) => parseInt(h, 16)));
}
function macOf(u8, off = 0) {
const parts = [];
for (let i = off; i < off + 6; i += 1) {
parts.push(u8[i].toString(16).padStart(2, '0'));
}
return parts.join(':');
}
function banner(text, kind) {
const el = $('banner');
if (!text) {
el.hidden = true;
return;
}
el.textContent = text;
el.className = `banner${kind ? ` ${kind}` : ''}`;
el.hidden = false;
}
function readAuto() {
try {
const v = localStorage.getItem(AUTO_KEY);
return v === null ? true : v === '1';
} catch (_e) {
return true;
}
}
function writeAuto(on) {
try {
localStorage.setItem(AUTO_KEY, on ? '1' : '0');
} catch (_e) {
// storage unavailable: setting lasts for this page only
}
}
async function api(method, path, body) {
const r = await fetch(path, {
method,
headers: body === undefined ? {} : { 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
let data = null;
try {
data = await r.json();
} catch (_e) {
data = null;
}
if (!r.ok) {
throw new Error((data && data.error) || `${method} ${path}: HTTP ${r.status}`);
}
return data;
}
/** The driver's hostname from its NVS store, if it has one. */
function hostnameOf(nvsText) {
try {
const v = JSON.parse(nvsText).led.hostname;
return Array.isArray(v) && v[0] === 'str' && v[1] ? String(v[1]) : '';
} catch (_e) {
return '';
}
}
// ----- strips: power and workers ------------------------------------------
function makeStrip(info) {
return {
info,
id: info.id,
mac: info.mac,
macBytes: macBytes(info.mac),
name: info.label,
bootedLeds: 0,
state: 'off',
worker: null,
frame: new Uint8Array(info.leds * 3),
lit: false,
logs: [],
rx: 0,
tx: 0,
error: '',
};
}
function setState(s, state, error = '') {
s.state = state;
s.error = error;
app.dirty = true;
updateChips();
if (app.selected === s) {
renderDrawer();
}
}
function addLog(s, text) {
for (const line of String(text).split('\n')) {
s.logs.push(line);
}
if (s.logs.length > LOG_LINES) {
s.logs.splice(0, s.logs.length - LOG_LINES);
}
if (app.selected === s) {
const el = $('d-log');
const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 8;
el.textContent = s.logs.join('\n');
if (atBottom) {
el.scrollTop = el.scrollHeight;
}
}
}
function powerOn(s) {
if (app.takenOver) {
return;
}
if (s.state !== 'off' && s.state !== 'crashed') {
return;
}
setState(s, 'queued');
app.queue.push(s);
pumpQueue();
}
function powerOff(s) {
const i = app.queue.indexOf(s);
if (i >= 0) {
app.queue.splice(i, 1);
}
if (s.worker) {
s.worker.terminate();
s.worker = null;
if (s.state === 'loading') {
app.booting = Math.max(0, app.booting - 1);
}
}
s.frame = new Uint8Array(s.info.leds * 3);
setState(s, 'off');
pumpQueue();
}
function reset(s) {
powerOff(s);
addLog(s, '--- reset ---');
powerOn(s);
}
async function pumpQueue() {
const limit = Math.max(1, Number(app.cfg.drivers.boot_concurrency) || 4);
while (app.queue.length && app.booting < limit) {
const s = app.queue.shift();
app.booting += 1;
try {
await startWorker(s);
} catch (err) {
app.booting = Math.max(0, app.booting - 1);
addLog(s, `boot failed: ${err}`);
setState(s, 'crashed', String(err));
}
}
}
async function startWorker(s) {
const nvs = await api('GET', `/sim/api/flash/${s.mac}`);
const nvsText = JSON.stringify(nvs);
s.name = hostnameOf(nvsText) || s.info.label;
if (s.state !== 'queued') {
app.booting -= 1;
return;
}
const worker = new Worker(workerUrl, { type: 'module' });
s.worker = worker;
s.bootedLeds = s.info.leds;
setState(s, 'loading');
worker.onmessage = (ev) => onWorkerMessage(s, worker, ev.data || {});
worker.onerror = (ev) => {
if (s.worker !== worker) {
return;
}
ev.preventDefault();
addLog(s, `worker error: ${ev.message || ev}`);
driverStopped(s, worker, String(ev.message || 'worker error'), false);
};
worker.postMessage({
t: 'boot',
mac: s.mac.replace(/:/g, ''),
nvs: nvsText,
fps: app.cfg.drivers.fps ?? 30,
});
}
function driverStopped(s, worker, error, isReset) {
if (s.worker !== worker) {
return;
}
if (s.state === 'loading') {
app.booting = Math.max(0, app.booting - 1);
}
worker.terminate();
s.worker = null;
if (isReset) {
s.frame = new Uint8Array(s.info.leds * 3);
setState(s, 'off');
addLog(s, '--- esp_restart() ---');
powerOn(s);
return;
}
setState(s, 'crashed', error);
pumpQueue();
}
function onWorkerMessage(s, worker, m) {
if (s.worker !== worker) {
return;
}
switch (m.t) {
case 'state':
if (m.state === 'running' && s.state === 'loading') {
app.booting = Math.max(0, app.booting - 1);
setState(s, 'running');
pumpQueue();
clearTimeout(app.seedTimer);
app.seedTimer = setTimeout(() => seedPlacements(false), 4000); // once its announce has registered it
}
break;
case 'log':
addLog(s, m.text);
break;
case 'tx': {
// dest(6) + packet. The bridge forwards everything it hears upstream.
const data = m.data;
if (data.length <= 6) {
break;
}
s.tx += 1;
const up = new Uint8Array(data.length);
up.set(s.macBytes, 0);
up.set(data.subarray(6), 6);
if (app.wsOpen) {
app.ws.send(up);
}
if (app.selected === s) {
renderFacts();
}
break;
}
case 'px':
s.frame = m.data;
app.dirty = true;
break;
case 'flash': {
if (app.wsOpen) {
app.ws.send(JSON.stringify({ t: 'flash', mac: s.mac, data: m.data }));
}
const name = hostnameOf(m.data);
if (name && name !== s.name) {
s.name = name;
app.dirty = true;
if (app.selected === s) {
renderDrawer();
}
}
break;
}
case 'exit':
driverStopped(s, worker, m.error || 'stopped', Boolean(m.reset));
break;
default:
break;
}
}
// ----- bridge link ---------------------------------------------------------
function deliver(s, payload) {
if (s.state !== 'running' || !s.worker) {
return; // powered off or still booting: the packet is lost, as on air
}
s.worker.postMessage({ t: 'rx', data: payload });
s.rx += 1;
if (app.selected === s) {
renderFacts();
}
}
function onDownlink(u8) {
if (u8.length < 7) {
return;
}
const dest = macOf(u8, 0);
// The driver sees the bridge as the sender.
const payload = new Uint8Array(u8.length);
payload.set(app.bridgeMac, 0);
payload.set(u8.subarray(6), 6);
if (dest === BROADCAST) {
for (const s of app.strips) {
deliver(s, payload);
}
return;
}
const s = app.byMac.get(dest);
if (s) {
deliver(s, payload);
}
}
function connectBridge() {
if (app.takenOver) {
return;
}
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
const ws = new WebSocket(`${proto}://${location.host}/sim/ws`);
ws.binaryType = 'arraybuffer';
app.ws = ws;
ws.onopen = () => {
app.wsOpen = true;
if (!app.takenOver) {
banner('');
}
updateChips();
};
ws.onmessage = (ev) => {
if (typeof ev.data === 'string') {
let m = null;
try {
m = JSON.parse(ev.data);
} catch (_e) {
return;
}
if (m.t === 'takeover') {
app.takenOver = true;
for (const s of app.strips) {
powerOff(s);
}
banner('The rig is running in another tab. This page has powered its strips off; reload to take it back.', 'info');
setButtons();
}
return;
}
onDownlink(new Uint8Array(ev.data));
};
ws.onclose = () => {
app.wsOpen = false;
updateChips();
if (app.takenOver) {
return;
}
banner('Lost the simulator server. Reconnecting…');
setTimeout(connectBridge, 2000);
};
}
// ----- room: strips from fixtures, saving, switching -------------------------
/** Bring the strip list in line with the room: new fixtures appear off, removed ones power off. */
function syncStrips() {
const infos = RigLayout.roomStrips(app.room);
const old = new Map(app.strips.map((s) => [s.id, s]));
const next = [];
for (const info of infos) {
let s = old.get(info.id);
if (s && s.mac !== info.mac) {
powerOff(s);
s = null;
}
if (s) {
old.delete(info.id);
s.info = info;
if (s.state === 'off') {
s.name = info.label;
s.frame = new Uint8Array(info.leds * 3);
}
} else {
s = makeStrip(info);
}
next.push(s);
}
for (const s of old.values()) {
powerOff(s);
app.sel.delete(s);
if (app.selected === s) {
app.selected = null;
}
}
app.strips = next;
app.byMac = new Map(next.map((s) => [s.mac, s]));
layoutView();
updateChips();
renderDrawer();
}
function scheduleSave() {
clearTimeout(app.saveTimer);
$('save-state').textContent = 'saving…';
app.saveTimer = setTimeout(saveRoom, 400);
}
async function saveRoom() {
const name = app.roomName;
try {
const out = await api('PUT', `/sim/api/rooms/${encodeURIComponent(name)}`, app.room);
if (name === app.roomName) {
$('save-state').textContent = 'saved';
seedPlacements(true);
app.room.width = out.room.width;
app.room.depth = out.room.depth;
}
} catch (err) {
$('save-state').textContent = 'not saved';
banner(`Saving the room failed: ${err.message}. Reloaded it from the server.`);
app.room = await api('GET', `/sim/api/rooms/${encodeURIComponent(name)}`);
syncStrips();
}
}
function changed() {
syncStrips();
scheduleSave();
}
async function switchRoom(name) {
if (name === app.roomName) {
return;
}
let cfg;
try {
cfg = await api('POST', '/sim/api/room', { name });
} catch (err) {
banner(`Could not switch room: ${err.message}`);
$('room-select').value = app.roomName;
return;
}
for (const s of app.strips) {
powerOff(s);
}
app.strips = [];
app.sel = new Set();
app.selected = null;
applyConfig(cfg);
if (readAuto()) {
app.strips.forEach(powerOn);
}
}
function applyConfig(cfg) {
app.cfg = cfg;
app.room = cfg.room;
app.roomName = cfg.room_name;
const sel = $('room-select');
sel.replaceChildren(...cfg.rooms.map((n) => new Option(n, n, false, n === cfg.room_name)));
app.lastDef = Object.keys(app.room.definitions)[0];
app.zoom = 1; // each room opens fitted
app.pan = { x: 0, y: 0 };
syncStrips();
}
/** A label for a new strip: drivers.name with n from its MAC, which no other room uses, so the name is unique too. */
function nextLabel(mac) {
const fmt = String(app.cfg.drivers.name || 'sim-{n:02d}');
const n0 = parseInt(mac.split(':').slice(-2).join(''), 16);
for (let n = n0; n < n0 + 1000; n += 1) {
const label = fmt
.replace(/\{n(?::0?(\d+)d)?\}/, (_m, w) => String(n).padStart(Number(w) || 0, '0'))
.replace(/\{[^}]*\}/g, '');
if (!(label in app.room.fixtures) && !Object.values(app.room.fixtures).some((f) => f.label === label)) {
return label;
}
}
return mac.replace(/:/g, '');
}
async function addFixture(x, y) {
let mac;
try {
const taken = Object.values(app.room.fixtures).map((f) => f.mac);
mac = (await api('POST', '/sim/api/next-mac', { taken })).mac;
} catch (err) {
banner(`Could not add a strip: ${err.message}`);
return;
}
const label = nextLabel(mac);
app.room.fixtures[label] = {
label,
def: app.lastDef in app.room.definitions ? app.lastDef : Object.keys(app.room.definitions)[0],
mac,
x: round3(Math.round(x / SNAP_M) * SNAP_M),
y: round3(Math.round(y / SNAP_M) * SNAP_M),
direction: 90,
};
changed();
select(app.strips.find((s) => s.id === label) || null);
renderDrawer();
}
/** Delete every selected strip from the room. */
function deleteSelected() {
const doomed = [...app.sel].filter((s) => s.id in app.room.fixtures);
if (!doomed.length) {
return;
}
for (const s of doomed) {
delete app.room.fixtures[s.id];
}
setSelection([]);
changed();
}
/** Move every strip by one offset (snapped to 0.05 m, spacing kept) so their bounding box sits in the middle
* of the room: x = 0 (the room runs -width/2 .. width/2), y = depth / 2. */
function centreStrips() {
const infos = RigLayout.roomStrips(app.room);
if (!infos.length) {
return;
}
let x0 = Infinity;
let x1 = -Infinity;
let y0 = Infinity;
let y1 = -Infinity;
for (const i of infos) {
for (const [x, y] of [[i.x, i.y], [i.x1, i.y1]]) {
x0 = Math.min(x0, x);
x1 = Math.max(x1, x);
y0 = Math.min(y0, y);
y1 = Math.max(y1, y);
}
}
const dx = Math.round((0 - (x0 + x1) / 2) / SNAP_M) * SNAP_M;
const dy = Math.round((app.room.depth / 2 - (y0 + y1) / 2) / SNAP_M) * SNAP_M;
for (const f of Object.values(app.room.fixtures)) {
f.x = round3(f.x + dx);
f.y = round3(f.y + dy);
}
changed();
renderDrawer();
}
// ----- the controller: rig layout and the browser bridge -------------------------------
/** Where each bar is for the controller's rig layout: the room fitted to its 1000 x 700 canvas (y up),
* x0,y0 at pixel 0, keyed by MAC without colons. */
function rigPlacements() {
const W = 1000;
const H = 700;
const M = 20;
const s = Math.min((W - 2 * M) / app.room.width, (H - 2 * M) / app.room.depth);
const tx = (x) => Math.round((W / 2 + x * s) * 10) / 10;
const ty = (y) => Math.round((H / 2 + (y - app.room.depth / 2) * s) * 10) / 10;
const out = {};
for (const st of RigLayout.roomStrips(app.room)) {
out[st.mac.replace(/:/g, '')] = { x0: tx(st.x), y0: ty(st.y), x1: tx(st.x1), y1: ty(st.y1) };
}
return out;
}
/** Give the controller the room's places: every bar it knows (all = true, after an edit), else only the bars it
* has not placed yet. Bars that have not registered yet are tried again a little later. */
async function seedPlacements(all = false) {
clearTimeout(app.seedTimer);
let devices;
try {
devices = await api('GET', '/devices');
} catch (_e) {
return;
}
const places = rigPlacements();
const todo = {};
let missing = 0;
for (const [mac, pl] of Object.entries(places)) {
const dev = devices[mac];
if (!dev) {
missing += 1;
} else if (all || !(dev.placement && typeof dev.placement === 'object')) {
todo[mac] = pl;
}
}
if (Object.keys(todo).length) {
const body = { placements: todo };
if (!Object.values(devices).some((d) => d && d.placement)) {
body.center = { x: 500, y: 350 }; // a fresh rig: the room's centre
}
try {
await api('POST', '/devices/layout', body);
} catch (_e) {
// the controller logs it; the next seed tries again
}
}
if (missing && app.strips.some((s) => s.state !== 'off')) {
app.seedTimer = setTimeout(() => seedPlacements(false), 5000);
}
}
/** Put "browser" in the controller's bridges, so its ESP-NOW frames reach this page. */
async function addBridge() {
try {
const st = await api('GET', '/settings/bridge');
const addrs = (st.bridges || []).map((b) => b.addr).filter((a) => a && a !== 'browser');
await api('PUT', '/settings/bridge', { bridges: [...addrs, 'browser'] });
app.cfg.bridge.running = true;
banner('');
} catch (err) {
banner(`Could not add the browser bridge: ${err.message}`);
}
updateChips();
}
// ----- UI: chips, drawer, dialogs ------------------------------------------------
function updateChips() {
if (!app.cfg) {
return;
}
const b = app.cfg.bridge;
// "Add the browser bridge" shows when the controller is connected but its bridge is not running
$('add-bridge').hidden = !app.wsOpen || b.running;
}
function renderFacts() {
const s = app.selected;
if (!s) {
return;
}
const st = $('d-state');
st.textContent = s.state + (s.error && s.state === 'crashed' ? ` – ${s.error.split('\n').slice(-2).join(' ')}` : '');
st.className = `state-${s.state}`;
const i = s.info;
$('d-pos').textContent = `${i.x.toFixed(2)}, ${i.y.toFixed(2)} m · heading ${i.direction}° · ${i.leds} LEDs`;
$('d-packets').textContent = `${s.rx} received · ${s.tx} sent`;
const stale = s.state !== 'off' && s.bootedLeds && s.bootedLeds !== i.leds;
$('d-note').hidden = !stale;
$('d-note').textContent = stale ? `Running with ${s.bootedLeds} LEDs: power-cycle it to use ${i.leds}.` : '';
}
function renderEditForm() {
const s = app.selected;
const f = s && app.room.fixtures[s.id];
$('d-edit').hidden = !app.edit || !f;
if (!app.edit || !f) {
return;
}
const sel = $('e-def');
sel.replaceChildren(
...Object.entries(app.room.definitions).map(
([k, d]) => new Option(`${k} (${d.leds} LEDs, ${Math.round(1 / d.pitch_m)}/m)`, k, false, k === f.def),
),
);
const set = (id, v) => {
if (document.activeElement !== $(id)) {
$(id).value = v;
}
};
set('e-label', f.label);
set('e-leds', f.leds ?? '');
$('e-leds').placeholder = String(app.room.definitions[f.def].leds);
set('e-x', round3(f.x));
set('e-y', round3(f.y));
set('e-dir', f.direction);
}
function renderDrawer() {
const s = app.selected;
// In Edit mode the drawer stays open, so selecting a strip never resizes the room under the pointer
const wasHidden = $('drawer').hidden;
$('drawer').hidden = !s && !app.edit;
$('d-empty').hidden = Boolean(s);
if (app.emptyHtml === undefined) {
app.emptyHtml = $('d-empty').innerHTML; // the default text, restored when the selection is not several strips
}
if (app.sel.size > 1) {
$('d-empty').textContent =
`${app.sel.size} strips selected. Drag one of them to move them all · Shift-click adds or removes · Delete removes them.`;
} else {
$('d-empty').innerHTML = app.emptyHtml;
}
$('d-body').hidden = !s;
if (wasHidden !== $('drawer').hidden) {
requestAnimationFrame(layoutView);
}
if (!s) {
return;
}
$('d-name').textContent = s.name;
$('d-meta').textContent = `${s.id} · ${s.mac}`;
renderFacts();
renderEditForm();
const off = s.state === 'off' || s.state === 'crashed';
$('d-on').disabled = !off || app.takenOver;
$('d-off').disabled = off;
$('d-reset').disabled = app.takenOver;
const el = $('d-log');
el.textContent = s.logs.join('\n');
el.scrollTop = el.scrollHeight;
}
/** The selection is a set of strips. The drawer shows the strip when exactly one is selected. */
function setSelection(list) {
app.sel = new Set(list);
app.selected = list.length === 1 ? list[0] : null;
app.dirty = true;
renderDrawer();
}
function select(s) {
setSelection(s ? [s] : []);
}
function setButtons() {
const ok = !app.takenOver;
renderDrawer();
}
function setEdit(on) {
app.edit = on;
document.body.classList.toggle('editing', on);
$('edit-toggle').textContent = on ? 'Done' : 'Edit room';
$('edit-tools').hidden = !on;
$('save-state').textContent = '';
app.dirty = true;
renderDrawer();
}
function fixtureField(key, raw) {
const s = app.selected;
const f = s && app.room.fixtures[s.id];
if (!f) {
return;
}
if (key === 'label') {
f.label = String(raw).trim().slice(0, 47) || s.id;
} else if (key === 'def') {
f.def = raw;
app.lastDef = raw;
} else if (key === 'leds') {
const n = Math.round(Number(raw));
if (raw === '' || !n) {
delete f.leds;
} else {
f.leds = Math.max(1, Math.min(512, n));
}
} else {
const v = Number(raw);
if (!Number.isFinite(v)) {
return;
}
f[key] = key === 'direction' ? wrapDeg(v) : Math.round(v * 1000) / 1000;
}
changed();
}
function round3(v) {
return Math.round(v * 1000) / 1000;
}
function wrapDeg(d) {
let a = ((d % 360) + 360) % 360;
if (a > 180) {
a -= 360;
}
return Math.round(a * 10) / 10;
}
function openRoomDialog() {
$('r-width').value = app.room.width;
$('r-depth').value = app.room.depth;
renderDefs();
$('room-dialog').showModal();
}
function renderDefs() {
const rows = Object.entries(app.room.definitions).map(([k, d]) => {
const used = Object.values(app.room.fixtures).filter((f) => f.def === k).length;
const tr = document.createElement('tr');
tr.innerHTML =
`<td><code></code></td><td><input type="number" min="1" max="512" step="1" data-k="leds"></td>` +
`<td><input type="number" min="1" max="1000" step="1" data-k="per_m"></td><td class="muted"></td><td></td>`;
tr.querySelector('code').textContent = k;
tr.querySelector('[data-k=leds]').value = d.leds;
tr.querySelector('[data-k=per_m]').value = Math.round(1 / d.pitch_m);
tr.children[3].textContent = used ? `${used} strip${used === 1 ? '' : 's'}` : 'unused';
for (const inp of tr.querySelectorAll('input')) {
inp.onchange = () => {
const v = Number(inp.value);
if (!(v > 0)) {
return;
}
if (inp.dataset.k === 'leds') {
d.leds = Math.min(512, Math.round(v));
} else {
d.pitch_m = Math.round((1 / v) * 100000) / 100000;
}
changed();
};
}
if (!used && Object.keys(app.room.definitions).length > 1) {
const del = document.createElement('button');
del.type = 'button';
del.className = 'link';
del.textContent = 'remove';
del.onclick = () => {
delete app.room.definitions[k];
changed();
renderDefs();
};
tr.children[4].append(del);
}
return tr;
});
$('r-defs').replaceChildren(...rows);
}
function wireDialogs() {
$('room-settings').onclick = openRoomDialog;
$('r-close').onclick = () => $('room-dialog').close();
for (const id of ['r-width', 'r-depth']) {
$(id).onchange = () => {
const v = Number($(id).value);
if (v >= 0.5 && v <= 200) {
app.room[id === 'r-width' ? 'width' : 'depth'] = v;
changed();
}
};
}
$('r-add-def').onclick = () => {
const name = $('r-def-name').value.trim();
const leds = Math.round(Number($('r-def-leds').value));
const perM = Number($('r-def-perm').value) || 60;
if (!/^[A-Za-z0-9_.#-]{1,40}$/.test(name) || name in app.room.definitions || !(leds >= 1 && leds <= 512)) {
$('r-def-name').focus();
return;
}
app.room.definitions[name] = { leds, pitch_m: Math.round((1 / perM) * 100000) / 100000 };
app.lastDef = name;
$('r-def-name').value = '';
changed();
renderDefs();
};
$('room-new').onclick = () => {
$('n-name').value = '';
$('n-width').value = app.room.width;
$('n-depth').value = app.room.depth;
$('n-copy').checked = false;
$('n-error').textContent = '';
$('new-dialog').showModal();
$('n-name').focus();
};
$('n-cancel').onclick = () => $('new-dialog').close();
$('new-form').onsubmit = async (ev) => {
ev.preventDefault();
const name = $('n-name').value.trim();
try {
await api('POST', '/sim/api/rooms', {
name,
width: Number($('n-width').value),
depth: Number($('n-depth').value),
copy_from: $('n-copy').checked ? app.roomName : undefined,
});
} catch (err) {
$('n-error').textContent = err.message;
return;
}
$('new-dialog').close();
await switchRoom(name);
setEdit(true);
};
$('room-delete').onclick = async () => {
const others = app.cfg.rooms.filter((n) => n !== app.roomName);
if (!others.length) {
banner('This is the only room: make another one before deleting it.', 'info');
return;
}
if (!confirm(`Delete room "${app.roomName}"? Its file rooms/${app.roomName}.json is removed; the strips' flash is kept.`)) {
return;
}
const doomed = app.roomName;
await switchRoom(others[0]);
try {
const info = await api('DELETE', `/sim/api/rooms/${encodeURIComponent(doomed)}`);
app.cfg.rooms = info.rooms;
$('room-select').replaceChildren(...info.rooms.map((n) => new Option(n, n, false, n === app.roomName)));
} catch (err) {
banner(`Could not delete the room: ${err.message}`);
}
};
}
// ----- canvas ----------------------------------------------------------------
function layoutView() {
const c = app.canvas;
const rect = c.getBoundingClientRect();
app.dpr = window.devicePixelRatio || 1;
c.width = Math.max(1, Math.round(rect.width * app.dpr));
c.height = Math.max(1, Math.round(rect.height * app.dpr));
app.size = { w: rect.width, h: rect.height };
app.view = RigLayout.fit(app.room, rect.width, rect.height, 28, {
z: app.zoom,
x: app.pan.x,
y: app.pan.y,
});
app.geo = RigLayout.stripGeometry(app.view, app.strips.map((s) => s.info));
app.dirty = true;
}
const ZOOM_MIN = 0.5;
const ZOOM_MAX = 8;
/** Zoom by factor f, keeping the room point under canvas (px, py) where it is (the centre without one). */
function zoomAt(f, px, py) {
if (!app.view || !app.room) {
return;
}
const cx = px == null ? app.size.w / 2 : px;
const cy = py == null ? app.size.h / 2 : py;
const wx = app.view.mx(cx);
const wy = app.view.my(cy);
const z = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, app.zoom * f));
const s = app.view.base * z;
app.zoom = z;
// so the point under (cx, cy) stays there: sx(wx) = cx and sy(wy) = cy at the new scale
app.pan = {
x: cx - wx * s - app.size.w / 2,
y: cy + wy * s - app.size.h / 2 - (app.room.depth / 2) * s,
};
layoutView();
}
function zoomFit() {
if (!app.room) {
return;
}
app.zoom = 1;
app.pan = { x: 0, y: 0 };
layoutView();
}
function colourAt(frame, i) {
const j = i * 3;
const r = frame[j] | 0;
const g = frame[j + 1] | 0;
const b = frame[j + 2] | 0;
if (r === 0 && g === 0 && b === 0) {
return null;
}
return `rgb(${r},${g},${b})`;
}
function drawRoom() {
const ctx = app.ctx;
const v = app.view;
const w = app.room.width;
const d = app.room.depth;
const x0 = v.sx(-w / 2);
const x1 = v.sx(w / 2);
const y0 = v.sy(d);
const y1 = v.sy(0);
ctx.fillStyle = FLOOR;
ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
ctx.strokeStyle = GRID;
ctx.lineWidth = 1;
ctx.beginPath();
// the grid step in metres: 1 m, or a coarser one where zoomed out so lines stay at least 6 px apart
const step = [1, 2, 5, 10, 20, 50].find((s) => s * v.scale >= 6) || 100;
for (let x = Math.ceil(-w / 2 / step) * step; x <= w / 2; x += step) {
ctx.moveTo(Math.round(v.sx(x)) + 0.5, y0);
ctx.lineTo(Math.round(v.sx(x)) + 0.5, y1);
}
for (let y = step; y < d; y += step) {
ctx.moveTo(x0, Math.round(v.sy(y)) + 0.5);
ctx.lineTo(x1, Math.round(v.sy(y)) + 0.5);
}
ctx.stroke();
ctx.strokeStyle = WALL;
ctx.lineWidth = 2;
ctx.strokeRect(x0, y0, x1 - x0, y1 - y0);
ctx.font = '11px system-ui, -apple-system, Segoe UI, Roboto, sans-serif';
ctx.fillStyle = LABEL;
ctx.textAlign = 'left';
ctx.textBaseline = 'bottom';
ctx.fillText(`${app.roomName} · ${w} × ${d} m · ${step} m grid · ${Math.round(app.zoom * 100)}%`, x0, y0 - 6);
}
function drawStrip(s, sg) {
const ctx = app.ctx;
const leds = s.info.leds;
const gap = sg.pitch >= 3 ? 1 : 0;
let lit = false;
ctx.save();
ctx.translate(sg.ax, sg.ay);
ctx.rotate(sg.ang);
const shown = Math.min(leds, s.frame.length / 3);
for (let i = 0; i < leds; i += 1) {
const col = i < shown ? colourAt(s.frame, i) : null;
if (col) {
lit = true;
}
ctx.fillStyle = col || OFF_COLOUR;
ctx.fillRect(i * sg.pitch, -LED_H / 2, Math.max(1, sg.pitch - gap), LED_H);
}
if (app.sel.has(s)) {
ctx.strokeStyle = SELECT;
ctx.lineWidth = 1.5;
ctx.strokeRect(-1.5, -LED_H / 2 - 1.5, sg.len + 3, LED_H + 3);
}
// power state dot just before pixel 0 (the data-in end)
ctx.fillStyle = STATE_COLOUR[s.state] || STATE_COLOUR.off;
ctx.beginPath();
ctx.arc(-7, 0, 3.5, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
if (app.edit) {
// turn handle at the strip's far end
ctx.strokeStyle = app.sel.has(s) ? SELECT : LABEL;
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.arc(sg.bx, sg.by, HANDLE_R, 0, Math.PI * 2);
ctx.stroke();
}
ctx.font = '11px system-ui, -apple-system, Segoe UI, Roboto, sans-serif';
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
ctx.fillStyle = lit ? LABEL_LIT : LABEL;
// label on the side of the strip that faces up the screen
const nx = Math.sin(sg.ang);
const ny = -Math.cos(sg.ang);
const side = ny <= 0 ? 1 : -1;
ctx.fillText(s.name, (sg.ax + sg.bx) / 2 + nx * 13 * side, (sg.ay + sg.by) / 2 + ny * 13 * side);
s.lit = lit;
}
function frame() {
if (app.view && app.dirty) {
app.dirty = false;
const ctx = app.ctx;
const c = app.canvas;
ctx.setTransform(app.dpr, 0, 0, app.dpr, 0, 0);
ctx.fillStyle = BG;
ctx.fillRect(0, 0, c.width / app.dpr, c.height / app.dpr);
drawRoom();
app.strips.forEach((s, i) => drawStrip(s, app.geo[i]));
if (app.marquee) {
const m = app.marquee;
ctx.save();
ctx.setLineDash([5, 4]);
ctx.strokeStyle = SELECT;
ctx.fillStyle = 'rgba(90,169,255,0.08)';
ctx.lineWidth = 1;
ctx.fillRect(m.x0, m.y0, m.x1 - m.x0, m.y1 - m.y0);
ctx.strokeRect(m.x0 + 0.5, m.y0 + 0.5, m.x1 - m.x0, m.y1 - m.y0);
ctx.restore();
}
}
requestAnimationFrame(frame);
}
/** Whether a strip's segment passes through the box (canvas px), sampled along its length. */
function stripTouchesBox(sg, x0, y0, x1, y1) {
for (let i = 0; i <= 20; i += 1) {
const t = i / 20;
const x = sg.ax + (sg.bx - sg.ax) * t;
const y = sg.ay + (sg.by - sg.ay) * t;
if (x >= x0 && x <= x1 && y >= y0 && y <= y1) {
return true;
}
}
return false;
}
/** What is under the pointer: {s, part: 'handle' | 'body'} or null. */
function hitTest(x, y) {
if (app.edit) {
for (let i = app.strips.length - 1; i >= 0; i -= 1) {
const sg = app.geo[i];
if (Math.hypot(x - sg.bx, y - sg.by) <= HANDLE_R + 3) {
return { s: app.strips[i], part: 'handle' };
}
}
}
let best = null;
let bestD = 10;
app.strips.forEach((s, i) => {
const d = RigLayout.distToStrip(app.geo[i], x, y);
if (d < bestD) {
bestD = d;
best = s;
}
});
return best ? { s: best, part: 'body' } : null;
}
function pointerPos(ev) {
const r = app.canvas.getBoundingClientRect();
return [ev.clientX - r.left, ev.clientY - r.top];
}
function wireCanvas() {
const c = app.canvas;
// Middle-button drag would autoscroll the page: the canvas pans instead
c.addEventListener('mousedown', (ev) => {
if (ev.button === 1) {
ev.preventDefault();
}
});
// Right-drag pans the view, so the browser's menu stays off the canvas
c.addEventListener('contextmenu', (ev) => ev.preventDefault());
c.addEventListener(
'wheel',
(ev) => {
ev.preventDefault();
const [x, y] = pointerPos(ev);
const dy = ev.deltaMode === 1 ? ev.deltaY * 16 : ev.deltaY; // lines -> px
zoomAt(Math.exp(-dy * 0.0015), x, y);
},
{ passive: false },
);
c.addEventListener('pointerdown', (ev) => {
const [x, y] = pointerPos(ev);
if (ev.button === 1 || ev.button === 2 || app.spaceDown) {
// middle or right button, or Space held: pan the view, whatever is under the pointer
app.drag = { kind: 'pan', x, y, panX: app.pan.x, panY: app.pan.y };
c.setPointerCapture(ev.pointerId);
c.style.cursor = 'grabbing';
return;
}
const hit = hitTest(x, y);
if (!app.edit) {
if (hit) {
select(app.selected === hit.s ? null : hit.s);
} else if (app.zoom > 1) {
// zoomed in: a drag on empty floor moves the view
app.drag = { kind: 'pan', x, y, panX: app.pan.x, panY: app.pan.y };
c.setPointerCapture(ev.pointerId);
c.style.cursor = 'grabbing';
}
return;
}
if (!hit) {
// a click adds a strip. A drag selects the strips in its box (Shift adds to the selection), or, zoomed in,
// pans the view (see pointermove)
app.drag = { kind: 'floor', x, y, panX: app.pan.x, panY: app.pan.y, shift: ev.shiftKey };
return;
}
const additive = ev.shiftKey || ev.ctrlKey || ev.metaKey;
if (hit.part === 'handle') {
select(hit.s);
app.drag = { kind: 'turn', s: hit.s, moved: false };
c.setPointerCapture(ev.pointerId);
return;
}
if (additive) {
if (app.sel.has(hit.s)) {
// Shift-click on a selected strip takes it out of the selection
setSelection([...app.sel].filter((s) => s !== hit.s));
return;
}
setSelection([...app.sel, hit.s]);
} else if (!app.sel.has(hit.s)) {
setSelection([hit.s]);
} // else: a strip of the selection, so the whole selection moves together
// every selected strip moves by the same offset, from where it was when the drag began
const items = [...app.sel].map((s) => ({ s, startX: app.room.fixtures[s.id].x, startY: app.room.fixtures[s.id].y }));
app.drag = {
kind: 'move',
s: hit.s,
items,
mx: app.view.mx(x),
my: app.view.my(y),
moved: false,
};
c.setPointerCapture(ev.pointerId);
});
c.addEventListener('pointermove', (ev) => {
const [x, y] = pointerPos(ev);
const d = app.drag;
if (!d) {
if (app.spaceDown) {
c.style.cursor = 'grab';
} else if (app.edit) {
const hit = hitTest(x, y);
c.style.cursor = hit ? (hit.part === 'handle' ? 'crosshair' : 'move') : app.zoom > 1 ? 'grab' : 'copy';
} else {
c.style.cursor = hitTest(x, y) ? 'pointer' : app.zoom > 1 ? 'grab' : 'default';
}
return;
}
if (d.kind === 'pan') {
app.pan = { x: d.panX + x - d.x, y: d.panY + y - d.y };
layoutView();
return;
}
if (d.kind === 'floor' && app.zoom > 1 && !d.shift && Math.hypot(x - d.x, y - d.y) >= 4) {
// zoomed in, the drag is a pan, not a box: the view follows the pointer from where the drag began
app.drag = { kind: 'pan', x: d.x, y: d.y, panX: d.panX, panY: d.panY };
app.marquee = null;
c.setPointerCapture(ev.pointerId);
c.style.cursor = 'grabbing';
app.pan = { x: d.panX + x - d.x, y: d.panY + y - d.y };
layoutView();
return;
}
if (d.kind === 'floor') {
app.marquee = { x0: d.x, y0: d.y, x1: x, y1: y };
app.dirty = true;
return;
}
const f = app.room.fixtures[d.s.id];
if (!f) {
app.drag = null;
return;
}
const wx = app.view.mx(x);
const wy = app.view.my(y);
if (d.kind === 'move') {
// one snapped offset for the whole selection, so the strips keep their spacing
const snap = ev.altKey ? 0.001 : SNAP_M;
const dx = Math.round((wx - d.mx) / snap) * snap;
const dy = Math.round((wy - d.my) / snap) * snap;
for (const it of d.items) {
const g = app.room.fixtures[it.s.id];
if (g) {
g.x = round3(it.startX + dx);
g.y = round3(it.startY + dy);
}
}
} else {
const deg = (Math.atan2(wx - f.x, wy - f.y) * 180) / Math.PI;
f.direction = wrapDeg(ev.shiftKey ? deg : Math.round(deg / SNAP_DEG) * SNAP_DEG);
}
d.moved = true;
const infos = new Map(RigLayout.roomStrips(app.room).map((i) => [i.id, i]));
for (const s of d.kind === 'move' ? d.items.map((it) => it.s) : [d.s]) {
if (infos.has(s.id)) {
s.info = Object.assign(s.info, infos.get(s.id));
}
}
app.geo = RigLayout.stripGeometry(app.view, app.strips.map((s) => s.info));
app.dirty = true;
renderFacts();
renderEditForm();
});
const end = (ev) => {
const d = app.drag;
app.drag = null;
if (!d) {
return;
}
if (d.kind === 'floor') {
const m = app.marquee;
app.marquee = null;
app.dirty = true;
const [x, y] = pointerPos(ev);
if (ev.type !== 'pointerup') {
return;
}
if (Math.hypot(x - d.x, y - d.y) >= 4) {
// a box: the strips it touches are selected (Shift: added to the selection)
const x0 = Math.min(d.x, x);
const x1 = Math.max(d.x, x);
const y0 = Math.min(d.y, y);
const y1 = Math.max(d.y, y);
const inside = app.strips.filter((s, i) => stripTouchesBox(app.geo[i], x0, y0, x1, y1));
const additive = ev.shiftKey || ev.ctrlKey || ev.metaKey;
setSelection(additive ? [...new Set([...app.sel, ...inside])] : inside);
return;
}
const wx = app.view.mx(x);
const wy = app.view.my(y);
if (Math.abs(wx) <= app.room.width / 2 && wy >= 0 && wy <= app.room.depth) {
addFixture(wx, wy);
} else {
select(null);
}
return;
}
if (d.moved) {
changed();
}
};
c.addEventListener('pointerup', end);
c.addEventListener('pointercancel', end);
}
// ----- boot --------------------------------------------------------------------
function wireUi() {
const auto = $('auto-power');
auto.checked = readAuto();
auto.onchange = () => writeAuto(auto.checked);
$('room-select').onchange = () => switchRoom($('room-select').value);
$('add-bridge').onclick = addBridge;
$('edit-toggle').onclick = () => setEdit(!app.edit);
$('zoom-in').onclick = () => zoomAt(1.25);
$('zoom-out').onclick = () => zoomAt(1 / 1.25);
$('zoom-fit').onclick = () => zoomFit();
$('add-strip').onclick = () => {
// the middle of what the canvas shows, kept inside the room
const w = app.room.width;
const d = app.room.depth;
addFixture(
Math.min(w / 2, Math.max(-w / 2, app.view.mx(app.size.w / 2))),
Math.min(d, Math.max(0, app.view.my(app.size.h / 2))),
);
};
$('centre-strips').onclick = () => centreStrips();
$('d-close').onclick = () => select(null);
$('d-on').onclick = () => app.selected && powerOn(app.selected);
$('d-off').onclick = () => app.selected && powerOff(app.selected);
$('d-reset').onclick = () => app.selected && reset(app.selected);
$('d-delete').onclick = () => deleteSelected();
$('d-clear').onclick = () => {
if (app.selected) {
app.selected.logs = [];
$('d-log').textContent = '';
}
};
$('e-label').onchange = () => fixtureField('label', $('e-label').value);
$('e-def').onchange = () => fixtureField('def', $('e-def').value);
$('e-leds').onchange = () => fixtureField('leds', $('e-leds').value);
$('e-x').onchange = () => fixtureField('x', $('e-x').value);
$('e-y').onchange = () => fixtureField('y', $('e-y').value);
$('e-dir').onchange = () => fixtureField('direction', $('e-dir').value);
wireDialogs();
wireCanvas();
new ResizeObserver(() => layoutView()).observe($('rig'));
window.addEventListener('keydown', (ev) => {
const typing = /^(INPUT|SELECT|TEXTAREA)$/.test(document.activeElement && document.activeElement.tagName);
if (ev.key === 'Escape' && app.sel.size && !typing) {
select(null);
} else if (app.edit && app.sel.size && !typing && (ev.key === 'Delete' || ev.key === 'Backspace')) {
ev.preventDefault();
deleteSelected();
} else if (ev.key === ' ' && !typing) {
app.spaceDown = true; // hold Space and drag the canvas to pan
ev.preventDefault();
} else if (ev.key === '0' && !typing && !ev.ctrlKey && !ev.metaKey && !ev.altKey) {
zoomFit();
}
});
window.addEventListener('keyup', (ev) => {
if (ev.key === ' ') {
app.spaceDown = false;
}
});
window.addEventListener('blur', () => {
app.spaceDown = false;
});
}
async function main() {
// Beside the controller (its Simulator split view, in an iframe): no link back to the controller
let embedded = false;
try {
embedded = window.top !== window;
} catch (_e) {
embedded = true;
}
document.body.classList.toggle('embedded', embedded);
app.canvas = $('rig-canvas');
app.ctx = app.canvas.getContext('2d');
let cfg;
try {
cfg = await api('GET', '/sim/api/config');
} catch (err) {
banner(`Could not load /sim/api/config: ${err}`);
return;
}
app.bridgeMac = macBytes(cfg.bridge.mac);
document.title = `${cfg.bridge.name} · LED Rig Simulator`;
wireUi();
applyConfig(cfg);
requestAnimationFrame(frame);
setButtons();
connectBridge();
if (readAuto()) {
app.strips.forEach(powerOn);
}
}
// Test hook: ?debug=1 exposes the strips' current frames (read-only) for the playback checks
if (params.get('debug') === '1') {
window.simDebug = () => app.strips.map((s) => ({ name: s.name, frame: Array.from(s.frame) }));
}
main();
})();