Files
led-controller/led-simulator/web/app.js
T
jimmyandClaude Opus 5.5 35207a868a sim: fixture editor for DDP and Art-Net/DMX fixtures
The rig sim receives Art-Net (UDP 6454, answers ArtPoll) and DDP (each port the
room's DDP strips use) in sim_net.c and passes changed universes and pixels to
the page over /sim/ws, now with a kind byte in front of each binary frame.

Rooms gain fixture types: ddp strips, artnet pixel strips, and artnet cans and
movers that read named channels from the room's dmx_definitions (the qlcplus
stage map's format). Overlapping DMX channels are refused. Cans and movers are
decoded and drawn as in the qlcplus stage simulator (dmx.js, dmx-draw.js).

In Edit mode: pick a type to add, edit port/offset/universe/address/colour
order/definition, see a can's or mover's live channels, make a controller
output aimed at the sim and send its test. The room dialog lists DMX
definitions, with presets, a channel editor, and .qxf and stage map import.

GET /sim/api/dmx shows what the receiver has had. Tests: test/api/test_sim_net.py
and test/browser/dmx_decode.test.mjs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:13:58 +13:00

2133 lines
71 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 0x00 + dest_mac(6) + ESP-NOW packet (the controller transmits)
* controller -> page binary 0x01 + u16 universe + 512 bytes (an Art-Net universe changed)
* controller -> page binary 0x02 + u16 port + u32 offset + RGB (a DDP port's pixels changed)
* 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).
*
* Besides the ESP-NOW bars a room can hold network fixtures, which the controller's sim receives over UDP and
* passes on here: DDP strips, Art-Net pixel strips, and DMX cans and movers drawn the way the qlcplus stage
* simulator draws them (dmx.js decodes, dmx-draw.js draws).
*/
/* global RigLayout, RigDmx, RigDmxDraw */
(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: '',
universes: new Map(), // Art-Net universe -> Uint8Array(512), as the sim last received it
ddp: new Map(), // DDP port -> Uint8Array of RGB from offset 0
netAt: new Map(), // 'u<n>' / 'p<port>' -> when it last arrived (ms)
netDirty: false,
outputs: new Map(), // fixture id -> controller output id made for it on this page
};
const NET_FRESH_MS = 2000; // a network fixture is "receiving" while data came in this recently
const NET_LEDS_MAX = 4096; // SIM_NET_DDP_PIXELS in sim_net.h
// ----- 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,
type: info.type,
kind: info.kind,
mac: info.mac,
macBytes: info.mac ? macBytes(info.mac) : null,
name: info.label,
bootedLeds: 0,
state: 'off',
worker: null,
frame: new Uint8Array(info.leds * 3),
lit: false,
logs: [],
rx: 0,
tx: 0,
error: '',
live: null, // a can's or mover's decoded view (RigDmx.viewFixture)
};
}
function isNet(s) {
return s.type !== 'espnow';
}
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 || isNet(s)) {
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);
}
}
/** An Art-Net universe or a DDP port's pixels from the sim's receiver (sim_net.h). */
function onNetFrame(u8) {
const dv = new DataView(u8.buffer, u8.byteOffset, u8.byteLength);
if (u8[0] === 1 && u8.length >= 3 + 512) {
const uni = dv.getUint16(1, true);
app.universes.set(uni, u8.slice(3, 3 + 512));
app.netAt.set(`u${uni}`, performance.now());
} else if (u8[0] === 2 && u8.length >= 7) {
const port = dv.getUint16(1, true);
const off = dv.getUint32(3, true);
const data = u8.subarray(7);
let buf = app.ddp.get(port);
if (!buf || buf.length < off + data.length) {
const grown = new Uint8Array(off + data.length);
if (buf) {
grown.set(buf);
}
buf = grown;
}
buf.set(data, off);
app.ddp.set(port, buf);
app.netAt.set(`p${port}`, performance.now());
}
app.netDirty = true;
}
/** Wire bytes to r, g, b. color_order names the colour in each wire slot ("grb": green first), as in outputs.c. */
function toRgb(src, order) {
if (!/^(rgb|rbg|grb|gbr|brg|bgr)$/.test(order) || order === 'rgb') {
return src;
}
const at = [0, 1, 2].map((k) => 'rgb'.indexOf(order[k])); // wire slot k carries colour at[k]
const out = new Uint8Array(src.length);
for (let i = 0; i + 2 < src.length; i += 3) {
for (let k = 0; k < 3; k += 1) {
out[i + at[k]] = src[i + k];
}
}
return out;
}
/** Where a network fixture's data comes from, and whether it is arriving. */
function netSource(f) {
if (f.type === 'ddp') {
return `p${f.port}`;
}
return `u${f.universe}`;
}
function netFresh(f) {
const t = app.netAt.get(netSource(f));
return t !== undefined && performance.now() - t < NET_FRESH_MS;
}
/** Fill the network fixtures' frames (pixels) and views (cans, movers) from what has arrived. */
function updateNet() {
for (const s of app.strips) {
const f = app.room.fixtures[s.id];
if (!f || !isNet(s)) {
continue;
}
const was = s.state;
s.state = netFresh(f) ? 'running' : 'off';
if (s.state !== was) {
app.dirty = true;
}
if (s.info.point) {
const def = (app.room.dmx_definitions || {})[f.dmx_def];
s.live = RigDmx.viewFixture(
{ kind: f.kind, universe: f.universe, address: f.address, channel_names: def ? def.channels : [], pan_reverse: f.pan_reverse },
app.universes,
);
continue;
}
const leds = s.info.leds;
let raw;
if (f.type === 'ddp') {
const buf = app.ddp.get(f.port);
raw = new Uint8Array(leds * 3);
if (buf) {
const a = (f.offset || 0) * 3;
raw.set(buf.subarray(a, Math.min(buf.length, a + leds * 3)));
}
} else {
raw = RigDmx.artnetPixels(app.universes, f.universe, f.address, leds);
}
s.frame = toRgb(raw, f.color_order || 'rgb');
}
}
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;
}
const u8 = new Uint8Array(ev.data);
if (u8[0] === 0) {
onDownlink(u8.subarray(1));
} else if (u8[0] === 1 || u8[0] === 2) {
onNetFrame(u8);
}
};
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 || s.type !== info.type || s.kind !== info.kind)) {
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.filter((s) => s.mac).map((s) => [s.mac, s]));
app.netDirty = true;
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.room.dmx_definitions = app.room.dmx_definitions || {};
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, '');
}
/** A label like can-1 that no fixture in the room has. */
function nextNetLabel(prefix) {
const taken = new Set(Object.entries(app.room.fixtures).flatMap(([id, f]) => [id, f.label]));
for (let n = 1; ; n += 1) {
if (!taken.has(`${prefix}-${n}`)) {
return `${prefix}-${n}`;
}
}
}
/** The first DMX address from universe 0 up where count channels are free; fromStart: only at address 1 (a pixel
* strip, so a controller output, which sends from channel 1, can feed it). */
function nextDmxAddress(count, fromStart = false) {
const used = [];
for (const f of Object.values(app.room.fixtures)) {
if (f.type === 'artnet') {
used.push(...RigDmx.dmxRuns(f, app.room, RigLayout.fixtureLeds(app.room, f)));
}
}
for (let u = 0; u < 32768; u += 1) {
const runs = used.filter((r) => r[0] === u).sort((a, b) => a[1] - b[1]);
let a = 0;
for (const [, s0, e0] of runs) {
if (s0 - a >= count || (fromStart && a === 0 && s0 >= count)) {
break;
}
a = Math.max(a, e0);
if (fromStart) {
break; // address 1 is taken in this universe
}
}
if (a + count <= 512 && !(fromStart && a > 0)) {
return { universe: u, address: a + 1 };
}
}
return { universe: 0, address: 1 };
}
/** The DMX definition for a new can or mover: the last one used for that kind, else a qlcplus preset. */
function dmxDefFor(kind) {
const defs = app.room.dmx_definitions;
const want = kind === 'mover' ? 'Small Eye 7 Mover' : 'beamZ BCC145';
const isMover = (d) => d.channels.some((c) => /^pan$/i.test(c)) && d.channels.some((c) => /^tilt$/i.test(c));
const used = Object.values(app.room.fixtures).find((f) => f.kind === kind && defs[f.dmx_def]);
if (used) {
return used.dmx_def;
}
const fit = Object.keys(defs).find((k) => isMover(defs[k]) === (kind === 'mover'));
if (fit) {
return fit;
}
defs[want] = JSON.parse(JSON.stringify(RigDmx.PRESET_DEFINITIONS[want]));
return want;
}
async function addFixture(x, y) {
const type = $('add-type').value || 'espnow';
const pos = { x: round3(Math.round(x / SNAP_M) * SNAP_M), y: round3(Math.round(y / SNAP_M) * SNAP_M) };
const def = app.lastDef in app.room.definitions ? app.lastDef : Object.keys(app.room.definitions)[0];
let label;
if (type === 'espnow') {
let mac;
try {
const taken = Object.values(app.room.fixtures).map((f) => f.mac).filter(Boolean);
mac = (await api('POST', '/sim/api/next-mac', { taken })).mac;
} catch (err) {
banner(`Could not add a strip: ${err.message}`);
return;
}
label = nextLabel(mac);
app.room.fixtures[label] = { label, def, mac, ...pos, direction: 90 };
} else if (type === 'ddp') {
label = nextNetLabel('ddp');
// after the last DDP strip on 4048, so a new strip gets its own pixels
let offset = 0;
for (const f of Object.values(app.room.fixtures)) {
if (f.type === 'ddp' && f.port === 4048) {
offset = Math.max(offset, (f.offset || 0) + RigLayout.fixtureLeds(app.room, f));
}
}
app.room.fixtures[label] = { label, type, def, port: 4048, offset: Math.min(offset, NET_LEDS_MAX - 1), color_order: 'rgb', ...pos, direction: 90 };
} else if (type === 'artnet') {
label = nextNetLabel('art');
const leds = app.room.definitions[def].leds;
const at = nextDmxAddress(Math.min(510, leds * 3), true);
app.room.fixtures[label] = { label, type, kind: 'pixels', def, ...at, color_order: 'rgb', ...pos, direction: 90 };
} else {
label = nextNetLabel(type);
const dmxDef = dmxDefFor(type);
const at = nextDmxAddress(app.room.dmx_definitions[dmxDef].channels.length);
app.room.fixtures[label] = {
label, type: 'artnet', kind: type, dmx_def: dmxDef, ...at, ...pos, direction: 0,
...(type === 'mover' ? { zero: 0, pan_reverse: false } : {}),
};
}
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)) {
if (!st.mac) {
continue; // a network fixture: the controller has no device for it
}
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;
}
/** What a network fixture listens to, for the drawer's subtitle. */
function netWhere(f) {
if (f.type === 'ddp') {
return `DDP :${f.port} · from pixel ${f.offset || 0}`;
}
const what = f.kind === 'pixels' ? 'Art-Net pixels' : `DMX ${f.kind} · ${f.dmx_def}`;
return `${what} · universe ${f.universe} · address ${f.address}`;
}
function renderFacts() {
const s = app.selected;
if (!s) {
return;
}
const st = $('d-state');
const i = s.info;
const f = app.room.fixtures[s.id] || {};
if (isNet(s)) {
const on = netFresh(f);
st.textContent = on ? 'receiving' : 'no data';
st.className = `state-${on ? 'running' : 'off'}`;
const where = i.point ? `heading ${f.kind === 'mover' ? f.zero || 0 : f.direction}°` : `heading ${i.direction}° · ${i.leds} LEDs`;
$('d-pos').textContent = `${i.x.toFixed(2)}, ${i.y.toFixed(2)} m · ${where}`;
const t = app.netAt.get(netSource(f));
$('d-packets').textContent = t === undefined ? 'nothing yet' : `last ${((performance.now() - t) / 1000).toFixed(1)} s ago`;
$('d-note').hidden = true;
return;
}
st.textContent = s.state + (s.error && s.state === 'crashed' ? ` – ${s.error.split('\n').slice(-2).join(' ')}` : '');
st.className = `state-${s.state}`;
$('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}.` : '';
}
/** A can's or mover's channels as they arrive, like the qlcplus detail panel. */
function renderLive() {
const s = app.selected;
const table = $('d-channels');
const f = s && app.room.fixtures[s.id];
if (!f || !s.info.point) {
table.hidden = true;
return;
}
renderFacts();
const def = app.room.dmx_definitions[f.dmx_def];
const names = def ? def.channels : [];
const values = (s.live && s.live.channels) || [];
table.hidden = false;
const body = table.tBodies[0];
if (body.rows.length !== names.length || body.dataset.def !== f.dmx_def || body.dataset.addr !== String(f.address)) {
body.dataset.def = f.dmx_def;
body.dataset.addr = String(f.address);
body.replaceChildren(...names.map((n, k) => {
const tr = document.createElement('tr');
tr.innerHTML = '<td class="muted"></td><td></td><td class="num"></td>';
tr.cells[0].textContent = String(f.address + k);
tr.cells[1].textContent = n;
return tr;
}));
}
for (let k = 0; k < names.length; k += 1) {
const v = values[k] || 0;
const cell = body.rows[k].cells[2];
if (cell.textContent !== String(v)) {
cell.textContent = String(v);
body.rows[k].classList.toggle('on', v > 0);
}
}
}
/** The controller output that would send to this fixture, or why there is none. */
function outputFor(f) {
const leds = RigLayout.fixtureLeds(app.room, f);
const base = { name: `sim ${f.label}`.slice(0, 60), host: '127.0.0.1', pixel_count: leds, color_order: f.color_order || 'rgb', enabled: true };
if (f.type === 'ddp') {
if (f.offset) {
return { why: 'Controller outputs send DDP from pixel 0: set First pixel to 0 to make one.' };
}
return { body: { ...base, protocol: 'ddp', port: f.port } };
}
if (f.type === 'artnet' && f.kind === 'pixels') {
if (f.address !== 1) {
return { why: 'Controller outputs send Art-Net pixels from channel 1: set the DMX address to 1 to make one.' };
}
return { body: { ...base, protocol: 'artnet', universe: f.universe } };
}
return { why: '' };
}
function renderOutput() {
const s = app.selected;
const f = s && app.room.fixtures[s.id];
const box = $('d-net');
const pixels = f && isNet(s) && !s.info.point;
box.hidden = !pixels;
if (!pixels) {
return;
}
const o = outputFor(f);
$('d-mkout').disabled = !o.body;
$('d-testout').hidden = !app.outputs.has(s.id);
if (!$('d-out-note').dataset.sticky) {
$('d-out-note').textContent = o.why || 'Adds an output in the controller\'s Outputs, sending to this sim (127.0.0.1).';
}
}
async function makeOutput() {
const s = app.selected;
const f = s && app.room.fixtures[s.id];
const o = f && outputFor(f);
if (!o || !o.body) {
return;
}
const note = $('d-out-note');
try {
const out = await api('POST', '/outputs', o.body);
const id = out && (out.id || (out.output && out.output.id));
app.outputs.set(s.id, id);
note.textContent = `Made output "${o.body.name}"${id ? ` (${id})` : ''}. Send test sends red, green, blue, white, then black.`;
} catch (err) {
note.textContent = `Could not make the output: ${err.message}`;
}
note.dataset.sticky = '1';
renderOutput();
}
async function testOutput() {
const s = app.selected;
const id = s && app.outputs.get(s.id);
if (!id) {
return;
}
const note = $('d-out-note');
$('d-testout').disabled = true;
note.textContent = 'Sending the test…';
try {
const r = await api('POST', `/outputs/${encodeURIComponent(id)}/test`, { step_s: 1 });
const st = (r && r.status) || {};
note.textContent = `Test sent: ${st.packets ?? '?'} packets${st.last_error ? ` · ${st.last_error}` : ''}.`;
} catch (err) {
note.textContent = `Test failed: ${err.message}`;
}
$('d-testout').disabled = false;
}
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 type = f.type || 'espnow';
const point = RigLayout.isPoint(f);
const show = {
strip: !point,
ddp: type === 'ddp',
artnet: type === 'artnet',
pixels: type !== 'espnow' && !point,
dmx: point,
mover: point && f.kind === 'mover',
heading: !(point && f.kind === 'mover'),
};
for (const el of $('d-edit').querySelectorAll('[data-for]')) {
el.hidden = !show[el.dataset.for];
}
$('e-x-name').textContent = point ? 'x' : 'Pixel 0 x';
$('e-y-name').textContent = point ? 'y' : 'Pixel 0 y';
$('e-leds').max = String(type === 'espnow' ? 512 : NET_LEDS_MAX);
const set = (id, v) => {
if (document.activeElement !== $(id)) {
$(id).value = v;
}
};
if (!point) {
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),
),
);
set('e-leds', f.leds ?? '');
$('e-leds').placeholder = String(app.room.definitions[f.def].leds);
} else {
$('e-dmxdef').replaceChildren(
...Object.entries(app.room.dmx_definitions).map(
([k, d]) => new Option(`${k} (${d.channels.length} ch)`, k, false, k === f.dmx_def),
),
);
}
set('e-label', f.label);
set('e-x', round3(f.x));
set('e-y', round3(f.y));
set('e-dir', f.direction);
set('e-port', f.port ?? 4048);
set('e-offset', f.offset ?? 0);
set('e-universe', f.universe ?? 0);
set('e-address', f.address ?? 1);
set('e-order', f.color_order || 'rgb');
set('e-zero', f.zero ?? 0);
$('e-panrev').checked = Boolean(f.pan_reverse);
}
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;
const f = app.room.fixtures[s.id] || {};
$('d-meta').textContent = isNet(s) ? `${s.id} · ${netWhere(f)}` : `${s.id} · ${s.mac}`;
$('d-power').hidden = isNet(s);
$('d-log-head').hidden = isNet(s);
$('d-log').hidden = isNet(s);
if (app.drawerFor !== s) {
app.drawerFor = s;
delete $('d-out-note').dataset.sticky;
}
renderFacts();
renderEditForm();
renderOutput();
renderLive();
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(isNet(s) ? NET_LEDS_MAX : 512, n));
}
} else if (key === 'color_order' || key === 'dmx_def') {
f[key] = raw;
} else if (key === 'pan_reverse') {
f.pan_reverse = Boolean(raw);
} else if (['port', 'offset', 'universe', 'address'].includes(key)) {
const lim = { port: [1, 65535], offset: [0, NET_LEDS_MAX - 1], universe: [0, 32767], address: [1, 512] }[key];
const n = Math.round(Number(raw));
if (!Number.isFinite(n)) {
return;
}
f[key] = Math.max(lim[0], Math.min(lim[1], n));
} else {
const v = Number(raw);
if (!Number.isFinite(v)) {
return;
}
f[key] = key === 'direction' || key === 'zero' ? 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();
renderDmxDefs();
$('r-dmx-edit').hidden = true;
roomNote('');
$('room-dialog').showModal();
}
// ----- DMX definitions: the channel lists of the room's cans and movers -------------------
/** A line under the room dialog's DMX tools: what an import did (ok) or why it failed. */
function roomNote(text, ok = false) {
$('r-error').textContent = text;
$('r-error').className = ok ? 'muted small' : 'error';
}
function renderDmxDefs() {
const defs = app.room.dmx_definitions;
const rows = Object.entries(defs).map(([k, d]) => {
const used = Object.values(app.room.fixtures).filter((f) => f.dmx_def === k).length;
const tr = document.createElement('tr');
tr.innerHTML = '<td><code></code><div class="muted small"></div></td><td></td><td class="muted"></td><td></td><td></td>';
tr.querySelector('code').textContent = k;
tr.querySelector('div').textContent = [d.manufacturer, d.model].filter(Boolean).join(' ');
tr.cells[1].textContent = d.mode || '';
tr.cells[2].textContent = `${d.channels.length} ch · ${used ? `${used} fixture${used === 1 ? '' : 's'}` : 'unused'}`;
const edit = document.createElement('button');
edit.type = 'button';
edit.className = 'link';
edit.textContent = 'edit';
edit.onclick = () => openDmxEdit(k);
tr.cells[3].append(edit);
if (!used) {
const del = document.createElement('button');
del.type = 'button';
del.className = 'link';
del.textContent = 'remove';
del.onclick = () => {
delete defs[k];
changed();
renderDmxDefs();
};
tr.cells[4].append(del);
}
return tr;
});
if (!rows.length) {
const tr = document.createElement('tr');
tr.innerHTML = '<td colspan="5" class="muted">None yet. Adding a DMX can or mover adds a qlcplus preset.</td>';
rows.push(tr);
}
$('r-dmx').replaceChildren(...rows);
const presets = Object.keys(RigDmx.PRESET_DEFINITIONS).filter((k) => !(k in defs));
$('r-dmx-preset').replaceChildren(new Option(presets.length ? 'Add a preset…' : 'Presets: all added', ''),
...presets.map((k) => new Option(`${k} (${RigDmx.PRESET_DEFINITIONS[k].channels.length} ch)`, k)));
}
/** Edit (or, with no name, make) a DMX definition in the form under the table. */
function openDmxEdit(name, draft) {
const d = draft || app.room.dmx_definitions[name] || { manufacturer: '', model: '', mode: '', channels: [] };
app.dmxEditing = { name: name || '', d };
$('r-dmx-name').value = name || '';
$('r-dmx-mode').value = d.mode || '';
$('r-dmx-chans').value = d.channels.join('\n');
$('r-dmx-error').textContent = '';
$('r-dmx-edit').hidden = false;
$('r-dmx-name').focus();
}
function saveDmxEdit() {
const ed = app.dmxEditing;
const defs = app.room.dmx_definitions;
const name = $('r-dmx-name').value.trim();
const channels = $('r-dmx-chans').value.split('\n').map((c) => c.trim()).filter(Boolean);
const err = (t) => {
$('r-dmx-error').textContent = t;
};
if (!name || name.length > 60) {
return err('A definition needs a name (up to 60 characters).');
}
if (name !== ed.name && name in defs) {
return err('There is already a definition with that name.');
}
if (!channels.length || channels.length > 512 || channels.some((c) => c.length > 40)) {
return err('List 1-512 channels, one per line, each up to 40 characters.');
}
const d = { manufacturer: ed.d.manufacturer || '', model: ed.d.model || '', mode: $('r-dmx-mode').value.trim(), channels };
if (ed.name && ed.name !== name) {
delete defs[ed.name];
for (const f of Object.values(app.room.fixtures)) {
if (f.dmx_def === ed.name) {
f.dmx_def = name;
}
}
}
defs[name] = d;
$('r-dmx-edit').hidden = true;
changed();
renderDmxDefs();
}
async function readFile(input) {
const file = input.files && input.files[0];
input.value = '';
return file ? file.text() : null;
}
/** A QLC+ fixture definition: one DMX definition per mode, named "<model> <mode>". */
async function importQxf(input) {
const text = await readFile(input);
if (text === null) {
return;
}
let modes;
try {
modes = RigDmx.parseQxf(text);
} catch (err) {
roomNote(`Could not read that fixture definition: ${err.message}`);
return;
}
const defs = app.room.dmx_definitions;
for (const m of modes) {
let name = `${m.manufacturer} ${m.model}${modes.length > 1 ? ` ${m.mode}` : ''}`.trim().slice(0, 60) || 'fixture';
for (let n = 2; name in defs; n += 1) {
name = `${name.replace(/ \(\d+\)$/, '')} (${n})`;
}
defs[name] = { manufacturer: m.manufacturer.slice(0, 60), model: m.model.slice(0, 60), mode: m.mode.slice(0, 60),
channels: m.channels.map((c) => c.slice(0, 40)) };
}
roomNote(`Added ${modes.length} definition${modes.length === 1 ? '' : 's'} from the .qxf.`, true);
changed();
renderDmxDefs();
}
/** A qlcplus stage/map.json: its definitions, and its cans and movers placed in this room (y moved so they fit). */
async function importStageMap(input) {
const text = await readFile(input);
if (text === null) {
return;
}
let map;
try {
map = JSON.parse(text);
} catch (_e) {
roomNote('That file is not JSON.');
return;
}
const defs = app.room.dmx_definitions;
for (const [k, d] of Object.entries(map.definitions || {})) {
if (Array.isArray(d.channels) && d.channels.length) {
defs[k.slice(0, 60)] = { manufacturer: String(d.manufacturer || ''), model: String(d.model || ''),
mode: String(d.mode || ''), channels: d.channels.map((c) => String(c).slice(0, 40)) };
}
}
const fx = Object.entries(map.fixtures || {}).filter(([, f]) => Number.isFinite(f.x) && Number.isFinite(f.y));
const ys = fx.map(([, f]) => f.y);
const xs = fx.map(([, f]) => Math.abs(f.x));
const dy = ys.length ? 0.5 - Math.min(...ys) : 0;
let added = 0;
for (const [key, f] of fx) {
const kind = f.kind === 'mover' ? 'mover' : 'can';
const dmxDef = f.def && defs[f.def] ? f.def : dmxDefFor(kind);
let id = String(key).replace(/[^A-Za-z0-9_.#-]/g, '') || nextNetLabel(kind);
while (id in app.room.fixtures) {
id = nextNetLabel(id);
}
const address = f.address != null ? Number(f.address) + 1 : f.dmx != null ? Number(f.dmx) : nextDmxAddress(defs[dmxDef].channels.length).address;
app.room.fixtures[id] = {
label: String(f.label || key).slice(0, 47), type: 'artnet', kind, dmx_def: dmxDef,
universe: Number(f.universe) || 0, address, x: round3(f.x), y: round3(f.y + dy),
direction: wrapDeg(Number(f.direction) || 0),
...(kind === 'mover' ? { zero: wrapDeg(Number(f.zero) || 0), pan_reverse: Boolean(f.pan_reverse) } : {}),
};
added += 1;
}
if (fx.length) {
// grow the room to hold them
app.room.width = Math.max(app.room.width, Math.ceil((Math.max(...xs) * 2 + 1) * 10) / 10, Number(map.building_width) || 0);
app.room.depth = Math.max(app.room.depth, Math.ceil((Math.max(...ys) + dy + 0.5) * 10) / 10);
$('r-width').value = app.room.width;
$('r-depth').value = app.room.depth;
}
roomNote(`Added ${Object.keys(map.definitions || {}).length} definitions and ${added} fixtures from ${map.name || 'the stage map'}.`, true);
changed();
renderDmxDefs();
}
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-dmx-preset').onchange = () => {
const k = $('r-dmx-preset').value;
if (k && !(k in app.room.dmx_definitions)) {
app.room.dmx_definitions[k] = JSON.parse(JSON.stringify(RigDmx.PRESET_DEFINITIONS[k]));
changed();
}
renderDmxDefs();
};
$('r-dmx-new').onclick = () => openDmxEdit('');
$('r-dmx-cancel').onclick = () => {
$('r-dmx-edit').hidden = true;
};
$('r-dmx-save').onclick = saveDmxEdit;
$('r-dmx-qxf').onchange = () => importQxf($('r-dmx-qxf'));
$('r-dmx-map').onchange = () => importStageMap($('r-dmx-map'));
$('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;
}
/** A can or mover: its light under everything, its body on top (see frame). */
function pointFixture(s) {
const f = app.room.fixtures[s.id] || {};
return { id: s.id, kind: s.kind, label: s.name, x: s.info.x, y: s.info.y, direction: f.direction || 0, zero: f.zero || 0 };
}
function drawPointHandle(s, sg) {
if (!app.edit) {
return;
}
const ctx = app.ctx;
ctx.strokeStyle = app.sel.has(s) ? SELECT : LABEL;
ctx.lineWidth = 1.5;
ctx.setLineDash([3, 3]);
ctx.beginPath();
ctx.moveTo(sg.ax, sg.ay);
ctx.lineTo(sg.bx, sg.by);
ctx.stroke();
ctx.setLineDash([]);
ctx.beginPath();
ctx.arc(sg.bx, sg.by, HANDLE_R, 0, Math.PI * 2);
ctx.stroke();
}
function frame() {
if (app.room && app.netDirty) {
app.netDirty = false;
updateNet();
app.dirty = true;
if (app.selected && isNet(app.selected)) {
renderLive();
}
}
const animated = app.room && app.strips.some((s) => s.info.point && s.live && RigDmxDraw.animated(pointFixture(s), s.live));
if (app.view && (app.dirty || animated)) {
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) => !s.info.point && drawStrip(s, app.geo[i]));
const points = app.strips.map((s, i) => [s, app.geo[i]]).filter(([s]) => s.info.point);
if (points.length) {
const v = app.view;
ctx.save();
ctx.beginPath();
ctx.rect(v.sx(-app.room.width / 2), v.sy(app.room.depth), app.room.width * v.scale, app.room.depth * v.scale);
ctx.clip(); // beams stay on the floor
ctx.globalCompositeOperation = 'lighter';
for (const [s] of points) {
RigDmxDraw.drawLight(ctx, v, pointFixture(s), s.live || { patched: false });
}
ctx.restore();
for (const [s, sg] of points) {
drawPointHandle(s, sg);
s.bodyR = RigDmxDraw.drawBody(ctx, v, pointFixture(s), s.live || { patched: false }, app.sel.has(s));
}
}
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) {
if (sg.point) {
return sg.ax >= x0 && sg.ax <= x1 && sg.ay >= y0 && sg.ay <= 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 sg = app.geo[i];
const d = sg.point ? Math.max(0, Math.hypot(x - sg.ax, y - sg.ay) - (s.bodyR || 13)) : RigLayout.distToStrip(sg, 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[f.type === 'artnet' && f.kind === 'mover' ? 'zero' : '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();
try {
$('add-type').value = localStorage.getItem('ledsim.addType') || 'espnow';
} catch (_e) {
// storage unavailable: start with ESP-NOW bars
}
$('add-type').onchange = () => {
try {
localStorage.setItem('ledsim.addType', $('add-type').value);
} catch (_e) {
// the choice lasts for this page only
}
};
$('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);
for (const [id, key] of [['e-port', 'port'], ['e-offset', 'offset'], ['e-universe', 'universe'], ['e-address', 'address'],
['e-order', 'color_order'], ['e-dmxdef', 'dmx_def'], ['e-zero', 'zero']]) {
$(id).onchange = () => fixtureField(key, $(id).value);
}
$('e-panrev').onchange = () => fixtureField('pan_reverse', $('e-panrev').checked);
$('d-mkout').onclick = makeOutput;
$('d-testout').onclick = testOutput;
setInterval(() => {
if (app.selected && isNet(app.selected)) {
renderFacts(); // "last … s ago"
}
if (app.strips.some(isNet)) {
app.netDirty = true; // a fixture whose data stopped goes back to "no data"
}
}, 500);
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();
})();