Merge dev into main: the pad controller, simulator, Chataigne export and test show.

Keep main's Temple of Techno show over dev's older copy from the first venue
workspaces commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-10-22 20:00:21 +13:00
commit 72c227b153
106 files changed
+33054 -420

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
{
"version": "0.0.1",
"configurations": [
{
"name": "padcontroller",
"runtimeExecutable": ".venv/bin/python",
"runtimeArgs": ["-m", "padcontroller", "--no-browser"],
"port": 8770
},
{
"name": "simulator",
"runtimeExecutable": ".venv/bin/python",
"runtimeArgs": ["-m", "simulator", "--http", "127.0.0.1:8766", "--artnet", "127.0.0.1:6455", "--demo"],
"port": 8766
}
]
}
+8
View File
@@ -0,0 +1,8 @@
{
"mcpServers": {
"qlcplus-show": {
"command": "python3",
"args": ["-m", "showfile.mcp"]
}
}
}
+1
View File
@@ -3,3 +3,4 @@ __pycache__/
*.qxw~
.DS_Store
.venv/
chataigne/*/*_autosave/
+42
View File
@@ -0,0 +1,42 @@
# CLAUDE.md
## Before working on the rig
At the start of a session, and before testing anything that needs the pad or
the stage view, make sure the MIDI controller is working and the simulator is on:
1. Both user services are running:
```bash
systemctl --user is-active padcontroller simulator
```
If either is not `active`, start it with `systemctl --user start <name>`.
If the unit is missing, install it with `padcontroller/systemd/install.sh` or
`simulator/systemd/install.sh`. Check `journalctl --user -u <name> -n 50`
if it won't stay up.
2. The MIDI controller is connected and passed through:
```bash
aconnect -l
```
It should list the `SMC-PAD` client (USB `SINCO SMC-PAD-Master` or
`SMC-PAD Bluetooth`) and the `padcontroller` virtual port. A service that is
active with no `SMC-PAD` client means the pad is off or not paired: ask the
user to switch it on rather than carrying on without it.
3. The simulator answers on http://127.0.0.1:8765:
```bash
curl -sf -o /dev/null http://127.0.0.1:8765 && echo ok
```
`shows/test.show.json` (and the `shows/test.qxw` built from it) sends Art-Net
to 127.0.0.1 only, so testing drives the simulator and never the real rig. Keep
it that way; don't point it at a 192.168.1.x node.
Tell the user what was down and what you did about it. The preview
configurations in `.claude/launch.json` run separate copies on other ports
(8770, 8766) and don't count as the services being up.
+4 -3
View File
@@ -8,11 +8,12 @@ mido = "*"
python-rtmidi = "*"
[dev-packages]
pytest = "*"
[requires]
python_version = "3.12"
[scripts]
positions = "python scripts/position_movers.py"
pattern = "python -m pattern_pad"
midi = "python scripts/midi.py"
midi = "python scripts/pad/midi.py"
padcontroller-midi = "python -m padcontroller.midi"
padcontroller = "python -m padcontroller"
Generated
+44 -2
View File
@@ -1,7 +1,7 @@
{
"_meta": {
"hash": {
"sha256": "2d3b4d17f2edcaf6aca89b25728de94c131f89c846aebf67a8c6ec4981497791"
"sha256": "42b99998dcced8eeecfc0b83f3589f113501d6245312302009027c9a91e11fa6"
},
"pipfile-spec": 6,
"requires": {
@@ -67,5 +67,47 @@
"version": "==1.5.8"
}
},
"develop": {}
"develop": {
"iniconfig": {
"hashes": [
"sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960",
"sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7"
],
"markers": "python_version >= '3.10'",
"version": "==2.3.1"
},
"packaging": {
"hashes": [
"sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79",
"sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c"
],
"markers": "python_version >= '3.9'",
"version": "==26.3"
},
"pluggy": {
"hashes": [
"sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec",
"sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8"
],
"markers": "python_version >= '3.10'",
"version": "==1.7.0"
},
"pygments": {
"hashes": [
"sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9",
"sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c"
],
"markers": "python_version >= '3.9'",
"version": "==2.21.0"
},
"pytest": {
"hashes": [
"sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313",
"sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c"
],
"index": "pypi",
"markers": "python_version >= '3.10'",
"version": "==9.1.1"
}
}
}
+92 -5
View File
@@ -12,7 +12,10 @@ shows/ Workspaces to open in QLC+
simple.qxw Manual board: M1/M2 pads, shared + individual RGBW
small_eye.qxw Movers-only figure-of-8 show
archive/ Older scratch workspaces
scripts/ Generators / patchers for the shows
scripts/ Launchers (pattern_studio.sh, flash_luxdmx_xiao.sh)
pad/ SMC-PAD tools: lamps, MIDI patching, capture decoding
shows/ Generators / patchers for the shows and Chataigne
anim/ showfile animations to preview over Art-Net
stage/ Stage map (SVG, JSON, canvas)
tests/ Art-Net / fixture helpers used by scripts
```
@@ -26,16 +29,16 @@ tests/ Art-Net / fixture helpers used by scripts
```bash
# Rebuild simple manual board
python3 scripts/make_simple_vc.py
python3 scripts/shows/make_simple_vc.py
# Rewrite can/mover patterns from stage layout
python3 scripts/integrate_u_patterns.py
python3 scripts/shows/integrate_u_patterns.py
# Unify Patterns + Movers into one Show frame
python3 scripts/unify_vc.py
python3 scripts/shows/unify_vc.py
# Figure-of-8 (live Art-Net or write/merge workspace)
python3 scripts/figure8_small_eye.py --write-qxw shows/small_eye.qxw
python3 scripts/shows/figure8_small_eye.py --write-qxw shows/small_eye.qxw
```
## Fixtures / DMX
@@ -47,3 +50,87 @@ python3 scripts/figure8_small_eye.py --write-qxw shows/small_eye.qxw
Copy `.qxf` files from `fixtures/` into QLC+’s fixture library if the
manufacturer/model is missing.
## SMC-PAD pad controller
`padcontroller.midi` reads the SMC-PAD, smooths its knobs, applies the Play
layer, and sends the result on a virtual MIDI port named `padcontroller` for
QLC+. Run it by hand with `.venv/bin/python -m padcontroller.midi`, or install
it as a systemd user service that starts at login and waits for the pad:
```bash
padcontroller/systemd/install.sh
```
Options after the command go to the pad controller (for example `--lock-knobs`).
`--no-enable` installs it without starting it at login (start it with
`systemctl --user start padcontroller`). `--uninstall` removes the service. Logs: `journalctl --user -u padcontroller -f`.
### Virtual pad
`padcontroller.virtualpad` presses pads and turns knobs without touching the
pad. It sends into the pad controller's input, so presses get the Play layer
and smoothing like the real thing. It refuses unless QLC+ last opened
`shows/test.qxw` (127.0.0.1 only); `--force` skips that.
```bash
.venv/bin/python -m padcontroller.virtualpad press 52 # Colour 1 Red
.venv/bin/python -m padcontroller.virtualpad press 52 --play # Play held: Colour 2 Red
.venv/bin/python -m padcontroller.virtualpad press --pad 1 # by pad number (shows/midi_map.json)
.venv/bin/python -m padcontroller.virtualpad cc 34 64
```
`tests/test_e2e_pad.py` uses it to press colour pads and check the simulator's
`/api/state`. It drives the live rig, so it only runs with `PAD_E2E=1`:
```bash
PAD_E2E=1 .venv/bin/python -m pytest tests/test_e2e_pad.py -v
```
The rest of the suite runs offline. Use pytest, since most tests are plain
`def test_` functions that `unittest` doesn't find (`pipenv install --dev`
installs it):
```bash
.venv/bin/python -m pytest
```
## Stage simulator
`python -m simulator` listens for Art-Net on port 6454 and draws the rig at
http://127.0.0.1:8765. The Stage drop-down on the page switches between the
stage maps in `stage/`. No QLC+ show is needed: `stage/map.json` holds every
address. `--show <file.qxw>` only fills in addresses a stage map leaves out and
shows where that workspace sends Art-Net. It can run as a systemd user service
the same way:
```bash
simulator/systemd/install.sh
```
Options after the command go to the simulator (for example `--show shows/test.qxw`).
`--no-enable` installs it without starting it at login (start it with
`systemctl --user start simulator`). `--uninstall` removes the service.
Logs: `journalctl --user -u simulator -f`.
## Chataigne
`scripts/shows/make_chataigne.py` turns a show spec into a Chataigne project, so the
SMC-PAD can drive the same colour pads and sliders without QLC+.
```bash
python3 scripts/shows/make_chataigne.py shows/test.show.json chataigne/test
```
Open `chataigne/test/test.noisette`. The **Pad** (MIDI) module reads the SMC-PAD
directly (`--pad` picks the port: USB `SINCO SMC-PAD-Master` by default, or
`SMC-PAD Bluetooth`). The script does the Play-layer shift that `padcontroller/layer.py` does for
QLC+, with no knob smoothing, so the pad controller is not needed. Set the lamps with
`scripts/pad/pad_lamps.py`. The **Lights** (DMX) module sends Art-Net to the
node in the spec. The **Preview** module sends a copy to 127.0.0.1 for the simulator (`--preview ''` leaves it out). If it comes up on the wrong output, set DMX Type to Art-Net,
the remote host, and an output universe of net 0, subnet 0, universe 0.
The project also has a dashboard with the same buttons and sliders as the
virtual console, coloured like it. Chataigne serves it on port 9999 for a
phone or browser. Pads, knobs and dashboard stay in step.
Edit `chataigne/show.template.js` for behaviour; the generated `test.js` is
overwritten.
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+210
View File
@@ -0,0 +1,210 @@
// Pads pick colours, sliders mix a custom colour, like the QLC+ virtual console.
// It reads the pad directly: Play shifts bank 2 here, as padcontroller/layer.py does
// when QLC+ is used.
// Generated by scripts/shows/make_chataigne.py: edit this template, not the output.
//
// Runs as a script on the MIDI module "Pad" so it gets the pad and knob events.
// DMX goes out through the DMX module "Lights", and a copy through "Preview" if it exists.
/*__DATA__*/
var LAMP = "Lamp";
var LAMP_OFF = 0.3; // brightness of a pad's tile when it is not playing
var FADE_RATE = 100; // script updates per second
var PLAY_CC = 27; // hold Play to move bank 2 (notes 52-67) up 16, like padcontroller/layer.py
var BANK_FIRST = 52;
var BANK_LAST = 67;
var BANK_SHIFT = 16;
var DMX_SIZE = 513; // channels are 1-based
var states = [];
var sent = [];
var lookup = {};
var lampParams = [];
var sliderParams = [];
var nowParams = [];
var busy = false;
var primed = false;
var playHeld = false;
function init()
{
script.setUpdateRate(FADE_RATE);
for (var i = 0; i < DMX_SIZE; i++) sent[i] = -1;
states = [];
for (var g = 0; g < GROUPS.length; g++)
{
var level = [], from = [], to = [], touched = [];
for (var c = 0; c < DMX_SIZE; c++) { level[c] = 0; from[c] = 0; to[c] = 0; touched[c] = 0; }
var group = GROUPS[g];
for (var p = 0; p < group.pads.length; p++) mark(touched, group.pads[p].levels);
for (var s = 0; s < group.sliders.length; s++) mark(touched, group.sliders[s].levels);
var mix = [];
for (var m = 0; m < group.sliders.length; m++) mix[m] = 0;
states[g] = {active: -1, elapsed: 0, duration: 0, level: level, from: from, to: to, touched: touched, mix: mix};
// Controls on the script's Params, for the dashboard to show.
sliderParams[g] = [];
lampParams[g] = [];
for (var q = 0; q < group.pads.length; q++)
{
script.addTrigger(group.pads[q].id, group.name + " " + group.pads[q].name);
lampParams[g][q] = script.addColorParameter(group.pads[q].id + LAMP, group.name + " " + group.pads[q].name + " lamp", shade(group.pads[q].rgb, LAMP_OFF));
lookup[group.pads[q].id] = {g: g, p: q, s: -1};
}
for (var r = 0; r < group.sliders.length; r++)
{
sliderParams[g][r] = script.addFloatParameter(group.sliders[r].id, group.name + " " + group.sliders[r].name, 0, 0, 1);
lookup[group.sliders[r].id] = {g: g, p: -1, s: r};
}
nowParams[g] = script.addStringParameter(group.now, group.name + " scene", "");
}
script.log("show script ready: " + GROUPS.length + " groups");
}
function mark(touched, levels)
{
for (var i = 0; i < levels.length; i += 2) touched[levels[i]] = 1;
}
// A pad press starts its scene and fades the others out. A second press stops it.
function noteOnEvent(channel, pitch, velocity)
{
if (velocity == 0) return;
if (playHeld && pitch >= BANK_FIRST && pitch <= BANK_LAST) pitch += BANK_SHIFT;
for (var g = 0; g < GROUPS.length; g++)
{
var pads = GROUPS[g].pads;
for (var p = 0; p < pads.length; p++)
{
if (pads[p].note == pitch) { press(g, p); return; }
}
}
}
// A control on the dashboard changed.
function scriptParameterChanged(param)
{
if (busy) return;
var hit = lookup[param.name];
if (!hit) return;
if (hit.p >= 0) press(hit.g, hit.p);
else states[hit.g].mix[hit.s] = param.get();
}
function shade(rgb, level)
{
return [rgb[0] * level, rgb[1] * level, rgb[2] * level, 1];
}
// Light the playing pad's strip on the board and show its name.
function show(g, name)
{
busy = true;
nowParams[g].set(name);
var pads = GROUPS[g].pads;
for (var p = 0; p < pads.length; p++) lampParams[g][p].set(shade(pads[p].rgb, states[g].active == p ? 1 : LAMP_OFF));
busy = false;
}
function press(g, p)
{
var st = states[g];
var pad = GROUPS[g].pads[p];
for (var c = 0; c < DMX_SIZE; c++) { st.from[c] = st.level[c]; st.to[c] = 0; }
if (st.active == p)
{
st.active = -1;
st.duration = pad.fadeOut;
show(g, "");
}
else
{
for (var i = 0; i < pad.levels.length; i += 2) st.to[pad.levels[i]] = pad.levels[i + 1];
st.active = p;
st.duration = pad.fadeIn;
show(g, pad.name);
}
st.elapsed = 0;
}
function ccEvent(channel, number, value)
{
if (number == PLAY_CC) { playHeld = value > 0; return; }
for (var g = 0; g < GROUPS.length; g++)
{
var sliders = GROUPS[g].sliders;
for (var s = 0; s < sliders.length; s++)
{
if (sliders[s].cc == number)
{
states[g].mix[s] = value / 127;
busy = true;
sliderParams[g][s].set(value / 127);
busy = false;
}
}
}
}
// The dashboard web server does not always start when a project loads with it enabled, so switch
// it off and on once the script is running.
function startWeb()
{
var settings = root.projectSettings;
if (!settings || !settings.dashboardSettings) return;
var web = settings.dashboardSettings.enableDashboardServer;
if (!web) return;
web.set(false);
web.set(true);
script.log("dashboard web server restarted");
}
function update(deltaTime)
{
// A colour control's starting value is read in a different colour model and saved values load
// after init, so paint every tile once the script is running.
if (!primed)
{
primed = true;
startWeb();
for (var g = 0; g < GROUPS.length; g++) show(g, states[g].active >= 0 ? GROUPS[g].pads[states[g].active].name : "");
}
var out = [];
for (var c = 0; c < DMX_SIZE; c++) out[c] = 0;
for (var g = 0; g < GROUPS.length; g++) render(g, deltaTime, out);
var first = -1, last = -1;
for (var i = 1; i < DMX_SIZE; i++)
{
if (out[i] != sent[i]) { if (first < 0) first = i; last = i; }
}
if (first < 0) return;
var values = [];
for (var j = first; j <= last; j++) { values.push(out[j]); sent[j] = out[j]; }
root.modules.lights.send(first, values);
if (root.modules.preview) root.modules.preview.send(first, values);
}
function render(g, deltaTime, out)
{
var st = states[g];
st.elapsed += deltaTime * 1000;
var t = st.duration > 0 ? Math.min(1, st.elapsed / st.duration) : 1;
for (var c = 1; c < DMX_SIZE; c++)
{
if (!st.touched[c]) continue;
st.level[c] = st.from[c] + (st.to[c] - st.from[c]) * t;
out[c] = Math.max(out[c], st.level[c]);
}
var sliders = GROUPS[g].sliders;
for (var s = 0; s < sliders.length; s++)
{
var levels = sliders[s].levels;
for (var i = 0; i < levels.length; i += 2)
{
out[levels[i]] = Math.max(out[levels[i]], levels[i + 1] * st.mix[s]);
}
}
for (var k = 1; k < DMX_SIZE; k++) out[k] = Math.round(out[k]);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 69 B

+269
View File
@@ -0,0 +1,269 @@
// Pads pick colours, sliders mix a custom colour, like the QLC+ virtual console.
// It reads the pad directly: Play shifts bank 2 here, as padcontroller/layer.py does
// when QLC+ is used.
// Generated by scripts/shows/make_chataigne.py: edit this template, not the output.
//
// Runs as a script on the MIDI module "Pad" so it gets the pad and knob events.
// DMX goes out through the DMX module "Lights", and a copy through "Preview" if it exists.
var GROUPS = [
{
name: "Colour 1",
now: "now1",
pads: [
{id: "c1Red", rgb: [1.0, 0.0, 0.0], note: 52, name: "Red", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,255,91,0,92,0,93,0,96,255,98,255,99,0,100,0,101,0,104,255,106,255,107,0,108,0,109,0,112,255,114,255,115,0,116,0,117,0,120,255,122,255,123,0,124,0,125,0,128,255,130,255,131,0,132,0,133,0,136,255,138,255,139,0,140,0,141,0,144,255,146,255,147,0,148,0,149,0,152,255,154,255,155,0,156,0,157,0,160,255,162,255,163,0,164,0,165,0,168,255,170,255,171,0,172,0,173,0,176,255,178,255,179,0,180,0,181,0,184,255,186,255,187,0,188,0,189,0,192,255,194,255,195,0,196,0,197,0,200,255,202,255,203,0,204,0,205,0]},
{id: "c1Orange", rgb: [1.0, 0.498, 0.0], note: 53, name: "Orange", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,255,91,127,92,0,93,0,96,255,98,255,99,127,100,0,101,0,104,255,106,255,107,127,108,0,109,0,112,255,114,255,115,127,116,0,117,0,120,255,122,255,123,127,124,0,125,0,128,255,130,255,131,127,132,0,133,0,136,255,138,255,139,127,140,0,141,0,144,255,146,255,147,127,148,0,149,0,152,255,154,255,155,127,156,0,157,0,160,255,162,255,163,127,164,0,165,0,168,255,170,255,171,127,172,0,173,0,176,255,178,255,179,127,180,0,181,0,184,255,186,255,187,127,188,0,189,0,192,255,194,255,195,127,196,0,197,0,200,255,202,255,203,127,204,0,205,0]},
{id: "c1Yellow", rgb: [1.0, 1.0, 0.0], note: 54, name: "Yellow", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,255,91,255,92,0,93,0,96,255,98,255,99,255,100,0,101,0,104,255,106,255,107,255,108,0,109,0,112,255,114,255,115,255,116,0,117,0,120,255,122,255,123,255,124,0,125,0,128,255,130,255,131,255,132,0,133,0,136,255,138,255,139,255,140,0,141,0,144,255,146,255,147,255,148,0,149,0,152,255,154,255,155,255,156,0,157,0,160,255,162,255,163,255,164,0,165,0,168,255,170,255,171,255,172,0,173,0,176,255,178,255,179,255,180,0,181,0,184,255,186,255,187,255,188,0,189,0,192,255,194,255,195,255,196,0,197,0,200,255,202,255,203,255,204,0,205,0]},
{id: "c1Lime", rgb: [0.498, 1.0, 0.0], note: 55, name: "Lime", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,127,91,255,92,0,93,0,96,255,98,127,99,255,100,0,101,0,104,255,106,127,107,255,108,0,109,0,112,255,114,127,115,255,116,0,117,0,120,255,122,127,123,255,124,0,125,0,128,255,130,127,131,255,132,0,133,0,136,255,138,127,139,255,140,0,141,0,144,255,146,127,147,255,148,0,149,0,152,255,154,127,155,255,156,0,157,0,160,255,162,127,163,255,164,0,165,0,168,255,170,127,171,255,172,0,173,0,176,255,178,127,179,255,180,0,181,0,184,255,186,127,187,255,188,0,189,0,192,255,194,127,195,255,196,0,197,0,200,255,202,127,203,255,204,0,205,0]},
{id: "c1Green", rgb: [0.0, 1.0, 0.0], note: 56, name: "Green", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,0,91,255,92,0,93,0,96,255,98,0,99,255,100,0,101,0,104,255,106,0,107,255,108,0,109,0,112,255,114,0,115,255,116,0,117,0,120,255,122,0,123,255,124,0,125,0,128,255,130,0,131,255,132,0,133,0,136,255,138,0,139,255,140,0,141,0,144,255,146,0,147,255,148,0,149,0,152,255,154,0,155,255,156,0,157,0,160,255,162,0,163,255,164,0,165,0,168,255,170,0,171,255,172,0,173,0,176,255,178,0,179,255,180,0,181,0,184,255,186,0,187,255,188,0,189,0,192,255,194,0,195,255,196,0,197,0,200,255,202,0,203,255,204,0,205,0]},
{id: "c1Spring", rgb: [0.0, 1.0, 0.498], note: 57, name: "Spring", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,0,91,255,92,127,93,0,96,255,98,0,99,255,100,127,101,0,104,255,106,0,107,255,108,127,109,0,112,255,114,0,115,255,116,127,117,0,120,255,122,0,123,255,124,127,125,0,128,255,130,0,131,255,132,127,133,0,136,255,138,0,139,255,140,127,141,0,144,255,146,0,147,255,148,127,149,0,152,255,154,0,155,255,156,127,157,0,160,255,162,0,163,255,164,127,165,0,168,255,170,0,171,255,172,127,173,0,176,255,178,0,179,255,180,127,181,0,184,255,186,0,187,255,188,127,189,0,192,255,194,0,195,255,196,127,197,0,200,255,202,0,203,255,204,127,205,0]},
{id: "c1Cyan", rgb: [0.0, 1.0, 1.0], note: 58, name: "Cyan", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,0,91,255,92,255,93,0,96,255,98,0,99,255,100,255,101,0,104,255,106,0,107,255,108,255,109,0,112,255,114,0,115,255,116,255,117,0,120,255,122,0,123,255,124,255,125,0,128,255,130,0,131,255,132,255,133,0,136,255,138,0,139,255,140,255,141,0,144,255,146,0,147,255,148,255,149,0,152,255,154,0,155,255,156,255,157,0,160,255,162,0,163,255,164,255,165,0,168,255,170,0,171,255,172,255,173,0,176,255,178,0,179,255,180,255,181,0,184,255,186,0,187,255,188,255,189,0,192,255,194,0,195,255,196,255,197,0,200,255,202,0,203,255,204,255,205,0]},
{id: "c1Azure", rgb: [0.0, 0.498, 1.0], note: 59, name: "Azure", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,0,91,127,92,255,93,0,96,255,98,0,99,127,100,255,101,0,104,255,106,0,107,127,108,255,109,0,112,255,114,0,115,127,116,255,117,0,120,255,122,0,123,127,124,255,125,0,128,255,130,0,131,127,132,255,133,0,136,255,138,0,139,127,140,255,141,0,144,255,146,0,147,127,148,255,149,0,152,255,154,0,155,127,156,255,157,0,160,255,162,0,163,127,164,255,165,0,168,255,170,0,171,127,172,255,173,0,176,255,178,0,179,127,180,255,181,0,184,255,186,0,187,127,188,255,189,0,192,255,194,0,195,127,196,255,197,0,200,255,202,0,203,127,204,255,205,0]},
{id: "c1Blue", rgb: [0.0, 0.0, 1.0], note: 60, name: "Blue", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,0,91,0,92,255,93,0,96,255,98,0,99,0,100,255,101,0,104,255,106,0,107,0,108,255,109,0,112,255,114,0,115,0,116,255,117,0,120,255,122,0,123,0,124,255,125,0,128,255,130,0,131,0,132,255,133,0,136,255,138,0,139,0,140,255,141,0,144,255,146,0,147,0,148,255,149,0,152,255,154,0,155,0,156,255,157,0,160,255,162,0,163,0,164,255,165,0,168,255,170,0,171,0,172,255,173,0,176,255,178,0,179,0,180,255,181,0,184,255,186,0,187,0,188,255,189,0,192,255,194,0,195,0,196,255,197,0,200,255,202,0,203,0,204,255,205,0]},
{id: "c1Violet", rgb: [0.498, 0.0, 1.0], note: 61, name: "Violet", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,127,91,0,92,255,93,0,96,255,98,127,99,0,100,255,101,0,104,255,106,127,107,0,108,255,109,0,112,255,114,127,115,0,116,255,117,0,120,255,122,127,123,0,124,255,125,0,128,255,130,127,131,0,132,255,133,0,136,255,138,127,139,0,140,255,141,0,144,255,146,127,147,0,148,255,149,0,152,255,154,127,155,0,156,255,157,0,160,255,162,127,163,0,164,255,165,0,168,255,170,127,171,0,172,255,173,0,176,255,178,127,179,0,180,255,181,0,184,255,186,127,187,0,188,255,189,0,192,255,194,127,195,0,196,255,197,0,200,255,202,127,203,0,204,255,205,0]},
{id: "c1Magenta", rgb: [1.0, 0.0, 1.0], note: 62, name: "Magenta", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,255,91,0,92,255,93,0,96,255,98,255,99,0,100,255,101,0,104,255,106,255,107,0,108,255,109,0,112,255,114,255,115,0,116,255,117,0,120,255,122,255,123,0,124,255,125,0,128,255,130,255,131,0,132,255,133,0,136,255,138,255,139,0,140,255,141,0,144,255,146,255,147,0,148,255,149,0,152,255,154,255,155,0,156,255,157,0,160,255,162,255,163,0,164,255,165,0,168,255,170,255,171,0,172,255,173,0,176,255,178,255,179,0,180,255,181,0,184,255,186,255,187,0,188,255,189,0,192,255,194,255,195,0,196,255,197,0,200,255,202,255,203,0,204,255,205,0]},
{id: "c1Pink", rgb: [1.0, 0.157, 0.471], note: 63, name: "Pink", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,255,91,40,92,120,93,0,96,255,98,255,99,40,100,120,101,0,104,255,106,255,107,40,108,120,109,0,112,255,114,255,115,40,116,120,117,0,120,255,122,255,123,40,124,120,125,0,128,255,130,255,131,40,132,120,133,0,136,255,138,255,139,40,140,120,141,0,144,255,146,255,147,40,148,120,149,0,152,255,154,255,155,40,156,120,157,0,160,255,162,255,163,40,164,120,165,0,168,255,170,255,171,40,172,120,173,0,176,255,178,255,179,40,180,120,181,0,184,255,186,255,187,40,188,120,189,0,192,255,194,255,195,40,196,120,197,0,200,255,202,255,203,40,204,120,205,0]},
{id: "c1Warm", rgb: [1.0, 0.941, 0.627], note: 64, name: "Warm", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,255,91,120,92,40,93,120,96,255,98,255,99,120,100,40,101,120,104,255,106,255,107,120,108,40,109,120,112,255,114,255,115,120,116,40,117,120,120,255,122,255,123,120,124,40,125,120,128,255,130,255,131,120,132,40,133,120,136,255,138,255,139,120,140,40,141,120,144,255,146,255,147,120,148,40,149,120,152,255,154,255,155,120,156,40,157,120,160,255,162,255,163,120,164,40,165,120,168,255,170,255,171,120,172,40,173,120,176,255,178,255,179,120,180,40,181,120,184,255,186,255,187,120,188,40,189,120,192,255,194,255,195,120,196,40,197,120,200,255,202,255,203,120,204,40,205,120]},
{id: "c1White", rgb: [1.0, 1.0, 1.0], note: 65, name: "White", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,0,91,0,92,0,93,255,96,255,98,0,99,0,100,0,101,255,104,255,106,0,107,0,108,0,109,255,112,255,114,0,115,0,116,0,117,255,120,255,122,0,123,0,124,0,125,255,128,255,130,0,131,0,132,0,133,255,136,255,138,0,139,0,140,0,141,255,144,255,146,0,147,0,148,0,149,255,152,255,154,0,155,0,156,0,157,255,160,255,162,0,163,0,164,0,165,255,168,255,170,0,171,0,172,0,173,255,176,255,178,0,179,0,180,0,181,255,184,255,186,0,187,0,188,0,189,255,192,255,194,0,195,0,196,0,197,255,200,255,202,0,203,0,204,0,205,255]},
{id: "c1Cool", rgb: [0.784, 0.941, 1.0], note: 66, name: "Cool", fadeIn: 1000, fadeOut: 1000, levels: [88,255,90,80,91,120,92,255,93,120,96,255,98,80,99,120,100,255,101,120,104,255,106,80,107,120,108,255,109,120,112,255,114,80,115,120,116,255,117,120,120,255,122,80,123,120,124,255,125,120,128,255,130,80,131,120,132,255,133,120,136,255,138,80,139,120,140,255,141,120,144,255,146,80,147,120,148,255,149,120,152,255,154,80,155,120,156,255,157,120,160,255,162,80,163,120,164,255,165,120,168,255,170,80,171,120,172,255,173,120,176,255,178,80,179,120,180,255,181,120,184,255,186,80,187,120,188,255,189,120,192,255,194,80,195,120,196,255,197,120,200,255,202,80,203,120,204,255,205,120]},
{id: "c1Custom", rgb: [1.0, 0.235, 0.0], note: 67, name: "Custom", fadeIn: 1000, fadeOut: 1000, levels: [88,0,96,0,104,0,112,0,120,0,128,0,136,0,144,0,152,0,160,0,168,0,176,0,184,0,192,0,200,0]},
],
sliders: [
{id: "s1Dim", cc: 30, name: "Dim", levels: [88,255,96,255,104,255,112,255,120,255,128,255,136,255,144,255,152,255,160,255,168,255,176,255,184,255,192,255,200,255]},
{id: "s1R", cc: 31, name: "R", levels: [90,255,98,255,106,255,114,255,122,255,130,255,138,255,146,255,154,255,162,255,170,255,178,255,186,255,194,255,202,255]},
{id: "s1G", cc: 32, name: "G", levels: [91,255,99,255,107,255,115,255,123,255,131,255,139,255,147,255,155,255,163,255,171,255,179,255,187,255,195,255,203,255]},
{id: "s1B", cc: 33, name: "B", levels: [92,255,100,255,108,255,116,255,124,255,132,255,140,255,148,255,156,255,164,255,172,255,180,255,188,255,196,255,204,255]},
{id: "s1W", cc: 34, name: "W", levels: [93,255,101,255,109,255,117,255,125,255,133,255,141,255,149,255,157,255,165,255,173,255,181,255,189,255,197,255,205,255]},
]
},
{
name: "Colour 2",
now: "now2",
pads: [
{id: "c2Red", rgb: [1.0, 0.0, 0.0], note: 68, name: "Red", fadeIn: 1000, fadeOut: 1000, levels: [9,255,10,0,11,255,12,0,13,0,14,0,15,255,16,0,17,0,18,0,19,255,20,0,21,0,22,0,23,255,24,0,25,0,26,0,27,255,28,0,29,0,30,0,31,255,32,0,33,0,34,0,35,255,36,0,37,0,38,0,53,255,54,0,55,255,56,0,57,0,58,0,59,255,60,0,61,0,62,0,63,255,64,0,65,0,66,0,67,255,68,0,69,0,70,0,71,255,72,0,73,0,74,0,75,255,76,0,77,0,78,0,79,255,80,0,81,0,82,0,266,255,267,0,268,255,269,0,270,0,271,0,272,255,273,0,274,0,275,0,276,255,277,0,278,0,279,0,280,255,281,0,282,0,283,0,284,255,285,0,286,0,287,0,288,255,289,0,290,0,291,0,292,255,293,0,294,0,295,0,309,255,310,0,311,255,312,0,313,0,314,0,315,255,316,0,317,0,318,0,319,255,320,0,321,0,322,0,323,255,324,0,325,0,326,0,327,255,328,0,329,0,330,0,331,255,332,0,333,0,334,0,335,255,336,0,337,0,338,0]},
{id: "c2Orange", rgb: [1.0, 0.498, 0.0], note: 69, name: "Orange", fadeIn: 1000, fadeOut: 1000, levels: [9,255,10,0,11,255,12,127,13,0,14,0,15,255,16,127,17,0,18,0,19,255,20,127,21,0,22,0,23,255,24,127,25,0,26,0,27,255,28,127,29,0,30,0,31,255,32,127,33,0,34,0,35,255,36,127,37,0,38,0,53,255,54,0,55,255,56,127,57,0,58,0,59,255,60,127,61,0,62,0,63,255,64,127,65,0,66,0,67,255,68,127,69,0,70,0,71,255,72,127,73,0,74,0,75,255,76,127,77,0,78,0,79,255,80,127,81,0,82,0,266,255,267,0,268,255,269,127,270,0,271,0,272,255,273,127,274,0,275,0,276,255,277,127,278,0,279,0,280,255,281,127,282,0,283,0,284,255,285,127,286,0,287,0,288,255,289,127,290,0,291,0,292,255,293,127,294,0,295,0,309,255,310,0,311,255,312,127,313,0,314,0,315,255,316,127,317,0,318,0,319,255,320,127,321,0,322,0,323,255,324,127,325,0,326,0,327,255,328,127,329,0,330,0,331,255,332,127,333,0,334,0,335,255,336,127,337,0,338,0]},
{id: "c2Yellow", rgb: [1.0, 1.0, 0.0], note: 70, name: "Yellow", fadeIn: 1000, fadeOut: 1000, levels: [9,255,10,0,11,255,12,255,13,0,14,0,15,255,16,255,17,0,18,0,19,255,20,255,21,0,22,0,23,255,24,255,25,0,26,0,27,255,28,255,29,0,30,0,31,255,32,255,33,0,34,0,35,255,36,255,37,0,38,0,53,255,54,0,55,255,56,255,57,0,58,0,59,255,60,255,61,0,62,0,63,255,64,255,65,0,66,0,67,255,68,255,69,0,70,0,71,255,72,255,73,0,74,0,75,255,76,255,77,0,78,0,79,255,80,255,81,0,82,0,266,255,267,0,268,255,269,255,270,0,271,0,272,255,273,255,274,0,275,0,276,255,277,255,278,0,279,0,280,255,281,255,282,0,283,0,284,255,285,255,286,0,287,0,288,255,289,255,290,0,291,0,292,255,293,255,294,0,295,0,309,255,310,0,311,255,312,255,313,0,314,0,315,255,316,255,317,0,318,0,319,255,320,255,321,0,322,0,323,255,324,255,325,0,326,0,327,255,328,255,329,0,330,0,331,255,332,255,333,0,334,0,335,255,336,255,337,0,338,0]},
{id: "c2Lime", rgb: [0.498, 1.0, 0.0], note: 71, name: "Lime", fadeIn: 1000, fadeOut: 1000, levels: [9,255,10,0,11,127,12,255,13,0,14,0,15,127,16,255,17,0,18,0,19,127,20,255,21,0,22,0,23,127,24,255,25,0,26,0,27,127,28,255,29,0,30,0,31,127,32,255,33,0,34,0,35,127,36,255,37,0,38,0,53,255,54,0,55,127,56,255,57,0,58,0,59,127,60,255,61,0,62,0,63,127,64,255,65,0,66,0,67,127,68,255,69,0,70,0,71,127,72,255,73,0,74,0,75,127,76,255,77,0,78,0,79,127,80,255,81,0,82,0,266,255,267,0,268,127,269,255,270,0,271,0,272,127,273,255,274,0,275,0,276,127,277,255,278,0,279,0,280,127,281,255,282,0,283,0,284,127,285,255,286,0,287,0,288,127,289,255,290,0,291,0,292,127,293,255,294,0,295,0,309,255,310,0,311,127,312,255,313,0,314,0,315,127,316,255,317,0,318,0,319,127,320,255,321,0,322,0,323,127,324,255,325,0,326,0,327,127,328,255,329,0,330,0,331,127,332,255,333,0,334,0,335,127,336,255,337,0,338,0]},
{id: "c2Green", rgb: [0.0, 1.0, 0.0], note: 72, name: "Green", fadeIn: 1000, fadeOut: 1000, levels: [9,255,10,0,11,0,12,255,13,0,14,0,15,0,16,255,17,0,18,0,19,0,20,255,21,0,22,0,23,0,24,255,25,0,26,0,27,0,28,255,29,0,30,0,31,0,32,255,33,0,34,0,35,0,36,255,37,0,38,0,53,255,54,0,55,0,56,255,57,0,58,0,59,0,60,255,61,0,62,0,63,0,64,255,65,0,66,0,67,0,68,255,69,0,70,0,71,0,72,255,73,0,74,0,75,0,76,255,77,0,78,0,79,0,80,255,81,0,82,0,266,255,267,0,268,0,269,255,270,0,271,0,272,0,273,255,274,0,275,0,276,0,277,255,278,0,279,0,280,0,281,255,282,0,283,0,284,0,285,255,286,0,287,0,288,0,289,255,290,0,291,0,292,0,293,255,294,0,295,0,309,255,310,0,311,0,312,255,313,0,314,0,315,0,316,255,317,0,318,0,319,0,320,255,321,0,322,0,323,0,324,255,325,0,326,0,327,0,328,255,329,0,330,0,331,0,332,255,333,0,334,0,335,0,336,255,337,0,338,0]},
{id: "c2Spring", rgb: [0.0, 1.0, 0.498], note: 73, name: "Spring", fadeIn: 1000, fadeOut: 1000, levels: [9,255,10,0,11,0,12,255,13,127,14,0,15,0,16,255,17,127,18,0,19,0,20,255,21,127,22,0,23,0,24,255,25,127,26,0,27,0,28,255,29,127,30,0,31,0,32,255,33,127,34,0,35,0,36,255,37,127,38,0,53,255,54,0,55,0,56,255,57,127,58,0,59,0,60,255,61,127,62,0,63,0,64,255,65,127,66,0,67,0,68,255,69,127,70,0,71,0,72,255,73,127,74,0,75,0,76,255,77,127,78,0,79,0,80,255,81,127,82,0,266,255,267,0,268,0,269,255,270,127,271,0,272,0,273,255,274,127,275,0,276,0,277,255,278,127,279,0,280,0,281,255,282,127,283,0,284,0,285,255,286,127,287,0,288,0,289,255,290,127,291,0,292,0,293,255,294,127,295,0,309,255,310,0,311,0,312,255,313,127,314,0,315,0,316,255,317,127,318,0,319,0,320,255,321,127,322,0,323,0,324,255,325,127,326,0,327,0,328,255,329,127,330,0,331,0,332,255,333,127,334,0,335,0,336,255,337,127,338,0]},
{id: "c2Cyan", rgb: [0.0, 1.0, 1.0], note: 74, name: "Cyan", fadeIn: 1000, fadeOut: 1000, levels: [9,255,10,0,11,0,12,255,13,255,14,0,15,0,16,255,17,255,18,0,19,0,20,255,21,255,22,0,23,0,24,255,25,255,26,0,27,0,28,255,29,255,30,0,31,0,32,255,33,255,34,0,35,0,36,255,37,255,38,0,53,255,54,0,55,0,56,255,57,255,58,0,59,0,60,255,61,255,62,0,63,0,64,255,65,255,66,0,67,0,68,255,69,255,70,0,71,0,72,255,73,255,74,0,75,0,76,255,77,255,78,0,79,0,80,255,81,255,82,0,266,255,267,0,268,0,269,255,270,255,271,0,272,0,273,255,274,255,275,0,276,0,277,255,278,255,279,0,280,0,281,255,282,255,283,0,284,0,285,255,286,255,287,0,288,0,289,255,290,255,291,0,292,0,293,255,294,255,295,0,309,255,310,0,311,0,312,255,313,255,314,0,315,0,316,255,317,255,318,0,319,0,320,255,321,255,322,0,323,0,324,255,325,255,326,0,327,0,328,255,329,255,330,0,331,0,332,255,333,255,334,0,335,0,336,255,337,255,338,0]},
{id: "c2Azure", rgb: [0.0, 0.498, 1.0], note: 75, name: "Azure", fadeIn: 1000, fadeOut: 1000, levels: [9,255,10,0,11,0,12,127,13,255,14,0,15,0,16,127,17,255,18,0,19,0,20,127,21,255,22,0,23,0,24,127,25,255,26,0,27,0,28,127,29,255,30,0,31,0,32,127,33,255,34,0,35,0,36,127,37,255,38,0,53,255,54,0,55,0,56,127,57,255,58,0,59,0,60,127,61,255,62,0,63,0,64,127,65,255,66,0,67,0,68,127,69,255,70,0,71,0,72,127,73,255,74,0,75,0,76,127,77,255,78,0,79,0,80,127,81,255,82,0,266,255,267,0,268,0,269,127,270,255,271,0,272,0,273,127,274,255,275,0,276,0,277,127,278,255,279,0,280,0,281,127,282,255,283,0,284,0,285,127,286,255,287,0,288,0,289,127,290,255,291,0,292,0,293,127,294,255,295,0,309,255,310,0,311,0,312,127,313,255,314,0,315,0,316,127,317,255,318,0,319,0,320,127,321,255,322,0,323,0,324,127,325,255,326,0,327,0,328,127,329,255,330,0,331,0,332,127,333,255,334,0,335,0,336,127,337,255,338,0]},
{id: "c2Blue", rgb: [0.0, 0.0, 1.0], note: 76, name: "Blue", fadeIn: 1000, fadeOut: 1000, levels: [9,255,10,0,11,0,12,0,13,255,14,0,15,0,16,0,17,255,18,0,19,0,20,0,21,255,22,0,23,0,24,0,25,255,26,0,27,0,28,0,29,255,30,0,31,0,32,0,33,255,34,0,35,0,36,0,37,255,38,0,53,255,54,0,55,0,56,0,57,255,58,0,59,0,60,0,61,255,62,0,63,0,64,0,65,255,66,0,67,0,68,0,69,255,70,0,71,0,72,0,73,255,74,0,75,0,76,0,77,255,78,0,79,0,80,0,81,255,82,0,266,255,267,0,268,0,269,0,270,255,271,0,272,0,273,0,274,255,275,0,276,0,277,0,278,255,279,0,280,0,281,0,282,255,283,0,284,0,285,0,286,255,287,0,288,0,289,0,290,255,291,0,292,0,293,0,294,255,295,0,309,255,310,0,311,0,312,0,313,255,314,0,315,0,316,0,317,255,318,0,319,0,320,0,321,255,322,0,323,0,324,0,325,255,326,0,327,0,328,0,329,255,330,0,331,0,332,0,333,255,334,0,335,0,336,0,337,255,338,0]},
{id: "c2Violet", rgb: [0.498, 0.0, 1.0], note: 77, name: "Violet", fadeIn: 1000, fadeOut: 1000, levels: [9,255,10,0,11,127,12,0,13,255,14,0,15,127,16,0,17,255,18,0,19,127,20,0,21,255,22,0,23,127,24,0,25,255,26,0,27,127,28,0,29,255,30,0,31,127,32,0,33,255,34,0,35,127,36,0,37,255,38,0,53,255,54,0,55,127,56,0,57,255,58,0,59,127,60,0,61,255,62,0,63,127,64,0,65,255,66,0,67,127,68,0,69,255,70,0,71,127,72,0,73,255,74,0,75,127,76,0,77,255,78,0,79,127,80,0,81,255,82,0,266,255,267,0,268,127,269,0,270,255,271,0,272,127,273,0,274,255,275,0,276,127,277,0,278,255,279,0,280,127,281,0,282,255,283,0,284,127,285,0,286,255,287,0,288,127,289,0,290,255,291,0,292,127,293,0,294,255,295,0,309,255,310,0,311,127,312,0,313,255,314,0,315,127,316,0,317,255,318,0,319,127,320,0,321,255,322,0,323,127,324,0,325,255,326,0,327,127,328,0,329,255,330,0,331,127,332,0,333,255,334,0,335,127,336,0,337,255,338,0]},
{id: "c2Magenta", rgb: [1.0, 0.0, 1.0], note: 78, name: "Magenta", fadeIn: 1000, fadeOut: 1000, levels: [9,255,10,0,11,255,12,0,13,255,14,0,15,255,16,0,17,255,18,0,19,255,20,0,21,255,22,0,23,255,24,0,25,255,26,0,27,255,28,0,29,255,30,0,31,255,32,0,33,255,34,0,35,255,36,0,37,255,38,0,53,255,54,0,55,255,56,0,57,255,58,0,59,255,60,0,61,255,62,0,63,255,64,0,65,255,66,0,67,255,68,0,69,255,70,0,71,255,72,0,73,255,74,0,75,255,76,0,77,255,78,0,79,255,80,0,81,255,82,0,266,255,267,0,268,255,269,0,270,255,271,0,272,255,273,0,274,255,275,0,276,255,277,0,278,255,279,0,280,255,281,0,282,255,283,0,284,255,285,0,286,255,287,0,288,255,289,0,290,255,291,0,292,255,293,0,294,255,295,0,309,255,310,0,311,255,312,0,313,255,314,0,315,255,316,0,317,255,318,0,319,255,320,0,321,255,322,0,323,255,324,0,325,255,326,0,327,255,328,0,329,255,330,0,331,255,332,0,333,255,334,0,335,255,336,0,337,255,338,0]},
{id: "c2Pink", rgb: [1.0, 0.157, 0.471], note: 79, name: "Pink", fadeIn: 1000, fadeOut: 1000, levels: [9,255,10,0,11,255,12,40,13,120,14,0,15,255,16,40,17,120,18,0,19,255,20,40,21,120,22,0,23,255,24,40,25,120,26,0,27,255,28,40,29,120,30,0,31,255,32,40,33,120,34,0,35,255,36,40,37,120,38,0,53,255,54,0,55,255,56,40,57,120,58,0,59,255,60,40,61,120,62,0,63,255,64,40,65,120,66,0,67,255,68,40,69,120,70,0,71,255,72,40,73,120,74,0,75,255,76,40,77,120,78,0,79,255,80,40,81,120,82,0,266,255,267,0,268,255,269,40,270,120,271,0,272,255,273,40,274,120,275,0,276,255,277,40,278,120,279,0,280,255,281,40,282,120,283,0,284,255,285,40,286,120,287,0,288,255,289,40,290,120,291,0,292,255,293,40,294,120,295,0,309,255,310,0,311,255,312,40,313,120,314,0,315,255,316,40,317,120,318,0,319,255,320,40,321,120,322,0,323,255,324,40,325,120,326,0,327,255,328,40,329,120,330,0,331,255,332,40,333,120,334,0,335,255,336,40,337,120,338,0]},
{id: "c2Warm", rgb: [1.0, 0.941, 0.627], note: 80, name: "Warm", fadeIn: 1000, fadeOut: 1000, levels: [9,255,10,0,11,255,12,120,13,40,14,120,15,255,16,120,17,40,18,120,19,255,20,120,21,40,22,120,23,255,24,120,25,40,26,120,27,255,28,120,29,40,30,120,31,255,32,120,33,40,34,120,35,255,36,120,37,40,38,120,53,255,54,0,55,255,56,120,57,40,58,120,59,255,60,120,61,40,62,120,63,255,64,120,65,40,66,120,67,255,68,120,69,40,70,120,71,255,72,120,73,40,74,120,75,255,76,120,77,40,78,120,79,255,80,120,81,40,82,120,266,255,267,0,268,255,269,120,270,40,271,120,272,255,273,120,274,40,275,120,276,255,277,120,278,40,279,120,280,255,281,120,282,40,283,120,284,255,285,120,286,40,287,120,288,255,289,120,290,40,291,120,292,255,293,120,294,40,295,120,309,255,310,0,311,255,312,120,313,40,314,120,315,255,316,120,317,40,318,120,319,255,320,120,321,40,322,120,323,255,324,120,325,40,326,120,327,255,328,120,329,40,330,120,331,255,332,120,333,40,334,120,335,255,336,120,337,40,338,120]},
{id: "c2White", rgb: [1.0, 1.0, 1.0], note: 81, name: "White", fadeIn: 1000, fadeOut: 1000, levels: [9,255,10,0,11,0,12,0,13,0,14,255,15,0,16,0,17,0,18,255,19,0,20,0,21,0,22,255,23,0,24,0,25,0,26,255,27,0,28,0,29,0,30,255,31,0,32,0,33,0,34,255,35,0,36,0,37,0,38,255,53,255,54,0,55,0,56,0,57,0,58,255,59,0,60,0,61,0,62,255,63,0,64,0,65,0,66,255,67,0,68,0,69,0,70,255,71,0,72,0,73,0,74,255,75,0,76,0,77,0,78,255,79,0,80,0,81,0,82,255,266,255,267,0,268,0,269,0,270,0,271,255,272,0,273,0,274,0,275,255,276,0,277,0,278,0,279,255,280,0,281,0,282,0,283,255,284,0,285,0,286,0,287,255,288,0,289,0,290,0,291,255,292,0,293,0,294,0,295,255,309,255,310,0,311,0,312,0,313,0,314,255,315,0,316,0,317,0,318,255,319,0,320,0,321,0,322,255,323,0,324,0,325,0,326,255,327,0,328,0,329,0,330,255,331,0,332,0,333,0,334,255,335,0,336,0,337,0,338,255]},
{id: "c2Cool", rgb: [0.784, 0.941, 1.0], note: 82, name: "Cool", fadeIn: 1000, fadeOut: 1000, levels: [9,255,10,0,11,80,12,120,13,255,14,120,15,80,16,120,17,255,18,120,19,80,20,120,21,255,22,120,23,80,24,120,25,255,26,120,27,80,28,120,29,255,30,120,31,80,32,120,33,255,34,120,35,80,36,120,37,255,38,120,53,255,54,0,55,80,56,120,57,255,58,120,59,80,60,120,61,255,62,120,63,80,64,120,65,255,66,120,67,80,68,120,69,255,70,120,71,80,72,120,73,255,74,120,75,80,76,120,77,255,78,120,79,80,80,120,81,255,82,120,266,255,267,0,268,80,269,120,270,255,271,120,272,80,273,120,274,255,275,120,276,80,277,120,278,255,279,120,280,80,281,120,282,255,283,120,284,80,285,120,286,255,287,120,288,80,289,120,290,255,291,120,292,80,293,120,294,255,295,120,309,255,310,0,311,80,312,120,313,255,314,120,315,80,316,120,317,255,318,120,319,80,320,120,321,255,322,120,323,80,324,120,325,255,326,120,327,80,328,120,329,255,330,120,331,80,332,120,333,255,334,120,335,80,336,120,337,255,338,120]},
{id: "c2Custom", rgb: [1.0, 0.235, 0.0], note: 83, name: "Custom", fadeIn: 1000, fadeOut: 1000, levels: [9,0,53,0,266,0,309,0]},
],
sliders: [
{id: "s2Dim", cc: 35, name: "Dim", levels: [9,255,53,255,266,255,309,255]},
{id: "s2R", cc: 36, name: "R", levels: [11,255,15,255,19,255,23,255,27,255,31,255,35,255,55,255,59,255,63,255,67,255,71,255,75,255,79,255,268,255,272,255,276,255,280,255,284,255,288,255,292,255,311,255,315,255,319,255,323,255,327,255,331,255,335,255]},
{id: "s2G", cc: 37, name: "G", levels: [12,255,16,255,20,255,24,255,28,255,32,255,36,255,56,255,60,255,64,255,68,255,72,255,76,255,80,255,269,255,273,255,277,255,281,255,285,255,289,255,293,255,312,255,316,255,320,255,324,255,328,255,332,255,336,255]},
{id: "s2B", cc: 38, name: "B", levels: [13,255,17,255,21,255,25,255,29,255,33,255,37,255,57,255,61,255,65,255,69,255,73,255,77,255,81,255,270,255,274,255,278,255,282,255,286,255,290,255,294,255,313,255,317,255,321,255,325,255,329,255,333,255,337,255]},
{id: "s2W", cc: 39, name: "W", levels: [14,255,18,255,22,255,26,255,30,255,34,255,38,255,58,255,62,255,66,255,70,255,74,255,78,255,82,255,271,255,275,255,279,255,283,255,287,255,291,255,295,255,314,255,318,255,322,255,326,255,330,255,334,255,338,255]},
]
},
];
var LAMP = "Lamp";
var LAMP_OFF = 0.3; // brightness of a pad's tile when it is not playing
var FADE_RATE = 100; // script updates per second
var PLAY_CC = 27; // hold Play to move bank 2 (notes 52-67) up 16, like padcontroller/layer.py
var BANK_FIRST = 52;
var BANK_LAST = 67;
var BANK_SHIFT = 16;
var DMX_SIZE = 513; // channels are 1-based
var states = [];
var sent = [];
var lookup = {};
var lampParams = [];
var sliderParams = [];
var nowParams = [];
var busy = false;
var primed = false;
var playHeld = false;
function init()
{
script.setUpdateRate(FADE_RATE);
for (var i = 0; i < DMX_SIZE; i++) sent[i] = -1;
states = [];
for (var g = 0; g < GROUPS.length; g++)
{
var level = [], from = [], to = [], touched = [];
for (var c = 0; c < DMX_SIZE; c++) { level[c] = 0; from[c] = 0; to[c] = 0; touched[c] = 0; }
var group = GROUPS[g];
for (var p = 0; p < group.pads.length; p++) mark(touched, group.pads[p].levels);
for (var s = 0; s < group.sliders.length; s++) mark(touched, group.sliders[s].levels);
var mix = [];
for (var m = 0; m < group.sliders.length; m++) mix[m] = 0;
states[g] = {active: -1, elapsed: 0, duration: 0, level: level, from: from, to: to, touched: touched, mix: mix};
// Controls on the script's Params, for the dashboard to show.
sliderParams[g] = [];
lampParams[g] = [];
for (var q = 0; q < group.pads.length; q++)
{
script.addTrigger(group.pads[q].id, group.name + " " + group.pads[q].name);
lampParams[g][q] = script.addColorParameter(group.pads[q].id + LAMP, group.name + " " + group.pads[q].name + " lamp", shade(group.pads[q].rgb, LAMP_OFF));
lookup[group.pads[q].id] = {g: g, p: q, s: -1};
}
for (var r = 0; r < group.sliders.length; r++)
{
sliderParams[g][r] = script.addFloatParameter(group.sliders[r].id, group.name + " " + group.sliders[r].name, 0, 0, 1);
lookup[group.sliders[r].id] = {g: g, p: -1, s: r};
}
nowParams[g] = script.addStringParameter(group.now, group.name + " scene", "");
}
script.log("show script ready: " + GROUPS.length + " groups");
}
function mark(touched, levels)
{
for (var i = 0; i < levels.length; i += 2) touched[levels[i]] = 1;
}
// A pad press starts its scene and fades the others out. A second press stops it.
function noteOnEvent(channel, pitch, velocity)
{
if (velocity == 0) return;
if (playHeld && pitch >= BANK_FIRST && pitch <= BANK_LAST) pitch += BANK_SHIFT;
for (var g = 0; g < GROUPS.length; g++)
{
var pads = GROUPS[g].pads;
for (var p = 0; p < pads.length; p++)
{
if (pads[p].note == pitch) { press(g, p); return; }
}
}
}
// A control on the dashboard changed.
function scriptParameterChanged(param)
{
if (busy) return;
var hit = lookup[param.name];
if (!hit) return;
if (hit.p >= 0) press(hit.g, hit.p);
else states[hit.g].mix[hit.s] = param.get();
}
function shade(rgb, level)
{
return [rgb[0] * level, rgb[1] * level, rgb[2] * level, 1];
}
// Light the playing pad's strip on the board and show its name.
function show(g, name)
{
busy = true;
nowParams[g].set(name);
var pads = GROUPS[g].pads;
for (var p = 0; p < pads.length; p++) lampParams[g][p].set(shade(pads[p].rgb, states[g].active == p ? 1 : LAMP_OFF));
busy = false;
}
function press(g, p)
{
var st = states[g];
var pad = GROUPS[g].pads[p];
for (var c = 0; c < DMX_SIZE; c++) { st.from[c] = st.level[c]; st.to[c] = 0; }
if (st.active == p)
{
st.active = -1;
st.duration = pad.fadeOut;
show(g, "");
}
else
{
for (var i = 0; i < pad.levels.length; i += 2) st.to[pad.levels[i]] = pad.levels[i + 1];
st.active = p;
st.duration = pad.fadeIn;
show(g, pad.name);
}
st.elapsed = 0;
}
function ccEvent(channel, number, value)
{
if (number == PLAY_CC) { playHeld = value > 0; return; }
for (var g = 0; g < GROUPS.length; g++)
{
var sliders = GROUPS[g].sliders;
for (var s = 0; s < sliders.length; s++)
{
if (sliders[s].cc == number)
{
states[g].mix[s] = value / 127;
busy = true;
sliderParams[g][s].set(value / 127);
busy = false;
}
}
}
}
// The dashboard web server does not always start when a project loads with it enabled, so switch
// it off and on once the script is running.
function startWeb()
{
var settings = root.projectSettings;
if (!settings || !settings.dashboardSettings) return;
var web = settings.dashboardSettings.enableDashboardServer;
if (!web) return;
web.set(false);
web.set(true);
script.log("dashboard web server restarted");
}
function update(deltaTime)
{
// A colour control's starting value is read in a different colour model and saved values load
// after init, so paint every tile once the script is running.
if (!primed)
{
primed = true;
startWeb();
for (var g = 0; g < GROUPS.length; g++) show(g, states[g].active >= 0 ? GROUPS[g].pads[states[g].active].name : "");
}
var out = [];
for (var c = 0; c < DMX_SIZE; c++) out[c] = 0;
for (var g = 0; g < GROUPS.length; g++) render(g, deltaTime, out);
var first = -1, last = -1;
for (var i = 1; i < DMX_SIZE; i++)
{
if (out[i] != sent[i]) { if (first < 0) first = i; last = i; }
}
if (first < 0) return;
var values = [];
for (var j = first; j <= last; j++) { values.push(out[j]); sent[j] = out[j]; }
root.modules.lights.send(first, values);
if (root.modules.preview) root.modules.preview.send(first, values);
}
function render(g, deltaTime, out)
{
var st = states[g];
st.elapsed += deltaTime * 1000;
var t = st.duration > 0 ? Math.min(1, st.elapsed / st.duration) : 1;
for (var c = 1; c < DMX_SIZE; c++)
{
if (!st.touched[c]) continue;
st.level[c] = st.from[c] + (st.to[c] - st.from[c]) * t;
out[c] = Math.max(out[c], st.level[c]);
}
var sliders = GROUPS[g].sliders;
for (var s = 0; s < sliders.length; s++)
{
var levels = sliders[s].levels;
for (var i = 0; i < levels.length; i += 2)
{
out[levels[i]] = Math.max(out[levels[i]], levels[i + 1] * st.mix[s]);
}
}
for (var k = 1; k < DMX_SIZE; k++) out[k] = Math.round(out[k]);
}
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
"""Pad Controller: the SMC-PAD preset editor and MIDI intercept."""
+33
View File
@@ -0,0 +1,33 @@
"""python3 -m padcontroller [--port 8770]"""
from __future__ import annotations
import argparse
import threading
import webbrowser
from padcontroller.server import make_server
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="padcontroller", description="Pad Controller: SMC-PAD preset editor")
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--port", type=int, default=8770)
parser.add_argument("--no-browser", action="store_true")
args = parser.parse_args(argv)
server = make_server(args.host, args.port)
url = f"http://{args.host}:{args.port}/"
print(f"Pad Controller → {url} Ctrl+C to quit")
if not args.no_browser:
threading.Timer(0.4, webbrowser.open, args=(url,)).start()
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
return 0
if __name__ == "__main__":
raise SystemExit(main())
+336
View File
@@ -0,0 +1,336 @@
"""Read and save the SMC-PAD preset over the Private USB port.
Writes go to the preset address, as MidiSuite sends them; the lamps follow
straight away. Save writes the bytes that differ, checks each read-back,
then sends the empty write MidiSuite's Save button sends, which keeps the
preset after a power cycle. It never sends erase.
"""
from __future__ import annotations
import glob
import sys
import time
from pathlib import Path
from padcontroller.preset import GLOBAL_LEN, IMAGE_LEN, changed_ranges
from padcontroller.sysex import (
CMD_READ,
MEM_GLOBAL,
MEM_PRESET,
RAM,
payload_data,
read_request,
save_request,
write_request,
)
ROOT = Path(__file__).resolve().parents[1]
READ_CHUNK = 512
WRITE_CHUNK = 64
class PadError(RuntimeError):
pass
def load_rtmidi():
for path in glob.glob(str(ROOT / ".venv" / "lib" / "python*" / "site-packages")):
if path not in sys.path:
sys.path.insert(0, path)
import rtmidi
return rtmidi
def private_port(names: list[str]) -> str:
for name in names:
if "Private" in name:
return name
raise PadError(
"SMC-PAD Private port not found. Ports:\n " + "\n ".join(names or ["(none)"])
)
def master_port(names: list[str]) -> str:
for name in names:
if "Master" in name:
return name
raise PadError(
"SMC-PAD Master port not found. Ports:\n " + "\n ".join(names or ["(none)"])
)
def transact(midiout, midiin, message: list[int], timeout: float = 0.8, expect: int | None = None) -> bytes:
while True:
item = midiin.get_message()
if not item or not item[0]:
break
midiout.send_message(message)
deadline = time.time() + timeout
while time.time() < deadline:
item = midiin.get_message()
if not item or not item[0]:
time.sleep(0.004)
continue
raw = bytes(item[0])
if raw[:1] != b"\xf0" or raw[-1:] != b"\xf7":
continue
decoded = decode_body(raw)
if expect is not None and (len(decoded) < 3 or decoded[2] != expect):
continue
return decoded
raise PadError("the pad did not answer")
def decode_body(raw: bytes) -> bytes:
from padcontroller.sysex import decode
return decode(raw[1:-1])
class Link:
"""One open Private port, input and output."""
def __init__(self):
rtmidi = load_rtmidi()
self.midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA)
self.midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA)
self.name = private_port(self.midiout.get_ports())
index = self.midiout.get_ports().index(self.name)
self.midiin.open_port(index)
self.midiin.ignore_types(sysex=False, timing=True, active_sense=True)
self.midiout.open_port(index)
def close(self) -> None:
for port in (self.midiout, self.midiin):
port.close_port()
port.delete()
def read(self, address: int, size: int, memory: int = MEM_PRESET) -> bytes:
reply = transact(self.midiout, self.midiin, read_request(address, size, memory), expect=CMD_READ)
data = payload_data(reply)
return data[:size]
def write(self, address: int, data: bytes, memory: int = MEM_PRESET) -> None:
transact(self.midiout, self.midiin, write_request(address, data, memory))
def __enter__(self) -> "Link":
return self
def __exit__(self, *exc) -> None:
self.close()
def read_image(link: Link | None = None) -> bytes:
own = link is None
if link is None:
link = Link()
try:
got = bytearray()
while len(got) < IMAGE_LEN:
ask = min(READ_CHUNK, IMAGE_LEN - len(got))
part = link.read(len(got), ask)
if not part:
raise PadError(f"empty read at {len(got)}")
got += part[:ask]
return bytes(got[:IMAGE_LEN])
finally:
if own:
link.close()
def _port_names(kind: str) -> list[str]:
rtmidi = load_rtmidi()
probe = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA) if kind == "out" else rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA)
try:
return list(probe.get_ports())
finally:
probe.delete()
def read_port_names() -> list[str]:
return _port_names("out")
def input_names() -> list[str]:
return _port_names("in")
def connected() -> str | None:
try:
return private_port(read_port_names())
except PadError:
return None
def read_global(link: Link | None = None) -> bytes:
"""The 12-byte settings block MidiSuite polls: tempo, swing, curve, transpose."""
own = link is None
if link is None:
link = Link()
try:
data = link.read(0, GLOBAL_LEN, MEM_GLOBAL)
if len(data) < GLOBAL_LEN:
raise PadError(f"global block read {len(data)} bytes, expected {GLOBAL_LEN}")
return data[:GLOBAL_LEN]
finally:
if own:
link.close()
def set_bank(bank: int, link: Link | None = None) -> int:
"""Switch the pad bank the way MidiSuite does: one live byte in the
global block. It does not commit; Save keeps whatever the block holds."""
from padcontroller.preset import GLOBAL_BANK
if bank not in (0, 1):
raise PadError("pad bank must be 0 or 1")
own = link is None
if link is None:
link = Link()
try:
link.write(GLOBAL_BANK, bytes((bank,)), MEM_GLOBAL)
got = read_global(link)[GLOBAL_BANK]
if got != bank:
raise PadError(f"the pad is on bank {got + 1}, not {bank + 1}")
return bank
finally:
if own:
link.close()
def save_image(desired: bytes, link: Link | None = None, settings: bytes | None = None) -> int:
"""Write differing bytes to the preset and commit them.
Returns how many bytes were written. An unchanged image still gets
MidiSuite's empty save, so Save always commits. The settings block,
when given and changed, is written whole, as MidiSuite does.
"""
if len(desired) != IMAGE_LEN:
raise PadError(f"preset image is {len(desired)} bytes, expected {IMAGE_LEN}")
if settings is not None and len(settings) != GLOBAL_LEN:
raise PadError(f"global block is {len(settings)} bytes, expected {GLOBAL_LEN}")
own = link is None
if link is None:
link = Link()
try:
current = read_image(link)
ranges = changed_ranges(current, desired, WRITE_CHUNK)
for address, data in ranges:
_write_checked(link, address, data)
written = sum(len(data) for _address, data in ranges)
if settings is not None and read_global(link) != settings:
link.write(0, settings, MEM_GLOBAL)
if read_global(link) != settings:
raise PadError("the pad did not keep the global settings")
written += len(settings)
_commit(link)
return written
finally:
if own:
link.close()
def write_colour(preset: int, index: int, rgb: tuple[int, int, int] | list[int]) -> int:
"""Light one pad. The same three-byte write MidiSuite sends while its
colour picker moves. It does not commit; Save does that."""
from padcontroller.preset import colour_offset
if len(rgb) != 3:
raise PadError("a pad colour needs red, green, and blue")
payload = bytes(int(channel) & 0xFF for channel in rgb)
offset = colour_offset(preset, index)
with Link() as link:
_write_checked(link, offset, payload)
return offset
def _write_checked(link: Link, address: int, data: bytes) -> None:
"""Write the preset address, as MidiSuite does, then read it back."""
link.write(address, data)
reply = transact(link.midiout, link.midiin, read_request(address, len(data)))
got = payload_data(reply)
if got[:len(data)] != data:
raise PadError(
f"read-back at {address:#x} was {got[:len(data)].hex()}, expected {data.hex()}"
)
def _commit(link: Link) -> None:
reply = transact(link.midiout, link.midiin, save_request())
if reply[:3] != b"\x00\x59\x00" or reply[6:7] != b"\x00":
raise PadError(f"the pad did not accept the save ({reply.hex()})")
def probe_relative(listen: float = 2.5) -> str:
"""Try knob type 0x03 in RAM only, on every preset's last knob.
Restores the original six bytes. Does not save. Returns ``relative``
when a turn of that knob sends a step, ``absolute`` when it sends a
running value, or ``silent`` when nothing arrives.
"""
from padcontroller.preset import KNOB_AT, KNOB_COUNT, KNOB_LEN, PRESET_COUNT, PRESET_LEN, RELATIVE_TYPE
knob = KNOB_COUNT - 1
offsets = [index * PRESET_LEN + KNOB_AT + knob * KNOB_LEN for index in range(PRESET_COUNT)]
rtmidi = load_rtmidi()
master_name = master_port(input_names())
heard: list[tuple[int, int, int]] = []
watched: set[tuple[int, int]] = set()
with Link() as link:
original = [link.read(offset, KNOB_LEN) for offset in offsets]
watched = {(rec[2], rec[3]) for rec in original}
try:
for offset, rec in zip(offsets, original):
link.write(RAM + offset, bytes((RELATIVE_TYPE,)) + rec[1:])
heard = _listen_cc(rtmidi, master_name, listen)
finally:
for offset, rec in zip(offsets, original):
link.write(RAM + offset, rec)
matched = [item for item in heard if (item[0], item[1]) in watched]
return _classify(matched)
def _listen_cc(rtmidi, port_name: str, listen: float) -> list[tuple[int, int, int]]:
midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA)
names = midiin.get_ports()
midiin.open_port(names.index(port_name))
midiin.ignore_types(sysex=True, timing=True, active_sense=True)
found: list[tuple[int, int, int]] = []
try:
deadline = time.time() + listen
while time.time() < deadline:
item = midiin.get_message()
if not item or not item[0]:
time.sleep(0.004)
continue
data = bytes(item[0])
if len(data) >= 3 and (data[0] & 0xF0) == 0xB0:
found.append((data[0] & 0x0F, data[1], data[2]))
finally:
midiin.close_port()
midiin.delete()
return found
def _classify(messages: list[tuple[int, int, int]]) -> str:
if not messages:
return "silent"
values = [value for _channel, _cc, value in messages]
unique = set(values)
if unique <= {0, 1, 127} or unique <= {63, 64, 65} or _steps(values):
return "relative"
if len(unique) >= 4:
return "absolute"
return "silent"
def _steps(values: list[int]) -> bool:
"""1..63 clockwise and 65..127 counter-clockwise, with no running ramp."""
for value in values:
if value == 0 or value == 64 or value > 127:
return False
if value >= 16 and value <= 111:
return False
return True
Binary file not shown.
+74
View File
@@ -0,0 +1,74 @@
"""Hold Play to move the bank 2 pads up a layer.
The SMC-PAD sends CC 27 as 127 when Play goes down and 0 when it comes up.
While it is down, pad notes 52–67 go out as 68–83, so QLC+ can tell a
second set of buttons from the first. Play itself is not passed on.
With lock_knobs, knobs 1–5 (CC 30–34) drive colour 1's sliders and knobs 6–10
(CC 35–39) drive colour 2's, but only after the Custom pad (note 67, or 83
with Play held) has been pressed. Pressing any other bank 2 pad locks them
again, and its sliders are sent back to zero so their scenes stop.
Locked knob turns are dropped.
The Sound pad (note 36) toggles QLC+'s audio triggers, which pump the cans'
Sound submaster in the Dimmers frame. Every press and release also sends CC 100
at full, so switching sound off leaves the cans at full rather than wherever
the music left them.
"""
from __future__ import annotations
PLAY_CC = 27
FIRST_NOTE = 52
LAST_NOTE = 67
SHIFT = 16
CUSTOM_NOTE = 67
KNOB_FIRST_CC = 30
KNOBS_PER_LAYER = 5
SOUND_NOTE = 36
SUBMASTER_CC = 100
class PlayLayer:
def __init__(self, lock_knobs: bool = False) -> None:
self.lock_knobs = lock_knobs
self.unlocked: set[int] = set() # layers 0 and 1
self.held = False
# (channel, note as pressed) -> note sent, so a release matches its press
self.sent: dict[tuple[int, int], int] = {}
def handle(self, data: list[int]) -> list[list[int]]:
"""The messages to send on. Empty when the message is swallowed."""
status = data[0]
kind = status & 0xF0
channel = status & 0x0F
if kind == 0xB0 and len(data) >= 3 and data[1] == PLAY_CC:
self.held = data[2] > 0
return []
if kind == 0xB0 and len(data) >= 3 and self.lock_knobs:
index = data[1] - KNOB_FIRST_CC
if 0 <= index < 2 * KNOBS_PER_LAYER and index // KNOBS_PER_LAYER not in self.unlocked:
return []
if kind not in (0x80, 0x90) or len(data) < 3:
return [list(data)]
note = data[1]
key = (channel, note)
is_on = kind == 0x90 and data[2] > 0
extra: list[list[int]] = []
if is_on and FIRST_NOTE <= note <= LAST_NOTE:
layer = 1 if self.held else 0
if note == CUSTOM_NOTE:
self.unlocked.add(layer)
elif layer in self.unlocked:
self.unlocked.discard(layer)
first = KNOB_FIRST_CC + layer * KNOBS_PER_LAYER
extra = [[0xB0, first + n, 0] for n in range(KNOBS_PER_LAYER)]
if note == SOUND_NOTE:
# Again on release, after any spectrum frame QLC+ still had queued
extra = [[0xB0, SUBMASTER_CC, 127]]
if is_on:
out = note + SHIFT if self.held and FIRST_NOTE <= note <= LAST_NOTE else note
self.sent[key] = out
else:
out = self.sent.pop(key, note)
return [[status, out, *data[2:]], *extra]
+245
View File
@@ -0,0 +1,245 @@
"""Pad controller: intercept the SMC-PAD's MIDI and smooth its knob CCs so RGBW fades feel less stepped.
Reads the physical pad (Bluetooth or USB), passes pad notes through
immediately, and eases Control Change values toward their targets at
~120 Hz before emitting on a virtual port named "padcontroller".
On start it also sets the pad lamps over USB (scripts/pad/pad_lamps.py): bank 1 off and
bank 2 in the colours from shows/test.qxw. On Bluetooth it says so and carries on.
While Play is held, bank 2 notes 52–67 go out as 68–83 (see padcontroller/layer.py).
Point QLC+ MIDI input at that virtual port (midi.qxw does this via
patch_smc_pad.py once the pad controller is running). Every 2 s it checks the
links: it reopens the pad when it is replugged (or moves to USB when that turns
up) and re-links QLC+ to the virtual port after a restart, so QLC+ can stay open.
Usage:
.venv/bin/python -m padcontroller.midi
# optional: --tau 0.05 (seconds; lower = snappier, higher = silkier)
padcontroller/systemd/install.sh runs it as a systemd user service.
"""
from __future__ import annotations
import argparse
import math
import re
import subprocess
import sys
import time
from dataclasses import dataclass, field
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
import glob
for p in glob.glob(str(ROOT / ".venv" / "lib" / "python*" / "site-packages")):
sys.path.insert(0, p)
import rtmidi
from padcontroller.layer import SUBMASTER_CC, PlayLayer # noqa: E402
# The lamp colours come from the show scripts, which are not part of this package.
sys.path.insert(0, str(ROOT / "scripts" / "pad"))
from pad_lamps import set_lamps # noqa: E402
VIRTUAL_NAME = "padcontroller"
# USB first when the pad is plugged in, Bluetooth otherwise.
SOURCE_HINTS = (
"SINCO SMC-PAD-Master",
"SMC-PAD Bluetooth",
"SINCO SMC-PAD-Private",
"SINCO",
"SMC-PAD",
)
def pick_source(names: list[str]) -> int | None:
"""Index of the best SMC-PAD port in names, or None when the pad is not there."""
for hint in SOURCE_HINTS:
for i, name in enumerate(names):
if hint in name and VIRTUAL_NAME not in name:
return i
return None
def find_source_port(midiin: rtmidi.MidiIn) -> int:
ports = midiin.get_ports()
i = pick_source(ports)
if i is None:
raise SystemExit(
"No SMC-PAD MIDI source found. Ports:\n " + "\n ".join(ports or ["(none)"])
)
return i
@dataclass
class AlsaPort:
addr: str # "client:port"
client: str
name: str
to: set[str] = field(default_factory=set)
sources: set[str] = field(default_factory=set)
def parse_aconnect(text: str) -> list[AlsaPort]:
"""The ports in `aconnect -l` output, with who they connect to and from."""
ports: list[AlsaPort] = []
client = client_name = None
for line in text.splitlines():
m = re.match(r"client (\d+): '([^']+)'", line)
if m:
client, client_name = m.group(1), m.group(2)
continue
m = re.match(r"\s+(\d+)\s+'([^']+)'", line)
if m and client is not None:
ports.append(AlsaPort(f"{client}:{m.group(1)}", client_name, m.group(2).strip()))
continue
m = re.match(r"\s+(Connecting To|Connected From):(.*)", line)
if m and ports:
addrs = set(re.findall(r"\d+:\d+", m.group(2)))
(ports[-1].to if m.group(1) == "Connecting To" else ports[-1].sources).update(addrs)
return ports
def missing_links(ports: list[AlsaPort], src_name: str | None) -> list[tuple[str, str]]:
"""(from, to) ALSA links the pad controller should have but doesn't.
The pad into padcontroller-in (Bluetooth MIDI sometimes drops it, and a replugged
USB pad comes back without it), and padcontroller out to every QLC+ client
(QLC+ only subscribes when it opens the port, so it loses it when we restart).
"""
links = []
ours_in = next((p for p in ports if p.client == "padcontroller-in"), None)
ours_out = next((p for p in ports if p.client == "padcontroller-out"), None)
m = re.search(r"(\d+:\d+)$", src_name or "")
if ours_in and m and m.group(1) not in ours_in.sources:
links.append((m.group(1), ours_in.addr))
if ours_out:
for p in ports:
if p.client == "qlcplus" and p.addr not in ours_out.to:
links.append((ours_out.addr, p.addr))
return links
def ensure_links(src_name: str | None) -> None:
try:
out = subprocess.check_output(["aconnect", "-l"], text=True)
except (FileNotFoundError, subprocess.CalledProcessError):
return
for src, dst in missing_links(parse_aconnect(out), src_name):
if subprocess.run(["aconnect", src, dst], capture_output=True).returncode == 0:
print(f"Linked {src} -> {dst}", flush=True)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument(
"--tau",
type=float,
default=0.055,
help="smoothing time constant in seconds (default 0.055)",
)
ap.add_argument("--rate", type=float, default=120.0, help="update Hz")
ap.add_argument(
"--lock-knobs",
action="store_true",
help="knobs 1-10 move test.qxw's custom sliders only after the Custom pad is pressed",
)
ap.add_argument("--no-lamps", action="store_true", help="leave the pad lamp colours alone")
args = ap.parse_args()
midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA, name="padcontroller-in")
midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA, name="padcontroller-out")
src = find_source_port(midiin)
src_name = midiin.get_ports()[src]
midiin.open_port(src)
midiin.ignore_types(timing=True, active_sense=True, sysex=True)
midiout.open_virtual_port(VIRTUAL_NAME)
# current/target as floats 0..127, keyed by (channel, cc)
current: dict[tuple[int, int], float] = {}
target: dict[tuple[int, int], float] = {}
last_sent: dict[tuple[int, int], int] = {}
layer = PlayLayer(lock_knobs=args.lock_knobs)
print(f"Source: {src_name}", flush=True)
print(f"Virtual: {VIRTUAL_NAME} (tau={args.tau}s @ {args.rate} Hz)", flush=True)
print("Pass notes through (Play held shifts bank 2 up 16); smooth CC. Ctrl+C to stop.", flush=True)
ensure_links(src_name)
if not args.no_lamps:
set_lamps()
dt = 1.0 / args.rate
alpha = 1.0 - math.exp(-dt / max(args.tau, 1e-4))
next_link_check = time.monotonic() + 2.0
try:
while True:
now = time.monotonic()
if now >= next_link_check:
# Follow the pad: reopen it when it comes back, and move to USB when plugged in.
names = midiin.get_ports()
best = pick_source(names)
best_name = names[best] if best is not None else None
if best_name != src_name:
midiin.close_port()
if best is not None:
midiin.open_port(best)
print(f"Source: {best_name}", flush=True)
else:
print("Source: (pad gone, waiting)", flush=True)
src_name = best_name
ensure_links(src_name)
next_link_check = now + 2.0
# Drain inbound
while True:
msg = midiin.get_message()
if msg is None:
break
data, _ = msg
if not data:
continue
for out in layer.handle(list(data)):
cmd = out[0] & 0xF0
if cmd == 0xB0 and len(out) >= 3 and out[1] != SUBMASTER_CC:
# Control Change → smooth
key = (out[0] & 0x0F, out[1])
target[key] = float(out[2])
if key not in current:
current[key] = float(out[2])
last_sent[key] = -1
else:
# Notes, aftertouch, PC, the Sound reset (always resent), etc. → immediate
midiout.send_message(out)
# Ease CC toward targets and emit when quantized value moves
for key, tgt in list(target.items()):
cur = current.get(key, tgt)
cur = cur + (tgt - cur) * alpha
# Snap when close so we actually reach the endpoint
if abs(tgt - cur) < 0.15:
cur = tgt
current[key] = cur
q = int(round(cur))
q = 0 if q < 0 else 127 if q > 127 else q
if last_sent.get(key) != q:
ch, cc = key
midiout.send_message([0xB0 | ch, cc, q])
last_sent[key] = q
time.sleep(dt)
except KeyboardInterrupt:
print("\nStopped.", flush=True)
finally:
midiin.close_port()
midiout.close_port()
del midiin
del midiout
if __name__ == "__main__":
main()
+317
View File
@@ -0,0 +1,317 @@
"""SMC-PAD preset image: 8 × 3539 bytes, the map MidiSuite edits."""
from __future__ import annotations
IMAGE_LEN = 28312
PRESET_LEN = 3539
PRESET_COUNT = 8
BUTTON_COUNT = 5
BUTTON_LEN = 23
BUTTON_NAMES = ("Left", "Right", "Play", "Stop", "Record")
KNOB_AT = 115
KNOB_COUNT = 16
KNOB_LEN = 6
KNOB_BANK = 8
GAP_AT = 211
PAD_AT = 212
PAD_LEN = 26
PAD_COUNT = 128
PAGE_LEN = 16
PAGE_COUNT = 8
RGB_AT = 4
# Global settings, memory type 4. Offsets are the fields MidiSuite's Glob
# panel showed against the factory block 78 00 32 04 00 00 02 00 01 01 00 00.
GLOBAL_LEN = 12
GLOBAL_TEMPO = 0 # two bytes, little-endian
GLOBAL_SWING = 2
GLOBAL_CURVE = 6
GLOBAL_TRANSPOSE = 7 # signed
GLOBAL_BANK = 11 # 0 is pad bank 1, 1 is pad bank 2; MidiSuite writes it to switch banks
# File bytes. Names are only values MidiSuite has shown for this pad's
# factory image, or a RAM probe on this pad has heard.
KNOB_TYPES = {0x00: "CC"}
BUTTON_TYPES = {0x02: "CC Push"}
# Set after a RAM-only probe hears a relative step from type 0x03.
RELATIVE_TYPE = 0x03
RELATIVE_CONFIRMED = False
FULL = 0xF0
SYSEX_ROOM = 16 # button bytes 6..21; byte 22 is the flag
def scale(value: int) -> int:
"""Map 0–255 onto the pad's 0–240 colour range."""
return (value * FULL + 127) // 255
def knob_type_names() -> dict[int, str]:
names = dict(KNOB_TYPES)
if RELATIVE_CONFIRMED:
names[RELATIVE_TYPE] = "Relative"
return names
def type_catalog() -> dict[str, list[dict[str, int | str]]]:
def rows(names: dict[int, str]) -> list[dict[str, int | str]]:
return [{"value": value, "name": name} for value, name in sorted(names.items())]
return {
"knob": rows(knob_type_names()),
"button": rows(BUTTON_TYPES),
}
class PresetError(ValueError):
pass
def _byte(value: object, label: str) -> int:
if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 255:
raise PresetError(f"{label} must be a byte")
return value
def _channel(value: object, label: str) -> int:
"""MIDI channel 1–16 as stored, which is 0–15."""
if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= 16:
raise PresetError(f"{label} must be MIDI channel 1–16")
return value - 1
def _hex(value: object, label: str) -> bytes:
if not isinstance(value, str) or len(value) % 2:
raise PresetError(f"{label} must be even-length hex")
try:
return bytes.fromhex(value)
except ValueError as exc:
raise PresetError(f"{label} is not hex") from exc
def unpack(image: bytes) -> dict:
if len(image) != IMAGE_LEN:
raise PresetError(f"preset image is {len(image)} bytes, expected {IMAGE_LEN}")
presets = []
for index in range(PRESET_COUNT):
block = image[index * PRESET_LEN:(index + 1) * PRESET_LEN]
presets.append(_unpack_preset(block))
return {"presets": presets, "types": type_catalog(), "relative": RELATIVE_CONFIRMED}
def pack(document: dict) -> bytes:
presets = document.get("presets")
if not isinstance(presets, list) or len(presets) != PRESET_COUNT:
raise PresetError(f"expected {PRESET_COUNT} presets")
out = bytearray()
for index, preset in enumerate(presets):
out += _pack_preset(preset, index)
if len(out) != IMAGE_LEN:
raise PresetError(f"packed {len(out)} bytes, expected {IMAGE_LEN}")
return bytes(out)
def colour_offset(preset: int, index: int) -> int:
"""Where one pad's colour sits. MidiSuite writes only this address."""
if not 0 <= preset < PRESET_COUNT:
raise PresetError(f"preset {preset + 1} is not on this controller")
if not 0 <= index < PAD_COUNT:
raise PresetError(f"pad {index + 1} is not on this controller")
return preset * PRESET_LEN + PAD_AT + index * PAD_LEN + RGB_AT
def unpack_global(raw: bytes) -> dict:
if len(raw) != GLOBAL_LEN:
raise PresetError(f"global block is {len(raw)} bytes, expected {GLOBAL_LEN}")
return {
"tempo": int.from_bytes(raw[GLOBAL_TEMPO:GLOBAL_TEMPO + 2], "little"),
"swing": raw[GLOBAL_SWING],
"curve": raw[GLOBAL_CURVE],
"transpose": int.from_bytes(raw[GLOBAL_TRANSPOSE:GLOBAL_TRANSPOSE + 1], "little", signed=True),
"bank": raw[GLOBAL_BANK],
"raw": raw.hex(),
}
def pack_global(block: dict) -> bytes:
"""The named fields over the bytes that were read, so unknown ones stay put."""
out = bytearray(_hex(block.get("raw", ""), "global block"))
if len(out) != GLOBAL_LEN:
raise PresetError(f"global block is {len(out)} bytes, expected {GLOBAL_LEN}")
tempo = block.get("tempo")
if isinstance(tempo, bool) or not isinstance(tempo, int) or not 1 <= tempo <= 0xFFFF:
raise PresetError("tempo must be a whole number of BPM")
out[GLOBAL_TEMPO:GLOBAL_TEMPO + 2] = tempo.to_bytes(2, "little")
out[GLOBAL_SWING] = _byte(block.get("swing"), "swing")
out[GLOBAL_CURVE] = _byte(block.get("curve"), "pad curve")
transpose = block.get("transpose")
if isinstance(transpose, bool) or not isinstance(transpose, int) or not -128 <= transpose <= 127:
raise PresetError("transpose must be -128 to 127")
out[GLOBAL_TRANSPOSE] = transpose & 0xFF
bank = block.get("bank", out[GLOBAL_BANK])
if isinstance(bank, bool) or bank not in (0, 1):
raise PresetError("pad bank must be 0 or 1")
out[GLOBAL_BANK] = bank
return bytes(out)
def changed_ranges(before: bytes, after: bytes, limit: int = 64) -> list[tuple[int, bytes]]:
"""Coalesce differing bytes, then split each run into write-sized pieces."""
if len(before) != len(after):
raise PresetError(f"cannot compare {len(before)} bytes with {len(after)}")
runs: list[tuple[int, int]] = []
start = None
for index, (old, new) in enumerate(zip(before, after)):
if old != new:
if start is None:
start = index
elif start is not None:
runs.append((start, index))
start = None
if start is not None:
runs.append((start, len(after)))
pieces: list[tuple[int, bytes]] = []
for run_at, run_end in runs:
at = run_at
while at < run_end:
stop = min(run_end, at + limit)
pieces.append((at, after[at:stop]))
at = stop
return pieces
def _unpack_preset(block: bytes) -> dict:
buttons = []
for index in range(BUTTON_COUNT):
rec = block[index * BUTTON_LEN:(index + 1) * BUTTON_LEN]
length = rec[5]
if length > SYSEX_ROOM:
sysex, padding = rec[6:22], b""
else:
sysex, padding = rec[6:6 + length], rec[6 + length:22]
buttons.append({
"name": BUTTON_NAMES[index],
"type": rec[0],
"channel": rec[1] + 1,
"number": rec[2],
"min": rec[3],
"max": rec[4],
"sysex": sysex.hex(),
"padding": padding.hex(),
"led": rec[22],
})
knobs = []
for index in range(KNOB_COUNT):
at = KNOB_AT + index * KNOB_LEN
rec = block[at:at + KNOB_LEN]
knobs.append({
"type": rec[0],
"speed": rec[1],
"channel": rec[2] + 1,
"number": rec[3],
"left": rec[4],
"right": rec[5],
})
pads = []
for index in range(PAD_COUNT):
at = PAD_AT + index * PAD_LEN
rec = block[at:at + PAD_LEN]
pads.append({
"channel": rec[0] + 1,
"note": rec[1],
"min": rec[2],
"max": rec[3],
"rgb": [rec[4], rec[5], rec[6]],
"led": rec[7],
"tail": rec[8:].hex(),
})
return {"gap": block[GAP_AT], "buttons": buttons, "knobs": knobs, "pads": pads}
def _pack_preset(preset: dict, index: int) -> bytes:
out = bytearray(PRESET_LEN)
buttons = preset.get("buttons")
knobs = preset.get("knobs")
pads = preset.get("pads")
if not isinstance(buttons, list) or len(buttons) != BUTTON_COUNT:
raise PresetError(f"preset {index + 1} needs {BUTTON_COUNT} buttons")
if not isinstance(knobs, list) or len(knobs) != KNOB_COUNT:
raise PresetError(f"preset {index + 1} needs {KNOB_COUNT} knobs")
if not isinstance(pads, list) or len(pads) != PAD_COUNT:
raise PresetError(f"preset {index + 1} needs {PAD_COUNT} pads")
for number, button in enumerate(buttons):
out[number * BUTTON_LEN:(number + 1) * BUTTON_LEN] = _pack_button(button, index, number)
for number, knob in enumerate(knobs):
at = KNOB_AT + number * KNOB_LEN
out[at:at + KNOB_LEN] = _pack_knob(knob, index, number)
out[GAP_AT] = _byte(preset.get("gap", 0), f"preset {index + 1} gap")
for number, pad in enumerate(pads):
at = PAD_AT + number * PAD_LEN
rec = _pack_pad(pad, index, number)
room = PRESET_LEN - at
if len(rec) > room:
raise PresetError(f"preset {index + 1} pad {number + 1} does not fit")
out[at:at + len(rec)] = rec
return bytes(out)
def _pack_button(button: dict, preset: int, index: int) -> bytes:
label = f"preset {preset + 1} {BUTTON_NAMES[index]}"
sysex = _hex(button.get("sysex", ""), f"{label} sysex")
if len(sysex) > SYSEX_ROOM:
raise PresetError(f"{label} sysex is longer than {SYSEX_ROOM} bytes")
padding = _hex(button.get("padding", ""), f"{label} padding")
room = SYSEX_ROOM - len(sysex)
padding = padding[:room]
rec = bytearray(BUTTON_LEN)
rec[0] = _byte(button.get("type"), f"{label} type")
rec[1] = _channel(button.get("channel"), f"{label} channel")
rec[2] = _byte(button.get("number"), f"{label} number")
rec[3] = _byte(button.get("min"), f"{label} min")
rec[4] = _byte(button.get("max"), f"{label} max")
rec[5] = len(sysex)
rec[6:6 + len(sysex)] = sysex
rec[6 + len(sysex):22] = padding + bytes(room - len(padding))
rec[22] = _byte(button.get("led"), f"{label} led")
return bytes(rec)
def _pack_knob(knob: dict, preset: int, index: int) -> bytes:
label = f"preset {preset + 1} knob {index + 1}"
# Any stored type byte round-trips. The editor only offers names it has seen.
return bytes((
_byte(knob.get("type"), f"{label} type"),
_byte(knob.get("speed"), f"{label} speed"),
_channel(knob.get("channel"), f"{label} channel"),
_byte(knob.get("number"), f"{label} number"),
_byte(knob.get("left"), f"{label} left"),
_byte(knob.get("right"), f"{label} right"),
))
def _pack_pad(pad: dict, preset: int, index: int) -> bytes:
label = f"preset {preset + 1} pad {index + 1}"
rgb = pad.get("rgb")
if not isinstance(rgb, list) or len(rgb) != 3:
raise PresetError(f"{label} colour needs three bytes")
tail = _hex(pad.get("tail", ""), f"{label} tail")
stored = PAD_LEN if index < PAD_COUNT - 1 else PRESET_LEN - (PAD_AT + (PAD_COUNT - 1) * PAD_LEN)
tail_room = stored - 8
if len(tail) > tail_room:
raise PresetError(f"{label} tail is longer than {tail_room} bytes")
rec = bytearray(stored)
rec[0] = _channel(pad.get("channel"), f"{label} channel")
rec[1] = _byte(pad.get("note"), f"{label} note")
rec[2] = _byte(pad.get("min"), f"{label} min velocity")
rec[3] = _byte(pad.get("max"), f"{label} max velocity")
rec[4] = _byte(rgb[0], f"{label} red")
rec[5] = _byte(rgb[1], f"{label} green")
rec[6] = _byte(rgb[2], f"{label} blue")
rec[7] = _byte(pad.get("led"), f"{label} led")
rec[8:8 + len(tail)] = tail
return bytes(rec)
+218
View File
@@ -0,0 +1,218 @@
"""Local editor: load the SMC-PAD preset, edit it, save it back."""
from __future__ import annotations
import json
import mimetypes
import threading
import traceback
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlparse
from padcontroller.device import Link, PadError, connected, read_global, read_image, save_image, set_bank, write_colour
from padcontroller.preset import IMAGE_LEN, PresetError, pack, pack_global, unpack, unpack_global
STATIC_DIR = Path(__file__).parent / "static"
# The image MidiSuite uploads for its factory reset, and its global block.
FACTORY_IMAGE = Path(__file__).parent / "factory.bin"
FACTORY_GLOBAL = bytes.fromhex("780032040000020001010000")
class ApiError(Exception):
def __init__(self, message: str, status: int = 400):
super().__init__(message)
self.status = status
class Editor:
def __init__(self):
self.lock = threading.Lock()
def status(self) -> dict:
port = connected()
return {"connected": port is not None, "port": port}
def load(self) -> dict:
with self.lock:
try:
with Link() as link:
document = unpack(read_image(link))
document["global"] = unpack_global(read_global(link))
return document
except PadError as exc:
raise ApiError(str(exc), 503) from exc
def save(self, document: dict) -> dict:
try:
desired = pack(document)
block = document.get("global")
settings = pack_global(block) if isinstance(block, dict) else None
except PresetError as exc:
raise ApiError(str(exc)) from exc
with self.lock:
try:
written = save_image(desired, settings=settings)
except PadError as exc:
raise ApiError(str(exc), 503) from exc
if written:
message = f"Saved on the pad. {written} bytes written."
else:
message = "Saved on the pad."
return {"ok": True, "message": message, "bytes": written}
def colour(self, body: dict) -> dict:
try:
preset = int(body["preset"])
index = int(body["index"])
rgb = body["rgb"]
if not isinstance(rgb, list) or len(rgb) != 3:
raise PresetError("a pad colour needs red, green, and blue")
except (KeyError, TypeError, ValueError) as exc:
raise ApiError("colour needs a preset, a pad, and an rgb colour") from exc
with self.lock:
try:
offset = write_colour(preset, index, rgb)
except PresetError as exc:
raise ApiError(str(exc)) from exc
except PadError as exc:
raise ApiError(str(exc), 503) from exc
return {"ok": True, "offset": offset}
def bank(self, body: dict) -> dict:
bank = body.get("bank")
if isinstance(bank, bool) or bank not in (0, 1):
raise ApiError("bank must be 0 or 1")
with self.lock:
try:
set_bank(bank)
except PadError as exc:
raise ApiError(str(exc), 503) from exc
return {"ok": True, "bank": bank}
def imported(self, raw: bytes) -> dict:
try:
return unpack(raw)
except PresetError as exc:
raise ApiError(str(exc)) from exc
def factory(self) -> dict:
document = unpack(FACTORY_IMAGE.read_bytes())
document["global"] = unpack_global(FACTORY_GLOBAL)
return document
def exported(self, document: dict) -> bytes:
try:
return pack(document)
except PresetError as exc:
raise ApiError(str(exc)) from exc
def make_server(host: str = "127.0.0.1", port: int = 8770) -> ThreadingHTTPServer:
editor = Editor()
handler = type("BoundHandler", (Handler,), {"editor": editor})
server = ThreadingHTTPServer((host, port), handler)
server.editor = editor # type: ignore[attr-defined]
return server
class Handler(BaseHTTPRequestHandler):
editor: Editor
def log_message(self, fmt: str, *args) -> None:
return
def _json(self, status: int, body: dict) -> None:
raw = json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(raw)
def _bytes(self, raw: bytes, content_type: str, filename: str | None = None) -> None:
self.send_response(200)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(raw)))
self.send_header("Cache-Control", "no-store")
if filename:
self.send_header("Content-Disposition", f'attachment; filename="{filename}"')
self.end_headers()
self.wfile.write(raw)
def _read(self) -> bytes:
n = int(self.headers.get("Content-Length") or 0)
return self.rfile.read(n) if n > 0 else b""
def _json_body(self) -> dict:
raw = self._read()
if not raw:
return {}
try:
body = json.loads(raw.decode("utf-8"))
except json.JSONDecodeError as exc:
raise ApiError(f"invalid JSON: {exc}") from exc
if not isinstance(body, dict):
raise ApiError("expected a JSON object")
return body
def _static(self, rel: str) -> None:
rel = rel.lstrip("/") or "index.html"
path = (STATIC_DIR / rel).resolve()
if STATIC_DIR.resolve() not in path.parents or not path.is_file():
self.send_error(404)
return
ctype = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
if ctype.startswith("text/") or ctype.endswith(("javascript", "json")):
ctype = f"{ctype}; charset=utf-8"
self._bytes(path.read_bytes(), ctype)
def _dispatch(self, method: str) -> None:
url = urlparse(self.path)
editor = self.editor
try:
if not url.path.startswith("/api/"):
if method != "GET":
self.send_error(405)
return
if url.path == "/favicon.ico":
self.send_response(204)
self.send_header("Content-Length", "0")
self.end_headers()
return
self._static(url.path)
return
route = (method, url.path)
if route == ("GET", "/api/status"):
self._json(200, editor.status())
elif route == ("POST", "/api/load"):
self._json(200, editor.load())
elif route == ("POST", "/api/save"):
self._json(200, editor.save(self._json_body()))
elif route == ("POST", "/api/colour"):
self._json(200, editor.colour(self._json_body()))
elif route == ("POST", "/api/bank"):
self._json(200, editor.bank(self._json_body()))
elif route == ("POST", "/api/import"):
raw = self._read()
if len(raw) != IMAGE_LEN:
raise ApiError(f"preset file is {len(raw)} bytes, expected {IMAGE_LEN}")
self._json(200, editor.imported(raw))
elif route == ("POST", "/api/factory"):
self._json(200, editor.factory())
elif route == ("POST", "/api/export"):
self._bytes(editor.exported(self._json_body()), "application/octet-stream", "smc-pad-preset.bin")
else:
self._json(404, {"error": f"no route {method} {url.path}"})
except ApiError as exc:
self._json(exc.status, {"error": str(exc)})
except Exception as exc: # noqa: BLE001 — surface anything else to the UI
traceback.print_exc()
self._json(500, {"error": f"{type(exc).__name__}: {exc}"})
def do_GET(self) -> None: # noqa: N802
self._dispatch("GET")
def do_POST(self) -> None: # noqa: N802
self._dispatch("POST")
+490
View File
@@ -0,0 +1,490 @@
const PAGE = 16;
const state = {
doc: null,
saved: null,
preset: 0,
page: 2,
bank: 0,
kind: null,
index: 0,
};
const $ = (id) => document.getElementById(id);
// Colours are stored as the picker gives them, 0–255, as MidiSuite writes them.
function cssColour(rgb) {
return `rgb(${rgb.join(",")})`;
}
function ink(rgb) {
const [r, g, b] = rgb;
return (r * 0.3 + g * 0.59 + b * 0.11) > 150 ? "#111" : "#f4f6fb";
}
function hexColour(rgb) {
return `#${rgb.map((part) => part.toString(16).padStart(2, "0")).join("")}`;
}
function setStatus(text, kind) {
const node = $("status");
node.textContent = text;
node.className = kind || "";
}
function dirty() {
return state.doc !== null && JSON.stringify(state.doc) !== state.saved;
}
function preset() {
return state.doc.presets[state.preset];
}
function selected() {
if (!state.doc || !state.kind) return null;
const block = preset();
if (state.kind === "pad") return block.pads[state.page * PAGE + state.index];
if (state.kind === "knob") return block.knobs[state.bank * 8 + state.index];
return block.buttons[state.index];
}
function typeChoices(kind, current) {
const known = (state.doc.types && state.doc.types[kind]) || [];
const options = known.map((item) => ({ value: item.value, name: item.name }));
if (!options.some((item) => item.value === current)) {
const hex = current.toString(16).padStart(2, "0");
options.push({ value: current, name: `0x${hex}` });
}
return options;
}
async function request(url, options) {
const response = await fetch(url, options);
const type = response.headers.get("Content-Type") || "";
if (type.includes("application/json")) {
const body = await response.json();
if (!response.ok) throw new Error(body.error || response.statusText);
return body;
}
if (!response.ok) throw new Error(response.statusText);
return response.blob();
}
function mark() {
const unsaved = dirty();
$("save").disabled = !state.doc;
$("export").disabled = !state.doc;
$("save").classList.toggle("dirty", unsaved);
return unsaved;
}
function touch() {
if (mark()) setStatus("Not saved on the pad.", "dirty");
else setStatus("No unsaved edits.", "ok");
}
function showEmpty(text, kind) {
const node = $("empty");
node.hidden = false;
node.textContent = text;
node.className = kind || "";
$("board").classList.remove("ready");
}
async function load(manual) {
if (manual && dirty() && !window.confirm("Load from the pad and drop these edits?")) return;
setStatus("Loading the pad…");
showEmpty("Loading the pad…");
try {
state.doc = await request("/api/load", { method: "POST" });
state.saved = JSON.stringify(state.doc);
render();
setStatus("Loaded from the pad.", "ok");
} catch (error) {
setStatus(error.message, "err");
showEmpty(error.message, "err");
}
}
async function save() {
if (!state.doc) return;
setStatus("Saving…");
$("save").disabled = true;
try {
const body = await request("/api/save", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(state.doc),
});
state.saved = JSON.stringify(state.doc);
setStatus(body.message, "ok");
} catch (error) {
setStatus(error.message, "err");
}
mark();
}
async function exportFile() {
if (!state.doc) return;
try {
const blob = await request("/api/export", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(state.doc),
});
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "smc-pad-preset.bin";
link.click();
URL.revokeObjectURL(url);
} catch (error) {
setStatus(error.message, "err");
}
}
async function importFile(file) {
setStatus("Reading file…");
try {
const raw = new Uint8Array(await file.arrayBuffer());
state.doc = await request("/api/import", {
method: "POST",
headers: { "Content-Type": "application/octet-stream" },
body: raw,
});
render();
setStatus("Imported. Save to pad to store it.", "dirty");
} catch (error) {
setStatus(error.message, "err");
}
}
function withBank(global, bank) {
const raw = global.raw.slice(0, 22) + bank.toString(16).padStart(2, "0") + global.raw.slice(24);
return { ...global, bank, raw };
}
async function switchBank(bank) {
try {
await request("/api/bank", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ bank }),
});
const wasDirty = dirty();
state.doc.global = withBank(state.doc.global, bank);
if (!wasDirty) {
const saved = JSON.parse(state.saved);
saved.global = withBank(saved.global, bank);
state.saved = JSON.stringify(saved);
}
state.page = bank ? 7 : 2;
$("page").value = String(state.page);
state.kind = state.kind === "pad" ? null : state.kind;
render();
setStatus(`Pad bank ${bank + 1}.`, "ok");
} catch (error) {
setStatus(error.message, "err");
}
}
async function factory() {
if (!window.confirm("Replace all eight presets with the factory settings? Nothing reaches the pad until you Save.")) return;
setStatus("Reading the factory preset…");
try {
state.doc = await request("/api/factory", { method: "POST" });
render();
setStatus("Factory settings loaded. Save to pad to store them.", "dirty");
} catch (error) {
setStatus(error.message, "err");
}
mark();
}
function render() {
if (!state.doc) return;
$("board").classList.add("ready");
renderGlobal();
renderPresets();
renderPages();
renderPads();
renderKnobs();
renderButtons();
renderInspector();
mark();
}
function renderGlobal() {
const row = $("global");
row.replaceChildren();
const block = state.doc.global;
if (!block) return;
const fields = [
["Tempo", "tempo", 1, 999],
["Swing", "swing", 0, 255],
["Pad curve", "curve", 0, 255],
["Transpose", "transpose", -128, 127],
];
for (const [label, key, min, max] of fields) {
row.append(field(label, numberInput(block, key, min, max)));
}
const toggle = document.createElement("button");
toggle.type = "button";
toggle.textContent = `Pad bank ${block.bank + 1}`;
toggle.title = "Switch the pad's bank now, as MidiSuite does";
toggle.addEventListener("click", () => switchBank(1 - block.bank));
row.append(toggle);
}
function renderPresets() {
const row = $("presets");
row.replaceChildren();
state.doc.presets.forEach((_preset, index) => {
const button = document.createElement("button");
button.type = "button";
button.textContent = String(index + 1);
button.classList.toggle("selected", index === state.preset);
button.addEventListener("click", () => {
state.preset = index;
render();
});
row.append(button);
});
}
function renderPages() {
const select = $("page");
const current = select.value;
select.replaceChildren();
const order = [2, 7, 0, 1, 3, 4, 5, 6];
const names = { 2: "Bank 1", 7: "Bank 2", 3: "Page 4 (not lit)" };
for (const page of order) {
const pads = preset().pads.slice(page * PAGE, page * PAGE + PAGE);
const option = document.createElement("option");
option.value = String(page);
const name = names[page] || `Page ${page + 1}`;
option.textContent = `${name} · notes ${pads[0].note}–${pads[PAGE - 1].note}`;
select.append(option);
}
select.value = current || String(state.page);
state.page = Number(select.value);
const pads = preset().pads.slice(state.page * PAGE, state.page * PAGE + PAGE);
$("page-notes").textContent = `notes ${pads[0].note}–${pads[PAGE - 1].note}`;
}
function paint(node, rgb) {
node.style.background = cssColour(rgb);
node.style.color = ink(rgb);
}
function renderPads() {
const grid = $("pads");
grid.replaceChildren();
const pads = preset().pads;
for (let row = 3; row >= 0; row -= 1) {
for (let col = 0; col < 4; col += 1) {
const index = row * 4 + col;
const pad = pads[state.page * PAGE + index];
const button = document.createElement("button");
button.type = "button";
button.className = "pad";
button.textContent = String(index + 1);
paint(button, pad.rgb);
button.style.opacity = pad.led ? "" : "0.35";
button.classList.toggle("selected", state.kind === "pad" && state.index === index);
button.addEventListener("click", () => select("pad", index));
grid.append(button);
}
}
}
function renderKnobs() {
const row = $("knobs");
row.replaceChildren();
for (let index = 0; index < 8; index += 1) {
const knob = preset().knobs[state.bank * 8 + index];
const button = document.createElement("button");
button.type = "button";
button.className = "knob";
button.textContent = String(state.bank * 8 + index + 1);
button.title = `CC ${knob.number}`;
button.classList.toggle("selected", state.kind === "knob" && state.index === index);
button.addEventListener("click", () => select("knob", index));
row.append(button);
}
}
function renderButtons() {
const row = $("buttons");
row.replaceChildren();
preset().buttons.forEach((button, index) => {
const node = document.createElement("button");
node.type = "button";
node.className = "btn";
node.textContent = button.name;
node.classList.toggle("selected", state.kind === "button" && state.index === index);
node.addEventListener("click", () => select("button", index));
row.append(node);
});
}
let colourTimer = 0;
function paintColour(index, rgb) {
const edited = state.preset;
preset().pads[index].rgb = rgb.slice();
renderPads();
window.clearTimeout(colourTimer);
colourTimer = window.setTimeout(() => sendColour(edited, index, rgb), 180);
}
async function sendColour(preset, index, rgb) {
try {
await request("/api/colour", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ preset, index, rgb }),
});
} catch (error) {
setStatus(error.message, "err");
}
}
function select(kind, index) {
state.kind = kind;
state.index = index;
render();
}
function field(label, node) {
const wrap = document.createElement("label");
wrap.className = "field";
wrap.append(label, node);
return wrap;
}
function numberInput(item, key, min, max) {
const input = document.createElement("input");
input.type = "number";
input.min = String(min);
input.max = String(max);
input.value = String(item[key]);
input.addEventListener("input", () => {
const value = Number(input.value);
if (!Number.isInteger(value) || value < min || value > max) return;
item[key] = value;
if (key === "led") renderPads();
if (key === "note") {
const pads = preset().pads.slice(state.page * PAGE, state.page * PAGE + PAGE);
$("page-notes").textContent = `notes ${pads[0].note}–${pads[PAGE - 1].note}`;
}
touch();
});
return input;
}
function renderInspector() {
const aside = $("inspector");
const item = selected();
aside.replaceChildren();
const title = document.createElement("h2");
if (!item) {
title.textContent = "Control";
const note = document.createElement("p");
note.className = "muted";
note.textContent = "Pick a pad, knob, or button.";
aside.append(title, note);
return;
}
if (state.kind === "pad") title.textContent = `Pad ${state.index + 1}`;
else if (state.kind === "knob") title.textContent = `Knob ${state.bank * 8 + state.index + 1}`;
else title.textContent = item.name;
aside.append(title);
if (state.kind !== "pad") {
const type = document.createElement("select");
typeChoices(state.kind, item.type).forEach((option) => {
const node = document.createElement("option");
node.value = String(option.value);
node.textContent = option.name;
node.selected = option.value === item.type;
type.append(node);
});
type.addEventListener("change", () => {
item.type = Number(type.value);
touch();
});
aside.append(field(state.kind === "button" ? "Mode" : "Type", type));
}
aside.append(field("Channel", numberInput(item, "channel", 1, 16)));
if (state.kind === "pad") {
aside.append(field("Note", numberInput(item, "note", 0, 127)));
aside.append(field("Min velocity", numberInput(item, "min", 0, 127)));
aside.append(field("Max velocity", numberInput(item, "max", 0, 127)));
const colour = document.createElement("input");
colour.type = "color";
colour.value = hexColour(item.rgb);
colour.addEventListener("input", () => {
const hex = colour.value;
const rgb = [1, 3, 5].map((at) => parseInt(hex.slice(at, at + 2), 16));
paintColour(state.page * PAGE + state.index, rgb);
touch();
});
aside.append(field("Colour", colour));
aside.append(field("Led", numberInput(item, "led", 0, 255)));
} else if (state.kind === "knob") {
aside.append(field("CC", numberInput(item, "number", 0, 127)));
aside.append(field("Speed", numberInput(item, "speed", 0, 127)));
aside.append(field("Min", numberInput(item, "left", 0, 127)));
aside.append(field("Max", numberInput(item, "right", 0, 127)));
if (state.doc.relative) {
const hint = document.createElement("p");
hint.className = "hint";
hint.textContent = "Relative sends the left value one way and the right value the other.";
aside.append(hint);
}
} else {
aside.append(field("CC", numberInput(item, "number", 0, 127)));
aside.append(field("Value 1", numberInput(item, "min", 0, 127)));
aside.append(field("Value 2", numberInput(item, "max", 0, 127)));
aside.append(field("Led", numberInput(item, "led", 0, 255)));
const sysex = document.createElement("input");
sysex.type = "text";
sysex.value = item.sysex;
sysex.spellcheck = false;
sysex.addEventListener("input", () => {
const hex = sysex.value.replace(/\s+/g, "").toLowerCase();
if (hex.length % 2 || /[^0-9a-f]/.test(hex) || hex.length > 32) return;
item.sysex = hex;
touch();
});
aside.append(field("SysEx", sysex));
}
const hint = document.createElement("p");
hint.className = "hint";
hint.textContent = "A pad colour lights the lamp as you pick it. Save keeps every edit after a power cycle.";
aside.append(hint);
}
$("load").addEventListener("click", () => load(true));
$("save").addEventListener("click", save);
$("export").addEventListener("click", exportFile);
$("factory").addEventListener("click", factory);
$("import").addEventListener("change", () => {
const file = $("import").files[0];
$("import").value = "";
if (file) importFile(file);
});
$("page").addEventListener("change", () => {
state.page = Number($("page").value);
state.kind = state.kind === "pad" ? null : state.kind;
render();
});
$("bank").addEventListener("change", () => {
state.bank = Number($("bank").value);
state.kind = state.kind === "knob" ? null : state.kind;
render();
});
load(false);
+46
View File
@@ -0,0 +1,46 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pad Controller</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<header>
<h1>Pad Controller</h1>
<button id="load" type="button">Load</button>
<button id="save" type="button" class="primary" disabled>Save to pad</button>
<button id="factory" type="button">Factory reset</button>
<button id="export" type="button" disabled>Export</button>
<label class="file">Import
<input id="import" type="file" accept=".bin,application/octet-stream">
</label>
<span class="spacer"></span>
<span id="status">Load the preset from the pad.</span>
</header>
<main>
<section id="board">
<p id="empty">Loading the pad…</p>
<div class="row" id="global"></div>
<div class="row" id="presets"></div>
<div class="row">
<label>Pad page <select id="page"></select></label>
<label>Knob bank <select id="bank">
<option value="0">1 · knobs 1–8</option>
<option value="1">2 · knobs 9–16</option>
</select></label>
<span id="page-notes" class="muted"></span>
</div>
<div id="pads"></div>
<div id="knobs"></div>
<div id="buttons"></div>
</section>
<aside id="inspector">
<h2>Control</h2>
<p class="muted">Load a preset, then pick a pad, knob, or button.</p>
</aside>
</main>
<script src="/app.js"></script>
</body>
</html>
+102
View File
@@ -0,0 +1,102 @@
:root {
--bg: #15171c;
--panel: #1e2129;
--panel-2: #262a34;
--line: #343946;
--text: #e6e8ee;
--muted: #8d94a6;
--accent: #5aa9ff;
--danger: #ff6b6b;
--ok: #52d273;
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; }
body {
background: var(--bg);
color: var(--text);
font: 13px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
display: flex;
flex-direction: column;
}
header {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 14px;
background: var(--panel);
border-bottom: 1px solid var(--line);
}
header h1 { font-size: 15px; margin: 0 8px 0 0; }
.spacer { flex: 1; }
#status { color: var(--muted); max-width: 46ch; }
#status.err { color: var(--danger); }
#status.ok { color: var(--ok); }
#status.dirty { color: var(--accent); }
button, select, input[type="number"], input[type="text"] {
background: var(--panel-2);
color: var(--text);
border: 1px solid var(--line);
border-radius: 6px;
padding: 6px 10px;
font: inherit;
}
button { cursor: pointer; }
button:disabled { opacity: 0.45; cursor: default; }
button.primary { background: #245a9e; border-color: #3d7dcc; }
button.primary.dirty { background: #1e6b38; border-color: var(--ok); }
button.selected, .pad.selected, .knob.selected, .btn.selected {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
label.file { color: var(--muted); }
label.file input { display: none; }
label.file { cursor: pointer; border: 1px solid var(--line); border-radius: 6px; padding: 6px 10px; background: var(--panel-2); color: var(--text); }
main { display: flex; min-height: 0; flex: 1; }
#empty { color: var(--muted); margin: 48px 0; }
#empty.err { color: var(--danger); }
#board.ready #empty { display: none; }
#board, #inspector { padding: 16px; }
#board { flex: 1; }
#inspector {
width: 320px;
background: var(--panel);
border-left: 1px solid var(--line);
overflow: auto;
}
#inspector h2 { margin: 0 0 12px; font-size: 15px; }
.muted { color: var(--muted); }
.row { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; flex-wrap: wrap; }
.row label { display: flex; align-items: center; gap: 6px; color: var(--muted); }
#presets { gap: 6px; }
#pads {
display: grid;
grid-template-columns: repeat(4, 76px);
gap: 8px;
margin: 8px 0 18px;
}
.pad, .knob, .btn {
border: 1px solid #0008;
color: #111;
font-weight: 650;
text-align: center;
}
.pad { height: 64px; border-radius: 8px; }
.knob {
width: 64px;
height: 64px;
border-radius: 50%;
background: #d7dbe6;
}
#knobs, #buttons { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 14px; }
.btn { min-width: 72px; height: 36px; border-radius: 6px; background: #c9ceda; }
.field { display: flex; flex-direction: column; gap: 4px; margin-bottom: 10px; color: var(--muted); }
.field input, .field select { width: 100%; }
.hint { color: var(--muted); margin-top: 8px; }
#global .field { margin-bottom: 0; }
#global input { width: 90px; }
+81
View File
@@ -0,0 +1,81 @@
"""SINCO / M-VAVE SysEx codec used by MidiSuite and the SMC-PAD."""
from __future__ import annotations
MEM_GLOBAL = 4
MEM_PRESET = 5
CMD_ACK = 0x00
CMD_WRITE = 0x22
CMD_READ = 0x23
RAM = 0x80000000
def encode(source: bytes) -> bytes:
"""Pack a protocol message into the 7-bit SysEx body."""
bit_num = 0
accum = 0
out = bytearray()
for byte in source:
accum = ((byte << (bit_num & 0x1F)) | accum) & 0xFFFFFFFF
bit_num += 1
while True:
out.append(accum & 0x7F)
accum = (accum >> 7) & 0xFFFFFFFF
if bit_num < 7:
break
bit_num -= 7
out.append(accum & 0x7F)
return bytes(out)
def decode(source: bytes) -> bytes:
bit_num = 0
last_val = 0
out = bytearray()
for byte in source:
accum = byte & (0xFFFFFFFF >> (32 - bit_num) if bit_num else 0)
if bit_num > 0:
out.append((last_val & 0x7F) | ((accum << (8 - bit_num)) & 0xFF))
last_val = byte >> bit_num
bit_num = (bit_num + 1) % 8
if last_val > 0:
out.append(last_val)
return bytes(out)
def checksum(payload: bytes) -> int:
total = 0
for byte in payload:
total = (total + byte) & 0xFF
return (~total) & 0xFF
def frame(command: int, payload: bytes) -> list[int]:
data = bytearray((0x00, 0x59, command))
data += len(payload).to_bytes(3, "little")
data += payload
data.append(checksum(payload))
return [0xF0, *encode(bytes(data)), 0xF7]
def read_request(address: int, size: int, memory: int = MEM_PRESET) -> list[int]:
payload = bytes([memory]) + address.to_bytes(4, "little") + size.to_bytes(3, "little")
return frame(CMD_READ, payload)
def write_request(address: int, data: bytes, memory: int = MEM_PRESET) -> list[int]:
payload = bytes([memory]) + address.to_bytes(4, "little") + len(data).to_bytes(3, "little") + data
return frame(CMD_WRITE, payload)
def save_request() -> list[int]:
"""Commit the running preset. MidiSuite's Save is this empty write."""
return write_request(0, b"")
def payload_data(decoded: bytes) -> bytes:
"""Bytes after the type, address, and length in a read reply."""
if decoded[:3] != b"\x00\x59\x23":
raise ValueError(f"unexpected reply {decoded[:8].hex()}")
payload = decoded[6:-1]
return payload[8:]
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env bash
# Install the SMC-PAD pad controller as a systemd user service and start it.
#
# padcontroller/systemd/install.sh # install, enable, start
# padcontroller/systemd/install.sh --lock-knobs # pass options to the pad controller
# padcontroller/systemd/install.sh --no-enable # install only; start it with
# # systemctl --user start padcontroller
# padcontroller/systemd/install.sh --uninstall
#
# Logs: journalctl --user -u padcontroller -f
set -euo pipefail
UNIT=padcontroller.service
HERE="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(cd "$HERE/../.." && pwd)"
DEST="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"
if [[ "${1:-}" == "--uninstall" ]]; then
systemctl --user disable --now "$UNIT" 2>/dev/null || true
rm -f "$DEST/$UNIT"
systemctl --user daemon-reload
echo "Removed $UNIT."
exit 0
fi
PYTHON="$ROOT/.venv/bin/python"
[[ -x "$PYTHON" ]] || PYTHON="$(command -v python3)"
"$PYTHON" -c "import rtmidi" 2>/dev/null || {
echo "$PYTHON cannot import rtmidi. Run pipenv install (or pip install python-rtmidi) first." >&2
exit 1
}
ENABLE=1
if [[ "${1:-}" == "--no-enable" ]]; then
ENABLE=
shift
fi
ARGS="$*"
mkdir -p "$DEST"
sed -e "s|@ROOT@|$ROOT|g" -e "s|@PYTHON@|$PYTHON|g" -e "s|@ARGS@|$ARGS|g" \
"$HERE/$UNIT" >"$DEST/$UNIT"
systemctl --user daemon-reload
if [[ -z "$ENABLE" ]]; then
# Undo an earlier enable, so it does not start at login here.
systemctl --user disable "$UNIT" 2>/dev/null || true
echo "Installed $DEST/$UNIT. It does not start at login."
echo "Start it with: systemctl --user start padcontroller"
exit 0
fi
systemctl --user enable "$UNIT"
systemctl --user restart "$UNIT"
echo "Installed $DEST/$UNIT and started it."
systemctl --user --no-pager status "$UNIT" | head -5 || true
@@ -0,0 +1,22 @@
# SMC-PAD pad controller (padcontroller.midi) as a systemd user service.
# install.sh fills in @ROOT@, @PYTHON@ and @ARGS@ and copies it to
# ~/.config/systemd/user/.
[Unit]
Description=SMC-PAD pad controller (virtual port "padcontroller")
After=sound.target
# Keep retrying while the pad is switched off or not paired yet.
StartLimitIntervalSec=0
[Service]
Type=simple
WorkingDirectory=@ROOT@
ExecStart=@PYTHON@ -m padcontroller.midi @ARGS@
Environment=PYTHONUNBUFFERED=1
# The pad controller closes its ports on Ctrl+C.
KillSignal=SIGINT
Restart=always
RestartSec=3
[Install]
WantedBy=default.target
+154
View File
@@ -0,0 +1,154 @@
"""Virtual pad: press SMC-PAD pads and turn knobs from the command line or a test.
Sends into the pad controller's input port (padcontroller-in), so presses go
through the same Play layer and CC smoothing as the real pad before QLC+ sees
them. The real pad stays connected; both feed the same port.
Before sending it checks that the workspace QLC+ opened last is shows/test.qxw,
which only sends Art-Net to 127.0.0.1 (the simulator). Pass --force to skip that.
Usage:
.venv/bin/python -m padcontroller.virtualpad press 52 # note 52 on channel 10
.venv/bin/python -m padcontroller.virtualpad press --pad 17 # pad number from shows/midi_map.json
.venv/bin/python -m padcontroller.virtualpad press 52 --play # with Play held (52 -> 68)
.venv/bin/python -m padcontroller.virtualpad cc 34 64 # knob CC 34 to 64 on channel 1
"""
from __future__ import annotations
import argparse
import configparser
import json
import time
from contextlib import contextmanager
from pathlib import Path
from typing import Iterator
import rtmidi
from padcontroller.layer import PLAY_CC
ROOT = Path(__file__).resolve().parents[1]
MIDI_MAP = ROOT / "shows" / "midi_map.json"
TEST_SHOW = ROOT / "shows" / "test.qxw"
QLC_CONF = Path.home() / ".config" / "qlcplus" / "Q Light Controller Plus.conf"
TARGET_CLIENT = "padcontroller-in"
# The SMC-PAD sends pads on MIDI channel 10 and knobs on channel 1 (0-based here).
PAD_CHANNEL = 9
KNOB_CHANNEL = 0
def last_workspace(conf: Path = QLC_CONF) -> Path | None:
"""The workspace QLC+ opened most recently, from its recent-files list."""
parser = configparser.ConfigParser(interpolation=None, strict=False)
try:
parser.read(conf)
recent = parser.get("workspace", "recent0")
except (configparser.Error, OSError):
return None
path = Path(recent)
return path if path.is_absolute() else Path.home() / path
def check_test_show(conf: Path = QLC_CONF) -> None:
"""Refuse to drive QLC+ unless its last workspace is the 127.0.0.1-only test show."""
ws = last_workspace(conf)
if ws is None or ws.resolve() != TEST_SHOW.resolve():
raise SystemExit(
f"QLC+'s last workspace is {ws or '(unknown)'}, not {TEST_SHOW.relative_to(ROOT)}. "
"Open the test show in QLC+ (or pass --force) so presses can't reach the real rig."
)
def pad_note(pad: int, midi_map: Path = MIDI_MAP) -> tuple[int, int]:
"""(channel, note) for a pad number in shows/midi_map.json."""
for entry in json.loads(midi_map.read_text())["pads"]:
if entry["pad"] == pad:
return entry["channel"], entry["note"]
raise SystemExit(f"Pad {pad} is not in {midi_map.relative_to(ROOT)}")
class VirtualPad:
"""An ALSA MIDI output linked to padcontroller-in."""
def __init__(self, target: str = TARGET_CLIENT) -> None:
self.out = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA, name="virtualpad")
ports = self.out.get_ports()
i = next((i for i, name in enumerate(ports) if name.startswith(target + ":")), None)
if i is None:
raise RuntimeError(
f"No {target} MIDI port; is the padcontroller service running? Ports:\n "
+ "\n ".join(ports or ["(none)"])
)
self.out.open_port(i, "virtualpad")
def close(self) -> None:
self.out.close_port()
def __enter__(self) -> VirtualPad:
return self
def __exit__(self, *exc: object) -> None:
self.close()
def send(self, data: list[int]) -> None:
self.out.send_message(data)
def press(self, note: int, channel: int = PAD_CHANNEL, velocity: int = 127, hold: float = 0.05) -> None:
"""Note on, wait hold seconds, note off: one tap of a pad."""
self.send([0x90 | channel, note, velocity])
time.sleep(hold)
self.send([0x80 | channel, note, 0])
def cc(self, cc: int, value: int, channel: int = KNOB_CHANNEL) -> None:
self.send([0xB0 | channel, cc, max(0, min(127, value))])
@contextmanager
def play(self) -> Iterator[None]:
"""Hold Play for the block, so bank 2 pads go out a layer up."""
self.cc(PLAY_CC, 127)
try:
yield
finally:
self.cc(PLAY_CC, 0)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--force", action="store_true", help="skip the check that QLC+ has the test show open")
sub = ap.add_subparsers(dest="cmd", required=True)
p = sub.add_parser("press", help="tap a pad")
p.add_argument("note", type=int, nargs="?", help="MIDI note (channel 10 unless --channel)")
p.add_argument("--pad", type=int, help="pad number from shows/midi_map.json instead of a note")
p.add_argument("--channel", type=int, default=PAD_CHANNEL + 1, help="MIDI channel 1-16 (default 10)")
p.add_argument("--hold", type=float, default=0.05, help="seconds between note on and off")
p.add_argument("--play", action="store_true", help="hold Play while pressing")
c = sub.add_parser("cc", help="set a knob")
c.add_argument("cc", type=int)
c.add_argument("value", type=int)
c.add_argument("--channel", type=int, default=KNOB_CHANNEL + 1, help="MIDI channel 1-16 (default 1)")
args = ap.parse_args()
if not args.force:
check_test_show()
with VirtualPad() as pad:
if args.cmd == "cc":
pad.cc(args.cc, args.value, args.channel - 1)
print(f"CC {args.cc} = {args.value} (channel {args.channel})")
return
if args.pad is not None:
channel, note = pad_note(args.pad)
elif args.note is not None:
channel, note = args.channel - 1, args.note
else:
raise SystemExit("press needs a note or --pad")
if args.play:
with pad.play():
pad.press(note, channel, hold=args.hold)
else:
pad.press(note, channel, hold=args.hold)
print(f"Pressed note {note} (channel {channel + 1}){' with Play held' if args.play else ''}")
if __name__ == "__main__":
main()
+6
View File
@@ -0,0 +1,6 @@
"""Mover Pattern Studio — design pan/tilt patterns and write them into QLC+ workspaces.
Run with: python3 -m patternstudio
"""
__version__ = "0.1.0"
+41
View File
@@ -0,0 +1,41 @@
"""python3 -m patternstudio [--port 8765] [--root .] [--no-browser]"""
from __future__ import annotations
import argparse
import sys
import threading
import webbrowser
from pathlib import Path
from .server import make_server
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(prog="patternstudio", description="Mover Pattern Studio for QLC+ workspaces")
p.add_argument("--root", default=str(Path(__file__).resolve().parents[1]), help="Project root (contains shows/, fixtures/)")
p.add_argument("--host", default="127.0.0.1")
p.add_argument("--port", type=int, default=8765)
p.add_argument("--no-browser", action="store_true", help="Do not open the browser")
args = p.parse_args(argv)
root = Path(args.root).resolve()
if not (root / "shows").is_dir():
print(f"warning: {root / 'shows'} does not exist — no workspaces will be listed", file=sys.stderr)
server = make_server(root, args.host, args.port)
url = f"http://{args.host}:{args.port}/"
print(f"Mover Pattern Studio → {url} (root {root}) Ctrl+C to quit")
if not args.no_browser:
threading.Timer(0.4, webbrowser.open, args=(url,)).start()
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.studio.live.stop() # type: ignore[attr-defined]
server.server_close()
return 0
if __name__ == "__main__":
sys.exit(main())
+119
View File
@@ -0,0 +1,119 @@
"""Minimal Art-Net output + a background runner that plays a pattern on the real heads."""
from __future__ import annotations
import socket
import threading
import time
from typing import Any
from .efx import Efx, Path as PathPattern, clamp8
from .qxw import Workspace
ARTNET_PORT = 6454
_HEADER = b"Art-Net\x00"
_OP_DMX = 0x5000
def build_artdmx(frame: bytes, universe: int, sequence: int) -> bytes:
data = bytearray(frame[:512])
if len(data) & 1:
data.append(0)
n = len(data)
pkt = bytearray(18 + n)
pkt[0:8] = _HEADER
pkt[8:10] = bytes((_OP_DMX & 0xFF, _OP_DMX >> 8))
pkt[10], pkt[11] = 0, 14
pkt[12] = sequence & 0xFF
pkt[13] = 0
pkt[14] = universe & 0xFF
pkt[15] = (universe >> 8) & 0x7F
pkt[16], pkt[17] = (n >> 8) & 0xFF, n & 0xFF
pkt[18:] = data
return bytes(pkt)
class LivePreview:
"""Runs one pattern at a time, ~40 Hz, until stopped. Thread-safe."""
def __init__(self):
self._lock = threading.Lock()
self._thread: threading.Thread | None = None
self._stop = threading.Event()
self.status: dict[str, Any] = {"running": False}
def start(self, ws: Workspace, pattern: Efx | PathPattern, ip: str, universe: int, hz: float = 40.0):
self.stop()
movers = {f.id: f for f in ws.fixtures if f.is_mover}
# Universe → frame; static channel values that light the head.
frames: dict[int, bytearray] = {}
for fx in pattern.fixtures:
f = movers[fx.id]
frame = frames.setdefault(f.universe, bytearray(512))
for ch, v in f.mode.preview_channels().items(): # type: ignore[union-attr]
if f.address + ch < 512:
frame[f.address + ch] = v
# QLC+ Art-Net plugin sends each QLC+ universe as `universe` + offset; we
# mirror that: QLC+ universe N goes to Art-Net universe (base + N - first).
base_uni = universe
first_uni = min(frames) if frames else 0
self._stop.clear()
self.status = {
"running": True,
"ip": ip,
"universe": universe,
"fixtures": [fx.id for fx in pattern.fixtures],
"kind": "efx" if isinstance(pattern, Efx) else "path",
}
def run():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
seq = 1
period = 1.0 / hz
t0 = time.monotonic()
try:
while not self._stop.is_set():
elapsed_ms = (time.monotonic() - t0) * 1000.0
for serial, fx in enumerate(pattern.fixtures):
f = movers[fx.id]
m = f.mode
pt = pattern.live_point(serial, elapsed_ms)
if pt is None or m is None:
continue
pan, tilt = pt
frame = frames[f.universe]
if m.pan_msb is not None:
frame[f.address + m.pan_msb] = clamp8(pan)
if m.tilt_msb is not None:
frame[f.address + m.tilt_msb] = clamp8(tilt)
if m.pan_lsb is not None:
frame[f.address + m.pan_lsb] = clamp8((pan - int(pan)) * 255)
if m.tilt_lsb is not None:
frame[f.address + m.tilt_lsb] = clamp8((tilt - int(tilt)) * 255)
for uni, frame in frames.items():
sock.sendto(build_artdmx(bytes(frame), base_uni + (uni - first_uni), seq), (ip, ARTNET_PORT))
seq = 1 if seq >= 255 else seq + 1
time.sleep(period)
# Blackout the channels we touched so the heads do not stay lit.
for uni, frame in frames.items():
for _ in range(3):
sock.sendto(build_artdmx(bytes(512), base_uni + (uni - first_uni), seq), (ip, ARTNET_PORT))
time.sleep(period)
finally:
sock.close()
with self._lock:
self.status = {"running": False}
with self._lock:
self._thread = threading.Thread(target=run, daemon=True)
self._thread.start()
def stop(self):
self._stop.set()
t = self._thread
if t and t.is_alive():
t.join(timeout=2.0)
self._thread = None
with self._lock:
self.status = {"running": False}
+418
View File
@@ -0,0 +1,418 @@
"""Pattern maths.
`EFX*` is a faithful port of QLC+ 4.12 `EFX::calculatePoint` / `rotateAndScale`
/ `EFXFixture::timeOffset`, so the preview here matches what QLC+ renders.
`Path*` samples a list of waypoints (optionally Catmull-Rom smoothed) into
keyframes that become a QLC+ Sequence.
Both produce the same output shape — a list of per-fixture keyframe tracks —
so the browser preview and the live Art-Net preview share one code path.
"""
from __future__ import annotations
import math
from dataclasses import dataclass, field
from typing import Any
ALGORITHMS = (
"Circle",
"Eight",
"Line",
"Line2",
"Diamond",
"Square",
"SquareChoppy",
"Leaf",
"Lissajous",
)
DIRECTIONS = ("Forward", "Backward")
RUN_ORDERS = ("Loop", "SingleShot", "PingPong")
PROPAGATIONS = ("Parallel", "Serial", "Asymmetric")
RELATIVE_ZERO = 127
PREVIEW_STEPS = 128 # same as EFX::preview
def clamp(v: float, lo: float = 0, hi: float = 255) -> float:
return max(lo, min(hi, v))
def clamp8(v: float) -> int:
return int(clamp(round(v)))
# --------------------------------------------------------------------------- EFX
@dataclass
class EfxFixture:
id: int
head: int = 0
direction: str = "Forward"
start_offset: int = 0
# Only used when `relative` is on: absolute home aim written to the base Scene.
pan: int = 128
tilt: int = 128
@classmethod
def from_dict(cls, d: dict[str, Any]) -> "EfxFixture":
return cls(
id=int(d["id"]),
head=int(d.get("head", 0)),
direction="Backward" if d.get("direction") == "Backward" else "Forward",
start_offset=int(d.get("start_offset", 0)) % 360,
pan=clamp8(d.get("pan", 128)),
tilt=clamp8(d.get("tilt", 128)),
)
@dataclass
class Efx:
algorithm: str = "Circle"
width: int = 40
height: int = 40
rotation: int = 0
start_offset: int = 0
x_offset: int = 128
y_offset: int = 128
x_frequency: int = 1
y_frequency: int = 1
x_phase: int = 0
y_phase: int = 0
duration_ms: int = 8000
fade_in_ms: int = 0
fade_out_ms: int = 0
direction: str = "Forward"
run_order: str = "Loop"
propagation: str = "Parallel"
relative: bool = False
fixtures: list[EfxFixture] = field(default_factory=list)
@classmethod
def from_dict(cls, d: dict[str, Any]) -> "Efx":
alg = d.get("algorithm", "Circle")
if alg not in ALGORITHMS:
raise ValueError(f"unknown algorithm {alg!r}")
return cls(
algorithm=alg,
width=int(clamp(int(d.get("width", 40)), 0, 127)),
height=int(clamp(int(d.get("height", 40)), 0, 127)),
rotation=int(d.get("rotation", 0)) % 360,
start_offset=int(d.get("start_offset", 0)) % 360,
x_offset=clamp8(d.get("x_offset", 128)),
y_offset=clamp8(d.get("y_offset", 128)),
x_frequency=int(clamp(int(d.get("x_frequency", 1)), 0, 5)),
y_frequency=int(clamp(int(d.get("y_frequency", 1)), 0, 5)),
x_phase=int(d.get("x_phase", 0)) % 360,
y_phase=int(d.get("y_phase", 0)) % 360,
duration_ms=max(20, int(d.get("duration_ms", 8000))),
fade_in_ms=max(0, int(d.get("fade_in_ms", 0))),
fade_out_ms=max(0, int(d.get("fade_out_ms", 0))),
direction=d.get("direction") if d.get("direction") in DIRECTIONS else "Forward",
run_order=d.get("run_order") if d.get("run_order") in RUN_ORDERS else "Loop",
propagation=d.get("propagation") if d.get("propagation") in PROPAGATIONS else "Parallel",
relative=bool(d.get("relative", False)),
fixtures=[EfxFixture.from_dict(f) for f in d.get("fixtures", [])],
)
# -- QLC+ port ---------------------------------------------------------
def _direction_iterator(self, fixture_dir: str, it: float) -> float:
if fixture_dir == self.direction:
return it
if self.algorithm == "Line":
return it - math.pi if it > math.pi else it + math.pi
return 2.0 * math.pi - it
def _raw_point(self, it: float) -> tuple[float, float]:
a = self.algorithm
if a == "Circle":
return math.cos(it + math.pi / 2), math.cos(it)
if a == "Eight":
return math.cos(it * 2 + math.pi / 2), math.cos(it)
if a == "Line":
return math.cos(it), math.cos(it)
if a == "Line2":
v = it / math.pi - 1
return v, v
if a == "Diamond":
return math.cos(it - math.pi / 2) ** 3, math.cos(it) ** 3
if a == "Square":
h = math.pi / 2
if it < h:
return (it * 2 / math.pi) * 2 - 1, 1.0
if it < math.pi:
return 1.0, (1 - (it - h) * 2 / math.pi) * 2 - 1
if it < math.pi * 1.5:
return (1 - (it - math.pi) * 2 / math.pi) * 2 - 1, -1.0
return -1.0, ((it - math.pi * 1.5) * 2 / math.pi) * 2 - 1
if a == "SquareChoppy":
return float(round(math.cos(it))), float(round(math.sin(it)))
if a == "Leaf":
return math.cos(it + math.pi / 2) ** 5, math.cos(it)
if a == "Lissajous":
return (
self._lissajous_axis(it, self.x_frequency, math.radians(self.x_phase)),
self._lissajous_axis(it, self.y_frequency, math.radians(self.y_phase)),
)
raise ValueError(a)
@staticmethod
def _lissajous_axis(it: float, freq: int, phase: float) -> float:
if freq > 0:
return math.cos(freq * it - phase)
# Frequency 0 = triangle wave (QLC+ "linear" axis).
it0 = (it + phase) / math.pi
fff = int(it0)
it0 -= fff - fff % 2
forward = 1 - math.floor(it0)
backward = 1 - forward
it0 -= math.floor(it0)
return (forward * it0 + backward * (1 - it0)) * 2 - 1
def point(self, fixture_dir: str, fixture_offset: int, it: float) -> tuple[float, float]:
"""Pan/tilt (0–255 float) for iterator `it` in 0..2π — EFX::calculatePoint."""
it = self._direction_iterator(fixture_dir, it)
it += math.radians((fixture_offset + self.start_offset) % 360)
if it >= 2 * math.pi:
it -= 2 * math.pi
x, y = self._raw_point(it)
r = math.radians(self.rotation)
c, s = math.cos(r), math.sin(r)
px = self.x_offset + x * c * self.width + y * s * self.height
py = self.y_offset + -x * s * self.width + y * c * self.height
return clamp(px), clamp(py)
def time_offset_ms(self, serial: int) -> int:
if self.propagation in ("Serial", "Asymmetric"):
return self.duration_ms // (len(self.fixtures) + 1) * serial
return 0
def sample(self, steps: int = PREVIEW_STEPS) -> dict[str, Any]:
tracks = []
for serial, fx in enumerate(self.fixtures):
pts = []
for i in range(steps):
it = 2 * math.pi * i / steps
px, py = self.point(fx.direction, fx.start_offset, it)
pts.append([round(px, 2), round(py, 2)])
tracks.append(
{
"id": fx.id,
"head": fx.head,
"points": pts,
# Asymmetric: shifted in phase, starts immediately.
# Serial: shifted in phase AND waits before starting.
"time_offset_ms": self.time_offset_ms(serial),
"start_delay_ms": self.time_offset_ms(serial) if self.propagation == "Serial" else 0,
}
)
return {
"kind": "efx",
"loop_ms": self.duration_ms,
"run_order": self.run_order,
"relative": self.relative,
"tracks": tracks,
}
def live_point(self, serial: int, elapsed_ms: float) -> tuple[float, float] | None:
"""Pan/tilt for a running fixture at wall time — EFXFixture::nextStep."""
fx = self.fixtures[serial]
loop = self.duration_ms
off = self.time_offset_ms(serial)
if self.propagation == "Serial" and elapsed_ms < off:
return None
cycles, pos = divmod(elapsed_ms, loop)
if self.run_order == "SingleShot" and cycles >= 1:
return None
d = fx.direction
if self.run_order == "PingPong" and int(cycles) % 2 == 1:
d = "Backward" if d == "Forward" else "Forward"
pos = (pos + off) % loop
it = 2 * math.pi * pos / loop
return self.point(d, fx.start_offset, it)
# --------------------------------------------------------------------------- Path
@dataclass
class PathPoint:
pan: float
tilt: float
fade_ms: int = 1000
hold_ms: int = 0
@classmethod
def from_dict(cls, d: dict[str, Any]) -> "PathPoint":
return cls(
pan=clamp(float(d["pan"])),
tilt=clamp(float(d["tilt"])),
fade_ms=max(0, int(d.get("fade_ms", 1000))),
hold_ms=max(0, int(d.get("hold_ms", 0))),
)
@dataclass
class PathFixture:
id: int
head: int = 0
pan_offset: int = 0
tilt_offset: int = 0
mirror_pan: bool = False # head hung the other way round: pan = 255 - pan
mirror_tilt: bool = False
@classmethod
def from_dict(cls, d: dict[str, Any]) -> "PathFixture":
return cls(
id=int(d["id"]),
head=int(d.get("head", 0)),
pan_offset=int(d.get("pan_offset", 0)),
tilt_offset=int(d.get("tilt_offset", 0)),
mirror_pan=bool(d.get("mirror_pan", False)),
mirror_tilt=bool(d.get("mirror_tilt", False)),
)
def apply(self, pan: float, tilt: float) -> tuple[float, float]:
if self.mirror_pan:
pan = 255 - pan
if self.mirror_tilt:
tilt = 255 - tilt
return clamp(pan + self.pan_offset), clamp(tilt + self.tilt_offset)
@dataclass
class Path:
points: list[PathPoint] = field(default_factory=list)
smooth: bool = False
subdivisions: int = 6 # extra steps per segment when smoothing
closed: bool = True # last point flows back into the first
run_order: str = "Loop"
direction: str = "Forward"
fixtures: list[PathFixture] = field(default_factory=list)
@classmethod
def from_dict(cls, d: dict[str, Any]) -> "Path":
return cls(
points=[PathPoint.from_dict(p) for p in d.get("points", [])],
smooth=bool(d.get("smooth", False)),
subdivisions=int(clamp(int(d.get("subdivisions", 6)), 1, 32)),
closed=bool(d.get("closed", True)),
run_order=d.get("run_order") if d.get("run_order") in RUN_ORDERS else "Loop",
direction=d.get("direction") if d.get("direction") in DIRECTIONS else "Forward",
fixtures=[PathFixture.from_dict(f) for f in d.get("fixtures", [])],
)
# -- steps ----------------------------------------------------------------
def steps(self) -> list[PathPoint]:
"""Resolved step list (smoothing expanded), in the pattern's base frame."""
pts = self.points
if len(pts) < 2 or not self.smooth:
return list(pts)
# A waypoint's fade_ms is the travel time *into* it. When the segment
# before it is split into `sub` sub-steps, each sub-step (and the
# waypoint itself) gets fade_ms / sub so the total travel time holds.
out: list[PathPoint] = []
n = len(pts)
sub = self.subdivisions
seg_count = n if self.closed else n - 1
def split_fade(p: PathPoint) -> int:
return max(1, p.fade_ms // sub)
for i in range(seg_count):
p0 = pts[(i - 1) % n] if (self.closed or i > 0) else pts[0]
p1 = pts[i]
p2 = pts[(i + 1) % n]
p3 = pts[(i + 2) % n] if (self.closed or i + 2 < n) else pts[-1]
arrive = split_fade(p1) if (self.closed or i > 0) else p1.fade_ms
out.append(PathPoint(p1.pan, p1.tilt, fade_ms=arrive, hold_ms=p1.hold_ms))
for k in range(1, sub):
t = k / sub
pan = _catmull(p0.pan, p1.pan, p2.pan, p3.pan, t)
tilt = _catmull(p0.tilt, p1.tilt, p2.tilt, p3.tilt, t)
out.append(PathPoint(clamp(pan), clamp(tilt), fade_ms=split_fade(p2), hold_ms=0))
if not self.closed:
last = pts[-1]
out.append(PathPoint(last.pan, last.tilt, fade_ms=split_fade(last), hold_ms=last.hold_ms))
return out
def loop_ms(self) -> int:
return sum(s.fade_ms + s.hold_ms for s in self.steps())
def sample(self) -> dict[str, Any]:
steps = self.steps()
tracks = []
for fx in self.fixtures:
keys = []
t = 0
for s in steps:
pan, tilt = fx.apply(s.pan, s.tilt)
t += s.fade_ms
keys.append([t, round(pan, 2), round(tilt, 2)])
if s.hold_ms:
t += s.hold_ms
keys.append([t, round(pan, 2), round(tilt, 2)])
tracks.append({"id": fx.id, "head": fx.head, "keys": keys})
return {
"kind": "path",
"loop_ms": self.loop_ms(),
"run_order": self.run_order,
"direction": self.direction,
"tracks": tracks,
"step_count": len(steps),
}
def live_point(self, serial: int, elapsed_ms: float) -> tuple[float, float] | None:
steps = self.steps()
if not steps:
return None
loop = self.loop_ms()
if loop <= 0:
pan, tilt = steps[0].pan, steps[0].tilt
return self.fixtures[serial].apply(pan, tilt)
cycles, pos = divmod(elapsed_ms, loop)
if self.run_order == "SingleShot" and cycles >= 1:
pos = loop
reverse = self.direction == "Backward"
if self.run_order == "PingPong" and int(cycles) % 2 == 1:
reverse = not reverse
order = list(reversed(steps)) if reverse else steps
t = 0.0
prev = order[-1]
for s in order:
if pos <= t + s.fade_ms:
f = (pos - t) / s.fade_ms if s.fade_ms else 1.0
pan = prev.pan + (s.pan - prev.pan) * f
tilt = prev.tilt + (s.tilt - prev.tilt) * f
return self.fixtures[serial].apply(pan, tilt)
t += s.fade_ms
if pos <= t + s.hold_ms:
return self.fixtures[serial].apply(s.pan, s.tilt)
t += s.hold_ms
prev = s
last = order[-1]
return self.fixtures[serial].apply(last.pan, last.tilt)
def _catmull(p0: float, p1: float, p2: float, p3: float, t: float) -> float:
t2, t3 = t * t, t * t * t
return 0.5 * (
2 * p1
+ (-p0 + p2) * t
+ (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2
+ (-p0 + 3 * p1 - 3 * p2 + p3) * t3
)
# --------------------------------------------------------------------------- entry
def pattern_from_dict(d: dict[str, Any]) -> Efx | Path:
kind = d.get("type", "efx")
if kind == "efx":
return Efx.from_dict({**d.get("efx", {}), "fixtures": d.get("fixtures", [])})
if kind == "path":
return Path.from_dict({**d.get("path", {}), "fixtures": d.get("fixtures", [])})
raise ValueError(f"unknown pattern type {kind!r}")
+263
View File
@@ -0,0 +1,263 @@
"""Locate and read QLC+ fixture definitions (.qxf) and work out which channels
in a mode are pan / tilt / dimmer / shutter / colour.
"""
from __future__ import annotations
import os
import re
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from functools import lru_cache
from pathlib import Path
NS = {"q": "http://www.qlcplus.org/FixtureDefinition"}
DIMMER_PRESETS = {"IntensityMasterDimmer", "IntensityDimmer"}
WHITE_PRESETS = {"IntensityWhite"}
RGB_PRESETS = ("IntensityRed", "IntensityGreen", "IntensityBlue")
@dataclass
class ChannelInfo:
index: int
name: str
preset: str | None
group: str | None
byte: int
shutter_open: int | None = None # DMX value that opens the shutter, if a shutter channel
@dataclass
class ModeInfo:
name: str
channels: list[ChannelInfo]
pan_msb: int | None = None
pan_lsb: int | None = None
tilt_msb: int | None = None
tilt_lsb: int | None = None
dimmers: list[int] = field(default_factory=list)
shutters: list[tuple[int, int]] = field(default_factory=list) # (channel, open value)
whites: list[int] = field(default_factory=list)
reds: list[int] = field(default_factory=list)
greens: list[int] = field(default_factory=list)
blues: list[int] = field(default_factory=list)
@property
def is_mover(self) -> bool:
return self.pan_msb is not None and self.tilt_msb is not None
def preview_channels(self) -> dict[int, int]:
"""Channel values that make the head visibly lit (white, open, full)."""
ch: dict[int, int] = {}
for d in self.dimmers:
ch[d] = 255
for s, v in self.shutters:
ch[s] = v
if self.whites:
for w in self.whites:
ch[w] = 255
else:
for c in self.reds + self.greens + self.blues:
ch[c] = 255
if not self.dimmers and not self.whites and not self.reds:
# Nothing we recognise as intensity — fall back to every Intensity-group channel.
for c in self.channels:
if c.group == "Intensity" or (c.preset or "").startswith("Intensity"):
ch[c.index] = 255
return ch
def to_dict(self) -> dict:
return {
"name": self.name,
"channel_count": len(self.channels),
"pan_msb": self.pan_msb,
"pan_lsb": self.pan_lsb,
"tilt_msb": self.tilt_msb,
"tilt_lsb": self.tilt_lsb,
"dimmers": self.dimmers,
"channels": [{"index": c.index, "name": c.name, "preset": c.preset, "group": c.group} for c in self.channels],
}
@dataclass
class FixtureDef:
path: Path
manufacturer: str
model: str
type: str
pan_max: int
tilt_max: int
modes: dict[str, ModeInfo]
def mode(self, name: str) -> ModeInfo | None:
if name in self.modes:
return self.modes[name]
# QLC+ sometimes stores "43 Channel" vs "43 Channel Mode" etc. — be lenient.
key = name.strip().lower()
for k, v in self.modes.items():
if k.strip().lower() == key:
return v
return None
# ----------------------------------------------------------------------------- parse
def _text(el: ET.Element | None, default: str = "") -> str:
return (el.text or default) if el is not None else default
def _parse_channel(el: ET.Element) -> ChannelInfo:
name = el.get("Name", "")
preset = el.get("Preset")
group_el = el.find("q:Group", NS)
group = _text(group_el) if group_el is not None else None
byte = int(group_el.get("Byte", "0")) if group_el is not None else 0
if preset and group is None:
# Presets imply the group; the ones we care about:
if preset.startswith("Position"):
group = "Pan" if "Pan" in preset else "Tilt"
elif preset.startswith("Intensity"):
group = "Intensity"
elif preset.startswith("Shutter") or preset.startswith("Strobe"):
group = "Shutter"
if preset.endswith("Fine"):
byte = 1
shutter_open = None
if group == "Shutter" or (preset or "").startswith("Shutter"):
caps = el.findall("q:Capability", NS)
if (preset or "").startswith("Shutter") and not caps:
shutter_open = 0 # QLC+ built-in shutter presets all start with "Open"
for cap in caps:
cp = cap.get("Preset", "")
label = (cap.text or "").strip().lower()
if cp == "ShutterOpen" or (not cp and label in ("open", "shutter open", "no function")):
shutter_open = int(cap.get("Min", "0"))
break
return ChannelInfo(index=-1, name=name, preset=preset, group=group, byte=byte, shutter_open=shutter_open)
def _resolve_mode(name: str, chans: list[ChannelInfo]) -> ModeInfo:
m = ModeInfo(name=name, channels=chans)
for c in chans:
p = c.preset or ""
if c.group == "Pan" or p in ("PositionPan", "PositionPanFine"):
if c.byte == 1 or p.endswith("Fine"):
m.pan_lsb = m.pan_lsb if m.pan_lsb is not None else c.index
else:
m.pan_msb = m.pan_msb if m.pan_msb is not None else c.index
elif c.group == "Tilt" or p in ("PositionTilt", "PositionTiltFine"):
if c.byte == 1 or p.endswith("Fine"):
m.tilt_lsb = m.tilt_lsb if m.tilt_lsb is not None else c.index
else:
m.tilt_msb = m.tilt_msb if m.tilt_msb is not None else c.index
elif p in DIMMER_PRESETS:
m.dimmers.append(c.index)
elif p in WHITE_PRESETS:
m.whites.append(c.index)
elif p == RGB_PRESETS[0]:
m.reds.append(c.index)
elif p == RGB_PRESETS[1]:
m.greens.append(c.index)
elif p == RGB_PRESETS[2]:
m.blues.append(c.index)
elif c.group == "Intensity" and not p:
lname = c.name.lower()
if "dimmer" in lname or "master" in lname or "bright" in lname:
m.dimmers.append(c.index)
if c.shutter_open is not None:
m.shutters.append((c.index, c.shutter_open))
return m
@lru_cache(maxsize=256)
def load_fixture_def(path: str) -> FixtureDef:
root = ET.parse(path).getroot()
channels: dict[str, ChannelInfo] = {}
for el in root.findall("q:Channel", NS):
ci = _parse_channel(el)
channels[ci.name] = ci
phys = root.find("q:Physical", NS)
focus = phys.find("q:Focus", NS) if phys is not None else None
pan_max = int(focus.get("PanMax", "0")) if focus is not None else 0
tilt_max = int(focus.get("TiltMax", "0")) if focus is not None else 0
modes: dict[str, ModeInfo] = {}
for mode_el in root.findall("q:Mode", NS):
name = mode_el.get("Name", "")
chans: list[ChannelInfo] = []
for ch_el in mode_el.findall("q:Channel", NS):
base = channels.get((ch_el.text or "").strip())
if base is None:
continue
ci = ChannelInfo(**{**base.__dict__, "index": int(ch_el.get("Number", len(chans)))})
chans.append(ci)
chans.sort(key=lambda c: c.index)
modes[name] = _resolve_mode(name, chans)
return FixtureDef(
path=Path(path),
manufacturer=_text(root.find("q:Manufacturer", NS)),
model=_text(root.find("q:Model", NS)),
type=_text(root.find("q:Type", NS)),
pan_max=pan_max,
tilt_max=tilt_max,
modes=modes,
)
# ----------------------------------------------------------------------------- locate
_HEAD_RE = re.compile(
rb"<Manufacturer>(.*?)</Manufacturer>.*?<Model>(.*?)</Model>", re.S
)
class FixtureLibrary:
"""Index of (manufacturer, model) → .qxf path across the usual search dirs."""
def __init__(self, project_root: Path, extra_dirs: list[Path] | None = None):
self.dirs: list[Path] = [project_root / "fixtures"]
self.dirs += extra_dirs or []
self.dirs.append(Path.home() / ".qlcplus" / "fixtures")
for d in ("/usr/share/qlcplus/fixtures", "/usr/local/share/qlcplus/fixtures"):
self.dirs.append(Path(d))
self._index: dict[tuple[str, str], Path] | None = None
def _build_index(self) -> dict[tuple[str, str], Path]:
idx: dict[tuple[str, str], Path] = {}
for d in self.dirs:
if not d.is_dir():
continue
for dirpath, _dirs, files in os.walk(d):
for fn in files:
if not fn.endswith(".qxf"):
continue
p = Path(dirpath) / fn
try:
with open(p, "rb") as fh:
head = fh.read(4096)
except OSError:
continue
m = _HEAD_RE.search(head)
if not m:
continue
key = (_unesc(m.group(1)).strip().lower(), _unesc(m.group(2)).strip().lower())
idx.setdefault(key, p) # first dir wins (project fixtures override system)
return idx
def find(self, manufacturer: str, model: str) -> FixtureDef | None:
if self._index is None:
self._index = self._build_index()
p = self._index.get((manufacturer.strip().lower(), model.strip().lower()))
if p is None:
return None
try:
return load_fixture_def(str(p))
except ET.ParseError:
return None
def _unesc(b: bytes) -> str:
s = b.decode("utf-8", "replace")
return s.replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", '"').replace("&apos;", "'")
+577
View File
@@ -0,0 +1,577 @@
"""Read QLC+ workspaces (.qxw) and write pattern functions into them.
Reading uses ElementTree. Writing is done on the raw text so QLC+'s own
formatting, DOCTYPE and everything we do not understand are left untouched.
"""
from __future__ import annotations
import re
import shutil
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from xml.sax.saxutils import quoteattr
from .efx import Efx, Path as PathPattern, RELATIVE_ZERO, clamp8
from .fixturedefs import FixtureDef, FixtureLibrary, ModeInfo
NS = {"q": "http://www.qlcplus.org/Workspace"}
INVALID_ID = 4294967295
@dataclass
class WsFixture:
id: int
name: str
manufacturer: str
model: str
mode_name: str
universe: int
address: int
channels: int
definition: FixtureDef | None = None
mode: ModeInfo | None = None
@property
def is_mover(self) -> bool:
return self.mode is not None and self.mode.is_mover
def to_dict(self) -> dict[str, Any]:
d: dict[str, Any] = {
"id": self.id,
"name": self.name,
"manufacturer": self.manufacturer,
"model": self.model,
"mode": self.mode_name,
"universe": self.universe,
"address": self.address,
"channels": self.channels,
"is_mover": self.is_mover,
"definition_found": self.definition is not None,
}
if self.definition:
d["pan_max"] = self.definition.pan_max
d["tilt_max"] = self.definition.tilt_max
if self.mode:
d["pan_msb"] = self.mode.pan_msb
d["tilt_msb"] = self.mode.tilt_msb
d["pan_lsb"] = self.mode.pan_lsb
d["tilt_lsb"] = self.mode.tilt_lsb
return d
@dataclass
class WsFunction:
id: int
type: str
name: str
def to_dict(self) -> dict[str, Any]:
return {"id": self.id, "type": self.type, "name": self.name}
@dataclass
class Workspace:
path: Path
text: str
fixtures: list[WsFixture]
functions: list[WsFunction]
artnet: dict[int, dict[str, Any]] # universe id → {"ip":..., "universe":...}
vc_widget_ids: list[int] = field(default_factory=list)
vc_bottom: int = 0 # lowest used Y in the root VC frame
# ------------------------------------------------------------------ load
@classmethod
def load(cls, path: Path, library: FixtureLibrary) -> "Workspace":
text = path.read_text(encoding="utf-8")
root = ET.fromstring(text)
engine = root.find("q:Engine", NS)
fixtures: list[WsFixture] = []
functions: list[WsFunction] = []
artnet: dict[int, dict[str, Any]] = {}
if engine is not None:
for fx in engine.findall("q:Fixture", NS):
manu = _t(fx, "Manufacturer")
model = _t(fx, "Model")
mode_name = _t(fx, "Mode")
wsf = WsFixture(
id=int(_t(fx, "ID", "0")),
name=_t(fx, "Name"),
manufacturer=manu,
model=model,
mode_name=mode_name,
universe=int(_t(fx, "Universe", "0")),
address=int(_t(fx, "Address", "0")),
channels=int(_t(fx, "Channels", "0")),
)
if manu != "Generic" or model != "Generic":
wsf.definition = library.find(manu, model)
if wsf.definition:
wsf.mode = wsf.definition.mode(mode_name)
fixtures.append(wsf)
for fn in engine.findall("q:Function", NS):
functions.append(
WsFunction(id=int(fn.get("ID", "0")), type=fn.get("Type", ""), name=fn.get("Name", ""))
)
iomap = engine.find("q:InputOutputMap", NS)
if iomap is not None:
for uni in iomap.findall("q:Universe", NS):
out = uni.find("q:Output", NS)
if out is None or out.get("Plugin") != "ArtNet":
continue
params = out.find("q:PluginParameters", NS)
ip = params.get("outputIP") if params is not None else None
art_uni = params.get("outputUni") if params is not None else None
artnet[int(uni.get("ID", "0"))] = {
"ip": ip or out.get("UID") or "",
"universe": int(art_uni) if art_uni is not None else int(uni.get("ID", "0")),
}
widget_ids: list[int] = []
bottom = 0
vc = root.find("q:VirtualConsole", NS)
if vc is not None:
for el in vc.iter():
wid = el.get("ID")
if wid is not None and not el.tag.endswith("}Function"):
try:
widget_ids.append(int(wid))
except ValueError:
pass
frame = vc.find("q:Frame", NS)
if frame is not None:
for child in frame:
ws = child.find("q:WindowState", NS)
if ws is not None:
try:
bottom = max(bottom, int(ws.get("Y", "0")) + int(ws.get("Height", "0")))
except ValueError:
pass
return cls(
path=path,
text=text,
fixtures=fixtures,
functions=functions,
artnet=artnet,
vc_widget_ids=widget_ids,
vc_bottom=bottom,
)
def fixture(self, fid: int) -> WsFixture | None:
return next((f for f in self.fixtures if f.id == fid), None)
def next_function_id(self) -> int:
return (max((f.id for f in self.functions), default=-1)) + 1
def next_widget_id(self) -> int:
return (max(self.vc_widget_ids, default=-1)) + 1
def function_by_name(self, name: str, ftype: str | None = None) -> WsFunction | None:
for f in self.functions:
if f.name == name and (ftype is None or f.type == ftype):
return f
return None
def to_dict(self) -> dict[str, Any]:
return {
"path": str(self.path),
"name": self.path.name,
"fixtures": [f.to_dict() for f in self.fixtures],
"functions": [f.to_dict() for f in self.functions],
"artnet": {str(k): v for k, v in self.artnet.items()},
}
# ------------------------------------------------------------------ import
def pattern_from_function(self, fid: int) -> dict[str, Any] | None:
"""Turn an existing EFX or pan/tilt Sequence back into an editable pattern."""
root = ET.fromstring(self.text)
engine = root.find("q:Engine", NS)
if engine is None:
return None
for fn in engine.findall("q:Function", NS):
if int(fn.get("ID", "-1")) != fid:
continue
if fn.get("Type") == "EFX":
return _efx_to_pattern(fn)
if fn.get("Type") == "Sequence":
return _sequence_to_pattern(fn, self)
return None
def _t(el: ET.Element, tag: str, default: str = "") -> str:
child = el.find(f"q:{tag}", NS)
return (child.text or default).strip() if child is not None and child.text is not None else default
def _efx_to_pattern(fn: ET.Element) -> dict[str, Any]:
speed = fn.find("q:Speed", NS)
axes = {ax.get("Name"): ax for ax in fn.findall("q:Axis", NS)}
def axis(name: str, tag: str, default: str) -> int:
ax = axes.get(name)
return int(_t(ax, tag, default)) if ax is not None else int(default)
fixtures = []
for fx in fn.findall("q:Fixture", NS):
fixtures.append(
{
"id": int(_t(fx, "ID", "0")),
"head": int(_t(fx, "Head", "0")),
"direction": _t(fx, "Direction", "Forward"),
"start_offset": int(_t(fx, "StartOffset", "0")),
}
)
return {
"name": fn.get("Name", ""),
"type": "efx",
"source_function_id": int(fn.get("ID", "0")),
"fixtures": fixtures,
"efx": {
"algorithm": _t(fn, "Algorithm", "Circle"),
"width": int(_t(fn, "Width", "0")),
"height": int(_t(fn, "Height", "0")),
"rotation": int(_t(fn, "Rotation", "0")),
"start_offset": int(_t(fn, "StartOffset", "0")),
"relative": _t(fn, "IsRelative", "0") == "1",
"x_offset": axis("X", "Offset", "127"),
"y_offset": axis("Y", "Offset", "127"),
"x_frequency": axis("X", "Frequency", "1"),
"y_frequency": axis("Y", "Frequency", "1"),
"x_phase": axis("X", "Phase", "0"),
"y_phase": axis("Y", "Phase", "0"),
"duration_ms": int(speed.get("Duration", "8000")) if speed is not None else 8000,
"fade_in_ms": int(speed.get("FadeIn", "0")) if speed is not None else 0,
"fade_out_ms": int(speed.get("FadeOut", "0")) if speed is not None else 0,
"direction": _t(fn, "Direction", "Forward"),
"run_order": _t(fn, "RunOrder", "Loop"),
"propagation": _t(fn, "PropagationMode", "Parallel"),
},
}
def _sequence_to_pattern(fn: ET.Element, ws: Workspace) -> dict[str, Any] | None:
steps = fn.findall("q:Step", NS)
if not steps:
return None
# Which fixtures carry pan/tilt in this sequence?
fixture_ids: list[int] = []
for s in steps:
for fid, _vals in _parse_step_values(s.text or ""):
if fid not in fixture_ids:
fixture_ids.append(fid)
movers = [ws.fixture(fid) for fid in fixture_ids]
movers = [m for m in movers if m is not None and m.is_mover]
if not movers:
return None
ref = movers[0]
points = []
for s in steps:
vals = dict(_parse_step_values(s.text or "")).get(ref.id, {})
pan = vals.get(ref.mode.pan_msb) # type: ignore[union-attr]
tilt = vals.get(ref.mode.tilt_msb) # type: ignore[union-attr]
if pan is None or tilt is None:
return None
points.append(
{"pan": pan, "tilt": tilt, "fade_ms": int(s.get("FadeIn", "0")), "hold_ms": int(s.get("Hold", "0"))}
)
return {
"name": fn.get("Name", ""),
"type": "path",
"source_function_id": int(fn.get("ID", "0")),
"fixtures": [{"id": m.id} for m in movers],
"path": {
"points": points,
"smooth": False,
"closed": True,
"direction": _t(fn, "Direction", "Forward"),
"run_order": _t(fn, "RunOrder", "Loop"),
},
}
def _parse_step_values(text: str) -> list[tuple[int, dict[int, int]]]:
"""'8:0,10,2,20:9:0,30,2,40' → [(8, {0:10, 2:20}), (9, {0:30, 2:40})]."""
out: list[tuple[int, dict[int, int]]] = []
parts = text.strip().split(":")
i = 0
while i + 1 < len(parts):
try:
fid = int(parts[i])
except ValueError:
break
nums = [int(x) for x in parts[i + 1].split(",") if x.strip() != ""]
out.append((fid, {nums[k]: nums[k + 1] for k in range(0, len(nums) - 1, 2)}))
i += 2
return out
# ----------------------------------------------------------------------------- render
def _speed(fade_in: int, fade_out: int, duration: int) -> str:
return f' <Speed FadeIn="{fade_in}" FadeOut="{fade_out}" Duration="{duration}"/>'
def render_efx(fid: int, name: str, efx: Efx) -> str:
fixtures = "\n".join(
f""" <Fixture>
<ID>{fx.id}</ID>
<Head>{fx.head}</Head>
<Direction>{fx.direction}</Direction>
<StartOffset>{fx.start_offset}</StartOffset>
</Fixture>"""
for fx in efx.fixtures
)
x_off = RELATIVE_ZERO if efx.relative else efx.x_offset
y_off = RELATIVE_ZERO if efx.relative else efx.y_offset
return f""" <Function ID="{fid}" Type="EFX" Name={quoteattr(name)}>
{fixtures}
<PropagationMode>{efx.propagation}</PropagationMode>
<Speed FadeIn="{efx.fade_in_ms}" FadeOut="{efx.fade_out_ms}" Duration="{efx.duration_ms}"/>
<Direction>{efx.direction}</Direction>
<RunOrder>{efx.run_order}</RunOrder>
<Algorithm>{efx.algorithm}</Algorithm>
<Width>{efx.width}</Width>
<Height>{efx.height}</Height>
<Rotation>{efx.rotation}</Rotation>
<StartOffset>{efx.start_offset}</StartOffset>
<IsRelative>{1 if efx.relative else 0}</IsRelative>
<Axis Name="X">
<Offset>{x_off}</Offset>
<Frequency>{efx.x_frequency}</Frequency>
<Phase>{efx.x_phase}</Phase>
</Axis>
<Axis Name="Y">
<Offset>{y_off}</Offset>
<Frequency>{efx.y_frequency}</Frequency>
<Phase>{efx.y_phase}</Phase>
</Axis>
</Function>"""
def render_scene(fid: int, name: str, values: dict[int, dict[int, int]], fade_in: int = 0) -> str:
vals = "\n".join(
f' <FixtureVal ID="{fxid}">{",".join(f"{ch},{v}" for ch, v in sorted(chs.items()))}</FixtureVal>'
for fxid, chs in values.items()
if chs
)
return f""" <Function ID="{fid}" Type="Scene" Name={quoteattr(name)}>
{_speed(fade_in, 0, fade_in)}
{vals}
</Function>"""
def render_collection(fid: int, name: str, members: list[int]) -> str:
steps = "\n".join(f' <Step Number="{i}">{m}</Step>' for i, m in enumerate(members))
return f""" <Function ID="{fid}" Type="Collection" Name={quoteattr(name)}>
{steps}
</Function>"""
def render_sequence(
fid: int,
scene_id: int,
name: str,
path: PathPattern,
movers: dict[int, WsFixture],
) -> tuple[str, str]:
"""Returns (bound scene xml, sequence xml)."""
steps = path.steps()
if not steps:
raise ValueError("path has no points")
def channels_for(fx_cfg, step) -> dict[int, int]:
m = movers[fx_cfg.id].mode
assert m is not None and m.pan_msb is not None and m.tilt_msb is not None
pan, tilt = fx_cfg.apply(step.pan, step.tilt)
ch = {m.pan_msb: clamp8(pan), m.tilt_msb: clamp8(tilt)}
# Fine channels: carry the fractional part like EFXFixture does.
if m.pan_lsb is not None:
ch[m.pan_lsb] = clamp8((pan - int(pan)) * 255)
if m.tilt_lsb is not None:
ch[m.tilt_lsb] = clamp8((tilt - int(tilt)) * 255)
return ch
step_xml = []
for i, s in enumerate(steps):
chunks = []
count = 0
for fx in path.fixtures:
ch = channels_for(fx, s)
count += len(ch)
chunks.append(f"{fx.id}:" + ",".join(f"{c},{v}" for c, v in sorted(ch.items())))
step_xml.append(
f' <Step Number="{i}" FadeIn="{s.fade_ms}" Hold="{s.hold_ms}" FadeOut="0" Values="{count}">'
+ ":".join(chunks)
+ "</Step>"
)
first = {fx.id: channels_for(fx, steps[0]) for fx in path.fixtures}
scene = render_scene(scene_id, f"{name} (base)", first)
seq = f""" <Function ID="{fid}" Type="Sequence" Name={quoteattr(name)} BoundScene="{scene_id}">
{_speed(steps[0].fade_ms, 0, steps[0].fade_ms + steps[0].hold_ms)}
<Direction>{path.direction}</Direction>
<RunOrder>{path.run_order}</RunOrder>
<SpeedModes FadeIn="PerStep" FadeOut="Common" Duration="PerStep"/>
{chr(10).join(step_xml)}
</Function>"""
return scene, seq
def render_vc_button(wid: int, caption: str, fid: int, x: int, y: int, w: int = 110, h: int = 60, bg: str = "4282664004") -> str:
return f""" <Button Caption={quoteattr(caption)} ID="{wid}" Icon="">
<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>{bg}</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="{fid}"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>"""
# ----------------------------------------------------------------------------- write
_FUNC_RE_TMPL = r'[ \t]*<Function ID="{fid}"[^>]*?(?:/>|>.*?</Function>)[ \t]*\r?\n?'
def remove_function(text: str, fid: int) -> str:
return re.sub(_FUNC_RE_TMPL.format(fid=fid), "", text, count=1, flags=re.S)
def insert_functions(text: str, xml: str) -> str:
"""Insert function XML at the end of the Engine section (order is not significant to QLC+)."""
idx = text.find("</Engine>")
if idx < 0:
raise ValueError("workspace has no <Engine> section")
# back up to the start of that line
line_start = text.rfind("\n", 0, idx) + 1
return text[:line_start] + xml + "\n" + text[line_start:]
def insert_vc_widget(text: str, xml: str) -> str:
vc = text.find("<VirtualConsole>")
if vc < 0:
raise ValueError("workspace has no <VirtualConsole>")
props = text.find("<Properties>", vc)
end = text.rfind("</Frame>", vc, props if props > 0 else len(text))
if end < 0:
raise ValueError("VirtualConsole has no root <Frame>")
line_start = text.rfind("\n", 0, end) + 1
return text[:line_start] + xml + "\n" + text[line_start:]
@dataclass
class ExportResult:
path: Path
backup: Path | None
function_ids: dict[str, int]
widget_id: int | None
replaced: list[int]
def to_dict(self) -> dict[str, Any]:
return {
"path": str(self.path),
"backup": str(self.backup) if self.backup else None,
"function_ids": self.function_ids,
"widget_id": self.widget_id,
"replaced": self.replaced,
}
def export_pattern(
ws: Workspace,
pattern: dict[str, Any],
*,
name: str,
overwrite: bool = True,
add_button: bool = False,
button_xy: tuple[int, int] | None = None,
out_path: Path | None = None,
backup: bool = True,
) -> ExportResult:
"""Write the pattern into `ws` (in place, or to `out_path`)."""
from .efx import pattern_from_dict
obj = pattern_from_dict(pattern)
name = name.strip() or "Mover Pattern"
text = ws.text
replaced: list[int] = []
ids: dict[str, int] = {}
xml_parts: list[str] = []
next_id = ws.next_function_id()
def alloc(kind: str, fname: str) -> int:
"""Reuse the ID of a same-named function (keeps VC buttons wired) or take a fresh one."""
nonlocal next_id, text
existing = ws.function_by_name(fname) if overwrite else None
if existing and existing.id not in replaced:
text = remove_function(text, existing.id)
replaced.append(existing.id)
ids[kind] = existing.id
return existing.id
fid = next_id
next_id += 1
ids[kind] = fid
return fid
movers = {f.id: f for f in ws.fixtures if f.is_mover}
for fx in obj.fixtures:
if fx.id not in movers:
raise ValueError(f"fixture {fx.id} is not a mover in this workspace")
if not obj.fixtures:
raise ValueError("pattern has no fixtures")
main_id: int
if isinstance(obj, Efx):
if obj.relative:
# Base positions scene + EFX around RELATIVE_ZERO + Collection to run both.
base_vals: dict[int, dict[int, int]] = {}
for fx in obj.fixtures:
m = movers[fx.id].mode
assert m is not None and m.pan_msb is not None and m.tilt_msb is not None
base_vals[fx.id] = {m.pan_msb: fx.pan, m.tilt_msb: fx.tilt}
scene_id = alloc("scene", f"{name} (home)")
efx_id = alloc("efx", f"{name} (EFX)")
coll_id = alloc("collection", name)
xml_parts.append(render_scene(scene_id, f"{name} (home)", base_vals, fade_in=obj.fade_in_ms))
xml_parts.append(render_efx(efx_id, f"{name} (EFX)", obj))
xml_parts.append(render_collection(coll_id, name, [scene_id, efx_id]))
main_id = coll_id
else:
efx_id = alloc("efx", name)
xml_parts.append(render_efx(efx_id, name, obj))
main_id = efx_id
else:
scene_id = alloc("scene", f"{name} (base)")
seq_id = alloc("sequence", name)
scene_xml, seq_xml = render_sequence(seq_id, scene_id, name, obj, movers)
xml_parts.append(scene_xml)
xml_parts.append(seq_xml)
main_id = seq_id
text = insert_functions(text, "\n".join(xml_parts))
widget_id = None
if add_button:
widget_id = ws.next_widget_id()
x, y = button_xy or (10, ws.vc_bottom + 10)
text = insert_vc_widget(text, render_vc_button(widget_id, name, main_id, x, y))
# Make sure what we are about to write is still well-formed before touching disk.
ET.fromstring(text)
target = out_path or ws.path
backup_path = None
if backup and target.exists():
backup_path = target.with_suffix(target.suffix + ".bak")
shutil.copyfile(target, backup_path)
target.write_text(text, encoding="utf-8")
return ExportResult(path=target, backup=backup_path, function_ids=ids, widget_id=widget_id, replaced=replaced)
+272
View File
@@ -0,0 +1,272 @@
"""Local HTTP server: static UI + small JSON API. Standard library only."""
from __future__ import annotations
import json
import mimetypes
import re
import traceback
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
from urllib.parse import parse_qs, urlparse
from .artnet import LivePreview
from .efx import pattern_from_dict
from .fixturedefs import FixtureLibrary
from .qxw import Workspace, export_pattern
STATIC_DIR = Path(__file__).parent / "static"
_SAFE_NAME = re.compile(r"[^A-Za-z0-9 _().#+-]+")
class ApiError(Exception):
def __init__(self, message: str, status: int = 400):
super().__init__(message)
self.status = status
class Studio:
"""Application state shared by all requests."""
def __init__(self, root: Path, shows_dir: str = "shows", patterns_dir: str = "patterns"):
self.root = root.resolve()
self.shows_dir = self.root / shows_dir
self.patterns_dir = self.root / patterns_dir
self.library = FixtureLibrary(self.root)
self.live = LivePreview()
# -- helpers ---------------------------------------------------------------
def resolve(self, rel: str) -> Path:
p = (self.root / rel).resolve()
if self.root not in p.parents and p != self.root:
raise ApiError("path is outside the project", 403)
return p
def workspace(self, rel: str) -> Workspace:
p = self.resolve(rel)
if not p.is_file() or p.suffix != ".qxw":
raise ApiError(f"not a workspace: {rel}", 404)
return Workspace.load(p, self.library)
# -- API -------------------------------------------------------------------
def list_workspaces(self) -> dict[str, Any]:
items = []
if self.shows_dir.is_dir():
for p in sorted(self.shows_dir.rglob("*.qxw"), key=lambda p: (len(p.parts), str(p).lower())):
items.append({"path": str(p.relative_to(self.root)), "name": p.name, "folder": str(p.parent.relative_to(self.root))})
return {"workspaces": items}
def get_workspace(self, q: dict[str, list[str]]) -> dict[str, Any]:
return self.workspace(_one(q, "path")).to_dict()
def get_function(self, q: dict[str, list[str]]) -> dict[str, Any]:
ws = self.workspace(_one(q, "path"))
pat = ws.pattern_from_function(int(_one(q, "id")))
if pat is None:
raise ApiError("function is not an EFX or a pan/tilt Sequence", 404)
return {"pattern": pat}
def sample(self, body: dict[str, Any]) -> dict[str, Any]:
try:
return pattern_from_dict(body["pattern"]).sample()
except (KeyError, ValueError, TypeError) as exc:
raise ApiError(f"bad pattern: {exc}") from exc
def export(self, body: dict[str, Any]) -> dict[str, Any]:
ws = self.workspace(body["path"])
out_rel = body.get("out_path")
out_path = self.resolve(out_rel) if out_rel else None
if out_path is not None and out_path.suffix != ".qxw":
raise ApiError("out_path must end in .qxw")
try:
res = export_pattern(
ws,
body["pattern"],
name=body.get("name") or body["pattern"].get("name") or "Mover Pattern",
overwrite=bool(body.get("overwrite", True)),
add_button=bool(body.get("add_button", False)),
button_xy=tuple(body["button_xy"]) if body.get("button_xy") else None,
out_path=out_path,
backup=bool(body.get("backup", True)),
)
except (ValueError, KeyError) as exc:
raise ApiError(str(exc)) from exc
d = res.to_dict()
d["path"] = str(res.path.relative_to(self.root))
return d
# -- pattern library ---------------------------------------------------------
def list_patterns(self) -> dict[str, Any]:
items = []
if self.patterns_dir.is_dir():
for p in sorted(self.patterns_dir.glob("*.json")):
try:
data = json.loads(p.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
continue
items.append({"file": p.name, "name": data.get("name", p.stem), "type": data.get("type", "efx"), "pattern": data})
return {"patterns": items}
def save_pattern(self, body: dict[str, Any]) -> dict[str, Any]:
pat = body["pattern"]
name = (body.get("name") or pat.get("name") or "pattern").strip()
pat["name"] = name
pattern_from_dict(pat) # validate
self.patterns_dir.mkdir(parents=True, exist_ok=True)
fn = _SAFE_NAME.sub("", name).strip().replace(" ", "_") or "pattern"
p = self.patterns_dir / f"{fn}.json"
p.write_text(json.dumps(pat, indent=1) + "\n", encoding="utf-8")
return {"file": p.name}
def delete_pattern(self, q: dict[str, list[str]]) -> dict[str, Any]:
fn = Path(_one(q, "file")).name
p = self.patterns_dir / fn
if p.suffix != ".json" or not p.is_file():
raise ApiError("no such pattern", 404)
p.unlink()
return {"deleted": fn}
# -- live Art-Net -------------------------------------------------------------
def live_start(self, body: dict[str, Any]) -> dict[str, Any]:
ws = self.workspace(body["path"])
try:
pat = pattern_from_dict(body["pattern"])
except (KeyError, ValueError, TypeError) as exc:
raise ApiError(f"bad pattern: {exc}") from exc
movers = {f.id for f in ws.fixtures if f.is_mover}
for fx in pat.fixtures:
if fx.id not in movers:
raise ApiError(f"fixture {fx.id} is not a mover")
if not pat.fixtures:
raise ApiError("pattern has no fixtures")
ip = body.get("ip") or next((a["ip"] for a in ws.artnet.values() if a.get("ip")), None)
if not ip:
raise ApiError("no Art-Net IP configured")
uni = int(body.get("universe", next((a["universe"] for a in ws.artnet.values()), 0)))
self.live.start(ws, pat, ip, uni)
return self.live.status
def live_stop(self) -> dict[str, Any]:
self.live.stop()
return self.live.status
def _one(q: dict[str, list[str]], key: str) -> str:
v = q.get(key)
if not v:
raise ApiError(f"missing query parameter {key!r}")
return v[0]
class Handler(BaseHTTPRequestHandler):
studio: Studio # set by make_server
server_version = "PatternStudio/0.1"
def log_message(self, fmt: str, *args: Any) -> None: # quieter default log
if self.path.startswith("/api/sample"):
return
super().log_message(fmt, *args)
# -- plumbing ----------------------------------------------------------------
def _json(self, status: int, data: Any) -> None:
raw = json.dumps(data).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(raw)
def _body(self) -> dict[str, Any]:
n = int(self.headers.get("Content-Length") or 0)
if n <= 0:
return {}
try:
return json.loads(self.rfile.read(n).decode("utf-8"))
except json.JSONDecodeError as exc:
raise ApiError(f"invalid JSON: {exc}") from exc
def _static(self, rel: str) -> None:
rel = rel.lstrip("/") or "index.html"
p = (STATIC_DIR / rel).resolve()
if STATIC_DIR.resolve() not in p.parents or not p.is_file():
self.send_error(404)
return
ctype = mimetypes.guess_type(p.name)[0] or "application/octet-stream"
raw = p.read_bytes()
self.send_response(200)
self.send_header("Content-Type", ctype if not ctype.startswith("text/") else f"{ctype}; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(raw)
def _dispatch(self, method: str) -> None:
url = urlparse(self.path)
q = parse_qs(url.query)
s = self.studio
try:
if not url.path.startswith("/api/"):
if method != "GET":
self.send_error(405)
return
if url.path == "/favicon.ico":
self.send_response(204)
self.end_headers()
return
self._static(url.path)
return
route = (method, url.path)
if route == ("GET", "/api/workspaces"):
self._json(200, s.list_workspaces())
elif route == ("GET", "/api/workspace"):
self._json(200, s.get_workspace(q))
elif route == ("GET", "/api/function"):
self._json(200, s.get_function(q))
elif route == ("POST", "/api/sample"):
self._json(200, s.sample(self._body()))
elif route == ("POST", "/api/export"):
self._json(200, s.export(self._body()))
elif route == ("GET", "/api/patterns"):
self._json(200, s.list_patterns())
elif route == ("POST", "/api/patterns"):
self._json(200, s.save_pattern(self._body()))
elif route == ("DELETE", "/api/patterns"):
self._json(200, s.delete_pattern(q))
elif route == ("POST", "/api/live/start"):
self._json(200, s.live_start(self._body()))
elif route == ("POST", "/api/live/stop"):
self._json(200, s.live_stop())
elif route == ("GET", "/api/live/status"):
self._json(200, s.live.status)
else:
self._json(404, {"error": f"no route {method} {url.path}"})
except ApiError as exc:
self._json(exc.status, {"error": str(exc)})
except Exception as exc: # noqa: BLE001 — surface anything else to the UI
traceback.print_exc()
self._json(500, {"error": f"{type(exc).__name__}: {exc}"})
def do_GET(self) -> None: # noqa: N802
self._dispatch("GET")
def do_POST(self) -> None: # noqa: N802
self._dispatch("POST")
def do_DELETE(self) -> None: # noqa: N802
self._dispatch("DELETE")
def make_server(root: Path, host: str = "127.0.0.1", port: int = 8765) -> ThreadingHTTPServer:
studio = Studio(root)
handler = type("BoundHandler", (Handler,), {"studio": studio})
server = ThreadingHTTPServer((host, port), handler)
server.studio = studio # type: ignore[attr-defined]
return server
+785
View File
@@ -0,0 +1,785 @@
/* Mover Pattern Studio — browser UI.
* All pattern maths lives on the server (patternstudio/efx.py); this file
* edits the pattern JSON, asks the server for sampled tracks and animates them.
*/
"use strict";
const $ = (sel) => document.querySelector(sel);
const PALETTE = ["#5aa9ff", "#ffb547", "#52d273", "#ff6b6b", "#c58bff", "#4fd8d8", "#ff8ad8", "#d6e35a"];
const ALGORITHMS = ["Circle", "Eight", "Line", "Line2", "Diamond", "Square", "SquareChoppy", "Leaf", "Lissajous"];
const EFX_SLIDERS = [
["width", "Width (pan)", 0, 127],
["height", "Height (tilt)", 0, 127],
["rotation", "Rotation °", 0, 359],
["start_offset", "Start offset °", 0, 359],
["x_offset", "Centre pan", 0, 255],
["y_offset", "Centre tilt", 0, 255],
["duration_ms", "Loop ms", 200, 60000],
["fade_in_ms", "Fade in ms", 0, 20000],
];
const state = {
workspaces: [],
wsPath: null,
ws: null,
pattern: defaultPattern(),
sample: null,
selected: -1, // selected waypoint
playing: true,
speed: 1,
clock: 0, // pattern time in ms
lastFrame: 0,
live: false,
library: [],
drag: null,
};
function defaultPattern() {
return {
name: "Mover Pattern",
type: "efx",
fixtures: [],
efx: {
algorithm: "Circle", width: 40, height: 30, rotation: 0, start_offset: 0,
x_offset: 128, y_offset: 128, x_frequency: 1, y_frequency: 1, x_phase: 0, y_phase: 0,
duration_ms: 8000, fade_in_ms: 0, fade_out_ms: 0,
direction: "Forward", run_order: "Loop", propagation: "Parallel", relative: false,
},
path: {
points: [], smooth: false, subdivisions: 6, closed: true, run_order: "Loop", direction: "Forward",
},
};
}
function fixtureConfig(id) {
return { id, head: 0, direction: "Forward", start_offset: 0, pan: 128, tilt: 128,
pan_offset: 0, tilt_offset: 0, mirror_pan: false, mirror_tilt: false };
}
// ------------------------------------------------------------------ API
async function api(method, url, body) {
const res = await fetch(url, {
method,
headers: body ? { "Content-Type": "application/json" } : undefined,
body: body ? JSON.stringify(body) : undefined,
});
const data = await res.json().catch(() => ({ error: res.statusText }));
if (!res.ok) throw new Error(data.error || res.statusText);
return data;
}
function setStatus(msg, cls = "") {
const el = $("#status");
el.textContent = msg;
el.className = cls;
}
// ------------------------------------------------------------------ workspace
async function loadWorkspaces() {
const d = await api("GET", "/api/workspaces");
state.workspaces = d.workspaces;
const sel = $("#ws-select");
sel.innerHTML = "";
for (const w of d.workspaces) {
const o = document.createElement("option");
o.value = w.path;
o.textContent = w.path.replace(/^shows\//, "");
sel.appendChild(o);
}
const remembered = localStorage.getItem("ps.ws");
const pick = d.workspaces.find((w) => w.path === remembered) || d.workspaces[0];
if (pick) {
sel.value = pick.path;
await loadWorkspace(pick.path);
} else {
setStatus("No .qxw files found in shows/", "err");
}
}
async function loadWorkspace(path) {
state.wsPath = path;
localStorage.setItem("ps.ws", path);
state.ws = await api("GET", `/api/workspace?path=${encodeURIComponent(path)}`);
const movers = state.ws.fixtures.filter((f) => f.is_mover);
// Keep fixture selections that still exist; default to all movers.
const ids = new Set(movers.map((f) => f.id));
state.pattern.fixtures = state.pattern.fixtures.filter((f) => ids.has(f.id));
if (!state.pattern.fixtures.length) state.pattern.fixtures = movers.map((m) => fixtureConfig(m.id));
const art = Object.values(state.ws.artnet)[0];
if (art) {
$("#live-ip").value = art.ip || "";
$("#live-uni").value = art.universe ?? 0;
}
renderFixtures();
renderFunctionList();
setStatus(`${movers.length} mover${movers.length === 1 ? "" : "s"} · ${state.ws.functions.length} functions`);
requestSample();
}
function moverById(id) {
return state.ws?.fixtures.find((f) => f.id === id);
}
// ------------------------------------------------------------------ fixtures panel
function renderFixtures() {
const box = $("#fixture-list");
box.innerHTML = "";
if (!state.ws) return;
const movers = state.ws.fixtures.filter((f) => f.is_mover);
const others = state.ws.fixtures.filter((f) => !f.is_mover);
$("#fixture-hint").textContent = movers.length ? "" : "no pan/tilt fixtures found";
const isEfx = state.pattern.type === "efx";
movers.forEach((m, i) => {
const cfg = state.pattern.fixtures.find((f) => f.id === m.id);
const el = document.createElement("div");
el.className = "fixture" + (cfg ? "" : " off");
const color = PALETTE[i % PALETTE.length];
const degs = m.pan_max ? ` · ${m.pan_max}°/${m.tilt_max}°` : "";
el.innerHTML = `
<label class="name">
<input type="checkbox" ${cfg ? "checked" : ""}>
<span class="swatch" style="background:${color}"></span>
<span>${esc(m.name)}</span>
<small>${esc(m.manufacturer)} ${esc(m.model)} · ${esc(m.mode)} · U${m.universe + 1} @ ${m.address + 1}${degs}</small>
</label>
<div class="opts"></div>`;
el.querySelector("input").addEventListener("change", (e) => {
if (e.target.checked) state.pattern.fixtures.push(fixtureConfig(m.id));
else state.pattern.fixtures = state.pattern.fixtures.filter((f) => f.id !== m.id);
renderFixtures();
requestSample();
});
const opts = el.querySelector(".opts");
if (cfg) {
if (isEfx) {
opts.appendChild(selectField("Dir", ["Forward", "Backward"], cfg.direction, (v) => { cfg.direction = v; requestSample(); }));
opts.appendChild(numField("Offset °", cfg.start_offset, 0, 359, (v) => { cfg.start_offset = v; requestSample(); }));
if (state.pattern.efx.relative) {
opts.appendChild(numField("Home pan", cfg.pan, 0, 255, (v) => { cfg.pan = v; requestSample(); }));
opts.appendChild(numField("Home tilt", cfg.tilt, 0, 255, (v) => { cfg.tilt = v; requestSample(); }));
}
} else {
opts.appendChild(checkField("Mirror pan", cfg.mirror_pan, (v) => { cfg.mirror_pan = v; requestSample(); }));
opts.appendChild(checkField("Mirror tilt", cfg.mirror_tilt, (v) => { cfg.mirror_tilt = v; requestSample(); }));
opts.appendChild(numField("Pan ±", cfg.pan_offset, -255, 255, (v) => { cfg.pan_offset = v; requestSample(); }));
opts.appendChild(numField("Tilt ±", cfg.tilt_offset, -255, 255, (v) => { cfg.tilt_offset = v; requestSample(); }));
}
}
box.appendChild(el);
});
if (others.length) {
const el = document.createElement("div");
el.className = "fixture notmover";
el.innerHTML = `<div class="name"><small>${others.length} non-mover fixture${others.length === 1 ? "" : "s"} hidden</small></div>`;
box.appendChild(el);
}
}
function selectField(label, options, value, onChange) {
const l = document.createElement("label");
l.append(label);
const s = document.createElement("select");
for (const o of options) { const op = document.createElement("option"); op.textContent = o; s.appendChild(op); }
s.value = value;
s.addEventListener("change", () => onChange(s.value));
l.appendChild(s);
return l;
}
function numField(label, value, min, max, onChange) {
const l = document.createElement("label");
l.append(label);
const i = document.createElement("input");
i.type = "number"; i.min = min; i.max = max; i.value = value;
i.addEventListener("input", () => { const v = Number(i.value); if (Number.isFinite(v)) onChange(v); });
l.appendChild(i);
return l;
}
function checkField(label, value, onChange) {
const l = document.createElement("label");
const i = document.createElement("input");
i.type = "checkbox"; i.checked = value;
i.addEventListener("change", () => onChange(i.checked));
l.append(i, label);
return l;
}
function esc(s) {
return String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
}
// ------------------------------------------------------------------ EFX panel
function buildEfxPanel() {
const alg = $("#efx-algorithm");
for (const a of ALGORITHMS) { const o = document.createElement("option"); o.textContent = a; alg.appendChild(o); }
alg.addEventListener("change", () => { state.pattern.efx.algorithm = alg.value; syncEfxForm(); requestSample(); });
const box = $("#efx-sliders");
for (const [key, label, min, max] of EFX_SLIDERS) {
const row = document.createElement("div");
row.className = "slider";
row.innerHTML = `<span>${label}</span><input type="range" min="${min}" max="${max}" data-key="${key}"><input type="number" min="${min}" max="${max}" data-key="${key}">`;
const [range, num] = row.querySelectorAll("input");
const apply = (v) => {
v = Math.max(min, Math.min(max, Math.round(Number(v) || 0)));
state.pattern.efx[key] = v;
range.value = v; num.value = v;
requestSample();
};
range.addEventListener("input", () => apply(range.value));
num.addEventListener("input", () => apply(num.value));
box.appendChild(row);
}
for (const key of ["direction", "run_order", "propagation", "x_frequency", "y_frequency", "x_phase", "y_phase"]) {
const el = $(`#efx-${key}`);
el.addEventListener("input", () => {
state.pattern.efx[key] = el.type === "number" ? Number(el.value) : el.value;
requestSample();
});
}
$("#efx-relative").addEventListener("change", (e) => {
state.pattern.efx.relative = e.target.checked;
renderFixtures();
syncEfxForm();
requestSample();
});
}
function syncEfxForm() {
const e = state.pattern.efx;
$("#efx-algorithm").value = e.algorithm;
for (const inp of $("#efx-sliders").querySelectorAll("input")) inp.value = e[inp.dataset.key];
for (const key of ["direction", "run_order", "propagation", "x_frequency", "y_frequency", "x_phase", "y_phase"]) $(`#efx-${key}`).value = e[key];
$("#efx-relative").checked = e.relative;
$("#lissajous-row").style.display = e.algorithm === "Lissajous" ? "" : "none";
// In relative mode the centre is each head's home; the shared offsets are meaningless.
for (const inp of $("#efx-sliders").querySelectorAll("input[data-key=x_offset],input[data-key=y_offset]")) inp.disabled = e.relative;
}
// ------------------------------------------------------------------ Path panel
function buildPathPanel() {
$("#pt-add").addEventListener("click", () => {
const pts = state.pattern.path.points;
const last = pts[pts.length - 1];
pts.push({ pan: last ? Math.min(255, last.pan + 20) : 128, tilt: last ? last.tilt : 128, fade_ms: last ? last.fade_ms : 1000, hold_ms: last ? last.hold_ms : 0 });
state.selected = pts.length - 1;
renderPoints(); requestSample();
});
$("#pt-clear").addEventListener("click", () => { state.pattern.path.points = []; state.selected = -1; renderPoints(); requestSample(); });
for (const key of ["closed", "smooth"]) {
$(`#path-${key}`).addEventListener("change", (e) => { state.pattern.path[key] = e.target.checked; requestSample(); });
}
$("#path-subdivisions").addEventListener("input", (e) => { state.pattern.path.subdivisions = Number(e.target.value) || 1; requestSample(); });
for (const key of ["run_order", "direction"]) {
$(`#path-${key}`).addEventListener("input", (e) => { state.pattern.path[key] = e.target.value; requestSample(); });
}
$("#path-all-fade").addEventListener("change", (e) => {
const v = Number(e.target.value); if (!Number.isFinite(v) || e.target.value === "") return;
for (const p of state.pattern.path.points) p.fade_ms = v;
e.target.value = ""; renderPoints(); requestSample();
});
$("#path-all-hold").addEventListener("change", (e) => {
const v = Number(e.target.value); if (!Number.isFinite(v) || e.target.value === "") return;
for (const p of state.pattern.path.points) p.hold_ms = v;
e.target.value = ""; renderPoints(); requestSample();
});
}
function syncPathForm() {
const p = state.pattern.path;
$("#path-closed").checked = p.closed;
$("#path-smooth").checked = p.smooth;
$("#path-subdivisions").value = p.subdivisions;
$("#path-run_order").value = p.run_order;
$("#path-direction").value = p.direction;
renderPoints();
}
function renderPoints() {
const tb = $("#point-table tbody");
tb.innerHTML = "";
state.pattern.path.points.forEach((pt, i) => {
const tr = document.createElement("tr");
if (i === state.selected) tr.className = "sel";
tr.innerHTML = `<td>${i + 1}</td>` +
["pan", "tilt", "fade_ms", "hold_ms"].map((k) => `<td><input type="number" data-k="${k}" value="${Math.round(pt[k])}" min="0" max="${k.endsWith("ms") ? 600000 : 255}" step="${k.endsWith("ms") ? 100 : 1}"></td>`).join("") +
`<td><button class="danger" title="Remove">×</button></td>`;
tr.addEventListener("click", () => { if (state.selected !== i) { state.selected = i; renderPoints(); } });
for (const inp of tr.querySelectorAll("input")) {
inp.addEventListener("input", () => {
const v = Number(inp.value);
if (!Number.isFinite(v)) return;
pt[inp.dataset.k] = inp.dataset.k.endsWith("ms") ? Math.max(0, v) : Math.max(0, Math.min(255, v));
requestSample();
});
}
tr.querySelector("button").addEventListener("click", (e) => {
e.stopPropagation();
state.pattern.path.points.splice(i, 1);
state.selected = Math.min(state.selected, state.pattern.path.points.length - 1);
renderPoints(); requestSample();
});
tb.appendChild(tr);
});
const s = state.sample;
$("#path-summary").textContent = s && s.kind === "path"
? `${s.step_count} sequence step${s.step_count === 1 ? "" : "s"} · loop ${(s.loop_ms / 1000).toFixed(1)} s`
: "";
}
// ------------------------------------------------------------------ type tabs
function setType(type) {
state.pattern.type = type;
for (const b of $("#type-tabs").querySelectorAll("button")) b.classList.toggle("active", b.dataset.type === type);
$("#efx-panel").hidden = type !== "efx";
$("#path-panel").hidden = type !== "path";
$("#canvas-hint").textContent = type === "efx" ? "Click or drag on the grid to place the shape's centre" : "Click to add a waypoint · drag to move";
renderFixtures();
if (type === "efx") syncEfxForm(); else syncPathForm();
requestSample();
}
// ------------------------------------------------------------------ sampling
let sampleTimer = null;
let sampleInFlight = false;
let sampleQueued = false;
function requestSample() {
clearTimeout(sampleTimer);
sampleTimer = setTimeout(doSample, 30);
if (state.live) scheduleLiveRestart();
}
async function doSample() {
if (sampleInFlight) { sampleQueued = true; return; }
sampleInFlight = true;
try {
state.sample = await api("POST", "/api/sample", { pattern: state.pattern });
if (state.pattern.type === "path") renderPoints();
} catch (err) {
setStatus(err.message, "err");
} finally {
sampleInFlight = false;
if (sampleQueued) { sampleQueued = false; doSample(); }
}
}
// ------------------------------------------------------------------ playback maths
function headPosition(track, kind, tMs) {
const s = state.sample;
const loop = s.loop_ms;
if (kind === "efx") {
const pts = track.points;
if (tMs < track.start_delay_ms) return { pan: pts[0][0], tilt: pts[0][1], waiting: true };
const cycles = Math.floor(tMs / loop);
if (s.run_order === "SingleShot" && cycles >= 1) return null;
let pos = (tMs + track.time_offset_ms) % loop;
let u = pos / loop;
if (s.run_order === "PingPong" && cycles % 2 === 1) u = 1 - u;
const f = u * pts.length;
const i = Math.floor(f) % pts.length;
const j = (i + 1) % pts.length;
const k = f - Math.floor(f);
return { pan: pts[i][0] + (pts[j][0] - pts[i][0]) * k, tilt: pts[i][1] + (pts[j][1] - pts[i][1]) * k };
}
// path: keys [t, pan, tilt] — piecewise linear, wraps from last key back to first
const keys = track.keys;
if (!keys.length) return null;
if (loop <= 0) return { pan: keys[0][1], tilt: keys[0][2] };
const cycles = Math.floor(tMs / loop);
let pos = tMs % loop;
let reverse = s.direction === "Backward";
if (s.run_order === "PingPong" && cycles % 2 === 1) reverse = !reverse;
if (s.run_order === "SingleShot" && cycles >= 1) pos = loop;
if (reverse) pos = loop - pos;
let prev = keys[keys.length - 1];
let tPrev = 0;
for (const key of keys) {
const [t, pan, tilt] = key;
if (pos <= t) {
const span = t - tPrev;
const k = span > 0 ? (pos - tPrev) / span : 1;
return { pan: prev[1] + (pan - prev[1]) * k, tilt: prev[2] + (tilt - prev[2]) * k };
}
tPrev = t; prev = key;
}
return { pan: prev[1], tilt: prev[2] };
}
// ------------------------------------------------------------------ canvas
const canvas = $("#canvas");
const ctx = canvas.getContext("2d");
let geom = { x0: 0, y0: 0, size: 0 };
function resizeCanvas() {
const r = canvas.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
canvas.width = Math.round(r.width * dpr);
canvas.height = Math.round(r.height * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
const margin = 44;
const size = Math.max(50, Math.min(r.width, r.height) - margin * 2);
geom = { x0: (r.width - size) / 2, y0: (r.height - size) / 2, size, w: r.width, h: r.height };
}
const toPx = (pan, tilt) => [geom.x0 + (pan / 255) * geom.size, geom.y0 + (tilt / 255) * geom.size];
const toDmx = (x, y) => [((x - geom.x0) / geom.size) * 255, ((y - geom.y0) / geom.size) * 255];
function draw(now) {
if (!state.lastFrame) state.lastFrame = now;
const dt = now - state.lastFrame;
state.lastFrame = now;
if (state.playing) state.clock += dt * state.speed;
ctx.clearRect(0, 0, geom.w, geom.h);
drawGrid();
const s = state.sample;
if (s && state.ws) {
const movers = state.ws.fixtures.filter((f) => f.is_mover);
const colorOf = (id) => PALETTE[Math.max(0, movers.findIndex((m) => m.id === id)) % PALETTE.length];
const showTrails = $("#show-trails").checked;
// Paths
for (const track of s.tracks) {
ctx.strokeStyle = colorOf(track.id);
ctx.globalAlpha = 0.55;
ctx.lineWidth = 1.5;
ctx.beginPath();
const pts = s.kind === "efx" ? track.points : track.keys.map((k) => [k[1], k[2]]);
pts.forEach((p, i) => { const [x, y] = toPx(p[0], p[1]); i ? ctx.lineTo(x, y) : ctx.moveTo(x, y); });
if (s.kind === "efx" || state.pattern.path.closed) ctx.closePath();
ctx.stroke();
ctx.globalAlpha = 1;
}
// Waypoints (path mode)
if (s.kind === "path") {
state.pattern.path.points.forEach((p, i) => {
const [x, y] = toPx(p.pan, p.tilt);
ctx.beginPath(); ctx.arc(x, y, i === state.selected ? 8 : 6, 0, Math.PI * 2);
ctx.fillStyle = i === state.selected ? "#fff" : "#9aa3b5"; ctx.fill();
ctx.fillStyle = "#0b1220"; ctx.font = "bold 9px system-ui"; ctx.textAlign = "center"; ctx.textBaseline = "middle";
ctx.fillText(String(i + 1), x, y + 0.5);
});
}
// EFX centre handle
if (s.kind === "efx" && !state.pattern.efx.relative) {
const [cx, cy] = toPx(state.pattern.efx.x_offset, state.pattern.efx.y_offset);
ctx.strokeStyle = "#ffffff"; ctx.globalAlpha = 0.8; ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(cx - 9, cy); ctx.lineTo(cx + 9, cy); ctx.moveTo(cx, cy - 9); ctx.lineTo(cx, cy + 9); ctx.stroke();
ctx.beginPath(); ctx.arc(cx, cy, 9, 0, Math.PI * 2); ctx.stroke();
ctx.globalAlpha = 1;
}
// Heads
const loop = s.loop_ms || 1;
for (const track of s.tracks) {
const color = colorOf(track.id);
if (showTrails) {
ctx.strokeStyle = color; ctx.lineWidth = 4; ctx.lineCap = "round";
const trailMs = Math.min(1200, loop * 0.15);
ctx.beginPath();
let first = true;
for (let k = 12; k >= 0; k--) {
const pos = headPosition(track, s.kind, Math.max(0, state.clock - (trailMs * k) / 12));
if (!pos) continue;
const [x, y] = toPx(pos.pan, pos.tilt);
ctx.globalAlpha = 0.05 + (1 - k / 12) * 0.35;
if (first) { ctx.moveTo(x, y); first = false; } else { ctx.lineTo(x, y); ctx.stroke(); ctx.beginPath(); ctx.moveTo(x, y); }
}
ctx.globalAlpha = 1;
}
const pos = headPosition(track, s.kind, state.clock);
if (!pos) continue;
const [x, y] = toPx(pos.pan, pos.tilt);
ctx.beginPath(); ctx.arc(x, y, 9, 0, Math.PI * 2);
ctx.fillStyle = color; ctx.globalAlpha = pos.waiting ? 0.35 : 1; ctx.fill(); ctx.globalAlpha = 1;
ctx.strokeStyle = "#0b1220"; ctx.lineWidth = 2; ctx.stroke();
ctx.fillStyle = "#e6e8ee"; ctx.font = "11px system-ui"; ctx.textAlign = "left"; ctx.textBaseline = "bottom";
const m = moverById(track.id);
ctx.fillText(`${m ? m.name : track.id} ${Math.round(pos.pan)},${Math.round(pos.tilt)}`, x + 12, y - 6);
}
$("#time").textContent = `${((state.clock % loop) / 1000).toFixed(2)} / ${(loop / 1000).toFixed(2)} s`;
}
requestAnimationFrame(draw);
}
function drawGrid() {
const { x0, y0, size } = geom;
ctx.fillStyle = "#101216";
ctx.fillRect(x0, y0, size, size);
ctx.strokeStyle = "#262a34"; ctx.lineWidth = 1;
for (let v = 0; v <= 256; v += 32) {
const p = (Math.min(v, 255) / 255) * size;
ctx.beginPath(); ctx.moveTo(x0 + p, y0); ctx.lineTo(x0 + p, y0 + size); ctx.stroke();
ctx.beginPath(); ctx.moveTo(x0, y0 + p); ctx.lineTo(x0 + size, y0 + p); ctx.stroke();
}
ctx.strokeStyle = "#3b4150"; ctx.strokeRect(x0 + 0.5, y0 + 0.5, size, size);
// Axis labels
const showDeg = $("#show-degrees").checked;
const ref = state.ws?.fixtures.find((f) => f.is_mover && f.pan_max);
ctx.fillStyle = "#8d94a6"; ctx.font = "11px system-ui";
ctx.textAlign = "center"; ctx.textBaseline = "top";
for (let v = 0; v <= 255; v += 64) {
const x = x0 + (v / 255) * size;
let label = String(v);
if (showDeg && ref) label += ` · ${Math.round((v / 255) * ref.pan_max)}°`;
ctx.fillText(label, x, y0 + size + 6);
}
ctx.fillText("PAN →", x0 + size / 2, y0 + size + 22);
ctx.textAlign = "right"; ctx.textBaseline = "middle";
for (let v = 0; v <= 255; v += 64) {
const y = y0 + (v / 255) * size;
let label = String(v);
if (showDeg && ref) label = `${Math.round((v / 255) * ref.tilt_max)}° · ` + label;
ctx.fillText(label, x0 - 6, y);
}
ctx.save(); ctx.translate(x0 - 34, y0 + size / 2); ctx.rotate(-Math.PI / 2);
ctx.textAlign = "center"; ctx.textBaseline = "bottom"; ctx.fillText("TILT (0 = top, like the QLC+ XY pad)", 0, 0); ctx.restore();
}
// Canvas interaction
function hitWaypoint(x, y) {
let best = -1, bestD = 12;
state.pattern.path.points.forEach((p, i) => {
const [px, py] = toPx(p.pan, p.tilt);
const d = Math.hypot(px - x, py - y);
if (d < bestD) { bestD = d; best = i; }
});
return best;
}
canvas.addEventListener("pointerdown", (e) => {
const r = canvas.getBoundingClientRect();
const x = e.clientX - r.left, y = e.clientY - r.top;
const inside = x >= geom.x0 && x <= geom.x0 + geom.size && y >= geom.y0 && y <= geom.y0 + geom.size;
if (state.pattern.type === "efx") {
if (state.pattern.efx.relative) return;
const [cx, cy] = toPx(state.pattern.efx.x_offset, state.pattern.efx.y_offset);
if (Math.hypot(cx - x, cy - y) < 14 || inside) {
state.drag = { kind: "centre" };
canvas.setPointerCapture(e.pointerId);
moveCentre(x, y);
}
return;
}
const hit = hitWaypoint(x, y);
if (hit >= 0) {
state.selected = hit;
state.drag = { kind: "point", index: hit };
canvas.setPointerCapture(e.pointerId);
renderPoints();
} else if (inside) {
const [pan, tilt] = toDmx(x, y);
const pts = state.pattern.path.points;
const last = pts[pts.length - 1];
const insertAt = state.selected >= 0 ? state.selected + 1 : pts.length;
pts.splice(insertAt, 0, { pan: clamp255(pan), tilt: clamp255(tilt), fade_ms: last ? last.fade_ms : 1000, hold_ms: last ? last.hold_ms : 0 });
state.selected = insertAt;
state.drag = { kind: "point", index: insertAt };
canvas.setPointerCapture(e.pointerId);
renderPoints(); requestSample();
}
});
canvas.addEventListener("pointermove", (e) => {
if (!state.drag) return;
const r = canvas.getBoundingClientRect();
const x = e.clientX - r.left, y = e.clientY - r.top;
if (state.drag.kind === "centre") moveCentre(x, y);
else {
const [pan, tilt] = toDmx(x, y);
const p = state.pattern.path.points[state.drag.index];
if (!p) return;
p.pan = clamp255(pan); p.tilt = clamp255(tilt);
const tr = $("#point-table tbody").children[state.drag.index];
if (tr) { tr.querySelector("[data-k=pan]").value = Math.round(p.pan); tr.querySelector("[data-k=tilt]").value = Math.round(p.tilt); }
requestSample();
}
});
const endDrag = () => { state.drag = null; };
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
function moveCentre(x, y) {
const [pan, tilt] = toDmx(x, y);
state.pattern.efx.x_offset = clamp255(pan);
state.pattern.efx.y_offset = clamp255(tilt);
syncEfxForm();
requestSample();
}
const clamp255 = (v) => Math.max(0, Math.min(255, Math.round(v)));
document.addEventListener("keydown", (e) => {
if (e.target.matches("input, select, textarea")) return;
if (e.code === "Space") { e.preventDefault(); togglePlay(); }
if ((e.key === "Delete" || e.key === "Backspace") && state.pattern.type === "path" && state.selected >= 0) {
state.pattern.path.points.splice(state.selected, 1);
state.selected = Math.min(state.selected, state.pattern.path.points.length - 1);
renderPoints(); requestSample();
}
});
function togglePlay() {
state.playing = !state.playing;
$("#play").textContent = state.playing ? "Pause" : "Play";
}
// ------------------------------------------------------------------ export
async function exportPattern() {
const btn = $("#exp-go"), out = $("#exp-result");
btn.disabled = true; out.textContent = "writing…"; out.className = "result";
try {
const body = {
path: state.wsPath,
pattern: state.pattern,
name: $("#pat-name").value.trim() || "Mover Pattern",
overwrite: $("#exp-overwrite").checked,
add_button: $("#exp-button").checked,
out_path: $("#exp-out").value.trim() || null,
};
const r = await api("POST", "/api/export", body);
const ids = Object.entries(r.function_ids).map(([k, v]) => `${k} #${v}`).join(", ");
out.textContent = `Wrote ${r.path} (${ids}${r.widget_id != null ? `, button #${r.widget_id}` : ""}${r.replaced.length ? `, replaced ${r.replaced.join(",")}` : ""}). Reload the workspace in QLC+.`;
out.className = "result ok";
if (!body.out_path) await loadWorkspace(state.wsPath);
else { await loadWorkspaces(); }
} catch (err) {
out.textContent = err.message; out.className = "result err";
} finally {
btn.disabled = false;
}
}
// ------------------------------------------------------------------ library + workspace functions
async function loadLibrary() {
try {
const d = await api("GET", "/api/patterns");
state.library = d.patterns;
} catch (err) { setStatus(err.message, "err"); }
const ul = $("#lib-list");
ul.innerHTML = "";
if (!state.library.length) { ul.innerHTML = '<li class="empty">No saved patterns yet</li>'; return; }
for (const item of state.library) {
const li = document.createElement("li");
li.innerHTML = `<span class="lname">${esc(item.name)} <small>${item.type}</small></span><button>Load</button><button class="danger">×</button>`;
const [load, del] = li.querySelectorAll("button");
load.addEventListener("click", () => applyPattern(item.pattern));
del.addEventListener("click", async () => {
if (!confirm(`Delete saved pattern "${item.name}"?`)) return;
await api("DELETE", `/api/patterns?file=${encodeURIComponent(item.file)}`);
loadLibrary();
});
ul.appendChild(li);
}
}
async function savePattern() {
const name = $("#pat-name").value.trim() || "Mover Pattern";
state.pattern.name = name;
try {
await api("POST", "/api/patterns", { name, pattern: state.pattern });
setStatus(`Saved "${name}" to patterns/`, "ok");
loadLibrary();
} catch (err) { setStatus(err.message, "err"); }
}
function renderFunctionList() {
const ul = $("#fn-list");
ul.innerHTML = "";
const fns = (state.ws?.functions || []).filter((f) => f.type === "EFX" || f.type === "Sequence");
if (!fns.length) { ul.innerHTML = '<li class="empty">None</li>'; return; }
for (const f of fns) {
const li = document.createElement("li");
li.innerHTML = `<span class="lname">${esc(f.name)} <small>${f.type} #${f.id}</small></span><button>Edit</button>`;
li.querySelector("button").addEventListener("click", async () => {
try {
const d = await api("GET", `/api/function?path=${encodeURIComponent(state.wsPath)}&id=${f.id}`);
applyPattern(d.pattern);
setStatus(`Loaded "${f.name}" — writing will replace it`, "ok");
} catch (err) { setStatus(err.message, "err"); }
});
ul.appendChild(li);
}
}
function applyPattern(pat) {
const base = defaultPattern();
const movers = new Set((state.ws?.fixtures || []).filter((f) => f.is_mover).map((f) => f.id));
const fixtures = (pat.fixtures || []).filter((f) => movers.has(f.id)).map((f) => ({ ...fixtureConfig(f.id), ...f }));
state.pattern = {
...base,
...pat,
efx: { ...base.efx, ...(pat.efx || {}) },
path: { ...base.path, ...(pat.path || {}) },
fixtures: fixtures.length ? fixtures : [...movers].map(fixtureConfig),
};
delete state.pattern.source_function_id;
$("#pat-name").value = state.pattern.name || "Mover Pattern";
state.selected = -1;
state.clock = 0;
setType(state.pattern.type);
syncEfxForm();
syncPathForm();
}
// ------------------------------------------------------------------ live Art-Net
let liveTimer = null;
function scheduleLiveRestart() {
clearTimeout(liveTimer);
liveTimer = setTimeout(startLive, 250);
}
async function startLive() {
try {
const st = await api("POST", "/api/live/start", {
path: state.wsPath, pattern: state.pattern,
ip: $("#live-ip").value.trim() || null, universe: Number($("#live-uni").value) || 0,
});
setStatus(`LIVE → ${st.ip} universe ${st.universe} (stop QLC+ output first)`, "ok");
} catch (err) {
setStatus(`Live failed: ${err.message}`, "err");
state.live = false; $("#live-toggle").checked = false;
}
}
async function stopLive() {
try { await api("POST", "/api/live/stop"); } catch (_) { /* ignore */ }
setStatus("Live stopped (blackout sent)");
}
window.addEventListener("pagehide", () => { if (state.live) navigator.sendBeacon("/api/live/stop", "{}"); });
// ------------------------------------------------------------------ boot
function bind() {
$("#ws-select").addEventListener("change", (e) => loadWorkspace(e.target.value).catch((err) => setStatus(err.message, "err")));
$("#ws-reload").addEventListener("click", () => loadWorkspace(state.wsPath).catch((err) => setStatus(err.message, "err")));
$("#pat-name").addEventListener("input", (e) => { state.pattern.name = e.target.value; });
for (const b of $("#type-tabs").querySelectorAll("button")) b.addEventListener("click", () => setType(b.dataset.type));
$("#play").addEventListener("click", togglePlay);
$("#speed").addEventListener("change", (e) => { state.speed = Number(e.target.value); });
$("#exp-go").addEventListener("click", exportPattern);
$("#lib-save").addEventListener("click", savePattern);
$("#live-toggle").addEventListener("change", (e) => {
state.live = e.target.checked;
if (state.live) startLive(); else stopLive();
});
window.addEventListener("resize", resizeCanvas);
}
(async function boot() {
buildEfxPanel();
buildPathPanel();
bind();
resizeCanvas();
requestAnimationFrame(draw);
setType("efx");
await loadLibrary();
try { await loadWorkspaces(); } catch (err) { setStatus(err.message, "err"); }
resizeCanvas();
})();
+151
View File
@@ -0,0 +1,151 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mover Pattern Studio</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<header>
<h1>Mover Pattern Studio</h1>
<label>Workspace
<select id="ws-select"></select>
</label>
<button id="ws-reload" title="Re-read the workspace from disk">Reload</button>
<span class="spacer"></span>
<label class="live">
<input type="checkbox" id="live-toggle"> Live Art-Net
</label>
<input id="live-ip" placeholder="IP" size="14" title="Art-Net destination (from workspace)">
<input id="live-uni" type="number" min="0" max="32767" value="0" size="4" title="Art-Net universe">
<span id="status"></span>
</header>
<main>
<aside id="controls">
<section class="card">
<h2>Pattern</h2>
<div class="row">
<label class="grow">Name <input id="pat-name" value="Mover Pattern"></label>
</div>
<div class="tabs" id="type-tabs">
<button data-type="efx" class="active">EFX (QLC+ shape)</button>
<button data-type="path">Path (waypoints → Sequence)</button>
</div>
</section>
<section class="card">
<h2>Fixtures <small id="fixture-hint"></small></h2>
<div id="fixture-list"></div>
</section>
<section class="card" id="efx-panel">
<h2>Shape</h2>
<div class="row">
<label class="grow">Algorithm
<select id="efx-algorithm"></select>
</label>
<label>Direction
<select id="efx-direction"><option>Forward</option><option>Backward</option></select>
</label>
</div>
<div id="efx-sliders"></div>
<div class="row" id="lissajous-row">
<label>X freq <input type="number" id="efx-x_frequency" min="0" max="5" value="1"></label>
<label>Y freq <input type="number" id="efx-y_frequency" min="0" max="5" value="1"></label>
<label>X phase <input type="number" id="efx-x_phase" min="0" max="359" value="0"></label>
<label>Y phase <input type="number" id="efx-y_phase" min="0" max="359" value="0"></label>
</div>
<div class="row">
<label>Run order
<select id="efx-run_order"><option>Loop</option><option>PingPong</option><option>SingleShot</option></select>
</label>
<label>Propagation
<select id="efx-propagation"><option>Parallel</option><option>Serial</option><option>Asymmetric</option></select>
</label>
<label class="check" title="EFX offsets each head from its own home position (exports Scene + EFX + Collection)">
<input type="checkbox" id="efx-relative"> Relative to home
</label>
</div>
<p class="hint">Tip: for a head hung the opposite way, set its direction to <b>Backward</b> — for Circle, Eight, Diamond, Leaf and Square this mirrors the shape in pan.</p>
</section>
<section class="card" id="path-panel" hidden>
<h2>Waypoints <small>click canvas to add · drag to move · Delete key removes</small></h2>
<table id="point-table">
<thead><tr><th>#</th><th>Pan</th><th>Tilt</th><th>Fade ms</th><th>Hold ms</th><th></th></tr></thead>
<tbody></tbody>
</table>
<div class="row">
<button id="pt-add">Add point</button>
<button id="pt-clear">Clear</button>
<label class="check"><input type="checkbox" id="path-closed" checked> Closed loop</label>
<label class="check"><input type="checkbox" id="path-smooth"> Smooth</label>
<label>Subdiv <input type="number" id="path-subdivisions" min="1" max="32" value="6"></label>
</div>
<div class="row">
<label>Run order
<select id="path-run_order"><option>Loop</option><option>PingPong</option><option>SingleShot</option></select>
</label>
<label>Direction
<select id="path-direction"><option>Forward</option><option>Backward</option></select>
</label>
<label>All fades <input type="number" id="path-all-fade" min="0" step="100" placeholder="ms"></label>
<label>All holds <input type="number" id="path-all-hold" min="0" step="100" placeholder="ms"></label>
</div>
<p class="hint" id="path-summary"></p>
</section>
<section class="card">
<h2>Write to workspace</h2>
<div class="row">
<label class="check"><input type="checkbox" id="exp-overwrite" checked> Replace same-named function</label>
<label class="check"><input type="checkbox" id="exp-button" checked> Add VC button</label>
</div>
<div class="row">
<label class="grow">Save as copy (optional) <input id="exp-out" placeholder="shows/new_show.qxw"></label>
</div>
<div class="row">
<button id="exp-go" class="primary">Write pattern</button>
<span id="exp-result" class="result"></span>
</div>
</section>
<section class="card">
<h2>Pattern library <small>patterns/*.json</small></h2>
<div class="row">
<button id="lib-save">Save current</button>
</div>
<ul id="lib-list" class="list"></ul>
</section>
<section class="card">
<h2>In this workspace <small>EFX &amp; pan/tilt Sequences</small></h2>
<ul id="fn-list" class="list"></ul>
</section>
</aside>
<section id="stage">
<div class="toolbar">
<button id="play" title="Space">Pause</button>
<label>Speed
<select id="speed">
<option value="0.25">¼×</option><option value="0.5">½×</option>
<option value="1" selected>1×</option><option value="2">2×</option><option value="4">4×</option>
</select>
</label>
<label class="check"><input type="checkbox" id="show-trails" checked> Trails</label>
<label class="check"><input type="checkbox" id="show-degrees" checked> Degrees</label>
<span id="time"></span>
<span class="spacer"></span>
<span class="hint" id="canvas-hint"></span>
</div>
<canvas id="canvas"></canvas>
</section>
</main>
<script src="/app.js"></script>
</body>
</html>
+147
View File
@@ -0,0 +1,147 @@
:root {
--bg: #15171c;
--panel: #1e2129;
--panel-2: #262a34;
--line: #343946;
--text: #e6e8ee;
--muted: #8d94a6;
--accent: #5aa9ff;
--accent-2: #ffb547;
--danger: #ff6b6b;
--ok: #52d273;
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; }
body {
background: var(--bg);
color: var(--text);
font: 13px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
display: flex;
flex-direction: column;
}
header {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 14px;
background: var(--panel);
border-bottom: 1px solid var(--line);
}
header h1 { font-size: 15px; margin: 0 12px 0 0; letter-spacing: .3px; }
header label { display: flex; align-items: center; gap: 6px; color: var(--muted); }
header .live { color: var(--text); }
header .live:has(input:checked) { color: var(--accent-2); font-weight: 600; }
.spacer { flex: 1; }
#status { color: var(--muted); font-variant-numeric: tabular-nums; max-width: 36ch; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
#status.err { color: var(--danger); }
#status.ok { color: var(--ok); }
main {
flex: 1;
display: grid;
grid-template-columns: 420px 1fr;
min-height: 0;
}
#controls {
overflow-y: auto;
padding: 10px;
display: flex;
flex-direction: column;
gap: 10px;
border-right: 1px solid var(--line);
}
.card {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 8px;
padding: 10px 12px;
}
.card h2 {
margin: 0 0 8px;
font-size: 12px;
text-transform: uppercase;
letter-spacing: .8px;
color: var(--muted);
display: flex;
justify-content: space-between;
gap: 8px;
}
.card h2 small { text-transform: none; letter-spacing: 0; font-weight: 400; color: var(--muted); opacity: .8; }
.row { display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: end; margin: 6px 0; }
.row label { display: flex; flex-direction: column; gap: 3px; color: var(--muted); font-size: 12px; }
.row label.grow { flex: 1; }
.row label.check { flex-direction: row; align-items: center; color: var(--text); }
.row label input:not([type=checkbox]), .row label select { width: 100%; }
input, select, button {
font: inherit;
color: var(--text);
background: var(--panel-2);
border: 1px solid var(--line);
border-radius: 5px;
padding: 5px 7px;
}
input[type=number] { width: 7ch; }
input[type=checkbox] { width: auto; accent-color: var(--accent); }
input:focus, select:focus { outline: 1px solid var(--accent); border-color: var(--accent); }
button { cursor: pointer; }
button:hover { border-color: var(--accent); }
button.primary { background: var(--accent); border-color: var(--accent); color: #0b1220; font-weight: 600; }
button.danger { color: var(--danger); }
button:disabled { opacity: .5; cursor: default; }
.tabs { display: flex; gap: 4px; margin-top: 6px; }
.tabs button { flex: 1; background: transparent; color: var(--muted); }
.tabs button.active { background: var(--panel-2); color: var(--text); border-color: var(--accent); }
.hint { color: var(--muted); font-size: 12px; margin: 6px 0 0; }
.hint b { color: var(--text); }
/* sliders: label | range | number */
.slider { display: grid; grid-template-columns: 92px 1fr 64px; gap: 8px; align-items: center; margin: 4px 0; }
.slider span { color: var(--muted); font-size: 12px; }
.slider input[type=range] { width: 100%; padding: 0; background: transparent; border: 0; accent-color: var(--accent); }
.slider input[type=number] { width: 100%; }
/* fixtures */
.fixture { display: grid; grid-template-columns: auto 1fr; gap: 4px 8px; padding: 6px 0; border-top: 1px solid var(--line); }
.fixture:first-child { border-top: 0; }
.fixture .name { display: flex; align-items: center; gap: 8px; grid-column: 1 / -1; }
.fixture .name .swatch { width: 10px; height: 10px; border-radius: 50%; display: inline-block; }
.fixture .name small { color: var(--muted); }
.fixture .opts { grid-column: 1 / -1; display: flex; flex-wrap: wrap; gap: 6px 12px; align-items: center; padding-left: 26px; }
.fixture .opts label { display: flex; align-items: center; gap: 4px; color: var(--muted); font-size: 12px; }
.fixture.off .opts { display: none; }
.fixture.notmover { opacity: .45; }
/* points table */
#point-table { width: 100%; border-collapse: collapse; }
#point-table th { color: var(--muted); font-weight: 500; text-align: left; font-size: 11px; padding: 2px 4px; }
#point-table td { padding: 2px 4px; }
#point-table td input { width: 100%; padding: 3px 5px; }
#point-table tr.sel td { background: rgba(90, 169, 255, .12); }
#point-table tr td:first-child { color: var(--muted); font-variant-numeric: tabular-nums; width: 2.5ch; }
.list { list-style: none; margin: 4px 0 0; padding: 0; max-height: 220px; overflow-y: auto; }
.list li { display: flex; align-items: center; gap: 8px; padding: 4px 0; border-top: 1px solid var(--line); }
.list li:first-child { border-top: 0; }
.list li .lname { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.list li small { color: var(--muted); }
.list li button { padding: 2px 8px; font-size: 12px; }
.list .empty { color: var(--muted); font-style: italic; }
.result { color: var(--muted); font-size: 12px; }
.result.ok { color: var(--ok); }
.result.err { color: var(--danger); }
/* stage */
#stage { display: flex; flex-direction: column; min-width: 0; min-height: 0; }
.toolbar { display: flex; align-items: center; gap: 12px; padding: 8px 12px; border-bottom: 1px solid var(--line); background: var(--panel); }
.toolbar label { display: flex; align-items: center; gap: 6px; color: var(--muted); }
#time { color: var(--muted); font-variant-numeric: tabular-nums; min-width: 12ch; }
#canvas { flex: 1; width: 100%; height: 100%; display: block; cursor: crosshair; touch-action: none; }
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Figure-of-8 on the two Small Eye movers.
Dry run (prints DMX samples, sends nothing):
python3 scripts/anim/anim_eight.py
python3 -m showfile run scripts/anim/anim_eight.py --seconds 1
Send Art-Net, for example at the stage simulator:
python3 scripts/anim/anim_eight.py --ip 127.0.0.1 --seconds 8
"""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from showfile import Show
from showfile.play import script_main
def build() -> Show:
show = Show(author="Jimmy")
m1 = show.patch(
"Small Eye 7", "Mover", "43 Channel", name="Small Eye 7 #1", address=0, key="m1"
)
m2 = show.patch(
"Small Eye 7", "Mover", "43 Channel", name="Small Eye 7 #2", address=44, key="m2"
)
show.efx(
"Figure of 8",
[m1, m2],
algorithm="Eight",
width=40,
height=30,
x_offset=128,
y_offset=140,
duration_ms=8000,
key="eight",
)
show.run("eight")
return show
if __name__ == "__main__":
script_main(build)
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""The whole stage: a colour chase on the cans and a figure-8 on every mover.
The patch, positions, and channel names come from stage/map.json.
Dry run (prints DMX samples, sends nothing):
python3 scripts/anim/anim_stage.py
python3 -m showfile run scripts/anim/anim_stage.py --seconds 1
Send Art-Net at the stage simulator:
python3 scripts/anim/anim_stage.py --ip 127.0.0.1 --seconds 12
"""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from showfile import Show
from showfile.play import script_main
def build() -> Show:
show = Show(author="Jimmy")
rig = show.patch_stage(ROOT / "stage" / "map.json")
red, green, blue = (rig.cans[0].channel(name) for name in ("Red", "Green", "Blue"))
dimmers = {
can.key: {can.channel("Dimmer"): 255, can.channel("Strobe"): 0}
for can in rig.cans
}
show.scene("Can dimmers", dimmers, key="dim")
frames = []
count = len(rig.cans)
for head in range(count):
frame = []
for index in range(count):
colour = _hsv(index / count)
distance = min((index - head) % count, (head - index) % count)
if distance == 0:
frame.append(colour)
elif distance == 1:
frame.append(tuple(channel // 3 for channel in colour))
else:
frame.append((0, 0, 0))
frames.append(frame)
show.colour_chase(
"Can chase",
rig.cans,
{"r": red, "g": green, "b": blue},
frames,
fade_ms=80,
hold_ms=140,
key="chase",
)
look = {}
movers = []
for index, mover in enumerate(rig.movers):
colour = (255, 40, 0) if index % 2 == 0 else (40, 80, 255)
values = {
mover.channel("Zoom"): 40,
mover.channel("Dynamic Effect"): 30 if index % 2 == 0 else 160,
mover.channel("Lens Rotate"): 210 if index % 2 == 0 else 40,
}
for channel in mover.named("White"):
values[channel] = 0
for red_ch, green_ch, blue_ch in zip(mover.named("Red"), mover.named("Green"), mover.named("Blue")):
values[red_ch] = colour[0]
values[green_ch] = colour[1]
values[blue_ch] = colour[2]
look[mover.key] = values
movers.append({"fixture": mover, "start_offset": index * 90})
show.scene("Mover look", look, key="look")
show.efx(
"Movers",
movers,
algorithm="Eight",
width=36,
height=22,
x_offset=128,
y_offset=140,
duration_ms=12000,
key="movers",
)
show.collection("Stage", ["dim", "chase", "look", "movers"], key="stage")
show.run("stage")
return show
def _hsv(hue: float) -> tuple[int, int, int]:
hue = hue % 1.0
segment = int(hue * 6) % 6
frac = hue * 6 - int(hue * 6)
fade = int(255 * (1 - frac))
rise = int(255 * frac)
if segment == 0:
return 255, rise, 0
if segment == 1:
return fade, 255, 0
if segment == 2:
return 0, 255, rise
if segment == 3:
return 0, fade, 255
if segment == 4:
return rise, 0, 255
return 255, 0, fade
if __name__ == "__main__":
script_main(build)
+219
View File
@@ -0,0 +1,219 @@
#!/usr/bin/env bash
# Flash LuxDMX onto a Seeed Studio XIAO ESP32S3.
#
# The XIAO is an ESP32-S3R8 (octal 8 MB PSRAM, native USB only). It shows up
# as an Espressif "USB JTAG/serial" port (/dev/ttyACM*), not a ttyUSB UART
# dongle. This downloads the current LuxDMX release and writes the
# octal-PSRAM image. esptool detects the flash size and rewrites the image
# header to match (this board reports 16 MB). The partition table ends at
# 4 MB, so either size fits. The write is a full erase, so the first boot
# opens the setup access point.
#
# scripts/flash_luxdmx_xiao.sh
# scripts/flash_luxdmx_xiao.sh --port /dev/ttyACM0
# scripts/flash_luxdmx_xiao.sh --plain # leave the PSRAM unused
# scripts/flash_luxdmx_xiao.sh --version v1.0.273
# scripts/flash_luxdmx_xiao.sh --dry-run
#
# A full USB flash erases saved Wi-Fi and config. To update a board that is
# already set up, use the device's own Firmware Update page instead.
#
# After it boots, join the open Wi-Fi "LuxDMX-setup" and open
# http://192.168.4.1. In /config apply the "Seeed XIAO ESP32-S3" template:
# DMX data is D0 (GPIO1) and the RDM return is D1 (GPIO2). The DevKit
# defaults (GPIO16/17) are not broken out on this board.
set -euo pipefail
REPO="tombueng/LuxDMX"
TAG="latest"
PORT=""
PLAIN=0
YES=0
DRY=0
BAUD=921600
usage() {
sed -n '2,22p' "$0" | sed 's/^# \{0,1\}//'
exit 2
}
while [[ $# -gt 0 ]]; do
case "$1" in
--port) PORT="${2:?}"; shift 2 ;;
--version) TAG="${2:?}"; shift 2 ;;
--baud) BAUD="${2:?}"; shift 2 ;;
--plain) PLAIN=1; shift ;;
--yes) YES=1; shift ;;
--dry-run) DRY=1; shift ;;
-h|--help) usage ;;
*) echo "Unknown option: $1" >&2; usage ;;
esac
done
# Ubuntu's esptool package is missing the ESP32-S3 flasher stub, so a
# version check is not enough. Use it only when that stub is actually there.
esptool_has_s3_stub() {
"$1" - << 'PY'
import pathlib, sys
try:
import esptool
except ImportError:
sys.exit(1)
root = pathlib.Path(esptool.__file__).resolve().parent / "targets" / "stub_flasher"
ok = (root / "stub_flasher_32s3.json").is_file() or any(root.glob("*/esp32s3.json"))
sys.exit(0 if ok else 1)
PY
}
if esptool_has_s3_stub python3; then
ESPTOOL=(python3 -m esptool)
else
VENV="${XDG_CACHE_HOME:-$HOME/.cache}/luxdmx/esptool-venv"
if [[ ! -x "$VENV/bin/python" ]] || ! esptool_has_s3_stub "$VENV/bin/python"; then
echo "System esptool has no ESP32-S3 stub. Installing one into ${VENV}…"
python3 -m venv "$VENV"
"$VENV/bin/pip" install -q 'esptool>=4.8,<5'
fi
ESPTOOL=("$VENV/bin/python" -m esptool)
fi
if [[ "$PLAIN" -eq 1 ]]; then
BOOT="bootloader-esp32s3.bin"
PARTS="partitions-esp32s3.bin"
APP="firmware-esp32s3.bin"
IMAGE="plain ESP32-S3 (PSRAM left unused)"
else
BOOT="bootloader-esp32s3-psram.bin"
PARTS="partitions-esp32s3-psram.bin"
APP="firmware-esp32s3-psram.bin"
IMAGE="ESP32-S3 octal PSRAM (XIAO ESP32S3 / S3R8)"
fi
find_port() {
if [[ -n "$PORT" ]]; then
[[ -e "$PORT" ]] || { echo "Port not found: $PORT" >&2; exit 1; }
echo "$PORT"
return
fi
local -a matches=()
local p
shopt -s nullglob
for p in /dev/serial/by-id/*; do
case "$p" in
*[Ee]spressif*|*[Ss]eeed*|*[Xx][Ii][Aa][Oo]*)
matches+=("$(readlink -f "$p")")
;;
esac
done
shopt -u nullglob
if [[ ${#matches[@]} -eq 1 ]]; then
echo "${matches[0]}"
return
fi
if [[ ${#matches[@]} -gt 1 ]]; then
echo "More than one Espressif/Seeed serial port. Pass --port." >&2
printf ' %s\n' "${matches[@]}" >&2
exit 1
fi
shopt -s nullglob
matches=(/dev/ttyACM*)
shopt -u nullglob
if [[ ${#matches[@]} -eq 1 && -e "${matches[0]}" ]]; then
echo "${matches[0]}"
return
fi
echo "No XIAO found. Plug in the USB-C port, then re-run." >&2
echo "If it still does not appear: hold B, tap R, release B, and pass --port." >&2
exit 1
}
CACHE_ROOT="${XDG_CACHE_HOME:-$HOME/.cache}/luxdmx"
mkdir -p "$CACHE_ROOT"
mapfile -t DL < <(python3 - "$CACHE_ROOT" "$TAG" "$BOOT" "$PARTS" "boot_app0.bin" "$APP" << 'PY'
import json, pathlib, sys, urllib.request
cache_root, tag, *names = sys.argv[1:]
api = f"https://api.github.com/repos/tombueng/LuxDMX/releases/tags/{tag}"
req = urllib.request.Request(api, headers={"Accept": "application/vnd.github+json", "User-Agent": "luxdmx-flash"})
with urllib.request.urlopen(req, timeout=60) as resp:
release = json.load(resp)
name = release.get("name") or release.get("tag_name") or tag
# "Latest → v1.0.273 (....)" — cache by the version, not the moving tag.
version = name
for token in name.replace("→", " ").replace("(", " ").split():
if token.startswith("v") and token[1:2].isdigit():
version = token
break
assets = {a["name"]: a for a in release.get("assets", [])}
missing = [n for n in names if n not in assets]
if missing:
sys.exit(f"Release {version} has no {', '.join(missing)}")
dest = pathlib.Path(cache_root) / version
dest.mkdir(parents=True, exist_ok=True)
for n in names:
path = dest / n
size = assets[n]["size"]
if path.is_file() and path.stat().st_size == size:
continue
url = assets[n]["browser_download_url"]
tmp = path.with_suffix(path.suffix + ".part")
urllib.request.urlretrieve(url, tmp)
if tmp.stat().st_size != size:
tmp.unlink(missing_ok=True)
sys.exit(f"Short download: {n}")
tmp.replace(path)
print(version)
print(dest)
PY
)
VERSION="${DL[0]}"
DIR="${DL[1]}"
PORT="$(find_port)"
echo "LuxDMX ${VERSION} (${IMAGE})"
echo "Port ${PORT} baud ${BAUD}"
echo "This erases the whole flash, including saved Wi-Fi and config."
if [[ "$DRY" -eq 1 ]]; then
echo "Dry run — not flashing."
exit 0
fi
if [[ "$YES" -ne 1 ]]; then
if [[ ! -t 0 ]]; then
echo "Pass --yes to flash without a prompt." >&2
exit 1
fi
read -r -p "Flash now? [y/N] " ans
[[ "$ans" == [yY] ]] || { echo "Cancelled."; exit 1; }
fi
set +e
"${ESPTOOL[@]}" --chip esp32s3 --port "$PORT" --baud "$BAUD" \
--before default_reset --after hard_reset \
write_flash --erase-all --flash_mode keep --flash_freq keep --flash_size detect --compress \
0x0000 "${DIR}/${BOOT}" \
0x8000 "${DIR}/${PARTS}" \
0xe000 "${DIR}/boot_app0.bin" \
0x10000 "${DIR}/${APP}"
rc=$?
set -e
if [[ $rc -ne 0 ]]; then
echo >&2
echo "Flash failed. Put the XIAO in download mode and run this again:" >&2
echo " hold B, tap R, release B, then: $0 --port $PORT --yes" >&2
exit $rc
fi
cat << 'EOF'
Flashed. On first boot the XIAO opens an open Wi-Fi network:
SSID LuxDMX-setup
URL http://192.168.4.1
In /config, apply the "Seeed XIAO ESP32-S3" template so the DMX pins
match the header (D0 = data out, D1 = RDM return). Then point QLC+
Art-Net at the address shown there, universe 0.
EOF
-305
View File
@@ -1,305 +0,0 @@
#!/usr/bin/env python3
"""Generate shows/simple.qxw — per-mover position + shared and individual RGBW."""
from __future__ import annotations
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "shows" / "simple.qxw"
# Fixture IDs match shows/xchc.qxw
CANS = list(range(8)) # BCC145 #1–#8
M1, M2 = 8, 9
MOVERS = [M1, M2]
# Can 8ch: Dim=0, R=2, G=3, B=4, W=5
# Mover 43ch: Center Bright=8; RGBW heads 1–7
MOVER_R = [10, 14, 18, 22, 26, 30, 34]
MOVER_G = [11, 15, 19, 23, 27, 31, 35]
MOVER_B = [12, 16, 20, 24, 28, 32, 36]
MOVER_W = [13, 17, 21, 25, 29, 33, 37]
COLORS = [
("R", 2, MOVER_R, "4294901760", "Red"),
("G", 3, MOVER_G, "4278255360", "Green"),
("B", 4, MOVER_B, "4278190335", "Blue"),
("W", 5, MOVER_W, "4294967295", "None"),
]
def appearance(
fg: str = "Default",
bg: str = "Default",
frame: str = "Sunken",
) -> str:
return f""" <Appearance>
<FrameStyle>{frame}</FrameStyle>
<ForegroundColor>{fg}</ForegroundColor>
<BackgroundColor>{bg}</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>"""
def slider(
wid: int,
caption: str,
x: int,
y: int,
w: int,
h: int,
channels: list[tuple[int, int]],
*,
value: int = 0,
fg: str = "Default",
cng: str = "None",
) -> str:
ch_xml = "\n".join(
f' <Channel Fixture="{fid}">{ch}</Channel>' for fid, ch in channels
)
return f""" <Slider Caption="{caption}" ID="{wid}" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
{appearance(fg=fg)}
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="{cng}" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="{value}">
{ch_xml}
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>"""
def xypad(wid: int, caption: str, fid: int, x: int, y: int, w: int, h: int) -> str:
return f""" <XYPad Caption="{caption}" ID="{wid}" InvertedAppearance="0">
<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
{appearance()}
<Fixture ID="{fid}" Head="0">
<Axis ID="X" LowLimit="0" HighLimit="1" Reverse="False"/>
<Axis ID="Y" LowLimit="0" HighLimit="1" Reverse="False"/>
</Fixture>
<Window hMin="0" hMax="255" vMin="0" vMax="255"/>
<Pan Position="128"/>
<Tilt Position="128"/>
</XYPad>"""
def label_frame(caption: str, x: int, y: int, w: int, h: int) -> str:
return f""" <Frame Caption="{caption}">
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>Default</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>
<AllowChildren>True</AllowChildren>
<AllowResize>True</AllowResize>
<ShowHeader>True</ShowHeader>
<ShowEnableButton>False</ShowEnableButton>
<ShowIntensityButton>False</ShowIntensityButton>
<Mixing>False</Mixing>
</Frame>"""
def fixture_xml() -> str:
parts = []
for i in range(8):
parts.append(
f""" <Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>{i}</ID>
<Name>BCC145 #{i + 1}</Name>
<Universe>0</Universe>
<Address>{87 + i * 8}</Address>
<Channels>8</Channels>
</Fixture>"""
)
for i, addr in enumerate((0, 44)):
parts.append(
f""" <Fixture>
<Manufacturer>Small Eye 7</Manufacturer>
<Model>Mover</Model>
<Mode>43 Channel</Mode>
<ID>{8 + i}</ID>
<Name>Small Eye 7 #{i + 1}</Name>
<Universe>0</Universe>
<Address>{addr}</Address>
<Channels>43</Channels>
</Fixture>"""
)
return "\n".join(parts)
def main() -> None:
pad_w, pad_h = 240, 240
sl_w, sl_h = 44, 240
ind_w, ind_h = 36, 160
gap = 8
widgets: list[str] = []
wid = 0
max_x = 0
max_y = 0
def place_slider(caption, x, y, w, h, channels, value=0, fg="Default", cng="None"):
nonlocal wid, max_x, max_y
widgets.append(
slider(wid, caption, x, y, w, h, channels, value=value, fg=fg, cng=cng)
)
wid += 1
max_x = max(max_x, x + w)
max_y = max(max_y, y + h)
y0 = 28
x = 10
widgets.append(xypad(wid, "M1 Position", M1, x, y0, pad_w, pad_h))
wid += 1
x += pad_w + gap
widgets.append(xypad(wid, "M2 Position", M2, x, y0, pad_w, pad_h))
wid += 1
x += pad_w + gap + 12
max_x = max(max_x, x)
max_y = max(max_y, y0 + pad_h)
place_slider("C Dim", x, y0, sl_w, sl_h, [(f, 0) for f in CANS], 255, "4294967295")
x += sl_w + 2
for name, can_ch, _mover_chs, fg, cng in COLORS:
place_slider(
f"C {name}",
x,
y0,
sl_w,
sl_h,
[(f, can_ch) for f in CANS],
fg=fg,
cng=cng,
)
x += sl_w + 2
x += 14
place_slider("M Dim", x, y0, sl_w, sl_h, [(f, 8) for f in MOVERS], 255, "4294967295")
x += sl_w + 2
for name, _can_ch, mover_chs, fg, cng in COLORS:
place_slider(
f"M {name}",
x,
y0,
sl_w,
sl_h,
[(f, c) for f in MOVERS for c in mover_chs],
fg=fg,
cng=cng,
)
x += sl_w + 2
y1 = y0 + pad_h + 36
x = 10
widgets.append(label_frame("Cans individual RGBW", x, y1 - 28, 200, 24))
for i, fid in enumerate(CANS):
col_x = x + i * (4 * (ind_w + 2) + 10)
for j, (name, can_ch, _m, fg, cng) in enumerate(COLORS):
place_slider(
f"{i + 1}{name}",
col_x + j * (ind_w + 2),
y1,
ind_w,
ind_h,
[(fid, can_ch)],
fg=fg,
cng=cng,
)
mx = x + 8 * (4 * (ind_w + 2) + 10) + 16
widgets.append(label_frame("Movers individual RGBW", mx, y1 - 28, 220, 24))
for mi, (fid, label) in enumerate(((M1, "M1"), (M2, "M2"))):
col_x = mx + mi * (4 * (ind_w + 2) + 14)
for j, (name, _can_ch, mover_chs, fg, cng) in enumerate(COLORS):
place_slider(
f"{label}{name}",
col_x + j * (ind_w + 2),
y1,
ind_w,
ind_h,
[(fid, c) for c in mover_chs],
fg=fg,
cng=cng,
)
total_w = max_x + 16
total_h = max_y + 16
qxw = f"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Workspace>
<Workspace xmlns="http://www.qlcplus.org/Workspace" CurrentWindow="VirtualConsole">
<Creator>
<Name>Q Light Controller Plus</Name>
<Version>4.12.7</Version>
<Author>Jimmy</Author>
</Creator>
<Engine>
<InputOutputMap>
<Universe Name="Universe 1" ID="0">
<Output Plugin="ArtNet" UID="192.168.1.92" Line="7">
<PluginParameters outputIP="192.168.1.228" outputUni="0"/>
</Output>
</Universe>
<Universe Name="Universe 2" ID="1"/>
<Universe Name="Universe 3" ID="2"/>
<Universe Name="Universe 4" ID="3"/>
</InputOutputMap>
{fixture_xml()}
<FixtureGroup ID="0">
<Name>BCC145 U</Name>
<Size X="8" Y="1"/>
<Head X="0" Y="0" Fixture="0">0</Head>
<Head X="1" Y="0" Fixture="1">0</Head>
<Head X="2" Y="0" Fixture="2">0</Head>
<Head X="3" Y="0" Fixture="3">0</Head>
<Head X="4" Y="0" Fixture="4">0</Head>
<Head X="5" Y="0" Fixture="5">0</Head>
<Head X="6" Y="0" Fixture="6">0</Head>
<Head X="7" Y="0" Fixture="7">0</Head>
</FixtureGroup>
<FixtureGroup ID="1">
<Name>Small Eye Movers</Name>
<Size X="2" Y="1"/>
<Head X="0" Y="0" Fixture="8">0</Head>
<Head X="1" Y="0" Fixture="9">0</Head>
</FixtureGroup>
</Engine>
<VirtualConsole>
<Frame Caption="">
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>Default</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
{"\n".join(widgets)}
</Frame>
<Properties>
<Size Width="{total_w}" Height="{total_h}"/>
<GrandMaster ChannelMode="Intensity" ValueMode="Reduce" SliderMode="Normal"/>
</Properties>
</VirtualConsole>
<SimpleDesk>
<Engine/>
</SimpleDesk>
</Workspace>
"""
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(qxw)
print(f"Wrote {OUT} ({total_w}x{total_h}, {wid} widgets)")
if __name__ == "__main__":
main()
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""Print the SMC-PAD SysEx in a usbmon capture.
sudo tcpdump -i usbmon1 -s 0 -U -w - > captures/pad.pcap
python3 scripts/pad/decode_usbmon.py captures/pad.pcap --device 21
Each USB-MIDI packet is reassembled into messages per cable, then SINCO
SysEx is decoded to its command, memory, address, and data.
"""
from __future__ import annotations
import argparse
import struct
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
from padcontroller.sysex import decode # noqa: E402
LINKTYPE_USB_LINUX_MMAPPED = 220
HEADER = struct.Struct("<QBBBBHBBqiiIIQiiII") # 64 bytes
# Payload bytes carried by each USB-MIDI code index number.
CIN_SIZE = {0x2: 2, 0x3: 3, 0x4: 3, 0x5: 1, 0x6: 2, 0x7: 3, 0x8: 3, 0x9: 3,
0xA: 3, 0xB: 3, 0xC: 2, 0xD: 2, 0xE: 3, 0xF: 1}
COMMANDS = {0x00: "ack", 0x22: "write", 0x23: "read"}
def packets(path: Path):
raw = path.read_bytes()
magic = struct.unpack_from("<I", raw)[0]
if magic not in (0xA1B2C3D4, 0xA1B23C4D):
raise SystemExit(f"{path} is not a little-endian pcap")
linktype = struct.unpack_from("<I", raw, 20)[0]
if linktype != LINKTYPE_USB_LINUX_MMAPPED:
raise SystemExit(f"{path} has link type {linktype}, expected usbmon ({LINKTYPE_USB_LINUX_MMAPPED})")
at = 24
while at + 16 <= len(raw):
sec, frac, incl, _orig = struct.unpack_from("<IIII", raw, at)
at += 16
yield sec + frac / 1e6, raw[at:at + incl]
at += incl
def transfers(path: Path, device: int | None):
"""(time, direction, data) for bulk and interrupt transfers that carry data."""
for stamp, frame in packets(path):
if len(frame) < HEADER.size:
continue
fields = HEADER.unpack_from(frame)
kind, xfer, endpoint, devnum = fields[1], fields[2], fields[3], fields[4]
if device is not None and devnum != device:
continue
if xfer not in (1, 3):
continue
data = frame[HEADER.size:]
inbound = bool(endpoint & 0x80)
# Host-to-pad data rides on the submit, pad-to-host on the completion.
if data and ((not inbound and kind == ord("S")) or (inbound and kind == ord("C"))):
yield stamp, "pad→host" if inbound else "host→pad", data
def messages(path: Path, device: int | None):
pending: dict[tuple[str, int], bytearray] = {}
for stamp, direction, data in transfers(path, device):
for at in range(0, len(data) - 3, 4):
head = data[at]
cin, cable = head & 0x0F, head >> 4
if head == 0:
continue
body = data[at + 1:at + 1 + CIN_SIZE.get(cin, 0)]
key = (direction, cable)
if cin in (0x4, 0x5, 0x6, 0x7) or (pending.get(key) and cin == 0xF):
buf = pending.setdefault(key, bytearray())
buf += body
if cin != 0x4 and buf.endswith(b"\xf7"):
yield stamp, direction, cable, bytes(buf)
del pending[key]
else:
yield stamp, direction, cable, bytes(body)
def describe(message: bytes) -> str:
if message[:1] != b"\xf0" or message[-1:] != b"\xf7":
return message.hex(" ")
inner = decode(message[1:-1])
if inner[:2] != b"\x00\x59" or len(inner) < 7:
return f"sysex {inner.hex(' ')}"
command = COMMANDS.get(inner[2], f"cmd {inner[2]:#04x}")
length = int.from_bytes(inner[3:6], "little")
payload = inner[6:6 + length]
if inner[2] in (0x22, 0x23) and len(payload) >= 8:
memory = payload[0]
address = int.from_bytes(payload[1:5], "little")
size = int.from_bytes(payload[5:8], "little")
data = payload[8:]
text = f"{command} mem {memory} addr {address:#010x} len {size}"
return f"{text} data {data.hex()}" if data else text
return f"{command} {payload.hex(' ')}"
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("capture", type=Path)
parser.add_argument("--device", type=int, help="USB device number from lsusb")
args = parser.parse_args(argv)
start = None
for stamp, direction, cable, message in messages(args.capture, args.device):
start = stamp if start is None else start
print(f"{stamp - start:8.3f} {direction} cable {cable} {describe(message)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+2 -2
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Print SMC-PAD pad and knob numbers.
pipenv run python scripts/midi.py
pipenv run python scripts/pad/midi.py
Each pad press prints pad N. Each knob turn prints knob N and its step
(+ for up, - for down).
@@ -18,7 +18,7 @@ from pathlib import Path
import mido
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
MAP_PATH = ROOT / "shows" / "midi_map.json"
# (channel, note) -> pad number. Loaded from shows/midi_map.json.
+268
View File
@@ -0,0 +1,268 @@
#!/usr/bin/env python3
"""Store scene colours in an SMC-PAD preset bank.
Pad bank 1 is notes 36–51 and pad bank 2 is notes 52–67, bottom-left
first. Note messages do not change these lamps. The colour is three
bytes in the preset, written over the Private USB port.
.venv/bin/python scripts/pad/pad_colours.py --xchc --bank 2
.venv/bin/python scripts/pad/pad_colours.py --colour-set --bank 2
.venv/bin/python scripts/pad/pad_colours.py --dry-run
.venv/bin/python scripts/pad/pad_colours.py --clear
.venv/bin/python scripts/pad/pad_colours.py --identify
--identify lights every pad on a page in that page's colour, in rainbow
order, in all eight presets, so the page on show can be read at a glance.
The write is checked by reading it back. It is sent to the running copy
and to the stored preset, and it leaves notes, channels, and knobs as
they are. An empty write at the start of the preset then commits it,
which is what MidiSuite's Save button sends.
"""
from __future__ import annotations
import argparse
import glob
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "scripts" / "pad"))
from patch_smc_pad import PAD_COLORS # noqa: E402
from padcontroller import preset # noqa: E402
from padcontroller.device import PadError, read_image, save_image, transact # noqa: E402
from padcontroller.device import private_port as _private_port # noqa: E402
from padcontroller.preset import scale # noqa: E402
from padcontroller.sysex import ( # noqa: E402
RAM,
decode,
encode,
payload_data,
read_request,
save_request,
write_request,
)
# Preset image, memory type 5. Each of these offsets is a note-36 pad,
# and the next 15 records are notes 37–51. The running copy is at RAM.
RECORD = 26
RGB_AT = 4
BANKS = (1044, 8122, 11661, 15200, 18739, 22278, 25817)
def led_rgb(r: int, g: int, b: int, w: int) -> tuple[int, int, int]:
return (min(255, r + w), min(255, g + w), min(255, b + w))
# shows/xchc.qxw functions 0–8, in that order. The pad lamps are RGB, so
# the white scene is stored as white rather than the can's white channel.
XCHC_COLOURS = (
("Red", 255, 0, 0),
("Orange", 255, 127, 0),
("Yellow", 255, 255, 0),
("Green", 0, 255, 0),
("Cyan", 0, 255, 255),
("Blue", 0, 0, 255),
("Violet", 127, 0, 255),
("Magenta", 255, 0, 255),
("White", 255, 255, 255),
)
# One colour per pad page, page 1 first. Rainbow order, so the page
# number can be counted from red.
PAGE_COLOURS = (
("Red", 255, 0, 0),
("Orange", 255, 100, 0),
("Yellow", 255, 255, 0),
("Green", 0, 255, 0),
("Cyan", 0, 255, 255),
("Blue", 0, 0, 255),
("Violet", 160, 0, 255),
("White", 255, 255, 255),
)
def identify_image(image: bytes) -> bytes:
"""The image with each pad page lit in its PAGE_COLOURS colour."""
out = bytearray(image)
for number in range(preset.PRESET_COUNT):
for index in range(preset.PAD_COUNT):
_name, red, green, blue = PAGE_COLOURS[index // preset.PAGE_LEN]
at = preset.colour_offset(number, index)
out[at:at + 3] = bytes((scale(red), scale(green), scale(blue)))
return bytes(out)
def scene_colours(clear: bool = False) -> list[tuple[str, bytes]]:
colours = []
for name, r, g, b, w in PAD_COLORS:
if clear:
colours.append((name, b"\x00\x00\x00"))
continue
red, green, blue = led_rgb(r, g, b, w)
colours.append((name, bytes((scale(red), scale(green), scale(blue)))))
return colours
def xchc_colours(clear: bool = False) -> list[tuple[str, bytes]]:
"""The nine xchc colour scenes, then the rest of the 16-pad bank off."""
colours = []
for name, red, green, blue in XCHC_COLOURS:
rgb = b"\x00\x00\x00" if clear else bytes((scale(red), scale(green), scale(blue)))
colours.append((name, rgb))
colours.extend(("", b"\x00\x00\x00") for _ in range(16 - len(colours)))
return colours
def colour_set(clear: bool = False) -> list[tuple[str, bytes]]:
"""The colours of shows/test.qxw in pad order, then the rest of the bank off."""
sys.path.insert(0, str(ROOT / "scripts" / "shows"))
from colour_sets import COLOURS
colours = []
for name, r, g, b, w in COLOURS:
rgb = b"\x00\x00\x00" if clear else bytes(scale(c) for c in led_rgb(r, g, b, w))
colours.append((name, rgb))
colours.extend(("", b"\x00\x00\x00") for _ in range(16 - len(colours)))
return colours
# Preset page whose records light each pad bank. Page 3 also sends notes
# 52–67 but its colours are not shown; bank 2 takes them from page 7.
BANK_PAGE = {1: 2, 2: 7}
def bank_bases(bank: int) -> tuple[int, ...]:
"""Preset addresses where this pad bank's note records start."""
if bank < 1:
raise ValueError(f"pad bank {bank} is not on this controller")
page = BANK_PAGE.get(bank, bank + 1)
skip = (page - 2) * 16 * RECORD
return tuple(base + skip for base in BANKS)
def colour_writes(
clear: bool = False,
bank: int = 1,
colours: list[tuple[str, bytes]] | None = None,
) -> list[tuple[str, int, bytes]]:
"""(name, address, rgb) for one pad bank in every preset."""
palette = scene_colours(clear) if colours is None else list(colours)
if clear and colours is not None:
palette = [(name, b"\x00\x00\x00") for name, _rgb in palette]
placed = []
for base in bank_bases(bank):
for index, (name, rgb) in enumerate(palette):
placed.append((name, base + index * RECORD + RGB_AT, rgb))
return placed
def payload_data(decoded: bytes) -> bytes:
"""Bytes after the type, address, and length in a read reply."""
if decoded[:3] != b"\x00\x59\x23":
raise ValueError(f"unexpected reply {decoded[:8].hex()}")
payload = decoded[6:-1]
return payload[8:]
def private_port(names: list[str]) -> str:
try:
return _private_port(names)
except PadError as exc:
raise SystemExit(str(exc)) from exc
def apply(
clear: bool,
bank: int = 1,
colours: list[tuple[str, bytes]] | None = None,
any_note: bool = False,
) -> None:
for path in glob.glob(str(ROOT / ".venv" / "lib" / "python*" / "site-packages")):
if path not in sys.path:
sys.path.insert(0, path)
import rtmidi
midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA)
midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA)
port = private_port(midiout.get_ports())
index = midiout.get_ports().index(port)
midiin.open_port(index)
midiin.ignore_types(sysex=False, timing=True, active_sense=True)
midiout.open_port(index)
print(f"Port: {port}", flush=True)
try:
note = 36 + (bank - 1) * 16
for base in bank_bases(bank):
reply = transact(midiout, midiin, read_request(base, 2))
mark = payload_data(reply)
if mark[0] != 0x09 or (not any_note and mark[1] != note):
raise SystemExit(
f"preset at {base} is {mark.hex()}, not the note-{note} pads; nothing was written"
)
bases = (RAM, 0)
shown = set()
for name, address, rgb in colour_writes(clear, bank, colours):
for base in bases:
transact(midiout, midiin, write_request(base + address, rgb))
if name in shown:
continue
check = payload_data(transact(midiout, midiin, read_request(address, 3)))
if check != rgb:
raise SystemExit(f"{name or 'pad'} read back {check.hex()}, expected {rgb.hex()}")
shown.add(name)
if name:
print(f" {name:<8} {address:#06x} {rgb.hex()}", flush=True)
reply = transact(midiout, midiin, save_request())
if reply[:3] != b"\x00\x59\x00" or reply[6:7] != b"\x00":
raise SystemExit(f"the pad did not accept the save ({reply.hex()})")
print("Saved on the pad.", flush=True)
finally:
for port in (midiout, midiin):
port.close_port()
port.delete()
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--bank", type=int, default=1, help="pad bank to write (2 is notes 52–67)")
parser.add_argument("--page", type=int, help="write preset page 0–7 instead (page 2 is bank 1, 3 is bank 2; 7 repeats 52–67)")
parser.add_argument("--xchc", action="store_true", help="use the solid colour scenes from shows/xchc.qxw")
parser.add_argument("--colour-set", action="store_true", help="use the 16 colours from shows/test.qxw")
parser.add_argument("--clear", action="store_true", help="store black on every scene pad")
parser.add_argument("--identify", action="store_true", help="light each pad page in its own colour")
parser.add_argument("--dry-run", action="store_true", help="print the colours and do not open a port")
args = parser.parse_args(argv)
if args.page is not None:
if not 2 <= args.page < preset.PAGE_COUNT:
parser.error("--page must be 2–7")
args.bank = args.page - 1
if args.identify:
for page, (name, red, green, blue) in enumerate(PAGE_COLOURS, 1):
print(f"page {page} {name:<7} {bytes((scale(red), scale(green), scale(blue))).hex()}")
if not args.dry_run:
try:
written = save_image(identify_image(read_image()))
except PadError as exc:
raise SystemExit(str(exc)) from exc
print(f"Saved on the pad ({written} bytes changed).")
return 0
palette = xchc_colours(args.clear) if args.xchc else colour_set(args.clear) if args.colour_set else None
if args.dry_run:
seen = set()
for name, address, rgb in colour_writes(args.clear, args.bank, palette):
if not name or name in seen:
continue
seen.add(name)
print(f"{name:<8} {address:#06x} {rgb.hex()}")
return 0
apply(args.clear, args.bank, palette, any_note=args.page is not None)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Set the SMC-PAD lamps: bank 1 off, bank 2 in the colours of shows/test.qxw.
.venv/bin/python scripts/pad/pad_lamps.py
Needs the USB Private port. padcontroller.midi does this on start; run this
when the pad is read by Chataigne instead.
"""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
def set_lamps() -> None:
"""Bank 1 lamps off, bank 2 lamps from shows/test.qxw. Needs the USB Private port."""
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "scripts" / "pad"))
import pad_colours
try:
pad_colours.apply(True, bank=1)
pad_colours.apply(False, bank=2, colours=pad_colours.colour_set())
except (SystemExit, Exception) as exc: # the Bluetooth link has no Private port
print(f"Lamps not set: {exc}", flush=True)
if __name__ == "__main__":
set_lamps()
+392
View File
@@ -0,0 +1,392 @@
#!/usr/bin/env python3
"""Build shows/midi.qxw — M-VAVE SMC-PAD controlling 20× BCC145 (Dim + RGBW)."""
from __future__ import annotations
import re
import shutil
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
OUT = ROOT / "shows" / "midi.qxw"
PROFILE_SRC = ROOT / "inputprofiles" / "M-VAVE-SMC-PAD.qxi"
PROFILE_DST = Path.home() / ".qlcplus" / "inputprofiles" / "M-VAVE-SMC-PAD.qxi"
PROFILE_NAME = "M-VAVE SMC-PAD"
MIDI_UNIVERSE_ID = 1 # Universe 2
OMNI_MIDICHANNEL = 16 # pads ch10 + knobs ch1
PAD_MIDI_CH = 9
# 20× BCC145, 8ch mode, physical/UI start channel 88
# QLC XML Address is 0-based: Address 87 → DMX/UI channel 88 (same as xchc.qxw).
BCC_COUNT = 20
BCC_START_ADDRESS = 87
BCC_CHANNELS = 8
UNIVERSE_CHANNELS = BCC_START_ADDRESS + BCC_COUNT * BCC_CHANNELS # 247
# 8ch map: 0 Dim, 1 Strobe, 2–5 RGBW, 6 Macro, 7 Speed
STROBE_CH, MACRO_CH, SPEED_CH = 1, 6, 7
# Knob bank 1 (CC 30–37): knobs 1–8 — master Dim/RGBW/Strobe/Macro/Speed
# Knob bank 2 (CC 38–44): knobs 9–15 — Dim boost for #9–#15 (HTP vs master)
KNOB_BANK1 = [
# (cc, caption, widget_id, dmx_ch, fg, cng, value, fixtures|None)
(32, "Dim", 0, 0, "4294967295", "None", 200, None),
(36, "R", 1, 2, "4294901760", "Red", 0, None),
(37, "G", 2, 3, "4278255360", "Green", 0, None),
(34, "B", 3, 4, "4278190335", "Blue", 0, None),
(35, "W", 4, 5, "4294967295", "None", 0, None),
(33, "Strobe", 5, STROBE_CH, "4294922844", "None", 0, None),
(30, "Macro", 6, MACRO_CH, "4288256409", "None", 0, None),
(31, "Speed", 7, SPEED_CH, "4286611584", "None", 0, None),
]
KNOB_BANK2 = [
# (cc, caption, widget_id, fixture_id)
(38, "F9", 20, 8),
(39, "F10", 21, 9),
(40, "F11", 22, 10),
(41, "F12", 23, 11),
(42, "F13", 24, 12),
(43, "F14", 25, 13),
(44, "F15", 26, 14),
]
# 4×4 pads → colour flashes / utility (scenes built below)
# note 36..51 with OMNI encoding
PAD_COLORS = [
# (name, r, g, b, w) — bottom row left→right, then up
("Red", 255, 0, 0, 0),
("Green", 0, 255, 0, 0),
("Blue", 0, 0, 255, 0),
("White", 0, 0, 0, 255),
("Yellow", 255, 255, 0, 0),
("Cyan", 0, 255, 255, 0),
("Magenta", 255, 0, 255, 0),
("Orange", 255, 80, 0, 0),
("Warm", 255, 120, 40, 80),
("Cool", 80, 120, 255, 40),
("Pink", 255, 40, 120, 0),
("Lime", 120, 255, 0, 0),
("Full", 255, 255, 255, 255),
("Half", 128, 128, 128, 128),
("Dim50", 0, 0, 0, 0), # blackout colour; dim stays
("Black", 0, 0, 0, 0),
]
def detect_midi_uid() -> str:
"""Prefer smoothed virtual port when the pad controller (padcontroller.midi) is running."""
try:
out = subprocess.check_output(["aconnect", "-l"], text=True)
except (FileNotFoundError, subprocess.CalledProcessError):
out = ""
for name in (
"padcontroller",
"SMC-PAD Bluetooth",
"SINCO SMC-PAD-Private",
"SINCO SMC-PAD-Master",
"SINCO",
):
if name in out:
return name
return "SMC-PAD Bluetooth"
ARTNET_OUTPUT_IP = "192.168.1.175"
# Device Art-Net universe (IceRay SwOut); keep in sync with the box
ARTNET_OUTPUT_UNI = "0"
ARTNET_LINE = "0"
def detect_artnet_uid() -> str:
"""Local IPv4 on the same /24 as the Art-Net node (prefer wlan/eth)."""
try:
out = subprocess.check_output(["ip", "-4", "-o", "addr", "show"], text=True)
except (FileNotFoundError, subprocess.CalledProcessError):
return "192.168.1.90"
prefix = ".".join(ARTNET_OUTPUT_IP.split(".")[:3]) + "."
candidates: list[str] = []
for line in out.splitlines():
# 2: wlo1 inet 192.168.1.90/24 ...
parts = line.split()
if len(parts) < 4 or parts[2] != "inet":
continue
ip = parts[3].split("/", 1)[0]
iface = parts[1]
if ip.startswith(prefix) and not iface.startswith(("lo", "vir", "docker", "br-", "mpq")):
candidates.append(ip)
return candidates[0] if candidates else "192.168.1.90"
def output_xml() -> str:
uid = detect_artnet_uid()
return f""" <Output Plugin="ArtNet" UID="{uid}" Line="{ARTNET_LINE}">
<PluginParameters outputIP="{ARTNET_OUTPUT_IP}" outputUni="{ARTNET_OUTPUT_UNI}" UniverseChannels="{UNIVERSE_CHANNELS}"/>
</Output>"""
def install_profile() -> None:
PROFILE_DST.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(PROFILE_SRC, PROFILE_DST)
def appearance(fg: str = "Default") -> str:
return f""" <Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>{fg}</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>"""
def fixture_ids() -> range:
return range(BCC_COUNT)
def slider(
wid: int,
caption: str,
x: int,
y: int,
dmx_ch: int,
*,
fg: str,
cng: str,
value: int,
midi_cc: int | None,
fixtures: range | list[int] | None = None,
width: int = 60,
height: int = 280,
) -> str:
inp = ""
if midi_cc is not None:
inp = f'\n <Input Universe="{MIDI_UNIVERSE_ID}" Channel="{midi_cc}"/>'
fids = list(fixture_ids() if fixtures is None else fixtures)
channels = "\n".join(
f' <Channel Fixture="{fid}">{dmx_ch}</Channel>' for fid in fids
)
return f""" <Slider Caption="{caption}" ID="{wid}" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="{x}" Y="{y}" Width="{width}" Height="{height}"/>
{appearance(fg)}
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="{cng}" Monitor="true">Level</SliderMode>
<Level LowLimit="0" HighLimit="255" Value="{value}">
{channels}
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>{inp}
</Slider>"""
def scene_xml(fid: int, name: str, r: int, g: int, b: int, w: int) -> str:
# BCC145 8ch: Dim left to slider; force Strobe/Macro/Speed off; set RGBW.
vals = [
(STROBE_CH, 0),
(2, r),
(3, g),
(4, b),
(5, w),
(MACRO_CH, 0),
(SPEED_CH, 0),
]
fv = "\n".join(
f' <FixtureVal ID="{fx}" Channel="{ch}">{v}</FixtureVal>'
for fx in fixture_ids()
for ch, v in vals
)
return f""" <Function ID="{fid}" Type="Scene" Name="{name}">
<Bus Role="Fade">1</Bus>
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<Direction>Forward</Direction>
<RunOrder>Loop</RunOrder>
{fv}
</Function>"""
def fixtures_xml() -> str:
blocks = []
for i in fixture_ids():
addr = BCC_START_ADDRESS + i * BCC_CHANNELS
blocks.append(
f""" <Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>{i}</ID>
<Name>BCC145 #{i + 1}</Name>
<Universe>0</Universe>
<Address>{addr}</Address>
<Channels>{BCC_CHANNELS}</Channels>
</Fixture>"""
)
return "\n".join(blocks)
def button_xml(wid: int, caption: str, x: int, y: int, func_id: int, midi_ch: int, bg: str) -> str:
return f""" <Button Caption="{caption}" ID="{wid}" Icon="">
<WindowState Visible="True" X="{x}" Y="{y}" Width="70" Height="56"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>{bg}</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="{func_id}"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
<Input Universe="{MIDI_UNIVERSE_ID}" Channel="{midi_ch}"/>
</Button>"""
def bg_color(r: int, g: int, b: int) -> str:
# QLC packed ARGB as decimal
return str((0xFF << 24) | (r << 16) | (g << 8) | b)
def build(uid: str) -> str:
functions = []
buttons = []
for i, (name, r, g, b, w) in enumerate(PAD_COLORS):
fid = 10 + i
note = 36 + i
midi_ch = (PAD_MIDI_CH << 12) | (128 + note)
functions.append(scene_xml(fid, name, r, g, b, w))
row, col = divmod(i, 4)
# pad grid: bottom row is notes 36-39 → visual row 3
vx = 20 + col * 80
vy = 20 + (3 - row) * 66
buttons.append(
button_xml(10 + i, name, vx, vy, fid, midi_ch, bg_color(r, g, b))
)
sliders = []
for i, (cc, cap, wid, dmx, fg, cng, val, fxs) in enumerate(KNOB_BANK1):
sliders.append(
slider(
wid,
cap,
360 + i * 58,
20,
dmx,
fg=fg,
cng=cng,
value=val,
midi_cc=cc,
fixtures=fxs,
)
)
for i, (cc, cap, wid, fx) in enumerate(KNOB_BANK2):
sliders.append(
slider(
wid,
cap,
360 + i * 58,
310,
0, # Dim
fg="4294967295",
cng="None",
value=200,
midi_cc=cc,
fixtures=[fx],
height=120,
)
)
vc_widgets = "\n".join(buttons + sliders)
funcs = "\n".join(functions)
fixtures = fixtures_xml()
dmx_out = output_xml()
return f"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Workspace>
<Workspace xmlns="http://www.qlcplus.org/Workspace" CurrentWindow="VirtualConsole">
<Creator>
<Name>Q Light Controller Plus</Name>
<Version>4.12.7</Version>
<Author>Jimmy</Author>
</Creator>
<Engine>
<InputOutputMap>
<Universe Name="Universe 1" ID="0">
{dmx_out}
</Universe>
<Universe Name="Universe 2" ID="1">
<Input Plugin="MIDI" UID="{uid}" Line="0" Profile="{PROFILE_NAME}">
<PluginParameters midichannel="{OMNI_MIDICHANNEL}"/>
</Input>
</Universe>
<Universe Name="Universe 3" ID="2"/>
<Universe Name="Universe 4" ID="3"/>
</InputOutputMap>
{fixtures}
{funcs}
</Engine>
<VirtualConsole>
<Frame Caption="">
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>Default</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
{vc_widgets}
</Frame>
<Properties>
<Size Width="900" Height="460"/>
<GrandMaster ChannelMode="Intensity" ValueMode="Reduce" SliderMode="Normal"/>
</Properties>
</VirtualConsole>
<SimpleDesk>
<Engine/>
</SimpleDesk>
</Workspace>
"""
def patch_qsettings(uid: str) -> None:
conf = Path.home() / ".config" / "qlcplus" / "Q Light Controller Plus.conf"
if not conf.exists():
return
text = conf.read_text()
key = uid.replace(" ", "%20")
pattern = rf"(Input\\{re.escape(key)}\\midichannel=)\d+"
if re.search(pattern, text):
text = re.sub(pattern, rf"\g<1>{OMNI_MIDICHANNEL}", text)
elif "[midiplugin]" in text and f"Input\\{key}\\midichannel=" not in text:
text = text.replace(
"[midiplugin]\n",
f"[midiplugin]\nInput\\{key}\\midichannel={OMNI_MIDICHANNEL}\n"
f"Input\\{key}\\mode=Control Change\n"
f"Input\\{key}\\initmessage=\n",
1,
)
conf.write_text(text)
def main() -> None:
uid = detect_midi_uid()
install_profile()
patch_qsettings(uid)
OUT.write_text(build(uid))
ui_start = BCC_START_ADDRESS + 1
ui_last = BCC_START_ADDRESS + BCC_COUNT * BCC_CHANNELS
print(f"Wrote {OUT}")
print(f" MIDI: {uid} OMNI on Universe 2")
print(
f" Art-Net → {ARTNET_OUTPUT_IP} uni {ARTNET_OUTPUT_UNI} "
f"(local {detect_artnet_uid()})"
)
print(
f" {BCC_COUNT}× BCC145 8ch @ UI {ui_start}–{ui_last} "
f"(XML Address {BCC_START_ADDRESS}–{BCC_START_ADDRESS + (BCC_COUNT - 1) * BCC_CHANNELS})"
)
print(" Bank1 knobs 1–8: Dim/RGBW/Strobe/Macro/Speed (all)")
print(" Bank2 knobs 9–15: Dim for #9–#15")
print(" 16 pads → colour scenes (all fixtures; strobe/macro forced off)")
if __name__ == "__main__":
main()
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env bash
# Reliable MIDI bring-up for shows/midi.qxw
#
# Order matters:
# 1) pad present (Bluetooth or USB)
# 2) pad controller (creates "padcontroller")
# 3) patch workspace to that port
# 4) open QLC+ last
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
cd "$ROOT"
PYTHON="${ROOT}/.venv/bin/python"
[[ -x "$PYTHON" ]] || PYTHON=python3
pad_present() {
aconnect -l 2>/dev/null | grep -Eq "SMC-PAD Bluetooth|SINCO|SMC-PAD"
}
echo "Waiting for SMC-PAD (Bluetooth or USB)…"
for _ in $(seq 1 30); do
if pad_present; then
break
fi
sleep 1
done
if ! pad_present; then
echo "No SMC-PAD in aconnect -l. Pair/connect the pad, then re-run." >&2
aconnect -l >&2 || true
exit 1
fi
# Restart the pad controller so it re-opens the pad port cleanly. Use the systemd
# user service when it is installed (padcontroller/systemd/install.sh).
SERVICE=padcontroller.service
LOG=/tmp/padcontroller.log
if systemctl --user is-enabled --quiet "$SERVICE" 2>/dev/null; then
systemctl --user restart "$SERVICE"
LOG=
else
# avoid pkill -f; it matches this script
while read -r pid; do
[[ -n "$pid" ]] && kill "$pid" 2>/dev/null || true
done < <(ps -eo pid,args | awk '/python.* -m padcontroller[.]midi/ {print $1}')
sleep 0.4
nohup "$PYTHON" -m padcontroller.midi --tau 0.055 >>"$LOG" 2>&1 &
fi
for _ in $(seq 1 20); do
if aconnect -l 2>/dev/null | grep -q 'padcontroller'; then
break
fi
sleep 0.25
done
if ! aconnect -l 2>/dev/null | grep -q 'padcontroller'; then
echo "The pad controller failed to create padcontroller." >&2
if [[ -n "$LOG" ]]; then
tail -20 "$LOG" >&2 || true
else
journalctl --user -u "$SERVICE" -n 20 --no-pager >&2 || true
fi
exit 1
fi
python3 scripts/pad/patch_smc_pad.py
kill "$(pgrep -x qlcplus)" 2>/dev/null || true
sleep 0.5
nohup qlcplus --open "$ROOT/shows/midi.qxw" >/tmp/qlcplus.log 2>&1 &
sleep 1.5
echo
echo "Chain (expect pad → padcontroller → qlcplus):"
aconnect -l | grep -E "SMC-PAD|SINCO|padcontroller|qlcplus" -A2 || aconnect -l
echo
echo "OK — twist a knob / hit a pad. If silent: re-run this script (don't pick Midi Through in IO)."
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env bash
# Launch Mover Pattern Studio (local web app) for the shows in this repo.
# scripts/pattern_studio.sh # opens http://127.0.0.1:8765 in your browser
# scripts/pattern_studio.sh --port 9000 --no-browser
set -euo pipefail
cd "$(dirname "$0")/.."
exec python3 -m patternstudio "$@"
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Add two sets of 16 colour scenes and their buttons to shows/test.show.json.
Colour 1 paints all 15 cans and colour 2 the four movers, so one colour
for each can be on at once. Each set is a solo frame and every scene
fades in and out over FADE_MS. Bank 2 (notes 52–67) picks colour 1.
Holding Play picks set B: the pad controller turns those notes into 68–83 while
Play is down. Bank 1 is kept for animations.
python3 scripts/shows/colour_sets.py && python3 -m showfile write shows/test.show.json -o shows/test.qxw
The sliders are Playback sliders over five scenes per set (Dim, R, G, B, W),
so they never override a channel. Knobs 1–5 move colour 1's sliders and knobs
6–10 colour 2's. Run the pad controller with --lock-knobs to make them work only
after the Custom pad is pressed; any other pad sends them back to zero (see
padcontroller/layer.py).
"""
from __future__ import annotations
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SPEC = ROOT / "shows" / "test.show.json"
FADE_MS = 1000
DIMMER, RED, GREEN, BLUE, WHITE = 0, 2, 3, 4, 5
PAD_BANK_2_FIRST_NOTE = 52
HELD_FIRST_NOTE = 68 # padcontroller/layer.py sends bank 2 here while Play is held
PROFILE = "M-VAVE SMC-PAD"
OMNI = 16 # QLC+ MIDI plugin channel that accepts every MIDI channel
PAD_MIDI_CH = 9 # the pads send notes on channel 10
KNOB_FIRST_CC = 30 # pad knob 1; colour 2's sliders follow colour 1's
PAD_PORT = "padcontroller" # padcontroller/midi.py; it applies the Play layer
# name, r, g, b, w. Bottom row first, four to a row. The cans have a white emitter, so the whites use it.
COLOURS = (
("Red", 255, 0, 0, 0),
("Orange", 255, 127, 0, 0),
("Yellow", 255, 255, 0, 0),
("Lime", 127, 255, 0, 0),
("Green", 0, 255, 0, 0),
("Spring", 0, 255, 127, 0),
("Cyan", 0, 255, 255, 0),
("Azure", 0, 127, 255, 0),
("Blue", 0, 0, 255, 0),
("Violet", 127, 0, 255, 0),
("Magenta", 255, 0, 255, 0),
("Pink", 255, 40, 120, 0),
("Warm", 255, 120, 40, 120),
("White", 0, 0, 0, 255),
("Cool", 80, 120, 255, 120),
)
# The top-right pad is the custom colour. Its button shows this swatch, but
# its scene is dark: the sliders next to it mix the colour from five scenes.
# Its pad lamp stays off.
CUSTOM = (("Custom", 255, 60, 0, 0),)
CANS = [f"#{n}" for n in range(1, 16)]
MOVERS = ["M1", "M2", "M3", "M4"]
# Mover channels: 8 is centre brightness, 9 centre strobe, then seven R G B W groups from 10.
MOVER_BRIGHTNESS, MOVER_STROBE, MOVER_GROUPS, MOVER_FIRST_COLOUR = 8, 9, 7, 10
def swatch(r: int, g: int, b: int, w: int) -> list[int]:
return [min(255, r + w), min(255, g + w), min(255, b + w)]
# Mixer beside each grid: caption, can channel, offset in a mover colour group (None is brightness).
SLIDERS = (
("Dim", DIMMER, None, [255, 255, 255]),
("R", RED, 0, [255, 0, 0]),
("G", GREEN, 1, [0, 255, 0]),
("B", BLUE, 2, [0, 0, 255]),
("W", WHITE, 3, [255, 255, 255]),
)
def component(cans: list[str], movers: list[str], can_channel: int, offset: int | None) -> dict:
"""One channel kind of this set at full, for a Playback slider to scale."""
values = {can: {can_channel: 255} for can in cans}
for mover in movers:
if offset is None:
values[mover] = {MOVER_BRIGHTNESS: 255}
else:
values[mover] = {MOVER_FIRST_COLOUR + group * 4 + offset: 255 for group in range(MOVER_GROUPS)}
return values
def custom_off(cans: list[str], movers: list[str]) -> dict:
"""The Custom pad's own scene: dark, so the sliders' scenes set the colour."""
values = {can: {DIMMER: 0} for can in cans}
values.update({mover: {MOVER_BRIGHTNESS: 0} for mover in movers})
return values
def sliders(label: str, first_cc: int) -> list[dict]:
"""Playback sliders. Each scales its own scene, so nothing is overridden."""
return [{
"type": "slider", "caption": caption, "function": f"custom_{label}_{caption}",
"x": 400 + index * 52, "y": 10, "w": 48, "h": 200, "fg": fg,
"input": {"universe": 1, "cc": [0, first_cc + index]},
} for index, (caption, _can, _offset, fg) in enumerate(SLIDERS)]
def main() -> None:
spec = json.loads(SPEC.read_text())
spec["universes"][1]["input"] = {"plugin": "MIDI", "uid": PAD_PORT, "profile": PROFILE, "channel": OMNI, "line": 0}
functions, frames = [], []
for si, (label, cans, movers) in enumerate((("1", CANS, []), ("2", [], MOVERS))):
buttons = []
for i, (name, r, g, b, w) in enumerate(COLOURS + CUSTOM):
key = f"colour_{label}_{i + 1}"
on = 255
values = {can: {DIMMER: on, RED: r, GREEN: g, BLUE: b, WHITE: w} for can in cans}
for mover in movers:
values[mover] = {MOVER_BRIGHTNESS: on, MOVER_STROBE: 0}
for group in range(MOVER_GROUPS):
first = MOVER_FIRST_COLOUR + group * 4
values[mover].update({first: r, first + 1: g, first + 2: b, first + 3: w})
if name == CUSTOM[0][0]:
values = custom_off(cans, movers)
functions.append({
"key": key, "type": "scene", "name": f"{label} {name}",
"fade_in": FADE_MS, "fade_out": FADE_MS, "values": values,
})
sw = swatch(r, g, b, w)
dark = sum(sw) > 380
button = {
"type": "button", "caption": name, "function": key,
# 4 wide like the pads: the first four colours are the bottom row.
"x": 10 + (i % 4) * 96, "y": 10 + (3 - i // 4) * 66, "w": 90, "h": 60,
"bg": sw,
"fg": [0, 0, 0] if dark else [255, 255, 255],
}
button["input"] = {"universe": 1, "note": [PAD_MIDI_CH, (HELD_FIRST_NOTE if si else PAD_BANK_2_FIRST_NOTE) + i]}
buttons.append(button)
for caption, can_channel, offset, _fg in SLIDERS:
functions.append({
"key": f"custom_{label}_{caption}", "type": "scene", "name": f"{label} Custom {caption}",
"values": component(cans, movers, can_channel, offset),
})
frames.append({
"type": "solo", "caption": f"Colour {label}", "x": 10, "y": 10 + si * 310,
"w": 400 + len(SLIDERS) * 52, "h": 300, "children": buttons + sliders(label, KNOB_FIRST_CC + si * len(SLIDERS)),
})
spec["functions"] = functions
spec["vc"] = frames
SPEC.write_text(json.dumps(spec, indent=2) + "\n")
if __name__ == "__main__":
main()
@@ -5,9 +5,9 @@ Traces QLC+'s Eight path (pan = -sin(2t), tilt = cos(t)), rides focus
with throw so the spot stays a similar size, and walks hue around the loop.
The whole 8 slowly drifts in a circle so it does not sit in one place.
python3 scripts/figure8_small_eye.py
python3 scripts/figure8_small_eye.py --write-qxw shows/small_eye.qxw
python3 scripts/figure8_small_eye.py --merge-xchc shows/xchc.qxw
python3 scripts/shows/figure8_small_eye.py
python3 scripts/shows/figure8_small_eye.py --write-qxw shows/small_eye.qxw
python3 scripts/shows/figure8_small_eye.py --merge-xchc shows/xchc.qxw
Stop QLC+ output before live mode so the two sources do not fight.
Quit live mode with Ctrl+C (sends blackout).
@@ -22,7 +22,7 @@ import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tests"))
from test_small_eye import (
@@ -182,7 +182,7 @@ def monitor_xml() -> str:
def main():
path = Path(__file__).resolve().parents[1] / "shows" / "xchc.qxw"
path = Path(__file__).resolve().parents[2] / "shows" / "xchc.qxw"
text = path.read_text()
for i, (name, rgb) in enumerate(COLORS.items()):
@@ -9,7 +9,7 @@ import subprocess
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
OUT = ROOT / "shows" / "cabaret.qxw"
ARTNET_NODE_FALLBACK = "192.168.1.227"
ARTNET_PORT = 6454
+325
View File
@@ -0,0 +1,325 @@
#!/usr/bin/env python3
"""Write a Chataigne project from a show spec.
python3 scripts/shows/make_chataigne.py shows/test.show.json chataigne/test
Writes <out>/<name>.noisette and <out>/<name>.js. The script holds the scenes and
the pad and slider mapping, and sends DMX through the project's DMX module, named Lights, and a copy to Preview. Solo
frames and scene fades follow what QLC+ does with the same spec.
"""
from __future__ import annotations
import argparse
import json
import struct
import zlib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
TEMPLATE = ROOT / "chataigne" / "show.template.js"
def absolute_levels(show: dict, stage: dict, values: dict[str, dict[str, int]]) -> dict[int, int]:
"""Map a scene's fixture channels to 1-based DMX channels in the output universe."""
levels: dict[int, int] = {}
for key, channels in values.items():
fixture = stage["fixtures"][key]
for offset, level in channels.items():
levels[int(fixture["address"]) + int(offset) + 1] = int(level)
return levels
SCALE = 1.25
MARGIN = 10
BUTTON = 28
def clear_png() -> bytes:
"""A 4x4 fully transparent PNG, for a trigger that should show what is behind it."""
def chunk(kind: bytes, data: bytes) -> bytes:
body = kind + data
return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body))
rows = b"".join(b"\x00" + b"\x00" * 16 for _ in range(4))
return (
b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", struct.pack(">IIBBBBB", 4, 4, 8, 6, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(rows))
+ chunk(b"IEND", b"")
)
def script_path(name: str) -> str:
"""Chataigne names the script after its file and the module after its title."""
return f"/modules/pad/scripts/{name}/params/"
def ident(prefix: str, number: int, name: str) -> str:
"""A control name Chataigne keeps as written: letters and digits, lower-case first."""
return f"{prefix}{number}" + "".join(c for c in name if c.isalnum())
def collect(show: dict, stage: dict) -> dict:
functions = {f["key"]: f for f in show["functions"]}
groups: dict[str, dict] = {}
for number, frame in enumerate(show["vc"], 1):
pads, sliders = [], []
for widget in frame.get("children", []):
kind = widget["type"]
function = functions[widget["function"]]
binding = widget.get("input") or {}
levels = absolute_levels(show, stage, function["values"])
if kind == "button" and "note" in binding:
pads.append({
"id": ident("c", number, widget["caption"]),
"box": box(frame, widget),
"bg": widget.get("bg", [60, 60, 60]),
"fg": widget.get("fg", [255, 255, 255]),
"note": binding["note"][1],
"name": widget["caption"],
"fade": [function.get("fade_in") or 0, function.get("fade_out") or 0],
"levels": levels,
})
elif kind == "slider" and "cc" in binding:
sliders.append({
"id": ident("s", number, widget["caption"]),
"box": box(frame, widget),
"fg": widget.get("fg", [255, 255, 255]),
"cc": binding["cc"][1],
"name": widget["caption"],
"levels": levels,
})
if pads or sliders:
groups[frame["caption"]] = {
"name": frame["caption"],
"now": f"now{number}",
"box": box(frame, {"x": 0, "y": -30, "w": frame["w"], "h": 26}),
"pads": pads,
"sliders": sliders,
}
return groups
def box(frame: dict, widget: dict) -> list[int]:
"""x, y, w, h of a widget on the dashboard. Frames sit side by side, as on the virtual console."""
return [round((frame["x"] + widget["x"]) * SCALE), round((frame["y"] + widget["y"]) * SCALE + 40),
round(widget["w"] * SCALE), round(widget["h"] * SCALE)]
def colour(rgb: list[int]) -> int:
"""A Chataigne colour value: ARGB as a signed 32-bit int."""
argb = (255 << 24) | (rgb[0] << 16) | (rgb[1] << 8) | rgb[2]
return argb - (1 << 32) if argb >= 1 << 31 else argb
def js_levels(levels: dict[int, int]) -> str:
return "[" + ",".join(f"{ch},{level}" for ch, level in sorted(levels.items())) + "]"
def render_data(groups: dict) -> str:
lines = ["var GROUPS = ["]
for caption, group in groups.items():
lines.append(" {")
lines.append(f" name: {json.dumps(caption)},")
lines.append(f" now: {json.dumps(group['now'])},")
lines.append(" pads: [")
for pad in group["pads"]:
lines.append(
f" {{id: {json.dumps(pad['id'])}, rgb: {json.dumps([round(c / 255, 3) for c in pad['bg']])}, note: {pad['note']}, name: {json.dumps(pad['name'])}, "
f"fadeIn: {pad['fade'][0]}, fadeOut: {pad['fade'][1]}, levels: {js_levels(pad['levels'])}}},"
)
lines.append(" ],")
lines.append(" sliders: [")
for slider in group["sliders"]:
lines.append(
f" {{id: {json.dumps(slider['id'])}, cc: {slider['cc']}, name: {json.dumps(slider['name'])}, levels: {js_levels(slider['levels'])}}},"
)
lines.append(" ]")
lines.append(" },")
lines.append("];")
return "\n".join(lines)
def dashboard_item(index: int, kind: str, target: str, box: list[int], label: str, colours: dict[str, list[int]]) -> dict:
parameters = [
{"value": [float(box[0]), float(box[1])], "controlAddress": "/viewUIPosition"},
{"value": [float(box[2]), float(box[3])], "controlAddress": "/viewUISize"},
{"value": target, "controlAddress": "/target"},
{"value": label, "controlAddress": "/customText", "enabled": True},
]
for address, rgb in colours.items():
parameters.append({"value": colour(rgb), "controlAddress": address, "enabled": True})
return {
"parameters": parameters,
"niceName": f"Item {index}",
"type": kind,
"ghostAddress": target,
"controllable": target,
}
def dashboard(groups: dict, name: str, view: tuple[int, int], overlay: str | None) -> dict:
"""A dashboard with a tile and button per pad, a slider per knob, and what each group is showing."""
items = []
for group in groups.values():
items.append(dashboard_item(
len(items) + 1, "DashboardParameterItem", script_path(name) + group["now"],
group["box"], group["name"], {},
))
for pad in group["pads"]:
x, y, w, h = pad["box"]
# Triggers draw grey whatever colour they are given, but a colour control always paints.
# The tile carries the colour and name; the trigger on it is a transparent image that takes the press.
small = overlay is None
tile = dashboard_item(
len(items) + 1, "DashboardParameterItem", script_path(name) + pad["id"] + "Lamp",
[x, y, w, h - BUTTON - 2 if small else h], pad["name"], {"/textColor": [255, 255, 255]},
)
tile["parameters"] += [
{"value": True, "controlAddress": "/readOnly"},
{"value": False, "controlAddress": "/showValue"},
]
items.append(tile)
press = dashboard_item(
len(items) + 1, "DashboardTriggerItem", script_path(name) + pad["id"],
[x, y + h - BUTTON, w, BUTTON] if small else [x, y, w, h], "Select" if small else "",
{"/backgroundColor": pad["bg"], "/textColor": pad["fg"]},
)
if overlay:
# A custom label that is a single space: with none, the trigger draws its own name.
press["parameters"][3].update({"value": " ", "enabled": True})
press["parameters"].append({"value": False, "controlAddress": "/showLabel"})
press["parameters"].append({"value": overlay, "controlAddress": "/customImage", "enabled": True})
items.append(press)
for slider in group["sliders"]:
items.append(dashboard_item(
len(items) + 1, "DashboardParameterItem", script_path(name) + slider["id"], slider["box"], slider["name"],
{"/foregroundColor": slider["fg"]},
))
# Dashboard coordinates start at the middle of the view, so move the board to its top left.
left = min(i["parameters"][0]["value"][0] for i in items)
top = min(i["parameters"][0]["value"][1] for i in items)
for i in items:
position = i["parameters"][0]["value"]
position[0] += MARGIN - view[0] / 2 - left
position[1] += MARGIN - view[1] / 2 - top
return {
"parameters": [{"value": False, "controlAddress": "/editMode"}],
"items": [
{
"niceName": "Board",
"type": "BaseItem",
"itemManager": {
# The web page puts the middle of the canvas at 0, 0, so the canvas has to be the view's size
# for the board to start at its top left.
"parameters": [{"value": [float(view[0]), float(view[1])], "controlAddress": "/canvasSize", "enabled": True}],
"items": items,
"viewOffset": [0, 0],
"viewZoom": 1.0,
},
}
],
"viewOffset": [0, 0],
"viewZoom": 1.0,
}
def dmx_module(name: str, host: str, universe: int, interface: str | None) -> dict:
device: dict = {"containers": {"output": {"parameters": [{"value": host, "controlAddress": "/remoteHost"}]}}}
if interface:
device["parameters"] = [{"value": interface, "controlAddress": "/networkInterface"}]
return {
"niceName": name,
"type": "DMX",
"params": {
"parameters": [
{"value": "Art-Net", "controlAddress": "/dmxType"},
{"value": 40, "controlAddress": "/sendRate"},
],
"containers": {
"artNet": {"containers": {"output": {"parameters": [{"value": host, "controlAddress": "/remoteHost"}]}}},
"outputUniverses": {
"items": [
{
"niceName": "Universe",
"parameters": [
{"value": 0, "controlAddress": "/net"},
{"value": 0, "controlAddress": "/subnet"},
{"value": universe, "controlAddress": "/universe"},
],
}
]
}
},
},
"device": device,
}
def project(
script: str, host: str, universe: int, interface: str, groups: dict, preview: str | None, pad: str, view: tuple[int, int], overlay: str | None
) -> dict:
"""A Chataigne project: a DMX module on Art-Net and a MIDI module that runs the show script."""
dmx = [dmx_module("Lights", host, universe, interface)]
if preview:
dmx.append(dmx_module("Preview", preview, universe, None))
midi = {
"niceName": "Pad",
"type": "MIDI",
"params": {"parameters": [{"value": [pad, ""], "inputName": pad, "controlAddress": "/devices"}]},
"scripts": {
"items": [{"niceName": "Show", "parameters": [{"value": script, "controlAddress": "/filePath"}]}]
},
}
return {
"metaData": {"version": "1.10.4"},
"projectSettings": {
"containers": {
"dashboardSettings": {
"parameters": [
{"value": True, "controlAddress": "/enableDashboardServer"},
{"value": 9999, "hexMode": False, "controlAddress": "/serverPort"},
]
}
}
},
"dashboardManager": dashboard(groups, Path(script).stem, view, overlay),
"modules": {"viewOffset": [0, 0], "viewZoom": 1.0, "items": [*dmx, midi]},
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("show", type=Path)
parser.add_argument("out", type=Path, help="directory to write into")
parser.add_argument("--host", help="Art-Net destination (default: from the show's output universe)")
parser.add_argument("--pad", default="SINCO SMC-PAD-Master", help="MIDI input the pad arrives on (Bluetooth: SMC-PAD Bluetooth)")
parser.add_argument("--view", default="1574x953", help="dashboard panel size in pixels, for the top-left placement")
parser.add_argument("--small-buttons", action="store_true", help="a grey Select button under each tile, instead of the whole tile pressing")
parser.add_argument("--preview", default="127.0.0.1", help="second Art-Net destination for the simulator; empty for none")
args = parser.parse_args()
show = json.loads(args.show.read_text())
stage = json.loads((ROOT / show["stage"]).read_text())
output = next(u["output"] for u in show["universes"] if u.get("output", {}).get("plugin") == "ArtNet")
name = args.show.name.removesuffix(".show.json")
groups = collect(show, stage)
source = TEMPLATE.read_text().replace("/*__DATA__*/", render_data(groups))
args.out.mkdir(parents=True, exist_ok=True)
(args.out / f"{name}.js").write_text(source)
overlay = None if args.small_buttons else str((args.out / "clear.png").resolve())
if overlay:
(args.out / "clear.png").write_bytes(clear_png())
doc = project(f"{name}.js", args.host or output["ip"], int(output["universe"]), output["uid"], groups, args.preview or None, args.pad, tuple(int(n) for n in args.view.split("x")), overlay)
(args.out / f"{name}.noisette").write_text(json.dumps(doc, indent=2) + "\n")
print(f"{args.out / (name + '.noisette')}: {len(groups)} groups, {sum(len(g['pads']) for g in groups.values())} pads")
if __name__ == "__main__":
main()
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env python3
"""Compile shows/simple.show.json into shows/simple.qxw."""
from __future__ import annotations
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from showfile.tools import write_show
def main() -> None:
spec = json.loads((ROOT / "shows" / "simple.show.json").read_text(encoding="utf-8"))
result = write_show(spec, "shows/simple.qxw", root=ROOT)
if not result["ok"]:
raise SystemExit(json.dumps(result, indent=2))
print(f"Wrote {result['path']} ({len(result['widgets'])} widgets)")
if __name__ == "__main__":
main()
+210
View File
@@ -0,0 +1,210 @@
#!/usr/bin/env python3
"""Add mover versions of the bank 1 pads to shows/test.qxw, on notes 84–99.
Pause on the pad toggles bank 1 between the cans and the movers: padcontroller
sends bank 1 (notes 36–51) as 84–99 while it is on (padcontroller/layer.py).
Each mover pad sits on its can pad's note plus 48:
92 Strobe flash the movers' centre strobe
96 Chase a stripe through the 7 rings of all four movers
97 Reverse the same, the other way
98 Zigzag mover by mover, M3, M1, M2, M4 (back, front, front, back)
99 Opposing rings outwards on the left movers, inwards on the right
The chases take their colour from the Colour 1 (cans) pads, as the cans'
chases take theirs from Colour 2, so they stand out. Knob 15 (CC 44), the
movers' level, is also their peak. The movers are not sound reactive: Sound and
Threshold (84 and 85) do nothing on their layer.
python3 scripts/shows/mover_bank.py
Run it once on a show without them; it stops if they are already there.
QLC+ has to reopen the show to see them.
"""
from __future__ import annotations
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SHOW = ROOT / "shows" / "test.qxw"
MOVERS_SHIFT = 48 # padcontroller/layer.py
NOTE_BASE = 36992 # QLC+ input channel of a channel-10 note: this plus the note
LEVEL_CC = 44 # knob 15: the Movers level slider, and the movers' peak here
# Fixture IDs left to right on stage: M3 back left, M1 and M2 front, M4 back right.
M1, M2, M3, M4 = 8, 9, 17, 18
LEFT_TO_RIGHT = (M3, M1, M2, M4)
RINGS = 7
BRIGHTNESS, STROBE = 8, 9
GROUP_RINGS, GROUP_ZIGZAG, GROUP_OPPOSING = 5, 6, 7
F_DIMMER, F_FWD, F_HOLD, F_REV, F_ZIG, F_ZIG_HOLD, F_OPP, F_STROBE = range(57, 65)
NO_FUNCTION = 4294967295
def note(can_note: int) -> int:
return NOTE_BASE + can_note + MOVERS_SHIFT
def group(gid: int, name: str, w: int, h: int, heads: list[tuple[int, int, int, int]]) -> str:
rows = "\n".join(f' <Head X="{x}" Y="{y}" Fixture="{f}">{head}</Head>' for x, y, f, head in heads)
return f' <FixtureGroup ID="{gid}">\n <Name>{name}</Name>\n <Size X="{w}" Y="{h}"/>\n{rows}\n </FixtureGroup>\n'
def groups() -> str:
# Rings down Y, one mover per column.
rings = [(x, r, f, r) for x, f in enumerate(LEFT_TO_RIGHT) for r in range(RINGS)]
# One mover per row, its rings across.
zigzag = [(r, y, f, r) for y, f in enumerate(LEFT_TO_RIGHT) for r in range(RINGS)]
# Left movers' rings run outwards as the right movers' run inwards.
opposing = [(x, y, f, y if x < 2 else RINGS - 1 - y) for x, f in enumerate(LEFT_TO_RIGHT) for y in range(RINGS)]
return (group(GROUP_RINGS, "Movers rings", 4, RINGS, rings)
+ group(GROUP_ZIGZAG, "Movers zigzag", RINGS, 4, zigzag)
+ group(GROUP_OPPOSING, "Movers opposing", 4, RINGS, opposing))
def scene(fid: int, name: str, values: dict[int, int], fade_out: int = 0) -> str:
vals = ",".join(f"{c},{v}" for c, v in values.items())
rows = "\n".join(f' <FixtureVal ID="{f}">{vals}</FixtureVal>' for f in LEFT_TO_RIGHT)
return (f' <Function ID="{fid}" Type="Scene" Name="{name}">\n'
f' <Speed FadeIn="0" FadeOut="{fade_out}" Duration="0"/>\n{rows}\n </Function>\n')
def matrix(fid: int, name: str, gid: int, direction: str, step_ms: int) -> str:
return f""" <Function ID="{fid}" Type="RGBMatrix" Name="{name}">
<Speed FadeIn="0" FadeOut="500" Duration="{step_ms}"/>
<Direction>{direction}</Direction>
<RunOrder>SingleShot</RunOrder>
<Algorithm Type="Script">Stripes</Algorithm>
<MonoColor>4294967040</MonoColor>
<ControlMode>RGB</ControlMode>
<FixtureGroup>{gid}</FixtureGroup>
<Property Name="orientation" Value="Vertical"/>
</Function>
"""
def chaser(fid: int, name: str, ms: int, step: int) -> str:
return f""" <Function ID="{fid}" Type="Chaser" Name="{name}">
<Speed FadeIn="0" FadeOut="0" Duration="{ms}"/>
<Direction>Forward</Direction>
<RunOrder>SingleShot</RunOrder>
<SpeedModes FadeIn="Common" FadeOut="Common" Duration="Common"/>
<Step Number="0" FadeIn="0" Hold="0" FadeOut="0">{step}</Step>
</Function>
"""
def functions() -> str:
# Each hold keeps the movers up while its run steps through, plus the run's fade.
return (scene(F_DIMMER, "Movers dimmer", {BRIGHTNESS: 255, STROBE: 0})
+ matrix(F_FWD, "Movers chase forward run", GROUP_RINGS, "Forward", 200)
+ chaser(F_HOLD, "Movers dimmer hold", RINGS * 200 + 500, F_DIMMER)
+ matrix(F_REV, "Movers chase reverse run", GROUP_RINGS, "Backward", 200)
+ matrix(F_ZIG, "Movers zigzag run", GROUP_ZIGZAG, "Forward", 200)
+ chaser(F_ZIG_HOLD, "Movers zigzag hold", 4 * 200 + 500, F_DIMMER)
+ matrix(F_OPP, "Movers opposing run", GROUP_OPPOSING, "Forward", 200)
+ scene(F_STROBE, "Movers strobe", {BRIGHTNESS: 255, STROBE: 230}, fade_out=50))
def appearance(indent: str, style: str = "None") -> str:
return (f"{indent}<Appearance>\n{indent} <FrameStyle>{style}</FrameStyle>\n"
f"{indent} <ForegroundColor>Default</ForegroundColor>\n{indent} <BackgroundColor>Default</BackgroundColor>\n"
f"{indent} <BackgroundImage>None</BackgroundImage>\n{indent} <Font>Default</Font>\n{indent}</Appearance>\n")
def button(wid: int, caption: str, x: int, y: int, size: int, function: int, channel: int | None,
action: str = "Toggle", indent: str = " ") -> str:
inp = f'{indent} <Input Universe="1" Channel="{channel}"/>\n' if channel is not None else ""
return (f'{indent}<Button Caption="{caption}" ID="{wid}" Icon="">\n'
f'{indent} <WindowState Visible="True" X="{x}" Y="{y}" Width="{size}" Height="{size}"/>\n'
+ appearance(indent + " ")
+ f'{indent} <Function ID="{function}"/>\n{indent} <Action>{action}</Action>\n'
f'{indent} <Intensity Adjust="False">100</Intensity>\n{inp}{indent}</Button>\n')
def submaster(wid: int, caption: str, x: int, y: int, h: int, cc: int, indent: str) -> str:
return (f'{indent}<Slider Caption="{caption}" ID="{wid}" WidgetStyle="Slider" InvertedAppearance="false">\n'
f'{indent} <WindowState Visible="True" X="{x}" Y="{y}" Width="52" Height="{h}"/>\n'
+ appearance(indent + " ", "Sunken")
+ f'{indent} <Input Universe="1" Channel="{cc}"/>\n'
f'{indent} <SliderMode ValueDisplayStyle="Exact" ClickAndGoType="None">Submaster</SliderMode>\n'
f'{indent} <Level LowLimit="0" HighLimit="255" Value="255"/>\n'
f'{indent} <Playback>\n{indent} <Function>{NO_FUNCTION}</Function>\n{indent} </Playback>\n{indent}</Slider>\n')
def frame(wid: int, caption: str, x: int, y: int, w: int, h: int, body: str, indent: str = " ",
header: bool = True, collapsed: bool = False) -> str:
return (f'{indent}<Frame Caption="{caption}" ID="{wid}">\n'
+ appearance(indent + " ", "Sunken")
+ f'{indent} <WindowState Visible="True" X="{x}" Y="{y}" Width="{w}" Height="{h}"/>\n'
f'{indent} <AllowChildren>True</AllowChildren>\n{indent} <AllowResize>True</AllowResize>\n'
f'{indent} <ShowHeader>{header}</ShowHeader>\n{indent} <ShowEnableButton>False</ShowEnableButton>\n'
f'{indent} <Collapsed>{collapsed}</Collapsed>\n{indent} <Disabled>False</Disabled>\n'
f'{body}{indent}</Frame>\n')
def vc(xml: str, next_id: int) -> str:
"""The new widgets."""
ids = iter(range(next_id, next_id + 100))
w = {name: next(ids) for name in (
"bank", "fwd", "rev", "zig", "opp", "strobe", "peak",
"runs", "fwd_run", "rev_run", "zig_run", "opp_run",
"colours", "fwd_col", "rev_col", "zig_col", "opp_col")}
bank = (button(w["fwd"], "Chase", 10, 10, 90, F_HOLD, note(48))
+ button(w["rev"], "Chase reverse", 100, 10, 90, F_HOLD, note(49))
+ button(w["zig"], "Zigzag", 190, 10, 90, F_ZIG_HOLD, note(50))
+ button(w["opp"], "Opposing", 280, 10, 90, F_HOLD, note(51))
+ button(w["strobe"], "Strobe", 10, 100, 90, F_STROBE, note(44), action="Flash")
+ submaster(w["peak"], "Peak", 378, 10, 360, LEVEL_CC, " "))
runs = (button(w["fwd_run"], "Chase run", 10, 10, 70, F_FWD, note(48))
+ button(w["rev_run"], "Reverse run", 80, 10, 70, F_REV, note(49))
+ button(w["zig_run"], "Zigzag run", 150, 10, 70, F_ZIG, note(50))
+ button(w["opp_run"], "Opposing run", 220, 10, 70, F_OPP, note(51)))
# The cans' Forward colour matrix follows the Colour 2 pads; these follow Colour 1, 16 notes lower.
template = re.search(r' <Matrix Caption="Forward colour" ID="61">.*? </Matrix>\n', xml, re.S).group(0)
def colour_matrix(wid: int, caption: str, fid: int, x: int, y: int) -> str:
m = template.replace('Caption="Forward colour" ID="61"', f'Caption="{caption}" ID="{wid}"')
m = m.replace('<Function ID="43" InstantApply', f'<Function ID="{fid}" InstantApply')
m = re.sub(r'X="\d+" Y="\d+" Width', f'X="{x}" Y="{y}" Width', m, count=1)
return re.sub(r'Channel="(\d+)"', lambda c: f'Channel="{int(c.group(1)) - 16}"', m)
colours = (colour_matrix(w["fwd_col"], "Movers chase colour", F_FWD, 10, 45)
+ colour_matrix(w["rev_col"], "Movers reverse colour", F_REV, 320, 45)
+ colour_matrix(w["zig_col"], "Movers zigzag colour", F_ZIG, 10, 275)
+ colour_matrix(w["opp_col"], "Movers opposing colour", F_OPP, 320, 275))
return (frame(w["bank"], "Movers pads", 1740, 5, 440, 380, bank, header=False)
+ frame(w["runs"], "Movers chase runs", 1740, 400, 310, 120, runs)
+ frame(w["colours"], "Movers chase colours", 1740, 530, 640, 510, colours, collapsed=True))
def main() -> None:
xml = SHOW.read_text()
if "Movers chase forward run" in xml:
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the mover pads")
next_id = max(int(i) for i in re.findall(r' ID="(\d+)"', xml.split("<VirtualConsole>")[1])
if int(i) != NO_FUNCTION) + 1
widgets = vc(xml, next_id)
# The strobe flash is HTP so it beats the colour scenes' centre strobe of 0, as on the cans.
for fid in LEFT_TO_RIGHT:
xml = re.sub(rf"( <ID>{fid}</ID>\n(?: .*\n)*? <Channels>43</Channels>\n)",
rf"\1 <ForcedHTP>{STROBE}</ForcedHTP>\n", xml, count=1)
xml = xml.replace(' <Function ID="0" Type="Scene"', groups() + ' <Function ID="0" Type="Scene"', 1)
xml = xml.replace(" </Engine>", functions() + " </Engine>", 1)
xml = xml.replace(" </Frame>\n <Properties>", widgets + " </Frame>\n <Properties>", 1)
xml = xml.replace('<Size Width="1880" Height="950"/>', '<Size Width="2400" Height="1050"/>', 1)
SHOW.write_text(xml)
print(f"Added the mover pads to {SHOW.relative_to(ROOT)} (widgets from ID {next_id})")
if __name__ == "__main__":
main()
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Add Pan, Tilt, Focus and Rotate sliders for the movers to shows/test.qxw.
As in templeoftechno.qxw, knobs 9–12 (CC 38–41) drive all four movers at once:
Knob 9 CC 38 Pan channel 0
Knob 10 CC 39 Tilt channel 2
Knob 11 CC 40 Focus channel 7
Knob 12 CC 41 Rotate channel 5 (Lens Rotate)
They sit in a Movers position frame beside Sound peak, below the cans' chase runs.
python3 scripts/shows/mover_position.py
Run it once on a show without them; it stops if they are already there.
QLC+ has to reopen the show to see them.
"""
from __future__ import annotations
import re
from pathlib import Path
from mover_bank import LEFT_TO_RIGHT, NO_FUNCTION, ROOT, appearance, frame
SHOW = ROOT / "shows" / "test.qxw"
# Caption, CC, mover channel, starting value: temple techno's.
SLIDERS = (
("Pan", 38, 0, 0),
("Tilt", 39, 2, 0),
("Focus", 40, 7, 70),
("Rotate", 41, 5, 0),
)
def level(wid: int, caption: str, x: int, cc: int, channel: int, value: int, indent: str = " ") -> str:
rows = "".join(f'{indent} <Channel Fixture="{f}">{channel}</Channel>\n' for f in LEFT_TO_RIGHT)
return (f'{indent}<Slider Caption="{caption}" ID="{wid}" WidgetStyle="Slider" InvertedAppearance="false">\n'
f'{indent} <WindowState Visible="True" X="{x}" Y="10" Width="52" Height="200"/>\n'
+ appearance(indent + " ", "Sunken")
+ f'{indent} <Input Universe="1" Channel="{cc}"/>\n'
f'{indent} <SliderMode ValueDisplayStyle="Exact" ClickAndGoType="None" Monitor="false">Level</SliderMode>\n'
f'{indent} <Level LowLimit="0" HighLimit="255" Value="{value}">\n{rows}{indent} </Level>\n'
f'{indent} <Playback>\n{indent} <Function>{NO_FUNCTION}</Function>\n{indent} </Playback>\n{indent}</Slider>\n')
def main() -> None:
xml = SHOW.read_text()
if 'Caption="Movers position"' in xml:
raise SystemExit(f"{SHOW.relative_to(ROOT)} already has the mover position sliders")
next_id = max(int(i) for i in re.findall(r' ID="(\d+)"', xml.split("<VirtualConsole>")[1])
if int(i) != NO_FUNCTION) + 1
sliders = "".join(level(next_id + 1 + i, caption, 10 + 58 * i, cc, channel, value)
for i, (caption, cc, channel, value) in enumerate(SLIDERS))
widgets = frame(next_id, "Movers position", 420, 630, 10 + 58 * len(SLIDERS), 250, sliders)
xml = xml.replace(" </Frame>\n <Properties>", widgets + " </Frame>\n <Properties>", 1)
SHOW.write_text(xml)
print(f"Added the mover position sliders to {SHOW.relative_to(ROOT)} (widgets from ID {next_id})")
if __name__ == "__main__":
main()
@@ -33,7 +33,7 @@ def btn(
</Button>"""
ROOT = Path(__file__).resolve().parents[1]
ROOT = Path(__file__).resolve().parents[2]
def main():
+23
View File
@@ -0,0 +1,23 @@
"""Build QLC+ workspaces and play their animations."""
from .model import ArtNetOutput, MidiBinding, MidiInput, Show, midi_cc, midi_note
from .play import frame_at, play
from .spec import SpecError, from_spec, show_schema
from .xmlutil import qlc_color
Show.from_spec = staticmethod(from_spec) # type: ignore[method-assign]
__all__ = [
"ArtNetOutput",
"MidiBinding",
"MidiInput",
"Show",
"SpecError",
"frame_at",
"from_spec",
"midi_cc",
"midi_note",
"play",
"qlc_color",
"show_schema",
]
+74
View File
@@ -0,0 +1,74 @@
"""Command line for the show tools. Each command prints one JSON object."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
from .spec import PROJECT_ROOT
from .tools import list_fixtures, run_script, sample_animation, show_schema, validate_show, write_show
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="showfile", description="Build and test QLC+ shows.")
sub = parser.add_subparsers(dest="cmd", required=True)
sub.add_parser("list-fixtures", help="List fixture modes and channel numbers.")
sub.add_parser("schema", help="Print the show spec JSON Schema.")
validate = sub.add_parser("validate", help="Validate a show spec without writing.")
validate.add_argument("spec")
write = sub.add_parser("write", help="Compile a show spec to a .qxw.")
write.add_argument("spec")
write.add_argument("-o", "--output", required=True)
sample = sub.add_parser("sample", help="Sample an efx or path block.")
sample.add_argument("block")
sample.add_argument("--steps", type=int, default=32)
run = sub.add_parser("run", help="Play a Python animation script or a JSON show.")
run.add_argument("script")
run.add_argument("--ip", help="Art-Net destination. Omit to print samples.")
run.add_argument("--seconds", type=float)
run.add_argument("--hz", type=float, default=40.0)
run.add_argument("--universe", type=int, default=0)
args = parser.parse_args(argv)
try:
payload = _dispatch(args)
except (OSError, json.JSONDecodeError) as exc:
payload = {"ok": False, "errors": [{"path": "", "message": str(exc)}]}
json.dump(payload, sys.stdout, indent=2)
sys.stdout.write("\n")
return 0 if payload.get("ok", True) else 1
def _dispatch(args: argparse.Namespace) -> dict[str, Any]:
if args.cmd == "list-fixtures":
return list_fixtures()
if args.cmd == "schema":
return show_schema()
if args.cmd == "validate":
return validate_show(_load(args.spec))
if args.cmd == "write":
return write_show(_load(args.spec), args.output)
if args.cmd == "sample":
return sample_animation(_load(args.block), args.steps)
if args.cmd == "run":
return run_script(args.script, seconds=args.seconds, ip=args.ip, universe=args.universe, hz=args.hz)
raise AssertionError(args.cmd)
def _load(path: str) -> dict[str, Any]:
source = Path(path)
if not source.is_absolute():
source = PROJECT_ROOT / source
return json.loads(source.read_text(encoding="utf-8"))
if __name__ == "__main__":
raise SystemExit(main())
+666
View File
@@ -0,0 +1,666 @@
"""EFX, sequences, paths, and chasers."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from patternstudio.efx import (
ALGORITHMS,
DIRECTIONS,
PROPAGATIONS,
RELATIVE_ZERO,
RUN_ORDERS,
Efx,
EfxFixture,
Path,
PathFixture,
PathPoint,
clamp8,
)
from .model import Show, blend_maps
from .xmlutil import attr
Axis = tuple[int | None, int | None, int | None, int | None]
def locate(
steps: list[Any],
elapsed_ms: float,
run_order: str,
direction: str,
) -> tuple[int, float, int | None, float]:
"""Return step index, fade progress, previous index, and ms into the step.
A looping timeline treats the last step as the fade source for the first,
so a loop is seamless. Single Shot fades the first step up from black and
holds the last step after the end.
"""
spans = [max(0, s.fade_ms) + max(0, s.hold_ms) + max(0, s.fade_out_ms) for s in steps]
total = float(sum(spans))
count = len(steps)
if count == 0 or total <= 0:
return 0, 1.0, None, 0.0
elapsed = max(0.0, float(elapsed_ms))
seamless = run_order != "SingleShot"
if run_order == "SingleShot" and elapsed >= total:
prev = count - 2 if count > 1 else None
return count - 1, 1.0, prev, spans[-1]
if run_order == "PingPong":
cycle = int(elapsed // total)
pos = elapsed % total
if cycle % 2 == 1:
pos = total - pos
elif run_order == "SingleShot":
pos = elapsed
else:
pos = elapsed % total
if direction == "Backward":
pos = total - pos
if pos >= total:
pos = total - 1e-6
if pos < 0:
pos = 0.0
acc = 0.0
for index, span in enumerate(spans):
fade = max(0, steps[index].fade_ms)
prev = None if index == 0 and not seamless else (index - 1) % count
if pos < acc + fade or span == 0:
prog = 1.0 if fade <= 0 else (pos - acc) / fade
return index, min(1.0, max(0.0, prog)), prev, pos - acc
if pos < acc + span or index == count - 1:
return index, 1.0, prev, pos - acc
acc += span
return count - 1, 1.0, None, spans[-1]
def _fixture(show: Show, item: Any) -> Any:
if isinstance(item, str):
return show.fixtures_by_key[item]
if isinstance(item, int) and not isinstance(item, bool):
return next(fx for fx in show.fixtures if fx.id == item)
return item
@dataclass
class EfxFunction:
id: int
key: str
name: str
pattern: Efx
homes: dict[int, tuple[int, int]]
relative: bool
axes: dict[int, Axis]
preview: dict[int, dict[int, int]]
primary: bool = True
type: str = "EFX"
def duration_ms(self, _show: Show) -> int:
return self.pattern.duration_ms
def apply(self, _show: Show, elapsed_ms: float, into: dict[int, dict[int, int]]) -> None:
for serial, fx in enumerate(self.pattern.fixtures):
bucket = into.setdefault(fx.id, {})
for ch, val in self.preview.get(fx.id, {}).items():
bucket.setdefault(ch, val)
point = self.pattern.live_point(serial, elapsed_ms)
if point is None:
continue
pan, tilt = point
if self.relative:
home_pan, home_tilt = self.homes.get(fx.id, (RELATIVE_ZERO, RELATIVE_ZERO))
pan = home_pan + (pan - RELATIVE_ZERO)
tilt = home_tilt + (tilt - RELATIVE_ZERO)
pan_msb, pan_lsb, tilt_msb, tilt_lsb = self.axes[fx.id]
_write_axis(bucket, pan_msb, pan_lsb, pan)
_write_axis(bucket, tilt_msb, tilt_lsb, tilt)
def render(self) -> str:
pattern = self.pattern
fixtures = "\n".join(
" <Fixture>\n"
f" <ID>{fx.id}</ID>\n"
f" <Head>{fx.head}</Head>\n"
f" <Direction>{fx.direction}</Direction>\n"
f" <StartOffset>{fx.start_offset}</StartOffset>\n"
" </Fixture>"
for fx in pattern.fixtures
)
return (
f' <Function ID="{self.id}" Type="EFX" Name={attr(self.name)}>\n'
f"{fixtures}\n"
f" <PropagationMode>{pattern.propagation}</PropagationMode>\n"
f' <Speed FadeIn="{pattern.fade_in_ms}" FadeOut="{pattern.fade_out_ms}" '
f'Duration="{pattern.duration_ms}"/>\n'
f" <Direction>{pattern.direction}</Direction>\n"
f" <RunOrder>{pattern.run_order}</RunOrder>\n"
f" <Algorithm>{pattern.algorithm}</Algorithm>\n"
f" <Width>{pattern.width}</Width>\n"
f" <Height>{pattern.height}</Height>\n"
f" <Rotation>{pattern.rotation}</Rotation>\n"
f" <StartOffset>{pattern.start_offset}</StartOffset>\n"
f" <IsRelative>{1 if self.relative else 0}</IsRelative>\n"
" <Axis Name=\"X\">\n"
f" <Offset>{pattern.x_offset}</Offset>\n"
f" <Frequency>{pattern.x_frequency}</Frequency>\n"
f" <Phase>{pattern.x_phase}</Phase>\n"
" </Axis>\n"
" <Axis Name=\"Y\">\n"
f" <Offset>{pattern.y_offset}</Offset>\n"
f" <Frequency>{pattern.y_frequency}</Frequency>\n"
f" <Phase>{pattern.y_phase}</Phase>\n"
" </Axis>\n"
" </Function>"
)
@dataclass
class SequenceStep:
values: dict[int, dict[int, int]]
fade_ms: int = 0
hold_ms: int = 0
fade_out_ms: int = 0
@dataclass
class SequenceFunction:
id: int
key: str
name: str
bound_id: int
steps: list[SequenceStep]
direction: str = "Forward"
run_order: str = "Loop"
primary: bool = True
type: str = "Sequence"
def duration_ms(self, _show: Show) -> int:
return sum(step.fade_ms + step.hold_ms + step.fade_out_ms for step in self.steps)
def apply(self, _show: Show, elapsed_ms: float, into: dict[int, dict[int, int]]) -> None:
index, prog, prev, _local = locate(self.steps, elapsed_ms, self.run_order, self.direction)
if not self.steps:
return
current = self.steps[index].values
previous = {} if prev is None else self.steps[prev].values
blend_maps(into, previous, current, prog)
def render(self) -> str:
lines = []
for index, step in enumerate(self.steps):
body, count = _step_values(step.values)
lines.append(
f' <Step Number="{index}" FadeIn="{step.fade_ms}" Hold="{step.hold_ms}" '
f'FadeOut="{step.fade_out_ms}" Values="{count}">{body}</Step>'
)
first = self.steps[0] if self.steps else SequenceStep({})
fade_mode, duration_mode = _speed_modes(self.steps)
return (
f' <Function ID="{self.id}" Type="Sequence" Name={attr(self.name)} '
f'BoundScene="{self.bound_id}">\n'
f' <Speed FadeIn="{first.fade_ms}" FadeOut="0" Duration="{first.fade_ms + first.hold_ms}"/>\n'
f" <Direction>{self.direction}</Direction>\n"
f" <RunOrder>{self.run_order}</RunOrder>\n"
f' <SpeedModes FadeIn="{fade_mode}" FadeOut="Common" Duration="{duration_mode}"/>\n'
+ "\n".join(lines)
+ "\n </Function>"
)
@dataclass
class ChaserStep:
function_id: int
fade_ms: int = 0
hold_ms: int = 0
fade_out_ms: int = 0
@dataclass
class ChaserFunction:
id: int
key: str
name: str
steps: list[ChaserStep]
direction: str = "Forward"
run_order: str = "Loop"
primary: bool = True
type: str = "Chaser"
def duration_ms(self, _show: Show) -> int:
return sum(step.fade_ms + step.hold_ms + step.fade_out_ms for step in self.steps)
def apply(self, show: Show, elapsed_ms: float, into: dict[int, dict[int, int]]) -> None:
from .model import Scene
if not self.steps:
return
index, prog, prev, local = locate(self.steps, elapsed_ms, self.run_order, self.direction)
current = show.functions_by_id[self.steps[index].function_id]
if isinstance(current, Scene):
previous: dict[int, dict[int, int]] = {}
if prev is not None:
prev_fn = show.functions_by_id[self.steps[prev].function_id]
if isinstance(prev_fn, Scene):
previous = prev_fn.values
else:
prev_fn.apply(show, prev_fn.duration_ms(show), previous)
blend_maps(into, previous, current.values, prog)
return
current.apply(show, local, into)
def render(self) -> str:
lines = [
f' <Step Number="{i}" FadeIn="{step.fade_ms}" Hold="{step.hold_ms}" '
f'FadeOut="{step.fade_out_ms}">{step.function_id}</Step>'
for i, step in enumerate(self.steps)
]
first = self.steps[0] if self.steps else ChaserStep(0)
fade_mode, duration_mode = _speed_modes(self.steps)
return (
f' <Function ID="{self.id}" Type="Chaser" Name={attr(self.name)}>\n'
f' <Speed FadeIn="{first.fade_ms}" FadeOut="0" Duration="{first.fade_ms + first.hold_ms}"/>\n'
f" <Direction>{self.direction}</Direction>\n"
f" <RunOrder>{self.run_order}</RunOrder>\n"
f' <SpeedModes FadeIn="{fade_mode}" FadeOut="Common" Duration="{duration_mode}"/>\n'
+ "\n".join(lines)
+ "\n </Function>"
)
def add_efx(show: Show, name: str, fixtures: list[Any], **kwargs: Any) -> Any:
key = kwargs.pop("key", None) or _auto_key(show, name)
relative = bool(kwargs.pop("relative", False))
homes_in = kwargs.pop("homes", None) or {}
entries = [_efx_entry(show, item, homes_in) for item in fixtures]
if not entries:
raise ValueError("efx has no fixtures")
for fixture, _direction, _offset, _pan, _tilt in entries:
if fixture.pan_msb is None or fixture.tilt_msb is None:
raise ValueError(f"{fixture.key} has no pan/tilt in mode {fixture.mode}")
pattern = _build_efx(entries, relative=relative, **kwargs)
homes = {fixture.id: (pan, tilt) for fixture, _d, _o, pan, tilt in entries}
axes = {
fixture.id: (fixture.pan_msb, fixture.pan_lsb, fixture.tilt_msb, fixture.tilt_lsb)
for fixture, *_rest in entries
}
preview = {fixture.id: fixture.preview_channels() for fixture, *_rest in entries}
if relative:
home_values = {}
for fixture, _d, _o, pan, tilt in entries:
channels: dict[int, int] = {}
if fixture.pan_msb is not None:
channels[fixture.pan_msb] = pan
if fixture.pan_lsb is not None:
channels[fixture.pan_lsb] = 0
if fixture.tilt_msb is not None:
channels[fixture.tilt_msb] = tilt
if fixture.tilt_lsb is not None:
channels[fixture.tilt_lsb] = 0
home_values[fixture.id] = channels
show.scene(f"{name} (home)", home_values, key=f"{key}.home", primary=False)
efx = EfxFunction(
id=show.alloc_function(),
key=f"{key}.efx",
name=f"{name} (EFX)",
pattern=pattern,
homes=homes,
relative=True,
axes=axes,
preview=preview,
primary=False,
)
show._add_function(efx)
return show.collection(name, [f"{key}.home", f"{key}.efx"], key=key, primary=True)
efx = EfxFunction(
id=show.alloc_function(),
key=key,
name=name,
pattern=pattern,
homes=homes,
relative=False,
axes=axes,
preview=preview,
)
return show._add_function(efx)
def add_sequence(
show: Show,
name: str,
steps: list[Any],
*,
direction: str = "Forward",
run_order: str = "Loop",
key: str | None = None,
primary: bool = True,
) -> SequenceFunction:
_check_choice("direction", direction, DIRECTIONS)
_check_choice("run_order", run_order, RUN_ORDERS)
fn_key = key or _auto_key(show, name)
norm = [_sequence_step(show, step) for step in steps]
if not norm:
raise ValueError("sequence has no steps")
show.scene(f"{name} (base)", norm[0].values, key=f"{fn_key}.base", primary=False)
bound = show.functions_by_key[f"{fn_key}.base"]
seq = SequenceFunction(
id=show.alloc_function(),
key=fn_key,
name=name,
bound_id=bound.id,
steps=norm,
direction=direction,
run_order=run_order,
primary=primary,
)
return show._add_function(seq)
def add_path(
show: Show,
name: str,
fixtures: list[Any],
points: list[Any],
*,
smooth: bool = False,
subdivisions: int = 6,
closed: bool = True,
run_order: str = "Loop",
direction: str = "Forward",
key: str | None = None,
) -> SequenceFunction:
entries = [_path_entry(show, item) for item in fixtures]
if not entries:
raise ValueError("path has no fixtures")
path_points = [_path_point(point) for point in points]
if len(path_points) < 1:
raise ValueError("path has no points")
for fixture, *_rest in entries:
if fixture.pan_msb is None or fixture.tilt_msb is None:
raise ValueError(f"{fixture.key} has no pan/tilt in mode {fixture.mode}")
path = Path(
points=path_points,
smooth=smooth,
subdivisions=int(subdivisions),
closed=closed,
run_order=run_order,
direction=direction,
fixtures=[
PathFixture(
id=fixture.id,
pan_offset=pan_offset,
tilt_offset=tilt_offset,
mirror_pan=mirror_pan,
mirror_tilt=mirror_tilt,
)
for fixture, pan_offset, tilt_offset, mirror_pan, mirror_tilt in entries
],
)
resolved = path.steps()
by_id = {fixture.id: fixture for fixture, *_rest in entries}
steps = []
for point in resolved:
values: dict[int, dict[int, int]] = {}
for cfg in path.fixtures:
fixture = by_id[cfg.id]
pan, tilt = cfg.apply(point.pan, point.tilt)
channels: dict[int, int] = {}
_write_axis(channels, fixture.pan_msb, fixture.pan_lsb, pan)
_write_axis(channels, fixture.tilt_msb, fixture.tilt_lsb, tilt)
values[fixture.id] = channels
steps.append(SequenceStep(values, fade_ms=point.fade_ms, hold_ms=point.hold_ms))
return add_sequence(show, name, steps, direction=direction, run_order=run_order, key=key)
def add_chaser(
show: Show,
name: str,
steps: list[Any],
*,
direction: str = "Forward",
run_order: str = "Loop",
key: str | None = None,
primary: bool = True,
) -> ChaserFunction:
_check_choice("direction", direction, DIRECTIONS)
_check_choice("run_order", run_order, RUN_ORDERS)
norm = [_chaser_step(show, step) for step in steps]
if not norm:
raise ValueError("chaser has no steps")
fn_key = key or _auto_key(show, name)
chaser = ChaserFunction(
id=show.alloc_function(),
key=fn_key,
name=name,
steps=norm,
direction=direction,
run_order=run_order,
primary=primary,
)
return show._add_function(chaser)
def add_colour_chase(
show: Show,
name: str,
fixtures: list[Any],
channels: dict[str, int],
frames: list[Any],
*,
fade_ms: int = 0,
hold_ms: int = 0,
run_order: str = "Loop",
key: str | None = None,
) -> ChaserFunction:
if not frames:
raise ValueError("colour chase has no frames")
fn_key = key or _auto_key(show, name)
names = list(channels)
scene_keys = []
for index, frame in enumerate(frames):
if len(frame) != len(fixtures):
raise ValueError(f"frame {index} has {len(frame)} colours for {len(fixtures)} fixtures")
values: dict[int, dict[int, int]] = {}
for fixture_item, colour in zip(fixtures, frame):
fixture = _fixture(show, fixture_item)
if isinstance(colour, dict):
values[fixture.id] = {int(ch): int(val) for ch, val in colour.items()}
else:
if len(colour) != len(names):
raise ValueError(
f"frame {index} colour has {len(colour)} values for channels {names}"
)
values[fixture.id] = {int(channels[names[i]]): int(colour[i]) for i in range(len(names))}
scene_key = f"{fn_key}.{index}"
show.scene(f"{name} {index + 1}", values, key=scene_key, primary=False)
scene_keys.append(scene_key)
steps = [
ChaserStep(show.functions_by_key[scene_key].id, fade_ms=int(fade_ms), hold_ms=int(hold_ms))
for scene_key in scene_keys
]
return add_chaser(show, name, steps, run_order=run_order, key=fn_key)
def _write_axis(bucket: dict[int, int], msb: int | None, lsb: int | None, value: float) -> None:
if msb is not None:
bucket[msb] = clamp8(value)
if lsb is not None:
bucket[lsb] = clamp8((value - int(value)) * 255)
def _step_values(values: dict[int, dict[int, int]]) -> tuple[str, int]:
chunks = []
count = 0
for fid, channels in sorted(values.items()):
if not channels:
continue
count += len(channels)
body = ",".join(f"{ch},{val}" for ch, val in sorted(channels.items()))
chunks.append(f"{fid}:{body}")
return ":".join(chunks), count
def _speed_modes(steps: list[Any]) -> tuple[str, str]:
if not steps:
return "Common", "Common"
first = (steps[0].fade_ms, steps[0].hold_ms, steps[0].fade_out_ms)
if all((step.fade_ms, step.hold_ms, step.fade_out_ms) == first for step in steps):
return "Common", "Common"
return "PerStep", "PerStep"
def _check_choice(label: str, value: str, allowed: tuple[str, ...]) -> None:
if value not in allowed:
raise ValueError(f"{label} must be one of {', '.join(allowed)}")
def _check_range(label: str, value: int, lo: int, hi: int) -> int:
number = int(value)
if not lo <= number <= hi:
raise ValueError(f"{label} must be {lo}–{hi}")
return number
def _build_efx(entries: list[tuple[Any, str, int, int, int]], *, relative: bool, **kwargs: Any) -> Efx:
algorithm = kwargs.get("algorithm", "Circle")
_check_choice("algorithm", algorithm, ALGORITHMS)
direction = kwargs.get("direction", "Forward")
run_order = kwargs.get("run_order", "Loop")
propagation = kwargs.get("propagation", "Parallel")
_check_choice("direction", direction, DIRECTIONS)
_check_choice("run_order", run_order, RUN_ORDERS)
_check_choice("propagation", propagation, PROPAGATIONS)
duration = int(kwargs.get("duration_ms", 8000))
if duration < 20:
raise ValueError("duration_ms must be at least 20")
x_offset = RELATIVE_ZERO if relative else _check_range("x_offset", kwargs.get("x_offset", 128), 0, 255)
y_offset = RELATIVE_ZERO if relative else _check_range("y_offset", kwargs.get("y_offset", 128), 0, 255)
return Efx(
algorithm=algorithm,
width=_check_range("width", kwargs.get("width", 40), 0, 127),
height=_check_range("height", kwargs.get("height", 40), 0, 127),
rotation=int(kwargs.get("rotation", 0)) % 360,
start_offset=int(kwargs.get("start_offset", 0)) % 360,
x_offset=x_offset,
y_offset=y_offset,
x_frequency=_check_range("x_frequency", kwargs.get("x_frequency", 1), 0, 5),
y_frequency=_check_range("y_frequency", kwargs.get("y_frequency", 1), 0, 5),
x_phase=int(kwargs.get("x_phase", 0)) % 360,
y_phase=int(kwargs.get("y_phase", 0)) % 360,
duration_ms=duration,
fade_in_ms=max(0, int(kwargs.get("fade_in_ms", 0))),
fade_out_ms=max(0, int(kwargs.get("fade_out_ms", 0))),
direction=direction,
run_order=run_order,
propagation=propagation,
relative=relative,
fixtures=[
EfxFixture(id=fixture.id, direction=direction, start_offset=offset, pan=pan, tilt=tilt)
for fixture, direction, offset, pan, tilt in entries
],
)
def _efx_entry(show: Show, item: Any, homes: dict[Any, Any]) -> tuple[Any, str, int, int, int]:
if isinstance(item, str) or (isinstance(item, int) and not isinstance(item, bool)):
fixture = _fixture(show, item)
direction, offset, pan, tilt = "Forward", 0, 128, 128
home_key: Any = item
elif hasattr(item, "pan_msb"):
fixture = item
direction, offset, pan, tilt = "Forward", 0, 128, 128
home_key = fixture.key
else:
fixture = _fixture(show, item["fixture"])
direction = item.get("direction", "Forward")
offset = int(item.get("start_offset", 0))
pan = int(item.get("pan", 128))
tilt = int(item.get("tilt", 128))
home_key = item["fixture"]
home = _home_for(homes, fixture, home_key)
if home is not None:
pan, tilt = int(home[0]), int(home[1])
return fixture, direction, offset, pan, tilt
def _home_for(homes: dict[Any, Any], fixture: Any, home_key: Any) -> Any:
if not homes:
return None
for candidate in (home_key, fixture.key, fixture.id):
if candidate in homes:
return homes[candidate]
for key, value in homes.items():
if key is fixture:
return value
return None
def _sequence_step(show: Show, step: Any) -> SequenceStep:
if isinstance(step, SequenceStep):
values = {
show.fixture_id(fid): {int(ch): int(val) for ch, val in channels.items()}
for fid, channels in step.values.items()
}
return SequenceStep(values, step.fade_ms, step.hold_ms, step.fade_out_ms)
values = {
show.fixture_id(fid): {int(ch): int(val) for ch, val in channels.items()}
for fid, channels in step["values"].items()
}
return SequenceStep(
values,
fade_ms=int(step.get("fade_ms", 0)),
hold_ms=int(step.get("hold_ms", 0)),
fade_out_ms=int(step.get("fade_out_ms", 0)),
)
def _path_entry(show: Show, item: Any) -> tuple[Any, int, int, bool, bool]:
if isinstance(item, str) or hasattr(item, "pan_msb"):
return _fixture(show, item), 0, 0, False, False
return (
_fixture(show, item["fixture"]),
int(item.get("pan_offset", 0)),
int(item.get("tilt_offset", 0)),
bool(item.get("mirror_pan", False)),
bool(item.get("mirror_tilt", False)),
)
def _path_point(point: Any) -> PathPoint:
if isinstance(point, PathPoint):
return point
return PathPoint(
pan=float(point["pan"]),
tilt=float(point["tilt"]),
fade_ms=int(point.get("fade_ms", 1000)),
hold_ms=int(point.get("hold_ms", 0)),
)
def _chaser_step(show: Show, step: Any) -> ChaserStep:
if isinstance(step, ChaserStep):
return ChaserStep(_function_id(show, step.function_id), step.fade_ms, step.hold_ms, step.fade_out_ms)
if isinstance(step, tuple):
function, fade, hold = step[0], step[1], step[2] if len(step) > 2 else 0
fade_out = step[3] if len(step) > 3 else 0
return ChaserStep(_function_id(show, function), int(fade), int(hold), int(fade_out))
return ChaserStep(
_function_id(show, step["function"] if isinstance(step, dict) else step),
fade_ms=int(step.get("fade_ms", 0)) if isinstance(step, dict) else 0,
hold_ms=int(step.get("hold_ms", 0)) if isinstance(step, dict) else 0,
fade_out_ms=int(step.get("fade_out_ms", 0)) if isinstance(step, dict) else 0,
)
def _function_id(show: Show, function: Any) -> int:
if isinstance(function, int) and not isinstance(function, bool):
return function
if isinstance(function, str):
return show.functions_by_key[function].id
return function.id
def _auto_key(show: Show, name: str) -> str:
from .model import _key_for
return _key_for(name, show.functions_by_key)
+187
View File
@@ -0,0 +1,187 @@
"""MCP stdio server for the show tools.
Cursor starts this with `python3 -m showfile.mcp`. The process speaks MCP
over Content-Length framing and does not require the third-party mcp package.
"""
from __future__ import annotations
import json
import sys
from typing import Any
from .tools import list_fixtures, run_script, sample_animation, show_schema, validate_show, write_show
_TOOLS = [
{
"name": "list_fixtures",
"description": (
"List fixture definitions in fixtures/. Each mode includes channel index, name, "
"preset, and which channels are pan and tilt. Use these channel numbers in a show spec."
),
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
},
{
"name": "show_schema",
"description": "Return the JSON Schema for a QLC+ show spec. Keys are strings; ids are assigned on write.",
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
},
{
"name": "validate_show",
"description": (
"Validate a show spec. Returns {ok, errors: [{path, message}]} and writes nothing. "
"Error paths look like functions.eight.fixtures."
),
"inputSchema": {
"type": "object",
"properties": {"spec": {"type": "object", "description": "Show spec."}},
"required": ["spec"],
},
},
{
"name": "write_show",
"description": (
"Write a show spec to a .qxw inside the project. Returns {ok, path, fixtures, functions, widgets} "
"with the QLC+ ids that were assigned. Refuses paths outside the project."
),
"inputSchema": {
"type": "object",
"properties": {
"spec": {"type": "object"},
"path": {"type": "string", "description": "Project-relative .qxw path, for example shows/look.qxw."},
},
"required": ["spec", "path"],
},
},
{
"name": "sample_animation",
"description": (
"Sample pan/tilt for one efx or path block so the shape can be checked before writing a show. "
"Returns tracks of points. Relative EFX points are the fixture's real pan/tilt, including its home."
),
"inputSchema": {
"type": "object",
"properties": {
"block": {"type": "object", "description": "An efx or path function object."},
"steps": {"type": "integer", "minimum": 1, "maximum": 128, "description": "EFX samples along one loop. Default 32."},
},
"required": ["block"],
},
},
{
"name": "run_animation",
"description": (
"Run an animation Python script (a file that defines build() -> Show) or a JSON show spec. "
"Without ip, returns DMX samples for testing and sends nothing. "
"With ip, streams Art-Net for `seconds` (or until the client cancels — prefer a short seconds value)."
),
"inputSchema": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "Project-relative .py script or .json spec."},
"seconds": {"type": "number"},
"ip": {"type": "string", "description": "Art-Net destination. Omit for a dry run."},
"universe": {"type": "integer"},
"hz": {"type": "number"},
},
"required": ["path"],
},
},
]
def serve() -> None:
framed = False
while True:
message, framed = _read(framed)
if message is None:
return
response = _handle(message)
if response is not None:
_write(response, framed)
def _handle(message: dict[str, Any]) -> dict[str, Any] | None:
method = message.get("method")
mid = message.get("id")
if method == "notifications/initialized" or method and method.startswith("notifications/"):
return None
if method == "initialize":
return _result(
mid,
{
"protocolVersion": "2024-11-05",
"capabilities": {"tools": {"listChanged": False}},
"serverInfo": {"name": "qlcplus-show", "version": "1.0.0"},
},
)
if method == "ping":
return _result(mid, {})
if method == "tools/list":
return _result(mid, {"tools": _TOOLS})
if method == "tools/call":
params = message.get("params") or {}
try:
payload = _call(str(params.get("name")), params.get("arguments") or {})
return _result(mid, {"content": [{"type": "text", "text": json.dumps(payload, indent=2)}], "isError": False})
except Exception as exc: # noqa: BLE001 — reported to the MCP client
return _result(mid, {"content": [{"type": "text", "text": str(exc)}], "isError": True})
if mid is not None:
return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": f"unknown method {method}"}}
return None
def _call(name: str, arguments: dict[str, Any]) -> Any:
if name == "list_fixtures":
return list_fixtures()
if name == "show_schema":
return show_schema()
if name == "validate_show":
return validate_show(arguments["spec"])
if name == "write_show":
return write_show(arguments["spec"], arguments["path"])
if name == "sample_animation":
return sample_animation(arguments["block"], int(arguments.get("steps", 32)))
if name == "run_animation":
return run_script(
arguments["path"],
seconds=arguments.get("seconds"),
ip=arguments.get("ip"),
universe=int(arguments.get("universe", 0)),
hz=float(arguments.get("hz", 40)),
)
raise KeyError(f"unknown tool {name}")
def _result(mid: Any, result: Any) -> dict[str, Any]:
return {"jsonrpc": "2.0", "id": mid, "result": result}
def _read(framed: bool) -> tuple[dict[str, Any] | None, bool]:
line = sys.stdin.buffer.readline()
if not line:
return None, framed
if line.lower().startswith(b"content-length:"):
length = int(line.split(b":", 1)[1].strip())
while True:
header = sys.stdin.buffer.readline()
if header in (b"\r\n", b"\n", b""):
break
body = sys.stdin.buffer.read(length)
return json.loads(body), True
if not line.strip():
return _read(framed)
return json.loads(line), framed
def _write(message: dict[str, Any], framed: bool) -> None:
data = json.dumps(message).encode()
if framed:
sys.stdout.buffer.write(f"Content-Length: {len(data)}\r\n\r\n".encode() + data)
else:
sys.stdout.buffer.write(data + b"\n")
sys.stdout.buffer.flush()
if __name__ == "__main__":
serve()
+584
View File
@@ -0,0 +1,584 @@
"""QLC+ show model: universes, fixtures, scenes, and the virtual-console root."""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from patternstudio.fixturedefs import FixtureLibrary, ModeInfo
from .xmlutil import appearance, attr, text
QLC_VERSION = "4.12.7"
INVALID_FUNCTION = 4294967295
def midi_note(channel: int, note: int) -> int:
"""QLC+ input channel for a MIDI note. Channel is 0–15."""
return (int(channel) << 12) | (128 + int(note))
def midi_cc(channel: int, cc: int) -> int:
"""QLC+ input channel for a MIDI control change. Channel is 0–15."""
return (int(channel) << 12) | int(cc)
def blend_maps(
into: dict[int, dict[int, int]],
prev: dict[int, dict[int, int]],
curr: dict[int, dict[int, int]],
prog: float,
) -> None:
"""Write prev→curr into `into`. Channels fade up from 0 when prev lacks them."""
prog = max(0.0, min(1.0, prog))
for fid in set(prev) | set(curr):
bucket = into.setdefault(fid, {})
channels = set(prev.get(fid, {})) | set(curr.get(fid, {}))
for ch in channels:
start = prev.get(fid, {}).get(ch, 0)
end = curr.get(fid, {}).get(ch, 0)
bucket[ch] = int(round(start + (end - start) * prog))
@dataclass
class MidiBinding:
universe: int
channel: int
@dataclass
class ArtNetOutput:
uid: str
ip: str
universe: int = 0
line: int = 0
@dataclass
class MidiInput:
uid: str
profile: str
channel: int = 0
line: int = 0
@dataclass
class Universe:
id: int
name: str
output: ArtNetOutput | None = None
midi: MidiInput | None = None
@dataclass
class Fixture:
id: int
key: str
manufacturer: str
model: str
mode: str
name: str
universe: int
address: int
channels: int
mode_info: ModeInfo | None = None
x: float | None = None
y: float | None = None
direction: float | None = None
zero: float | None = None
kind: str = ""
def named(self, name: str) -> list[int]:
"""Channel indexes for a name. "Red" is Red, or Red 1 … Red N when those exist."""
if self.mode_info is None:
raise ValueError(f"{self.key} has no channel map")
query = name.strip().lower()
exact: list[int] = []
numbered: list[tuple[int, int]] = []
for channel in self.mode_info.channels:
label = channel.name.strip()
if label.lower() == query:
exact.append(channel.index)
continue
head, sep, tail = label.rpartition(" ")
if sep and head.lower() == query and tail.isdigit():
numbered.append((int(tail), channel.index))
if exact:
return exact
if numbered:
numbered.sort()
return [index for _, index in numbered]
raise KeyError(f"{self.key} has no channel {name!r}")
def channel(self, name: str) -> int:
return self.named(name)[0]
@property
def pan_msb(self) -> int | None:
return None if self.mode_info is None else self.mode_info.pan_msb
@property
def pan_lsb(self) -> int | None:
return None if self.mode_info is None else self.mode_info.pan_lsb
@property
def tilt_msb(self) -> int | None:
return None if self.mode_info is None else self.mode_info.tilt_msb
@property
def tilt_lsb(self) -> int | None:
return None if self.mode_info is None else self.mode_info.tilt_lsb
def preview_channels(self) -> dict[int, int]:
if self.mode_info is None:
return {}
return self.mode_info.preview_channels()
@dataclass
class FixtureGroup:
id: int
name: str
columns: int
fixture_ids: list[int]
head: int = 0
@dataclass
class Scene:
id: int
key: str
name: str
values: dict[int, dict[int, int]]
fade_in: int = 0
fade_out: int = 0
duration: int = 0
primary: bool = True
type: str = "Scene"
def duration_ms(self, _show: Show) -> int:
return max(0, self.fade_in) + max(0, self.duration)
def apply(self, _show: Show, elapsed_ms: float, into: dict[int, dict[int, int]]) -> None:
prog = 1.0 if self.fade_in <= 0 else min(1.0, elapsed_ms / self.fade_in)
blend_maps(into, {}, self.values, prog)
def render(self) -> str:
vals = []
for fid, channels in sorted(self.values.items()):
if not channels:
continue
body = ",".join(f"{ch},{val}" for ch, val in sorted(channels.items()))
vals.append(f' <FixtureVal ID="{fid}">{body}</FixtureVal>')
inner = ("\n" + "\n".join(vals)) if vals else ""
return (
f' <Function ID="{self.id}" Type="Scene" Name={attr(self.name)}>\n'
f' <Speed FadeIn="{self.fade_in}" FadeOut="{self.fade_out}" Duration="{self.duration}"/>'
f"{inner}\n"
f" </Function>"
)
@dataclass
class Collection:
id: int
key: str
name: str
members: list[int]
primary: bool = True
type: str = "Collection"
def duration_ms(self, show: Show) -> int:
return max((show.functions_by_id[mid].duration_ms(show) for mid in self.members), default=0)
def apply(self, show: Show, elapsed_ms: float, into: dict[int, dict[int, int]]) -> None:
for mid in self.members:
show.functions_by_id[mid].apply(show, elapsed_ms, into)
def render(self) -> str:
steps = "\n".join(f' <Step Number="{i}">{mid}</Step>' for i, mid in enumerate(self.members))
return (
f' <Function ID="{self.id}" Type="Collection" Name={attr(self.name)}>\n'
f"{steps}\n"
f" </Function>"
)
@dataclass
class RawFunction:
id: int
key: str
name: str
xml: str
primary: bool = True
type: str = "Raw"
def duration_ms(self, _show: Show) -> int:
return 0
def apply(self, _show: Show, _elapsed_ms: float, _into: dict[int, dict[int, int]]) -> None:
return None
def render(self) -> str:
return self.xml
@dataclass
class Show:
author: str = "Jimmy"
version: str = QLC_VERSION
root: Path | None = None
universes: list[Universe] = field(default_factory=list)
fixtures: list[Fixture] = field(default_factory=list)
groups: list[FixtureGroup] = field(default_factory=list)
functions: list[Any] = field(default_factory=list)
playback: list[str] = field(default_factory=list)
vc_size: tuple[int, int] | None = None
def __post_init__(self) -> None:
from .vc import Frame
self._fixture_seq = 0
self._function_seq = 0
self._widget_seq = 0
self._group_seq = 0
self.fixtures_by_key: dict[str, Fixture] = {}
self.functions_by_key: dict[str, Any] = {}
self.functions_by_id: dict[int, Any] = {}
project = self.root or Path(__file__).resolve().parents[1]
self.library = FixtureLibrary(project)
self.vc = Frame(self, "", root=True)
# -- allocation -------------------------------------------------------
def alloc_fixture(self) -> int:
value = self._fixture_seq
self._fixture_seq += 1
return value
def alloc_function(self) -> int:
value = self._function_seq
self._function_seq += 1
return value
def alloc_widget(self) -> int:
value = self._widget_seq
self._widget_seq += 1
return value
def _add_function(self, fn: Any) -> Any:
if fn.key in self.functions_by_key:
raise ValueError(f"duplicate function key {fn.key!r}")
self.functions.append(fn)
self.functions_by_key[fn.key] = fn
self.functions_by_id[fn.id] = fn
return fn
def fixture_id(self, fx: Fixture | int | str) -> int:
if isinstance(fx, Fixture):
return fx.id
if isinstance(fx, int) and not isinstance(fx, bool):
return fx
try:
return self.fixtures_by_key[str(fx)].id
except KeyError as exc:
raise KeyError(f"no fixture {fx!r}") from exc
# -- patch ------------------------------------------------------------
def universe(
self,
uid: int,
name: str | None = None,
*,
output: ArtNetOutput | None = None,
midi: MidiInput | None = None,
) -> Universe:
uni = Universe(int(uid), name or f"Universe {int(uid) + 1}", output, midi)
self.universes.append(uni)
return uni
def patch(
self,
manufacturer: str,
model: str,
mode: str,
*,
address: int,
name: str | None = None,
universe: int = 0,
channels: int | None = None,
key: str | None = None,
) -> Fixture:
definition = self.library.find(manufacturer, model)
mode_info = definition.mode(mode) if definition is not None else None
if channels is None:
if mode_info is None:
raise ValueError(
f"no fixture definition for {manufacturer} {model} mode {mode!r}; pass channels="
)
channels = len(mode_info.channels)
elif mode_info is not None and channels != len(mode_info.channels):
mode_info = None
fid = self.alloc_fixture()
fx_key = key or f"fixture{fid}"
if fx_key in self.fixtures_by_key:
raise ValueError(f"duplicate fixture key {fx_key!r}")
fixture = Fixture(
id=fid,
key=fx_key,
manufacturer=manufacturer,
model=model,
mode=mode,
name=name or f"{model} #{fid + 1}",
universe=int(universe),
address=int(address),
channels=int(channels),
mode_info=mode_info,
)
self.fixtures.append(fixture)
self.fixtures_by_key[fx_key] = fixture
return fixture
def group(self, name: str, fixtures: list[Fixture | str | int], *, columns: int | None = None) -> FixtureGroup:
ids = [self.fixture_id(fx) for fx in fixtures]
group = FixtureGroup(
id=self._group_seq,
name=name,
columns=columns or max(1, len(ids)),
fixture_ids=ids,
)
self._group_seq += 1
self.groups.append(group)
return group
def patch_stage(self, path: str | Path | None = None) -> Any:
"""Patch every fixture in a stage map. Keys are the map ids, such as "#1" and "M1"."""
from .stage import patch_stage
return patch_stage(self, path)
def scene(
self,
name: str,
values: dict[Any, dict[Any, int]],
*,
key: str | None = None,
fade_in: int = 0,
fade_out: int = 0,
duration: int = 0,
primary: bool = True,
) -> Scene:
norm = _channel_map(self, values)
fn_key = key or _key_for(name, self.functions_by_key)
scene = Scene(
id=self.alloc_function(),
key=fn_key,
name=name,
values=norm,
fade_in=int(fade_in),
fade_out=int(fade_out),
duration=int(duration),
primary=primary,
)
return self._add_function(scene)
def collection(
self,
name: str,
members: list[Any],
*,
key: str | None = None,
primary: bool = True,
) -> Collection:
ids = []
for member in members:
if isinstance(member, int) and not isinstance(member, bool):
ids.append(member)
elif isinstance(member, str):
ids.append(self.functions_by_key[member].id)
else:
ids.append(member.id)
fn_key = key or _key_for(name, self.functions_by_key)
coll = Collection(
id=self.alloc_function(),
key=fn_key,
name=name,
members=ids,
primary=primary,
)
return self._add_function(coll)
def function_xml(self, xml: str, *, key: str | None = None, name: str = "Function") -> RawFunction:
fid = self.alloc_function()
fn_key = key or f"function{fid}"
stamped = _stamp_function_id(xml.strip(), fid)
raw = RawFunction(id=fid, key=fn_key, name=name, xml=stamped)
return self._add_function(raw)
def run(self, *keys: str) -> None:
missing = [key for key in keys if key not in self.functions_by_key]
if missing:
raise KeyError(f"no function {missing[0]!r}")
self.playback = list(keys)
def efx(self, name: str, fixtures: list[Any], **kwargs: Any) -> Any:
from .animate import add_efx
return add_efx(self, name, fixtures, **kwargs)
def sequence(self, name: str, steps: list[Any], **kwargs: Any) -> Any:
from .animate import add_sequence
return add_sequence(self, name, steps, **kwargs)
def path_sequence(self, name: str, fixtures: list[Any], points: list[Any], **kwargs: Any) -> Any:
from .animate import add_path
return add_path(self, name, fixtures, points, **kwargs)
def chaser(self, name: str, steps: list[Any], **kwargs: Any) -> Any:
from .animate import add_chaser
return add_chaser(self, name, steps, **kwargs)
def colour_chase(self, name: str, fixtures: list[Any], channels: dict[str, int], frames: list[Any], **kwargs: Any) -> Any:
from .animate import add_colour_chase
return add_colour_chase(self, name, fixtures, channels, frames, **kwargs)
# -- output -----------------------------------------------------------
def size(self) -> tuple[int, int]:
if self.vc_size is not None:
return self.vc_size
max_x = max_y = 0
for widget in self.vc.children:
max_x = max(max_x, widget.x + widget.w)
max_y = max(max_y, widget.y + widget.h)
return max_x + 16, max_y + 16
def xml(self) -> str:
from .xml import render_show
return render_show(self)
def write(self, path: Path | str) -> Path:
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(self.xml(), encoding="utf-8")
return target
def summary(self) -> dict[str, Any]:
return {
"fixtures": {
fx.key: {
"id": fx.id,
"name": fx.name,
"address": fx.address,
"channels": fx.channels,
"universe": fx.universe,
}
for fx in self.fixtures
},
"functions": {
fn.key: {"id": fn.id, "type": fn.type, "name": fn.name}
for fn in self.functions
},
"widgets": _widgets(self.vc),
}
def _channel_map(show: Show, values: Any) -> dict[int, dict[int, int]]:
pairs = values if isinstance(values, list) else values.items()
norm: dict[int, dict[int, int]] = {}
for fx, channels in pairs:
norm[show.fixture_id(fx)] = {int(ch): int(val) for ch, val in channels.items()}
return norm
def _widgets(frame: Any) -> list[dict[str, Any]]:
found: list[dict[str, Any]] = []
for child in frame.children:
found.append({"id": child.id, "type": child.type_name, "caption": child.caption})
if child.type_name in ("Frame", "SoloFrame"):
found.extend(_widgets(child))
return found
def _key_for(name: str, existing: dict[str, Any]) -> str:
base = "".join(ch.lower() if ch.isalnum() else "-" for ch in name).strip("-") or "function"
key = base
n = 2
while key in existing:
key = f"{base}-{n}"
n += 1
return key
def _stamp_function_id(xml: str, fid: int) -> str:
import re
if re.search(r"\bID=\"\d+\"", xml):
return re.sub(r"\bID=\"\d+\"", f'ID="{fid}"', xml, count=1)
return xml.replace("<Function ", f'<Function ID="{fid}" ', 1)
def fixture_xml(fx: Fixture) -> str:
return (
" <Fixture>\n"
f" <Manufacturer>{text(fx.manufacturer)}</Manufacturer>\n"
f" <Model>{text(fx.model)}</Model>\n"
f" <Mode>{text(fx.mode)}</Mode>\n"
f" <ID>{fx.id}</ID>\n"
f" <Name>{text(fx.name)}</Name>\n"
f" <Universe>{fx.universe}</Universe>\n"
f" <Address>{fx.address}</Address>\n"
f" <Channels>{fx.channels}</Channels>\n"
" </Fixture>"
)
def group_xml(group: FixtureGroup) -> str:
columns = max(1, group.columns)
rows = max(1, (len(group.fixture_ids) + columns - 1) // columns)
heads = []
for index, fid in enumerate(group.fixture_ids):
heads.append(
f' <Head X="{index % columns}" Y="{index // columns}" Fixture="{fid}">{group.head}</Head>'
)
body = "\n".join(heads)
return (
f' <FixtureGroup ID="{group.id}">\n'
f" <Name>{text(group.name)}</Name>\n"
f' <Size X="{columns}" Y="{rows}"/>\n'
f"{body}\n"
" </FixtureGroup>"
)
def universe_xml(uni: Universe) -> str:
if uni.output is None and uni.midi is None:
return f' <Universe Name={attr(uni.name)} ID="{uni.id}"/>'
parts = [f' <Universe Name={attr(uni.name)} ID="{uni.id}">']
if uni.output is not None:
out = uni.output
parts.append(
f' <Output Plugin="ArtNet" UID={attr(out.uid)} Line="{out.line}">\n'
f' <PluginParameters outputIP={attr(out.ip)} outputUni="{out.universe}"/>\n'
" </Output>"
)
if uni.midi is not None:
midi = uni.midi
parts.append(
f' <Input Plugin="MIDI" UID={attr(midi.uid)} Line="{midi.line}" Profile={attr(midi.profile)}>\n'
f' <PluginParameters midichannel="{midi.channel}"/>\n'
" </Input>"
)
parts.append(" </Universe>")
return "\n".join(parts)
def root_appearance() -> str:
return appearance(frame="None", indent=" ")
+160
View File
@@ -0,0 +1,160 @@
"""Play a show's animations without QLC+.
Dry-run returns DMX samples. Pass an IP to send Art-Net. A Python script
exposes this by defining build() -> Show and calling script_main(build).
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import socket
import sys
import time
from pathlib import Path
from typing import Any
from patternstudio.artnet import ARTNET_PORT, build_artdmx
from .model import Show
from .spec import SpecError, from_spec
def active_keys(show: Show, keys: list[str] | None = None) -> list[str]:
if keys is not None:
return list(keys)
if show.playback:
return list(show.playback)
return [fn.key for fn in show.functions if getattr(fn, "primary", False)]
def frame_at(show: Show, elapsed_ms: float, keys: list[str] | None = None) -> dict[str, dict[int, int]]:
"""Fixture key → channel → value at `elapsed_ms` for the functions being played."""
into: dict[int, dict[int, int]] = {}
for key in active_keys(show, keys):
show.functions_by_key[key].apply(show, elapsed_ms, into)
names = {fx.id: fx.key for fx in show.fixtures}
return {names[fid]: dict(channels) for fid, channels in into.items() if fid in names}
def dmx_frames(show: Show, values: dict[str, dict[int, int]]) -> dict[int, bytearray]:
"""QLC+ universe → 512-channel frame."""
frames: dict[int, bytearray] = {}
for key, channels in values.items():
fixture = show.fixtures_by_key[key]
frame = frames.setdefault(fixture.universe, bytearray(512))
for channel, value in channels.items():
slot = fixture.address + int(channel)
if 0 <= slot < 512:
frame[slot] = max(0, min(255, int(value)))
return frames
def sample_playback(show: Show, *, seconds: float | None = None, hz: float = 40.0) -> dict[str, Any]:
keys = active_keys(show)
if seconds is None:
duration = max((show.functions_by_key[key].duration_ms(show) for key in keys), default=0)
times = [0] if duration <= 0 else [int(duration * i / 4) for i in range(4)]
if duration > 0:
times.append(max(0, duration - 1))
else:
count = max(1, int(float(seconds) * hz))
times = [int(i * (1000.0 / hz)) for i in range(min(count, 500))]
duration = int(float(seconds) * 1000)
return {
"ok": True,
"functions": keys,
"duration_ms": duration,
"samples": [{"time_ms": t, "values": frame_at(show, t, keys)} for t in times],
}
def play(
show: Show,
*,
seconds: float | None = None,
ip: str | None = None,
universe: int = 0,
hz: float = 40.0,
) -> dict[str, Any]:
"""Sample the running functions, or stream them as Art-Net when `ip` is set."""
if not ip:
return sample_playback(show, seconds=seconds, hz=hz)
return _send(show, ip=ip, universe=universe, seconds=seconds, hz=hz)
def load_show(path: Path | str) -> Show:
"""Load a show from a build() script or a JSON spec."""
source = Path(path).resolve()
if source.suffix == ".json":
return from_spec(json.loads(source.read_text(encoding="utf-8")))
spec = importlib.util.spec_from_file_location(f"showfile_script_{source.stem}", source)
if spec is None or spec.loader is None:
raise SpecError([{"path": str(source), "message": "could not load the script"}])
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
if not hasattr(module, "build"):
raise SpecError([{"path": str(source), "message": "script must define build() -> Show"}])
show = module.build()
if not isinstance(show, Show):
raise SpecError([{"path": str(source), "message": "build() must return a Show"}])
return show
def script_main(build: Any, argv: list[str] | None = None) -> None:
"""Entry point for `python animation.py`. Prints one JSON object."""
args = _parser().parse_args(argv)
_emit(play(build(), seconds=args.seconds, ip=args.ip, universe=args.universe, hz=args.hz))
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Play this animation and print DMX samples, or send Art-Net.")
parser.add_argument("--ip", help="Art-Net destination. Omit to print samples and exit.")
parser.add_argument("--seconds", type=float, help="How long to play. Omit with --ip to run until Ctrl+C.")
parser.add_argument("--hz", type=float, default=40.0)
parser.add_argument("--universe", type=int, default=0, help="Art-Net universe for QLC+ universe 0.")
return parser
def _emit(payload: dict[str, Any]) -> None:
json.dump(payload, sys.stdout, indent=2)
sys.stdout.write("\n")
def _send(show: Show, *, ip: str, universe: int, seconds: float | None, hz: float) -> dict[str, Any]:
keys = active_keys(show)
period = 1.0 / hz if hz > 0 else 0.025
print(
f"Art-Net {ip} universe {universe} {', '.join(keys) or '(no functions)'} (Ctrl+C to stop)",
file=sys.stderr,
)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sequence = 1
sent = 0
stopped = False
started = time.monotonic()
try:
while True:
elapsed_ms = (time.monotonic() - started) * 1000.0
if seconds is not None and elapsed_ms >= seconds * 1000.0:
break
frames = dmx_frames(show, frame_at(show, elapsed_ms, keys))
if not frames:
frames = {0: bytearray(512)}
for qlc_universe, frame in frames.items():
packet = build_artdmx(bytes(frame), universe + qlc_universe, sequence)
sock.sendto(packet, (ip, ARTNET_PORT))
sequence = 1 if sequence >= 255 else sequence + 1
sent += 1
time.sleep(period)
except KeyboardInterrupt:
stopped = True
finally:
for qlc_universe in dmx_frames(show, frame_at(show, 0, keys)) or {0: bytearray()}:
for _ in range(3):
sock.sendto(build_artdmx(bytes(512), universe + qlc_universe, sequence), (ip, ARTNET_PORT))
sequence = 1 if sequence >= 255 else sequence + 1
sock.close()
return {"ok": True, "ip": ip, "universe": universe, "functions": keys, "frames": sent, "stopped": stopped}
+873
View File
@@ -0,0 +1,873 @@
"""JSON show spec: schema, validation, and Show.from_spec."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
from patternstudio.efx import ALGORITHMS, DIRECTIONS, PROPAGATIONS, RUN_ORDERS
from patternstudio.fixturedefs import FixtureLibrary
from .model import ArtNetOutput, MidiBinding, MidiInput, Show, midi_cc, midi_note
PROJECT_ROOT = Path(__file__).resolve().parents[1]
class SpecError(Exception):
def __init__(self, errors: list[dict[str, str]]):
self.errors = errors
detail = "; ".join(f"{item['path']}: {item['message']}" for item in errors)
super().__init__(detail or "invalid show spec")
def show_schema() -> dict[str, Any]:
"""JSON Schema for the document accepted by validate_show and write_show."""
return {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "qlcplus://show",
"title": "QLC+ show",
"type": "object",
"description": (
"A QLC+ workspace. Fixture, function, and widget ids are assigned on write. "
"Refer to fixtures and functions by their string keys. Channel numbers come from list_fixtures. "
"Addresses are 0-based, matching QLC+ (address 87 is DMX channel 88). "
"Set stage to a stage map path to patch that rig; fixture keys are the map ids."
),
"properties": {
"stage": {
"type": "string",
"description": "Stage map inside the project, for example stage/map.json. Patches every fixture before fixtures.",
},
"author": {"type": "string"},
"vc_size": {
"type": "array",
"items": {"type": "integer"},
"minItems": 2,
"maxItems": 2,
"description": "Virtual console width and height. Omitted means fit the widgets plus a 16px margin.",
},
"run": {
"type": "array",
"items": {"type": "string"},
"description": "Function keys to play when the show is run as a script. Defaults to every top-level function.",
},
"universes": {"type": "array", "items": {"$ref": "#/$defs/universe"}},
"fixtures": {"type": "array", "items": {"$ref": "#/$defs/fixture"}},
"groups": {"type": "array", "items": {"$ref": "#/$defs/group"}},
"functions": {"type": "array", "items": {"$ref": "#/$defs/function"}},
"vc": {"type": "array", "items": {"$ref": "#/$defs/widget"}},
},
"$defs": {
"universe": {
"type": "object",
"required": ["id"],
"properties": {
"id": {"type": "integer", "minimum": 0},
"name": {"type": "string"},
"output": {
"type": "object",
"required": ["uid", "ip"],
"properties": {
"plugin": {"const": "ArtNet"},
"uid": {"type": "string"},
"ip": {"type": "string"},
"universe": {"type": "integer"},
"line": {"type": "integer"},
},
},
"input": {
"type": "object",
"required": ["uid", "profile"],
"properties": {
"plugin": {"const": "MIDI"},
"uid": {"type": "string"},
"profile": {"type": "string"},
"channel": {"type": "integer", "description": "QLC+ MIDI plugin channel. 16 is omni."},
"line": {"type": "integer"},
},
},
},
},
"fixture": {
"type": "object",
"required": ["key", "manufacturer", "model", "mode", "address"],
"properties": {
"key": {"type": "string"},
"manufacturer": {"type": "string"},
"model": {"type": "string"},
"mode": {"type": "string"},
"name": {"type": "string"},
"universe": {"type": "integer"},
"address": {"type": "integer", "minimum": 0},
"channels": {"type": "integer", "minimum": 1, "description": "Required only when the fixture is not in the library."},
},
},
"group": {
"type": "object",
"required": ["name", "fixtures"],
"properties": {
"name": {"type": "string"},
"fixtures": {"type": "array", "items": {"type": "string"}},
"columns": {"type": "integer", "minimum": 1},
},
},
"function": {
"type": "object",
"required": ["key", "type", "name"],
"description": "type is scene, efx, sequence, path, chaser, colour_chase, or collection.",
"properties": {
"key": {"type": "string"},
"type": {"enum": ["scene", "efx", "sequence", "path", "chaser", "colour_chase", "collection"]},
"name": {"type": "string"},
},
},
"widget": {
"type": "object",
"required": ["type", "caption", "x", "y", "w", "h"],
"properties": {
"type": {"enum": ["slider", "button", "xypad", "frame", "solo"]},
"caption": {"type": "string"},
"x": {"type": "integer"},
"y": {"type": "integer"},
"w": {"type": "integer"},
"h": {"type": "integer"},
"pages": {"type": "integer", "minimum": 1, "description": "Frame only. More than 1 makes it a multipage frame."},
"loop": {"type": "boolean", "description": "Frame only. Next page after the last wraps to the first."},
"page": {"type": "integer", "minimum": 0, "description": "Frame inside a multipage frame: which page it is on, from 0."},
"fg": {"$ref": "#/$defs/colour"},
"bg": {"$ref": "#/$defs/colour"},
"function": {"type": "string", "description": "Function key for a button."},
"fixture": {"type": "string", "description": "Fixture key for an XY pad."},
"channels": {
"type": "array",
"items": {
"type": "array",
"prefixItems": [{"type": "string"}, {"type": "integer"}],
"minItems": 2,
"maxItems": 2,
},
},
"input": {
"type": "object",
"properties": {
"universe": {"type": "integer"},
"note": {"type": "array", "items": {"type": "integer"}, "minItems": 2, "maxItems": 2},
"cc": {"type": "array", "items": {"type": "integer"}, "minItems": 2, "maxItems": 2},
"channel": {"type": "integer"},
},
},
},
},
"colour": {
"description": "[r, g, b], or the string Default, or a QLC+ ARGB decimal.",
"oneOf": [
{"type": "array", "items": {"type": "integer"}, "minItems": 3, "maxItems": 3},
{"type": "string"},
{"type": "integer"},
],
},
},
}
def validate(data: Any, *, root: Path | None = None) -> None:
errors = collect_errors(data, root=root)
if errors:
raise SpecError(errors)
def collect_errors(data: Any, *, root: Path | None = None) -> list[dict[str, str]]:
errors: list[dict[str, str]] = []
if not isinstance(data, dict):
return [{"path": "", "message": "show spec must be an object"}]
project = root or PROJECT_ROOT
library = FixtureLibrary(project)
_check_universes(data.get("universes", []), errors)
fixtures = _check_stage(data.get("stage", None), project, library, errors)
for key, info in _check_fixtures(data.get("fixtures", []), library, errors).items():
if key in fixtures:
_err(errors, f"fixtures.{key}", "duplicate fixture key")
else:
fixtures[key] = info
keys = set(fixtures)
_check_groups(data.get("groups", []), keys, errors)
functions = data.get("functions", [])
fn_keys = _check_functions(functions, fixtures, errors)
_check_widgets(data.get("vc", []), keys, fn_keys, fixtures, errors, "vc")
run = data.get("run", [])
if run is not None and not isinstance(run, list):
_err(errors, "run", "must be a list of function keys")
elif isinstance(run, list):
for index, key in enumerate(run):
if key not in fn_keys:
_err(errors, f"run.{index}", f"unknown function {key!r}")
if "vc_size" in data:
size = data["vc_size"]
if not (isinstance(size, list) and len(size) == 2 and all(isinstance(n, int) for n in size)):
_err(errors, "vc_size", "must be [width, height]")
return errors
def from_spec(data: dict[str, Any], *, root: Path | None = None) -> Show:
validate(data, root=root)
try:
return _build(data, root=root)
except SpecError:
raise
except (ValueError, KeyError) as exc:
raise SpecError([{"path": "", "message": str(exc)}]) from exc
def _build(data: dict[str, Any], *, root: Path | None) -> Show:
show = Show(author=str(data.get("author") or "Jimmy"), root=root)
if "vc_size" in data:
show.vc_size = (int(data["vc_size"][0]), int(data["vc_size"][1]))
universes = data.get("universes")
if not universes:
for index in range(4):
show.universe(index, f"Universe {index + 1}")
else:
for uni in universes:
output = None
midi = None
if uni.get("output"):
out = uni["output"]
output = ArtNetOutput(
uid=str(out["uid"]),
ip=str(out["ip"]),
universe=int(out.get("universe", 0)),
line=int(out.get("line", 0)),
)
if uni.get("input"):
inp = uni["input"]
midi = MidiInput(
uid=str(inp["uid"]),
profile=str(inp["profile"]),
channel=int(inp.get("channel", 0)),
line=int(inp.get("line", 0)),
)
show.universe(int(uni["id"]), uni.get("name"), output=output, midi=midi)
if data.get("stage"):
show.patch_stage(data["stage"])
for fx in data.get("fixtures", []):
show.patch(
fx["manufacturer"],
fx["model"],
fx["mode"],
address=int(fx["address"]),
name=fx.get("name"),
universe=int(fx.get("universe", 0)),
channels=int(fx["channels"]) if "channels" in fx else None,
key=fx["key"],
)
for group in data.get("groups", []):
show.group(group["name"], list(group["fixtures"]), columns=group.get("columns"))
pending = []
for fn in data.get("functions", []):
if fn["type"] in ("chaser", "collection"):
pending.append(fn)
else:
_add_function(show, fn)
while pending:
ready = [fn for fn in pending if _refs_ready(show, fn)]
if not ready:
missing = pending[0]
raise SpecError([{"path": f"functions.{missing['key']}", "message": "references a function that is not defined"}])
for fn in ready:
_add_function(show, fn)
pending = [fn for fn in pending if fn not in ready]
_add_widgets(show, show.vc, data.get("vc", []))
if data.get("run"):
show.run(*data["run"])
return show
Show.from_spec = staticmethod(from_spec) # type: ignore[method-assign]
def _refs_ready(show: Show, fn: dict[str, Any]) -> bool:
if fn["type"] == "collection":
return all(key in show.functions_by_key for key in fn.get("members", []))
return all(step["function"] in show.functions_by_key for step in fn.get("steps", []))
def _add_function(show: Show, fn: dict[str, Any]) -> None:
kind = fn["type"]
key = fn["key"]
name = fn["name"]
if kind == "scene":
show.scene(name, fn.get("values") or {}, key=key, fade_in=int(fn.get("fade_in", 0)), fade_out=int(fn.get("fade_out", 0)), duration=int(fn.get("duration", 0)))
elif kind == "efx":
show.efx(name, fn.get("fixtures") or [], key=key, **_efx_kwargs(fn))
elif kind == "sequence":
show.sequence(name, fn.get("steps") or [], key=key, direction=fn.get("direction", "Forward"), run_order=fn.get("run_order", "Loop"))
elif kind == "path":
show.path_sequence(
name,
fn.get("fixtures") or [],
fn.get("points") or [],
key=key,
smooth=bool(fn.get("smooth", False)),
subdivisions=int(fn.get("subdivisions", 6)),
closed=bool(fn.get("closed", True)),
direction=fn.get("direction", "Forward"),
run_order=fn.get("run_order", "Loop"),
)
elif kind == "colour_chase":
show.colour_chase(
name,
fn.get("fixtures") or [],
fn.get("channels") or {},
fn.get("frames") or [],
key=key,
fade_ms=int(fn.get("fade_ms", 0)),
hold_ms=int(fn.get("hold_ms", 0)),
run_order=fn.get("run_order", "Loop"),
)
elif kind == "chaser":
show.chaser(name, fn.get("steps") or [], key=key, direction=fn.get("direction", "Forward"), run_order=fn.get("run_order", "Loop"))
elif kind == "collection":
show.collection(name, list(fn.get("members") or []), key=key)
def _efx_kwargs(fn: dict[str, Any]) -> dict[str, Any]:
fields = (
"algorithm", "width", "height", "rotation", "start_offset",
"x_offset", "y_offset", "x_frequency", "y_frequency", "x_phase", "y_phase",
"duration_ms", "fade_in_ms", "fade_out_ms", "direction", "run_order", "propagation",
"relative", "homes",
)
return {field: fn[field] for field in fields if field in fn}
def _add_widgets(show: Show, frame: Any, widgets: list[dict[str, Any]]) -> None:
for widget in widgets:
kind = widget["type"]
box = dict(x=int(widget["x"]), y=int(widget["y"]), w=int(widget["w"]), h=int(widget["h"]))
binding = _binding(widget["input"]) if widget.get("input") else None
if kind == "slider":
frame.slider(
widget["caption"],
[(pair[0], int(pair[1])) for pair in widget.get("channels", [])],
value=int(widget.get("value", 0)),
fg=widget.get("fg", "Default"),
cng=str(widget.get("cng", "None")),
inverted=bool(widget.get("inverted", False)),
input=binding,
function=widget.get("function"),
**box,
)
elif kind == "button":
frame.button(
widget["caption"],
widget["function"],
fg=widget.get("fg", "4294967295"),
bg=widget.get("bg", "Default"),
action=str(widget.get("action", "Toggle")),
input=binding,
**box,
)
elif kind == "xypad":
frame.xypad(
widget["caption"],
widget["fixture"],
reverse_pan=bool(widget.get("reverse_pan", False)),
reverse_tilt=bool(widget.get("reverse_tilt", False)),
pan=int(widget.get("pan", 128)),
tilt=int(widget.get("tilt", 128)),
input=binding,
**box,
)
else:
child = frame.frame(
widget["caption"],
solo=kind == "solo" or bool(widget.get("solo", False)),
header=bool(widget.get("header", True)),
pages=int(widget.get("pages", 1)),
loop=bool(widget.get("loop", False)),
page=int(widget.get("page", 0)),
**box,
)
_add_widgets(show, child, widget.get("children") or [])
def _binding(raw: dict[str, Any]) -> MidiBinding:
if "channel" in raw:
channel = int(raw["channel"])
elif "note" in raw:
channel = midi_note(int(raw["note"][0]), int(raw["note"][1]))
else:
channel = midi_cc(int(raw["cc"][0]), int(raw["cc"][1]))
return MidiBinding(int(raw["universe"]), channel)
def _check_universes(universes: Any, errors: list[dict[str, str]]) -> None:
if not isinstance(universes, list):
_err(errors, "universes", "must be a list")
return
for index, uni in enumerate(universes):
path = f"universes.{index}"
if not isinstance(uni, dict) or not isinstance(uni.get("id"), int):
_err(errors, path, "must be an object with an integer id")
continue
output = uni.get("output")
if output is not None:
if not isinstance(output, dict) or "uid" not in output or "ip" not in output:
_err(errors, f"{path}.output", "Art-Net output needs uid and ip")
midi = uni.get("input")
if midi is not None:
if not isinstance(midi, dict) or "uid" not in midi or "profile" not in midi:
_err(errors, f"{path}.input", "MIDI input needs uid and profile")
def _check_stage(
stage: Any,
root: Path,
library: FixtureLibrary,
errors: list[dict[str, str]],
) -> dict[str, dict[str, Any]]:
found: dict[str, dict[str, Any]] = {}
if stage is None:
return found
if not isinstance(stage, str) or not stage.strip():
_err(errors, "stage", "must be a path to a stage map")
return found
target = _stage_file(stage, root, errors)
if target is None:
return found
try:
document = json.loads(target.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
_err(errors, "stage", f"invalid JSON: {exc}")
return found
if not isinstance(document, dict):
_err(errors, "stage", "stage map must be an object")
return found
definitions = document.get("definitions")
fixtures = document.get("fixtures")
if not isinstance(definitions, dict) or not isinstance(fixtures, dict):
_err(errors, "stage", "stage map needs definitions and fixtures")
return found
for key, raw in fixtures.items():
path = f"stage.fixtures.{key}"
if not isinstance(raw, dict):
_err(errors, path, "must be an object")
continue
defin = definitions.get(raw.get("def"))
if not isinstance(defin, dict):
_err(errors, f"{path}.def", "unknown definition")
continue
if not isinstance(raw.get("address"), int) or raw["address"] < 0:
_err(errors, f"{path}.address", "must be an address of 0 or more")
continue
manufacturer = defin.get("manufacturer")
model = defin.get("model")
mode = defin.get("mode")
if not all(isinstance(item, str) and item for item in (manufacturer, model, mode)):
_err(errors, f"{path}.def", "definition needs manufacturer, model, and mode")
continue
definition = library.find(manufacturer, model)
mode_info = definition.mode(mode) if definition is not None else None
if mode_info is None:
_err(errors, path, f"unknown fixture {manufacturer} {model} mode {mode!r}")
continue
count = len(mode_info.channels)
if raw["address"] + count > 512:
_err(errors, f"{path}.address", "fixture extends past DMX channel 512")
if key in found:
_err(errors, path, "duplicate fixture key")
continue
found[key] = {"channels": count, "mover": mode_info.is_mover}
return found
def _stage_file(stage: str, root: Path, errors: list[dict[str, str]]) -> Path | None:
candidate = Path(stage)
base = root.resolve()
target = candidate.resolve() if candidate.is_absolute() else (base / candidate).resolve()
if target != base and base not in target.parents:
_err(errors, "stage", f"{stage} is outside the project")
return None
if not target.is_file():
_err(errors, "stage", f"stage map not found: {stage}")
return None
return target
def _check_fixtures(fixtures: Any, library: FixtureLibrary, errors: list[dict[str, str]]) -> dict[str, dict[str, Any]]:
found: dict[str, dict[str, Any]] = {}
if not isinstance(fixtures, list):
_err(errors, "fixtures", "must be a list")
return found
for index, fx in enumerate(fixtures):
path = f"fixtures.{index}"
if not isinstance(fx, dict):
_err(errors, path, "must be an object")
continue
key = fx.get("key")
if not isinstance(key, str) or not key:
_err(errors, f"{path}.key", "must be a non-empty string")
continue
path = f"fixtures.{key}"
if key in found:
_err(errors, path, "duplicate fixture key")
continue
for field in ("manufacturer", "model", "mode"):
if not isinstance(fx.get(field), str) or not fx[field]:
_err(errors, f"{path}.{field}", "must be a non-empty string")
if not isinstance(fx.get("address"), int) or fx["address"] < 0:
_err(errors, f"{path}.address", "must be an address of 0 or more")
continue
definition = None
if isinstance(fx.get("manufacturer"), str) and isinstance(fx.get("model"), str):
definition = library.find(fx["manufacturer"], fx["model"])
mode_info = definition.mode(fx["mode"]) if definition is not None and isinstance(fx.get("mode"), str) else None
if definition is None and "channels" not in fx:
_err(errors, path, "unknown fixture; add it under fixtures/ or set channels")
elif definition is not None and mode_info is None:
_err(errors, f"{path}.mode", f"unknown mode {fx.get('mode')!r}")
count = None
if mode_info is not None:
count = len(mode_info.channels)
if "channels" in fx and fx["channels"] != count:
_err(errors, f"{path}.channels", f"mode {fx['mode']} has {count} channels")
elif isinstance(fx.get("channels"), int) and fx["channels"] > 0:
count = fx["channels"]
elif "channels" in fx:
_err(errors, f"{path}.channels", "must be a positive integer")
if count is not None and fx["address"] + count > 512:
_err(errors, f"{path}.address", "fixture extends past DMX channel 512")
mover = bool(mode_info and mode_info.pan_msb is not None and mode_info.tilt_msb is not None)
found[key] = {"channels": count or 0, "mover": mover}
return found
def _check_groups(groups: Any, fixtures: set[str], errors: list[dict[str, str]]) -> None:
if not isinstance(groups, list):
_err(errors, "groups", "must be a list")
return
for index, group in enumerate(groups):
path = f"groups.{index}"
if not isinstance(group, dict) or not isinstance(group.get("name"), str):
_err(errors, path, "must be an object with a name")
continue
members = group.get("fixtures")
if not isinstance(members, list) or not members:
_err(errors, f"{path}.fixtures", "must list fixture keys")
continue
for member in members:
if member not in fixtures:
_err(errors, f"{path}.fixtures", f"unknown fixture {member!r}")
def _check_functions(
functions: Any,
fixtures: dict[str, dict[str, Any]],
errors: list[dict[str, str]],
) -> set[str]:
keys: set[str] = set()
if not isinstance(functions, list):
_err(errors, "functions", "must be a list")
return keys
for index, fn in enumerate(functions):
path = f"functions.{index}"
if not isinstance(fn, dict):
_err(errors, path, "must be an object")
continue
key = fn.get("key")
if not isinstance(key, str) or not key:
_err(errors, f"{path}.key", "must be a non-empty string")
continue
path = f"functions.{key}"
if key in keys:
_err(errors, path, "duplicate function key")
continue
keys.add(key)
kind = fn.get("type")
if kind not in ("scene", "efx", "sequence", "path", "chaser", "colour_chase", "collection"):
_err(errors, f"{path}.type", "must be scene, efx, sequence, path, chaser, colour_chase, or collection")
continue
if not isinstance(fn.get("name"), str) or not fn["name"]:
_err(errors, f"{path}.name", "must be a non-empty string")
if kind == "scene":
_check_values(fn.get("values") or {}, fixtures, errors, f"{path}.values")
elif kind == "efx":
_check_efx(fn, fixtures, errors, path)
elif kind == "sequence":
_check_sequence(fn, fixtures, errors, path)
elif kind == "path":
_check_path(fn, fixtures, errors, path)
elif kind == "colour_chase":
_check_chase(fn, fixtures, errors, path)
elif kind == "chaser":
_check_chaser_steps(fn.get("steps"), errors, path)
elif kind == "collection":
members = fn.get("members")
if not isinstance(members, list) or not members:
_err(errors, f"{path}.members", "must list function keys")
for fn in functions if isinstance(functions, list) else []:
if not isinstance(fn, dict) or fn.get("type") not in ("chaser", "collection"):
continue
path = f"functions.{fn.get('key')}"
if fn["type"] == "collection":
for member in fn.get("members") or []:
if member not in keys:
_err(errors, f"{path}.members", f"unknown function {member!r}")
else:
for index, step in enumerate(fn.get("steps") or []):
if isinstance(step, dict) and step.get("function") not in keys:
_err(errors, f"{path}.steps.{index}.function", f"unknown function {step.get('function')!r}")
return keys
def _check_values(values: Any, fixtures: dict[str, dict[str, Any]], errors: list[dict[str, str]], path: str) -> None:
if not isinstance(values, dict):
_err(errors, path, "must map fixture keys to channel values")
return
for key, channels in values.items():
if key not in fixtures:
_err(errors, f"{path}.{key}", f"unknown fixture {key!r}")
continue
if not isinstance(channels, dict):
_err(errors, f"{path}.{key}", "must map channel numbers to values")
continue
count = fixtures[key]["channels"]
for ch, val in channels.items():
try:
index = int(ch)
number = int(val)
except (TypeError, ValueError):
_err(errors, f"{path}.{key}.{ch}", "channel and value must be integers")
continue
if count and not 0 <= index < count:
_err(errors, f"{path}.{key}.{ch}", f"channel {index} is outside 0–{count - 1}")
if not 0 <= number <= 255:
_err(errors, f"{path}.{key}.{ch}", "value must be 0–255")
def _check_efx(fn: dict[str, Any], fixtures: dict[str, dict[str, Any]], errors: list[dict[str, str]], path: str) -> None:
entries = fn.get("fixtures")
if not isinstance(entries, list) or not entries:
_err(errors, f"{path}.fixtures", "must list fixture keys")
return
for item in entries:
key = item if isinstance(item, str) else item.get("fixture") if isinstance(item, dict) else None
if key not in fixtures:
_err(errors, f"{path}.fixtures", f"unknown fixture {key!r}")
elif not fixtures[key]["mover"]:
_err(errors, f"{path}.fixtures", f"{key} has no pan/tilt in this mode")
algorithm = fn.get("algorithm", "Circle")
if algorithm not in ALGORITHMS:
_err(errors, f"{path}.algorithm", f"must be one of {', '.join(ALGORITHMS)}")
_choice(errors, fn, "direction", DIRECTIONS, path, "Forward")
_choice(errors, fn, "run_order", RUN_ORDERS, path, "Loop")
_choice(errors, fn, "propagation", PROPAGATIONS, path, "Parallel")
_range(errors, fn, "width", 0, 127, path)
_range(errors, fn, "height", 0, 127, path)
_range(errors, fn, "x_offset", 0, 255, path)
_range(errors, fn, "y_offset", 0, 255, path)
_range(errors, fn, "x_frequency", 0, 5, path)
_range(errors, fn, "y_frequency", 0, 5, path)
if "duration_ms" in fn and (not isinstance(fn["duration_ms"], int) or fn["duration_ms"] < 20):
_err(errors, f"{path}.duration_ms", "must be at least 20")
homes = fn.get("homes") or {}
if homes and not isinstance(homes, dict):
_err(errors, f"{path}.homes", "must map fixture keys to [pan, tilt]")
elif isinstance(homes, dict):
for key, home in homes.items():
if key not in fixtures:
_err(errors, f"{path}.homes.{key}", f"unknown fixture {key!r}")
elif not (isinstance(home, list) and len(home) == 2 and all(isinstance(n, int) and 0 <= n <= 255 for n in home)):
_err(errors, f"{path}.homes.{key}", "must be [pan, tilt] in 0–255")
def _check_sequence(fn: dict[str, Any], fixtures: dict[str, dict[str, Any]], errors: list[dict[str, str]], path: str) -> None:
steps = fn.get("steps")
if not isinstance(steps, list) or not steps:
_err(errors, f"{path}.steps", "must be a list of steps")
return
_choice(errors, fn, "direction", DIRECTIONS, path, "Forward")
_choice(errors, fn, "run_order", RUN_ORDERS, path, "Loop")
for index, step in enumerate(steps):
if not isinstance(step, dict):
_err(errors, f"{path}.steps.{index}", "must be an object")
continue
_check_values(step.get("values") or {}, fixtures, errors, f"{path}.steps.{index}.values")
for field in ("fade_ms", "hold_ms", "fade_out_ms"):
if field in step and (not isinstance(step[field], int) or step[field] < 0):
_err(errors, f"{path}.steps.{index}.{field}", "must be 0 or more")
def _check_path(fn: dict[str, Any], fixtures: dict[str, dict[str, Any]], errors: list[dict[str, str]], path: str) -> None:
entries = fn.get("fixtures")
points = fn.get("points")
if not isinstance(entries, list) or not entries:
_err(errors, f"{path}.fixtures", "must list fixtures")
else:
for item in entries:
key = item if isinstance(item, str) else item.get("fixture") if isinstance(item, dict) else None
if key not in fixtures:
_err(errors, f"{path}.fixtures", f"unknown fixture {key!r}")
elif not fixtures[key]["mover"]:
_err(errors, f"{path}.fixtures", f"{key} has no pan/tilt in this mode")
if not isinstance(points, list) or not points:
_err(errors, f"{path}.points", "must list pan/tilt points")
else:
for index, point in enumerate(points):
if not isinstance(point, dict) or "pan" not in point or "tilt" not in point:
_err(errors, f"{path}.points.{index}", "must have pan and tilt")
_choice(errors, fn, "direction", DIRECTIONS, path, "Forward")
_choice(errors, fn, "run_order", RUN_ORDERS, path, "Loop")
def _check_chase(fn: dict[str, Any], fixtures: dict[str, dict[str, Any]], errors: list[dict[str, str]], path: str) -> None:
members = fn.get("fixtures")
frames = fn.get("frames")
channels = fn.get("channels")
if not isinstance(members, list) or not members:
_err(errors, f"{path}.fixtures", "must list fixture keys")
members = []
else:
for key in members:
if key not in fixtures:
_err(errors, f"{path}.fixtures", f"unknown fixture {key!r}")
if not isinstance(channels, dict) or not channels:
_err(errors, f"{path}.channels", "must map names such as r, g, b to channel numbers")
channels = {}
if not isinstance(frames, list) or not frames:
_err(errors, f"{path}.frames", "must list colour frames")
return
for index, frame in enumerate(frames):
if not isinstance(frame, list) or len(frame) != len(members):
_err(errors, f"{path}.frames.{index}", f"must have one colour for each of {len(members)} fixtures")
continue
for colour in frame:
if isinstance(colour, dict):
continue
if not isinstance(colour, list) or len(colour) != len(channels):
_err(errors, f"{path}.frames.{index}", f"colour must have {len(channels)} values")
break
if any(not isinstance(n, int) or not 0 <= n <= 255 for n in colour):
_err(errors, f"{path}.frames.{index}", "colour values must be 0–255")
def _check_chaser_steps(steps: Any, errors: list[dict[str, str]], path: str) -> None:
if not isinstance(steps, list) or not steps:
_err(errors, f"{path}.steps", "must list steps")
return
for index, step in enumerate(steps):
if not isinstance(step, dict) or not isinstance(step.get("function"), str):
_err(errors, f"{path}.steps.{index}.function", "must name a function key")
for field in ("fade_ms", "hold_ms", "fade_out_ms"):
if isinstance(step, dict) and field in step and (not isinstance(step[field], int) or step[field] < 0):
_err(errors, f"{path}.steps.{index}.{field}", "must be 0 or more")
def _check_widgets(
widgets: Any,
fixtures: set[str],
functions: set[str],
fixture_info: dict[str, dict[str, Any]],
errors: list[dict[str, str]],
path: str,
) -> None:
if not isinstance(widgets, list):
_err(errors, path, "must be a list")
return
for index, widget in enumerate(widgets):
here = f"{path}.{index}"
if not isinstance(widget, dict):
_err(errors, here, "must be an object")
continue
kind = widget.get("type")
if kind not in ("slider", "button", "xypad", "frame", "solo"):
_err(errors, f"{here}.type", "must be slider, button, xypad, frame, or solo")
continue
if not isinstance(widget.get("caption"), str):
_err(errors, f"{here}.caption", "must be a string")
for field in ("x", "y", "w", "h"):
if not isinstance(widget.get(field), int):
_err(errors, f"{here}.{field}", "must be an integer")
if kind == "slider":
channels = widget.get("channels")
if "function" in widget:
if widget["function"] not in functions:
_err(errors, f"{here}.function", f"unknown function {widget['function']!r}")
channels = []
elif not isinstance(channels, list) or not channels:
_err(errors, f"{here}.channels", "must list [fixture, channel] pairs")
else:
for pair in channels:
if not (isinstance(pair, list) and len(pair) == 2 and isinstance(pair[1], int)):
_err(errors, f"{here}.channels", "each entry is [fixture key, channel]")
continue
if pair[0] not in fixtures:
_err(errors, f"{here}.channels", f"unknown fixture {pair[0]!r}")
elif fixture_info[pair[0]]["channels"] and not 0 <= pair[1] < fixture_info[pair[0]]["channels"]:
_err(errors, f"{here}.channels", f"channel {pair[1]} is outside {pair[0]}")
elif kind == "button":
if widget.get("function") not in functions:
_err(errors, f"{here}.function", f"unknown function {widget.get('function')!r}")
if "action" in widget and widget["action"] not in ("Toggle", "Flash"):
_err(errors, f"{here}.action", "must be Toggle or Flash")
elif kind == "xypad":
if widget.get("fixture") not in fixtures:
_err(errors, f"{here}.fixture", f"unknown fixture {widget.get('fixture')!r}")
elif not fixture_info[widget["fixture"]]["mover"]:
_err(errors, f"{here}.fixture", f"{widget['fixture']} has no pan/tilt in this mode")
else:
_check_widgets(widget.get("children") or [], fixtures, functions, fixture_info, errors, f"{here}.children")
if "input" in widget:
_check_input(widget["input"], errors, f"{here}.input")
for field in ("fg", "bg"):
if field in widget:
_check_colour(widget[field], errors, f"{here}.{field}")
def _check_input(raw: Any, errors: list[dict[str, str]], path: str) -> None:
if not isinstance(raw, dict) or not isinstance(raw.get("universe"), int):
_err(errors, path, "must have a universe")
return
kinds = [name for name in ("note", "cc", "channel") if name in raw]
if len(kinds) != 1:
_err(errors, path, "set one of note, cc, or channel")
return
if "note" in raw:
pair = raw["note"]
if not (isinstance(pair, list) and len(pair) == 2 and all(isinstance(n, int) for n in pair)):
_err(errors, f"{path}.note", "must be [channel 0–15, note 0–127]")
elif not 0 <= pair[0] <= 15 or not 0 <= pair[1] <= 127:
_err(errors, f"{path}.note", "must be [channel 0–15, note 0–127]")
elif "cc" in raw:
pair = raw["cc"]
if not (isinstance(pair, list) and len(pair) == 2 and all(isinstance(n, int) for n in pair)):
_err(errors, f"{path}.cc", "must be [channel 0–15, cc 0–127]")
elif not 0 <= pair[0] <= 15 or not 0 <= pair[1] <= 127:
_err(errors, f"{path}.cc", "must be [channel 0–15, cc 0–127]")
def _check_colour(value: Any, errors: list[dict[str, str]], path: str) -> None:
if isinstance(value, str) or isinstance(value, int):
return
if isinstance(value, list) and len(value) == 3 and all(isinstance(n, int) and 0 <= n <= 255 for n in value):
return
_err(errors, path, "must be [r, g, b], Default, or an ARGB decimal")
def _choice(errors: list[dict[str, str]], fn: dict[str, Any], field: str, allowed: tuple[str, ...], path: str, default: str) -> None:
value = fn.get(field, default)
if value not in allowed:
_err(errors, f"{path}.{field}", f"must be one of {', '.join(allowed)}")
def _range(errors: list[dict[str, str]], fn: dict[str, Any], field: str, lo: int, hi: int, path: str) -> None:
if field not in fn:
return
value = fn[field]
if not isinstance(value, int) or not lo <= value <= hi:
_err(errors, f"{path}.{field}", f"must be {lo}–{hi}")
def _err(errors: list[dict[str, str]], path: str, message: str) -> None:
errors.append({"path": path, "message": message})
+79
View File
@@ -0,0 +1,79 @@
"""Patch a Show from a stage map."""
from __future__ import annotations
import json
from dataclasses import dataclass, field
from pathlib import Path
from .model import Fixture, Show
PROJECT_ROOT = Path(__file__).resolve().parents[1]
@dataclass
class StageRig:
path: Path
name: str
cans: list[Fixture] = field(default_factory=list)
movers: list[Fixture] = field(default_factory=list)
def __getitem__(self, key: str) -> Fixture:
for fixture in (*self.cans, *self.movers):
if fixture.key == key:
return fixture
raise KeyError(key)
def patch_stage(show: Show, path: str | Path | None = None) -> StageRig:
"""Patch every fixture in the stage map and group cans and movers."""
source = _map_path(path, show.root or PROJECT_ROOT)
document = json.loads(source.read_text(encoding="utf-8"))
definitions = document.get("definitions")
fixtures = document.get("fixtures")
if not isinstance(definitions, dict) or not isinstance(fixtures, dict):
raise ValueError(f"{source} needs definitions and fixtures")
rig = StageRig(path=source, name=str(document.get("name") or source.stem))
for key, raw in fixtures.items():
if not isinstance(raw, dict):
raise ValueError(f"{key} is not a fixture")
defin = definitions.get(raw.get("def"))
if not isinstance(defin, dict):
raise ValueError(f"{key} has no definition {raw.get('def')!r}")
fixture = show.patch(
str(defin["manufacturer"]),
str(defin["model"]),
str(defin["mode"]),
address=int(raw["address"]),
universe=int(raw.get("universe", 0)),
name=str(raw.get("label") or key),
key=str(key),
)
listed = raw.get("channels")
if isinstance(listed, int) and listed != fixture.channels:
raise ValueError(f"{key} says {listed} channels; {defin['mode']} has {fixture.channels}")
fixture.x = float(raw["x"]) if "x" in raw else None
fixture.y = float(raw["y"]) if "y" in raw else None
fixture.direction = float(raw["direction"]) if "direction" in raw else None
fixture.zero = float(raw["zero"]) if "zero" in raw else None
fixture.kind = str(raw.get("kind") or "")
if fixture.kind == "mover":
rig.movers.append(fixture)
else:
rig.cans.append(fixture)
if rig.cans:
show.group("Cans", rig.cans, columns=len(rig.cans))
if rig.movers:
show.group("Movers", rig.movers, columns=len(rig.movers))
return rig
def _map_path(path: str | Path | None, root: Path) -> Path:
source = Path(path) if path is not None else root / "stage" / "map.json"
base = root.resolve()
target = source.resolve() if source.is_absolute() else (base / source).resolve()
if target != base and base not in target.parents:
raise ValueError(f"{path} is outside the project")
if not target.is_file():
raise ValueError(f"stage map not found: {path or target}")
return target
+252
View File
@@ -0,0 +1,252 @@
"""Operations behind the CLI and the MCP server."""
from __future__ import annotations
from pathlib import Path
from typing import Any
from patternstudio.efx import (
ALGORITHMS,
DIRECTIONS,
PROPAGATIONS,
RUN_ORDERS,
Efx,
EfxFixture,
Path as EfxPath,
PathFixture,
PathPoint,
)
from patternstudio.fixturedefs import load_fixture_def
from .play import load_show, play
from .spec import PROJECT_ROOT, SpecError, collect_errors, from_spec, show_schema
__all__ = [
"list_fixtures",
"sample_animation",
"show_schema",
"validate_show",
"write_show",
"run_script",
]
def list_fixtures(root: Path | None = None) -> dict[str, Any]:
"""Manufacturer, model, modes, and channel maps from the project's fixtures/ directory."""
folder = (root or PROJECT_ROOT) / "fixtures"
fixtures = []
if folder.is_dir():
for path in sorted(folder.glob("*.qxf")):
definition = load_fixture_def(str(path))
fixtures.append(
{
"manufacturer": definition.manufacturer,
"model": definition.model,
"type": definition.type,
"modes": [
{
"name": mode.name,
"pan_msb": mode.pan_msb,
"pan_lsb": mode.pan_lsb,
"tilt_msb": mode.tilt_msb,
"tilt_lsb": mode.tilt_lsb,
"channels": [
{"index": ch.index, "name": ch.name, "preset": ch.preset, "group": ch.group}
for ch in mode.channels
],
}
for mode in definition.modes.values()
],
}
)
return {"fixtures": fixtures}
def validate_show(spec: dict[str, Any], root: Path | None = None) -> dict[str, Any]:
"""Check a show spec. Writes nothing."""
errors = collect_errors(spec, root=root)
return {"ok": not errors, "errors": errors}
def write_show(spec: dict[str, Any], path: str, root: Path | None = None) -> dict[str, Any]:
"""Write a .qxw inside the project and return the ids that were assigned."""
base = (root or PROJECT_ROOT).resolve()
try:
target = _inside(base, path)
show = from_spec(spec, root=base)
except SpecError as exc:
return {"ok": False, "errors": exc.errors}
target.parent.mkdir(parents=True, exist_ok=True)
show.write(target)
return {"ok": True, "path": str(target.relative_to(base)), **show.summary()}
def sample_animation(block: dict[str, Any], steps: int = 32) -> dict[str, Any]:
"""Pan/tilt samples for one efx or path block, before it is written into a show."""
if not isinstance(block, dict) or block.get("type") not in ("efx", "path"):
return {"ok": False, "errors": [{"path": "type", "message": "sample an efx or path block"}]}
count = max(1, min(128, int(steps)))
try:
if block["type"] == "efx":
return {"ok": True, **_sample_efx(block, count)}
return {"ok": True, **_sample_path(block)}
except (KeyError, TypeError, ValueError) as exc:
return {"ok": False, "errors": [{"path": "", "message": str(exc)}]}
def run_script(
path: str,
*,
seconds: float | None = None,
ip: str | None = None,
universe: int = 0,
hz: float = 40.0,
root: Path | None = None,
) -> dict[str, Any]:
"""Play a Python build() script, or a JSON spec, and return samples or send Art-Net."""
base = (root or PROJECT_ROOT).resolve()
try:
source = _inside(base, path)
show = load_show(source)
return play(show, seconds=seconds, ip=ip, universe=universe, hz=hz)
except SpecError as exc:
return {"ok": False, "errors": exc.errors}
def _inside(root: Path, rel: str) -> Path:
candidate = Path(rel)
target = candidate.resolve() if candidate.is_absolute() else (root / candidate).resolve()
if target != root and root not in target.parents:
raise SpecError([{"path": "path", "message": f"{rel} is outside the project"}])
return target
def _sample_efx(block: dict[str, Any], steps: int) -> dict[str, Any]:
algorithm = block.get("algorithm", "Circle")
if algorithm not in ALGORITHMS:
raise ValueError(f"unknown algorithm {algorithm!r}")
_choice(block.get("direction", "Forward"), DIRECTIONS, "direction")
_choice(block.get("run_order", "Loop"), RUN_ORDERS, "run_order")
_choice(block.get("propagation", "Parallel"), PROPAGATIONS, "propagation")
entries = block.get("fixtures") or []
if not entries:
raise ValueError("efx has no fixtures")
relative = bool(block.get("relative"))
homes = block.get("homes") or {}
fixtures = []
keys = []
for index, item in enumerate(entries):
if isinstance(item, str):
key, direction, offset = item, "Forward", 0
pan = tilt = 128
elif isinstance(item, dict) and "fixture" in item:
key = str(item["fixture"])
direction = item.get("direction", "Forward")
offset = int(item.get("start_offset", 0))
pan = int(item.get("pan", 128))
tilt = int(item.get("tilt", 128))
else:
raise ValueError("each efx fixture is a key or {fixture, ...}")
if key in homes:
pan, tilt = int(homes[key][0]), int(homes[key][1])
keys.append(key)
fixtures.append(EfxFixture(id=index, direction=direction, start_offset=offset, pan=pan, tilt=tilt))
width = _bounded(block.get("width", 40), 0, 127, "width")
height = _bounded(block.get("height", 40), 0, 127, "height")
duration = int(block.get("duration_ms", 8000))
if duration < 20:
raise ValueError("duration_ms must be at least 20")
pattern = Efx(
algorithm=algorithm,
width=width,
height=height,
rotation=int(block.get("rotation", 0)) % 360,
start_offset=int(block.get("start_offset", 0)) % 360,
x_offset=127 if relative else _bounded(block.get("x_offset", 128), 0, 255, "x_offset"),
y_offset=127 if relative else _bounded(block.get("y_offset", 128), 0, 255, "y_offset"),
x_frequency=_bounded(block.get("x_frequency", 1), 0, 5, "x_frequency"),
y_frequency=_bounded(block.get("y_frequency", 1), 0, 5, "y_frequency"),
x_phase=int(block.get("x_phase", 0)) % 360,
y_phase=int(block.get("y_phase", 0)) % 360,
duration_ms=duration,
direction=block.get("direction", "Forward"),
run_order=block.get("run_order", "Loop"),
propagation=block.get("propagation", "Parallel"),
relative=relative,
fixtures=fixtures,
)
sampled = pattern.sample(steps=steps)
for track, fx in zip(sampled["tracks"], fixtures):
track["key"] = keys[fx.id]
if relative:
track["points"] = [
[
round(max(0.0, min(255.0, fx.pan + (x - 127))), 2),
round(max(0.0, min(255.0, fx.tilt + (y - 127))), 2),
]
for x, y in track["points"]
]
return sampled
def _sample_path(block: dict[str, Any]) -> dict[str, Any]:
entries = block.get("fixtures") or []
points = block.get("points") or []
if not entries or not points:
raise ValueError("path needs fixtures and points")
fixtures = []
keys = []
for index, item in enumerate(entries):
if isinstance(item, str):
key, pan_offset, tilt_offset, mirror_pan, mirror_tilt = item, 0, 0, False, False
elif isinstance(item, dict):
key = str(item["fixture"])
pan_offset = int(item.get("pan_offset", 0))
tilt_offset = int(item.get("tilt_offset", 0))
mirror_pan = bool(item.get("mirror_pan", False))
mirror_tilt = bool(item.get("mirror_tilt", False))
else:
raise ValueError("each path fixture is a key or {fixture, mirror_pan}")
keys.append(key)
fixtures.append(
PathFixture(
id=index,
pan_offset=pan_offset,
tilt_offset=tilt_offset,
mirror_pan=mirror_pan,
mirror_tilt=mirror_tilt,
)
)
path = EfxPath(
points=[
PathPoint(
pan=float(point["pan"]),
tilt=float(point["tilt"]),
fade_ms=int(point.get("fade_ms", 1000)),
hold_ms=int(point.get("hold_ms", 0)),
)
for point in points
],
smooth=bool(block.get("smooth", False)),
subdivisions=int(block.get("subdivisions", 6)),
closed=bool(block.get("closed", True)),
run_order=block.get("run_order", "Loop"),
direction=block.get("direction", "Forward"),
fixtures=fixtures,
)
sampled = path.sample()
for track in sampled["tracks"]:
track["key"] = keys[track["id"]]
return sampled
def _choice(value: str, allowed: tuple[str, ...], label: str) -> None:
if value not in allowed:
raise ValueError(f"{label} must be one of {', '.join(allowed)}")
def _bounded(value: Any, lo: int, hi: int, label: str) -> int:
number = int(value)
if not lo <= number <= hi:
raise ValueError(f"{label} must be {lo}–{hi}")
return number
+326
View File
@@ -0,0 +1,326 @@
"""Virtual console widgets."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any
from .model import INVALID_FUNCTION, MidiBinding
from .xmlutil import appearance, attr
if TYPE_CHECKING:
from .model import Show
@dataclass
class Slider:
id: int
caption: str
channels: list[tuple[int, int]]
x: int
y: int
w: int
h: int
value: int = 0
fg: Any = "Default"
cng: str = "None"
inverted: bool = False
binding: MidiBinding | None = None
function_id: int | None = None # set for a Playback slider, which has no channels
type_name: str = "Slider"
def render(self, indent: str = " ") -> str:
inner = indent + " "
inv = "true" if self.inverted else "false"
channels = "\n".join(
f'{inner} <Channel Fixture="{fid}">{ch}</Channel>' for fid, ch in self.channels
)
extra = _input_xml(self.binding, inner)
return (
f"{indent}<Slider Caption={attr(self.caption)} ID=\"{self.id}\" "
f'WidgetStyle="Slider" InvertedAppearance="{inv}">\n'
f'{inner}<WindowState Visible="True" X="{self.x}" Y="{self.y}" '
f'Width="{self.w}" Height="{self.h}"/>\n'
f"{appearance(fg=self.fg, indent=inner)}\n"
f'{inner}<SliderMode ValueDisplayStyle="Exact" ClickAndGoType={attr(self.cng)} '
f'Monitor="true">{"Playback" if self.function_id is not None else "Level"}</SliderMode>\n'
f"{inner}<Reset/>\n"
f'{inner}<Level LowLimit="0" HighLimit="255" Value="{self.value}">\n'
f"{channels}\n"
f"{inner}</Level>\n"
f"{inner}<Playback>\n"
f"{inner} <Function>{INVALID_FUNCTION if self.function_id is None else self.function_id}</Function>\n"
f"{inner}</Playback>{extra}\n"
f"{indent}</Slider>"
)
@dataclass
class Button:
id: int
caption: str
function_id: int
x: int
y: int
w: int
h: int
fg: Any = "4294967295"
bg: Any = "Default"
action: str = "Toggle"
binding: MidiBinding | None = None
type_name: str = "Button"
def render(self, indent: str = " ") -> str:
inner = indent + " "
extra = _input_xml(self.binding, inner)
return (
f"{indent}<Button Caption={attr(self.caption)} ID=\"{self.id}\" Icon=\"\">\n"
f'{inner}<WindowState Visible="True" X="{self.x}" Y="{self.y}" '
f'Width="{self.w}" Height="{self.h}"/>\n'
f"{appearance(fg=self.fg, bg=self.bg, frame='None', indent=inner)}\n"
f'{inner}<Function ID="{self.function_id}"/>\n'
f"{inner}<Action>{self.action}</Action>\n"
f'{inner}<Intensity Adjust="False">100</Intensity>{extra}\n'
f"{indent}</Button>"
)
@dataclass
class XYPad:
id: int
caption: str
fixture_id: int
x: int
y: int
w: int
h: int
reverse_pan: bool = False
reverse_tilt: bool = False
pan: int = 128
tilt: int = 128
binding: MidiBinding | None = None
type_name: str = "XYPad"
def render(self, indent: str = " ") -> str:
inner = indent + " "
pan_rev = "True" if self.reverse_pan else "False"
tilt_rev = "True" if self.reverse_tilt else "False"
extra = _input_xml(self.binding, inner)
return (
f"{indent}<XYPad Caption={attr(self.caption)} ID=\"{self.id}\" InvertedAppearance=\"0\">\n"
f'{inner}<WindowState Visible="True" X="{self.x}" Y="{self.y}" '
f'Width="{self.w}" Height="{self.h}"/>\n'
f"{appearance(indent=inner)}\n"
f'{inner}<Fixture ID="{self.fixture_id}" Head="0">\n'
f'{inner} <Axis ID="X" LowLimit="0" HighLimit="1" Reverse="{pan_rev}"/>\n'
f'{inner} <Axis ID="Y" LowLimit="0" HighLimit="1" Reverse="{tilt_rev}"/>\n'
f"{inner}</Fixture>\n"
f'{inner}<Window hMin="0" hMax="255" vMin="0" vMax="255"/>\n'
f'{inner}<Pan Position="{self.pan}"/>\n'
f'{inner}<Tilt Position="{self.tilt}"/>{extra}\n'
f"{indent}</XYPad>"
)
@dataclass
class Frame:
show: Show
caption: str
x: int = 0
y: int = 0
w: int = 0
h: int = 0
solo: bool = False
root: bool = False
show_header: bool = True
pages: int = 1
loop: bool = False
page: int = 0
children: list[Any] = field(default_factory=list)
id: int | None = None
type_name: str = "Frame"
def __post_init__(self) -> None:
self.type_name = "SoloFrame" if self.solo else "Frame"
if not self.root and self.id is None:
self.id = self.show.alloc_widget()
def slider(
self,
caption: str,
channels: list[tuple[Any, int]],
*,
x: int,
y: int,
w: int,
h: int,
value: int = 0,
fg: Any = "Default",
cng: str = "None",
inverted: bool = False,
input: MidiBinding | None = None,
function: Any = None,
) -> Slider:
if isinstance(function, str):
function = self.show.functions_by_key[function].id
widget = Slider(
id=self.show.alloc_widget(),
caption=caption,
channels=[(self.show.fixture_id(fx), int(ch)) for fx, ch in channels],
x=x,
y=y,
w=w,
h=h,
value=int(value),
fg=fg,
cng=cng,
inverted=inverted,
binding=input,
function_id=function,
)
self.children.append(widget)
return widget
def button(
self,
caption: str,
function: Any,
*,
x: int,
y: int,
w: int,
h: int,
fg: Any = "4294967295",
bg: Any = "Default",
action: str = "Toggle",
input: MidiBinding | None = None,
) -> Button:
if isinstance(function, int):
fid = function
elif isinstance(function, str):
fid = self.show.functions_by_key[function].id
else:
fid = function.id
widget = Button(
id=self.show.alloc_widget(),
caption=caption,
function_id=fid,
x=x,
y=y,
w=w,
h=h,
fg=fg,
bg=bg,
action=action,
binding=input,
)
self.children.append(widget)
return widget
def xypad(
self,
caption: str,
fixture: Any,
*,
x: int,
y: int,
w: int,
h: int,
reverse_pan: bool = False,
reverse_tilt: bool = False,
pan: int = 128,
tilt: int = 128,
input: MidiBinding | None = None,
) -> XYPad:
widget = XYPad(
id=self.show.alloc_widget(),
caption=caption,
fixture_id=self.show.fixture_id(fixture),
x=x,
y=y,
w=w,
h=h,
reverse_pan=reverse_pan,
reverse_tilt=reverse_tilt,
pan=int(pan),
tilt=int(tilt),
binding=input,
)
self.children.append(widget)
return widget
def frame(
self,
caption: str,
*,
x: int,
y: int,
w: int,
h: int,
solo: bool = False,
header: bool = True,
pages: int = 1,
loop: bool = False,
page: int = 0,
) -> Frame:
child = Frame(self.show, caption, x, y, w, h, solo=solo, show_header=header, pages=pages, loop=loop, page=page)
self.children.append(child)
return child
def solo_frame(self, caption: str, *, x: int, y: int, w: int, h: int) -> Frame:
return self.frame(caption, x=x, y=y, w=w, h=h, solo=True)
def render(self, indent: str = " ") -> str:
inner = indent + " "
if self.root:
body = "\n".join(child.render(inner) for child in self.children)
parts = [
f"{indent}<Frame Caption=\"\">",
appearance(frame="None", indent=inner),
]
if body:
parts.append(body)
parts.append(f"{indent}</Frame>")
return "\n".join(parts)
tag = "SoloFrame" if self.solo else "Frame"
flags = [
f"{inner}<AllowChildren>True</AllowChildren>",
f"{inner}<AllowResize>True</AllowResize>",
f"{inner}<ShowHeader>{'True' if self.show_header else 'False'}</ShowHeader>",
f"{inner}<ShowEnableButton>False</ShowEnableButton>",
]
if not self.solo:
flags.append(f"{inner}<ShowIntensityButton>False</ShowIntensityButton>")
flags.append(f"{inner}<Mixing>False</Mixing>")
if self.pages > 1:
flags.append(
f'{inner}<Multipage PagesNum="{self.pages}" CurrentPage="0" PagesLoop="{"True" if self.loop else "False"}"/>'
)
nested = "\n".join(_on_page(child, inner) for child in self.children)
page_attr = f' Page="{self.page}"' if self.page else ""
parts = [
f"{indent}<{tag} Caption={attr(self.caption)} ID=\"{self.id}\"{page_attr}>",
appearance(indent=inner),
f'{inner}<WindowState Visible="True" X="{self.x}" Y="{self.y}" Width="{self.w}" Height="{self.h}"/>',
*flags,
]
if nested:
parts.append(nested)
parts.append(f"{indent}</{tag}>")
return "\n".join(parts)
def _on_page(child: Any, indent: str) -> str:
"""Render a child, tagging its opening element with the frame page it is on."""
text = child.render(indent)
page = getattr(child, "page", 0)
if not page or isinstance(child, Frame):
return text
head, sep, rest = text.partition(">")
return f'{head} Page="{page}"{sep}{rest}'
def _input_xml(binding: MidiBinding | None, indent: str) -> str:
if binding is None:
return ""
return f'\n{indent}<Input Universe="{binding.universe}" Channel="{binding.channel}"/>'
+48
View File
@@ -0,0 +1,48 @@
"""Serialize a Show to a QLC+ 4.12 workspace."""
from __future__ import annotations
from .model import Show, Universe, fixture_xml, group_xml, universe_xml
def render_show(show: Show) -> str:
universes = list(show.universes) or [Universe(i, f"Universe {i + 1}") for i in range(4)]
universes.sort(key=lambda uni: uni.id)
width, height = show.size()
engine = [" <InputOutputMap>"]
engine.extend(universe_xml(uni) for uni in universes)
engine.append(" </InputOutputMap>")
engine.extend(fixture_xml(fx) for fx in show.fixtures)
engine.extend(group_xml(group) for group in show.groups)
engine.extend(fn.render() for fn in show.functions)
widgets = show.vc.render(" ")
return (
'<?xml version="1.0" encoding="UTF-8"?>\n'
"<!DOCTYPE Workspace>\n"
'<Workspace xmlns="http://www.qlcplus.org/Workspace" CurrentWindow="VirtualConsole">\n'
" <Creator>\n"
" <Name>Q Light Controller Plus</Name>\n"
f" <Version>{show.version}</Version>\n"
f" <Author>{_author(show.author)}</Author>\n"
" </Creator>\n"
" <Engine>\n"
+ "\n".join(engine)
+ "\n </Engine>\n"
" <VirtualConsole>\n"
+ widgets
+ "\n <Properties>\n"
f' <Size Width="{width}" Height="{height}"/>\n'
' <GrandMaster ChannelMode="Intensity" ValueMode="Reduce" SliderMode="Normal"/>\n'
" </Properties>\n"
" </VirtualConsole>\n"
" <SimpleDesk>\n"
" <Engine/>\n"
" </SimpleDesk>\n"
"</Workspace>\n"
)
def _author(name: str) -> str:
from .xmlutil import text
return text(name)
+48
View File
@@ -0,0 +1,48 @@
"""Small XML helpers shared by the workspace writer."""
from __future__ import annotations
from xml.sax.saxutils import escape, quoteattr
def attr(value: object) -> str:
return quoteattr(str(value))
def text(value: object) -> str:
return escape(str(value))
def qlc_color(r: int, g: int, b: int) -> str:
"""QLC+ widget colour as a decimal ARGB word."""
return str((0xFF << 24) | ((int(r) & 255) << 16) | ((int(g) & 255) << 8) | (int(b) & 255))
def colour(value: object, default: str = "Default") -> str:
if value is None:
return default
if isinstance(value, str):
return value
if isinstance(value, int) and not isinstance(value, bool):
return str(value)
if isinstance(value, (list, tuple)) and len(value) == 3:
return qlc_color(int(value[0]), int(value[1]), int(value[2]))
raise TypeError(f"colour must be 'Default', an ARGB decimal, or [r, g, b], not {value!r}")
def appearance(
fg: object = "Default",
bg: object = "Default",
frame: str = "Sunken",
indent: str = " ",
) -> str:
inner = indent + " "
return (
f"{indent}<Appearance>\n"
f"{inner}<FrameStyle>{text(frame)}</FrameStyle>\n"
f"{inner}<ForegroundColor>{text(colour(fg))}</ForegroundColor>\n"
f"{inner}<BackgroundColor>{text(colour(bg))}</BackgroundColor>\n"
f"{inner}<BackgroundImage>None</BackgroundImage>\n"
f"{inner}<Font>Default</Font>\n"
f"{indent}</Appearance>"
)
+358
View File
@@ -0,0 +1,358 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Workspace>
<Workspace xmlns="http://www.qlcplus.org/Workspace" CurrentWindow="VirtualConsole">
<Creator>
<Name>Q Light Controller Plus</Name>
<Version>4.12.7</Version>
<Author>Jimmy</Author>
</Creator>
<Engine>
<InputOutputMap>
<Universe Name="Universe 1" ID="0">
<Output Plugin="ArtNet" UID="10.1.1.202" Line="0">
<PluginParameters outputIP="10.1.1.201" outputUni="1"/>
</Output>
</Universe>
<Universe Name="Universe 2" ID="1"/>
<Universe Name="Universe 3" ID="2"/>
<Universe Name="Universe 4" ID="3"/>
</InputOutputMap>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>0</ID>
<Name>BCC145</Name>
<Universe>0</Universe>
<Address>0</Address>
<Channels>8</Channels>
</Fixture>
<ChannelsGroup ID="0" Name="Red" Value="0">0,2</ChannelsGroup>
<ChannelsGroup ID="1" Name="Green" Value="0">0,3</ChannelsGroup>
<ChannelsGroup ID="2" Name="Blue" Value="0">0,4</ChannelsGroup>
<ChannelsGroup ID="3" Name="White" Value="0">0,5</ChannelsGroup>
<ChannelsGroup ID="4" Name="Dimmer" Value="0">0,0</ChannelsGroup>
<Function ID="0" Type="Scene" Name="Red" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,255,3,0,4,0,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="1" Type="Scene" Name="Orange" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,255,3,127,4,0,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="2" Type="Scene" Name="Yellow" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,255,3,255,4,0,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="3" Type="Scene" Name="Green" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,0,3,255,4,0,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="4" Type="Scene" Name="Cyan" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,0,3,255,4,255,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="5" Type="Scene" Name="Blue" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,0,3,0,4,255,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="6" Type="Scene" Name="Violet" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,127,3,0,4,255,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="7" Type="Scene" Name="Magenta" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,255,3,0,4,255,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="8" Type="Scene" Name="White" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,0,3,0,4,0,5,255,6,0,7,0</FixtureVal>
</Function>
<Function ID="9" Type="Scene" Name="Blackout" Path="Colors">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,0,1,0,2,0,3,0,4,0,5,0,6,0,7,0</FixtureVal>
</Function>
<Function ID="10" Type="Scene" Name="Built-in Gradient">
<Speed FadeIn="0" FadeOut="0" Duration="0"/>
<FixtureVal ID="0">0,255,1,0,2,0,3,0,4,0,5,0,6,225,7,80</FixtureVal>
</Function>
<Function ID="11" Type="Chaser" Name="Color Transition">
<Speed FadeIn="3000" FadeOut="0" Duration="4000"/>
<Direction>Forward</Direction>
<RunOrder>Loop</RunOrder>
<SpeedModes FadeIn="Common" FadeOut="Common" Duration="Common"/>
<Step Number="0" FadeIn="3000" Hold="1000" FadeOut="0">0</Step>
<Step Number="1" FadeIn="3000" Hold="1000" FadeOut="0">1</Step>
<Step Number="2" FadeIn="3000" Hold="1000" FadeOut="0">2</Step>
<Step Number="3" FadeIn="3000" Hold="1000" FadeOut="0">3</Step>
<Step Number="4" FadeIn="3000" Hold="1000" FadeOut="0">4</Step>
<Step Number="5" FadeIn="3000" Hold="1000" FadeOut="0">5</Step>
<Step Number="6" FadeIn="3000" Hold="1000" FadeOut="0">6</Step>
<Step Number="7" FadeIn="3000" Hold="1000" FadeOut="0">7</Step>
</Function>
</Engine>
<VirtualConsole>
<Frame Caption="">
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>Default</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Slider Caption="Dim" ID="0" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="20" Y="20" Width="44" Height="220"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="None" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="166">
<Channel Fixture="0">0</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="R" ID="1" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="72" Y="20" Width="44" Height="220"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4294901760</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="Red" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="0">
<Channel Fixture="0">2</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="G" ID="2" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="124" Y="20" Width="44" Height="220"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4278255360</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="Green" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="0">
<Channel Fixture="0">3</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="B" ID="3" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="176" Y="20" Width="44" Height="220"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4278190335</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="Blue" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="0">
<Channel Fixture="0">4</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="W" ID="4" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="228" Y="20" Width="44" Height="220"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="None" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="0">
<Channel Fixture="0">5</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Button Caption="Color Transition" ID="5" Icon="">
<WindowState Visible="True" X="300" Y="20" Width="180" Height="70"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4282664004</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="11"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Built-in Gradient" ID="6" Icon="">
<WindowState Visible="True" X="490" Y="20" Width="180" Height="70"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4280427042</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="10"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Blackout" ID="7" Icon="">
<WindowState Visible="True" X="680" Y="20" Width="120" Height="70"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4278190080</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="9"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Red" ID="8" Icon="">
<WindowState Visible="True" X="300" Y="110" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4294901760</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="0"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Orange" ID="9" Icon="">
<WindowState Visible="True" X="390" Y="110" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4278190080</ForegroundColor>
<BackgroundColor>4294944000</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="1"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Yellow" ID="10" Icon="">
<WindowState Visible="True" X="480" Y="110" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4278190080</ForegroundColor>
<BackgroundColor>4294967040</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="2"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Green" ID="11" Icon="">
<WindowState Visible="True" X="570" Y="110" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4278190080</ForegroundColor>
<BackgroundColor>4278255360</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="3"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Cyan" ID="12" Icon="">
<WindowState Visible="True" X="660" Y="110" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4278190080</ForegroundColor>
<BackgroundColor>4278255615</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="4"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Blue" ID="13" Icon="">
<WindowState Visible="True" X="300" Y="170" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4278190335</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="5"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Violet" ID="14" Icon="">
<WindowState Visible="True" X="390" Y="170" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4286578687</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="6"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Magenta" ID="15" Icon="">
<WindowState Visible="True" X="480" Y="170" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4294902015</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="7"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="White" ID="16" Icon="">
<WindowState Visible="True" X="570" Y="170" Width="80" Height="50"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4278190080</ForegroundColor>
<BackgroundColor>4294967295</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Function ID="8"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
</Frame>
<Properties>
<Size Width="860" Height="280"/>
<GrandMaster ChannelMode="Intensity" ValueMode="Reduce" SliderMode="Normal"/>
</Properties>
</VirtualConsole>
<SimpleDesk>
<Engine/>
</SimpleDesk>
</Workspace>
+272
View File
@@ -0,0 +1,272 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Workspace>
<Workspace xmlns="http://www.qlcplus.org/Workspace" CurrentWindow="VirtualConsole">
<Creator>
<Name>Q Light Controller Plus</Name>
<Version>4.12.7</Version>
<Author>Jimmy</Author>
</Creator>
<Engine>
<InputOutputMap>
<Universe Name="Universe 1" ID="0">
<Output Plugin="ArtNet" UID="192.168.1.91" Line="7">
<PluginParameters outputIP="192.168.1.228"/>
</Output>
</Universe>
<Universe Name="Universe 2" ID="1"/>
<Universe Name="Universe 3" ID="2"/>
<Universe Name="Universe 4" ID="3"/>
</InputOutputMap>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>0</ID>
<Name>BCC145 #1</Name>
<Universe>0</Universe>
<Address>87</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>1</ID>
<Name>BCC145 #2</Name>
<Universe>0</Universe>
<Address>95</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>2</ID>
<Name>BCC145 #3</Name>
<Universe>0</Universe>
<Address>103</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>3</ID>
<Name>BCC145 #4</Name>
<Universe>0</Universe>
<Address>111</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>4</ID>
<Name>BCC145 #5</Name>
<Universe>0</Universe>
<Address>119</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>5</ID>
<Name>BCC145 #6</Name>
<Universe>0</Universe>
<Address>127</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>6</ID>
<Name>BCC145 #7</Name>
<Universe>0</Universe>
<Address>135</Address>
<Channels>8</Channels>
</Fixture>
<Fixture>
<Manufacturer>beamZ</Manufacturer>
<Model>BCC145</Model>
<Mode>8 Channel</Mode>
<ID>7</ID>
<Name>BCC145 #8</Name>
<Universe>0</Universe>
<Address>143</Address>
<Channels>8</Channels>
</Fixture>
<FixtureGroup ID="0">
<Name>Cans</Name>
<Size X="8" Y="1"/>
<Head X="0" Y="0" Fixture="0">0</Head>
<Head X="1" Y="0" Fixture="1">0</Head>
<Head X="2" Y="0" Fixture="2">0</Head>
<Head X="3" Y="0" Fixture="3">0</Head>
<Head X="4" Y="0" Fixture="4">0</Head>
<Head X="5" Y="0" Fixture="5">0</Head>
<Head X="6" Y="0" Fixture="6">0</Head>
<Head X="7" Y="0" Fixture="7">0</Head>
</FixtureGroup>
</Engine>
<VirtualConsole>
<Frame Caption="">
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>Default</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Frame Caption="Cans RGBW" ID="0">
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>Default</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<WindowState Visible="True" X="10" Y="10" Width="160" Height="24"/>
<AllowChildren>True</AllowChildren>
<AllowResize>True</AllowResize>
<ShowHeader>True</ShowHeader>
<ShowEnableButton>False</ShowEnableButton>
<Collapsed>False</Collapsed>
<Disabled>False</Disabled>
</Frame>
<Slider Caption="Dim" ID="1" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="10" Y="42" Width="44" Height="240"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="None" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="255">
<Channel Fixture="0">0</Channel>
<Channel Fixture="1">0</Channel>
<Channel Fixture="2">0</Channel>
<Channel Fixture="3">0</Channel>
<Channel Fixture="4">0</Channel>
<Channel Fixture="5">0</Channel>
<Channel Fixture="6">0</Channel>
<Channel Fixture="7">0</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="R" ID="2" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="56" Y="42" Width="44" Height="240"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4294901760</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="Red" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="0">
<Channel Fixture="0">2</Channel>
<Channel Fixture="1">2</Channel>
<Channel Fixture="2">2</Channel>
<Channel Fixture="3">2</Channel>
<Channel Fixture="4">2</Channel>
<Channel Fixture="5">2</Channel>
<Channel Fixture="6">2</Channel>
<Channel Fixture="7">2</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="G" ID="3" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="102" Y="42" Width="44" Height="240"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4278255360</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="Green" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="0">
<Channel Fixture="0">3</Channel>
<Channel Fixture="1">3</Channel>
<Channel Fixture="2">3</Channel>
<Channel Fixture="3">3</Channel>
<Channel Fixture="4">3</Channel>
<Channel Fixture="5">3</Channel>
<Channel Fixture="6">3</Channel>
<Channel Fixture="7">3</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="B" ID="4" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="148" Y="42" Width="44" Height="240"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4278190335</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="Blue" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="0">
<Channel Fixture="0">4</Channel>
<Channel Fixture="1">4</Channel>
<Channel Fixture="2">4</Channel>
<Channel Fixture="3">4</Channel>
<Channel Fixture="4">4</Channel>
<Channel Fixture="5">4</Channel>
<Channel Fixture="6">4</Channel>
<Channel Fixture="7">4</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="W" ID="5" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="194" Y="42" Width="44" Height="240"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>Default</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<SliderMode ValueDisplayStyle="Exact" ClickAndGoType="None" Monitor="true">Level</SliderMode>
<Reset/>
<Level LowLimit="0" HighLimit="255" Value="0">
<Channel Fixture="0">5</Channel>
<Channel Fixture="1">5</Channel>
<Channel Fixture="2">5</Channel>
<Channel Fixture="3">5</Channel>
<Channel Fixture="4">5</Channel>
<Channel Fixture="5">5</Channel>
<Channel Fixture="6">5</Channel>
<Channel Fixture="7">5</Channel>
</Level>
<Playback>
<Function>4294967295</Function>
</Playback>
</Slider>
</Frame>
<Properties>
<Size Width="320" Height="320"/>
<GrandMaster ChannelMode="Intensity" ValueMode="Reduce" SliderMode="Normal"/>
</Properties>
</VirtualConsole>
<SimpleDesk>
<Engine/>
</SimpleDesk>
</Workspace>
+3225
View File
File diff suppressed because it is too large. Load diff
+42 -42
View File
@@ -447,7 +447,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Frame Caption="Cans individual RGBW">
<Frame Caption="Cans individual RGBW" ID="12">
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>Default</ForegroundColor>
@@ -463,7 +463,7 @@
<ShowIntensityButton>False</ShowIntensityButton>
<Mixing>False</Mixing>
</Frame>
<Slider Caption="1R" ID="12" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="1R" ID="13" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="10" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -481,7 +481,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="1G" ID="13" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="1G" ID="14" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="48" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -499,7 +499,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="1B" ID="14" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="1B" ID="15" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="86" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -517,7 +517,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="1W" ID="15" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="1W" ID="16" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="124" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -535,7 +535,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="2R" ID="16" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="2R" ID="17" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="172" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -553,7 +553,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="2G" ID="17" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="2G" ID="18" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="210" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -571,7 +571,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="2B" ID="18" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="2B" ID="19" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="248" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -589,7 +589,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="2W" ID="19" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="2W" ID="20" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="286" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -607,7 +607,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="3R" ID="20" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="3R" ID="21" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="334" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -625,7 +625,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="3G" ID="21" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="3G" ID="22" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="372" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -643,7 +643,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="3B" ID="22" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="3B" ID="23" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="410" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -661,7 +661,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="3W" ID="23" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="3W" ID="24" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="448" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -679,7 +679,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="4R" ID="24" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="4R" ID="25" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="496" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -697,7 +697,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="4G" ID="25" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="4G" ID="26" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="534" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -715,7 +715,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="4B" ID="26" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="4B" ID="27" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="572" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -733,7 +733,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="4W" ID="27" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="4W" ID="28" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="610" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -751,7 +751,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="5R" ID="28" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="5R" ID="29" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="658" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -769,7 +769,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="5G" ID="29" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="5G" ID="30" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="696" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -787,7 +787,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="5B" ID="30" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="5B" ID="31" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="734" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -805,7 +805,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="5W" ID="31" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="5W" ID="32" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="772" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -823,7 +823,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="6R" ID="32" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="6R" ID="33" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="820" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -841,7 +841,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="6G" ID="33" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="6G" ID="34" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="858" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -859,7 +859,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="6B" ID="34" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="6B" ID="35" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="896" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -877,7 +877,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="6W" ID="35" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="6W" ID="36" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="934" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -895,7 +895,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="7R" ID="36" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="7R" ID="37" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="982" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -913,7 +913,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="7G" ID="37" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="7G" ID="38" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="1020" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -931,7 +931,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="7B" ID="38" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="7B" ID="39" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="1058" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -949,7 +949,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="7W" ID="39" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="7W" ID="40" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="1096" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -967,7 +967,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="8R" ID="40" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="8R" ID="41" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="1144" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -985,7 +985,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="8G" ID="41" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="8G" ID="42" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="1182" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -1003,7 +1003,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="8B" ID="42" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="8B" ID="43" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="1220" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -1021,7 +1021,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="8W" ID="43" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="8W" ID="44" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="1258" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -1039,7 +1039,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Frame Caption="Movers individual RGBW">
<Frame Caption="Movers individual RGBW" ID="45">
<Appearance>
<FrameStyle>Sunken</FrameStyle>
<ForegroundColor>Default</ForegroundColor>
@@ -1055,7 +1055,7 @@
<ShowIntensityButton>False</ShowIntensityButton>
<Mixing>False</Mixing>
</Frame>
<Slider Caption="M1R" ID="44" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="M1R" ID="46" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="1322" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -1079,7 +1079,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="M1G" ID="45" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="M1G" ID="47" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="1360" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -1103,7 +1103,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="M1B" ID="46" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="M1B" ID="48" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="1398" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -1127,7 +1127,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="M1W" ID="47" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="M1W" ID="49" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="1436" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -1151,7 +1151,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="M2R" ID="48" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="M2R" ID="50" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="1488" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -1175,7 +1175,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="M2G" ID="49" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="M2G" ID="51" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="1526" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -1199,7 +1199,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="M2B" ID="50" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="M2B" ID="52" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="1564" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
@@ -1223,7 +1223,7 @@
<Function>4294967295</Function>
</Playback>
</Slider>
<Slider Caption="M2W" ID="51" WidgetStyle="Slider" InvertedAppearance="false">
<Slider Caption="M2W" ID="53" WidgetStyle="Slider" InvertedAppearance="false">
<WindowState Visible="True" X="1602" Y="304" Width="36" Height="160"/>
<Appearance>
<FrameStyle>Sunken</FrameStyle>
File diff suppressed because it is too large. Load diff
+3203
View File
File diff suppressed because it is too large. Load diff
+5394
View File
File diff suppressed because it is too large. Load diff
+139 -11
View File
@@ -13,7 +13,9 @@
<PluginParameters outputIP="192.168.1.228" outputUni="0" />
</Output>
</Universe>
<Universe Name="Universe 2" ID="1" />
<Universe Name="Universe 2" ID="1">
<Input Plugin="MIDI" UID="SMC-PAD Bluetooth" Line="1"/>
</Universe>
<Universe Name="Universe 3" ID="2" />
<Universe Name="Universe 4" ID="3" />
</InputOutputMap>
@@ -136,7 +138,7 @@
<Head X="7" Y="0" Fixture="7">0</Head>
</FixtureGroup>
<Function ID="0" Type="Scene" Name="Red">
<Speed FadeIn="0" FadeOut="0" Duration="0" />
<Speed FadeIn="1000" FadeOut="1000" Duration="0" />
<FixtureVal ID="0">1,0,2,255,3,0,4,0,5,0,6,0,7,0</FixtureVal>
<FixtureVal ID="1">1,0,2,255,3,0,4,0,5,0,6,0,7,0</FixtureVal>
<FixtureVal ID="2">1,0,2,255,3,0,4,0,5,0,6,0,7,0</FixtureVal>
@@ -149,7 +151,7 @@
<FixtureVal ID="9">0,128,2,80,4,0,5,191,6,0,7,70,8,255,9,0,10,255,11,0,12,0,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,37,0</FixtureVal>
</Function>
<Function ID="1" Type="Scene" Name="Orange">
<Speed FadeIn="0" FadeOut="0" Duration="0" />
<Speed FadeIn="1000" FadeOut="1000" Duration="0" />
<FixtureVal ID="0">1,0,2,255,3,127,4,0,5,0,6,0,7,0</FixtureVal>
<FixtureVal ID="1">1,0,2,255,3,127,4,0,5,0,6,0,7,0</FixtureVal>
<FixtureVal ID="2">1,0,2,255,3,127,4,0,5,0,6,0,7,0</FixtureVal>
@@ -162,7 +164,7 @@
<FixtureVal ID="9">0,128,2,80,4,0,5,191,6,0,7,70,8,255,9,0,10,255,11,127,12,0,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,37,0</FixtureVal>
</Function>
<Function ID="2" Type="Scene" Name="Yellow">
<Speed FadeIn="0" FadeOut="0" Duration="0" />
<Speed FadeIn="1000" FadeOut="1000" Duration="0" />
<FixtureVal ID="0">1,0,2,255,3,255,4,0,5,0,6,0,7,0</FixtureVal>
<FixtureVal ID="1">1,0,2,255,3,255,4,0,5,0,6,0,7,0</FixtureVal>
<FixtureVal ID="2">1,0,2,255,3,255,4,0,5,0,6,0,7,0</FixtureVal>
@@ -175,7 +177,7 @@
<FixtureVal ID="9">0,128,2,80,4,0,5,191,6,0,7,70,8,255,9,0,10,255,11,255,12,0,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,37,0</FixtureVal>
</Function>
<Function ID="3" Type="Scene" Name="Green">
<Speed FadeIn="0" FadeOut="0" Duration="0" />
<Speed FadeIn="1000" FadeOut="1000" Duration="0" />
<FixtureVal ID="0">1,0,2,0,3,255,4,0,5,0,6,0,7,0</FixtureVal>
<FixtureVal ID="1">1,0,2,0,3,255,4,0,5,0,6,0,7,0</FixtureVal>
<FixtureVal ID="2">1,0,2,0,3,255,4,0,5,0,6,0,7,0</FixtureVal>
@@ -188,7 +190,7 @@
<FixtureVal ID="9">0,128,2,80,4,0,5,191,6,0,7,70,8,255,9,0,10,0,11,255,12,0,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,37,0</FixtureVal>
</Function>
<Function ID="4" Type="Scene" Name="Cyan">
<Speed FadeIn="0" FadeOut="0" Duration="0" />
<Speed FadeIn="1000" FadeOut="1000" Duration="0" />
<FixtureVal ID="0">1,0,2,0,3,255,4,255,5,0,6,0,7,0</FixtureVal>
<FixtureVal ID="1">1,0,2,0,3,255,4,255,5,0,6,0,7,0</FixtureVal>
<FixtureVal ID="2">1,0,2,0,3,255,4,255,5,0,6,0,7,0</FixtureVal>
@@ -201,7 +203,7 @@
<FixtureVal ID="9">0,128,2,80,4,0,5,191,6,0,7,70,8,255,9,0,10,0,11,255,12,255,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,37,0</FixtureVal>
</Function>
<Function ID="5" Type="Scene" Name="Blue">
<Speed FadeIn="0" FadeOut="0" Duration="0" />
<Speed FadeIn="1000" FadeOut="1000" Duration="0" />
<FixtureVal ID="0">1,0,2,0,3,0,4,255,5,0,6,0,7,0</FixtureVal>
<FixtureVal ID="1">1,0,2,0,3,0,4,255,5,0,6,0,7,0</FixtureVal>
<FixtureVal ID="2">1,0,2,0,3,0,4,255,5,0,6,0,7,0</FixtureVal>
@@ -214,7 +216,7 @@
<FixtureVal ID="9">0,128,2,80,4,0,5,191,6,0,7,70,8,255,9,0,10,0,11,0,12,255,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,37,0</FixtureVal>
</Function>
<Function ID="6" Type="Scene" Name="Violet">
<Speed FadeIn="0" FadeOut="0" Duration="0" />
<Speed FadeIn="1000" FadeOut="1000" Duration="0" />
<FixtureVal ID="0">1,0,2,127,3,0,4,255,5,0,6,0,7,0</FixtureVal>
<FixtureVal ID="1">1,0,2,127,3,0,4,255,5,0,6,0,7,0</FixtureVal>
<FixtureVal ID="2">1,0,2,127,3,0,4,255,5,0,6,0,7,0</FixtureVal>
@@ -227,7 +229,7 @@
<FixtureVal ID="9">0,128,2,80,4,0,5,191,6,0,7,70,8,255,9,0,10,127,11,0,12,255,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,37,0</FixtureVal>
</Function>
<Function ID="7" Type="Scene" Name="Magenta">
<Speed FadeIn="0" FadeOut="0" Duration="0" />
<Speed FadeIn="1000" FadeOut="1000" Duration="0" />
<FixtureVal ID="0">1,0,2,255,3,0,4,255,5,0,6,0,7,0</FixtureVal>
<FixtureVal ID="1">1,0,2,255,3,0,4,255,5,0,6,0,7,0</FixtureVal>
<FixtureVal ID="2">1,0,2,255,3,0,4,255,5,0,6,0,7,0</FixtureVal>
@@ -240,7 +242,7 @@
<FixtureVal ID="9">0,128,2,80,4,0,5,191,6,0,7,70,8,255,9,0,10,255,11,0,12,255,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0,25,0,26,0,27,0,28,0,29,0,30,0,31,0,32,0,33,0,34,0,35,0,36,0,37,0</FixtureVal>
</Function>
<Function ID="8" Type="Scene" Name="White">
<Speed FadeIn="0" FadeOut="0" Duration="0" />
<Speed FadeIn="1000" FadeOut="1000" Duration="0" />
<FixtureVal ID="0">1,0,2,0,3,0,4,0,5,255,6,0,7,0</FixtureVal>
<FixtureVal ID="1">1,0,2,0,3,0,4,0,5,255,6,0,7,0</FixtureVal>
<FixtureVal ID="2">1,0,2,0,3,0,4,0,5,255,6,0,7,0</FixtureVal>
@@ -1382,7 +1384,7 @@
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<WindowState Visible="True" X="10" Y="10" Width="968" Height="300"/>
<WindowState Visible="True" X="10" Y="10" Width="968" Height="350"/>
<AllowChildren>True</AllowChildren>
<AllowResize>True</AllowResize>
<ShowHeader>True</ShowHeader>
@@ -1686,6 +1688,132 @@
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Red" ID="300" Icon="">
<WindowState Visible="True" X="10" Y="284" Width="100" Height="56"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4294901760</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Input Universe="1" Channel="180"/>
<Function ID="0"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Orange" ID="301" Icon="">
<WindowState Visible="True" X="116" Y="284" Width="100" Height="56"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4278190080</ForegroundColor>
<BackgroundColor>4294934272</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Input Universe="1" Channel="181"/>
<Function ID="1"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Yellow" ID="302" Icon="">
<WindowState Visible="True" X="222" Y="284" Width="100" Height="56"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4278190080</ForegroundColor>
<BackgroundColor>4294967040</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Input Universe="1" Channel="182"/>
<Function ID="2"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Green" ID="303" Icon="">
<WindowState Visible="True" X="328" Y="284" Width="100" Height="56"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4278255360</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Input Universe="1" Channel="183"/>
<Function ID="3"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Cyan" ID="304" Icon="">
<WindowState Visible="True" X="434" Y="284" Width="100" Height="56"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4278190080</ForegroundColor>
<BackgroundColor>4278255615</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Input Universe="1" Channel="184"/>
<Function ID="4"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Blue" ID="305" Icon="">
<WindowState Visible="True" X="540" Y="284" Width="100" Height="56"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4278190335</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Input Universe="1" Channel="185"/>
<Function ID="5"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Violet" ID="306" Icon="">
<WindowState Visible="True" X="646" Y="284" Width="100" Height="56"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4286513407</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Input Universe="1" Channel="186"/>
<Function ID="6"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="Magenta" ID="307" Icon="">
<WindowState Visible="True" X="752" Y="284" Width="100" Height="56"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4294967295</ForegroundColor>
<BackgroundColor>4294902015</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Input Universe="1" Channel="187"/>
<Function ID="7"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
<Button Caption="White" ID="308" Icon="">
<WindowState Visible="True" X="858" Y="284" Width="100" Height="56"/>
<Appearance>
<FrameStyle>None</FrameStyle>
<ForegroundColor>4278190080</ForegroundColor>
<BackgroundColor>4294967295</BackgroundColor>
<BackgroundImage>None</BackgroundImage>
<Font>Default</Font>
</Appearance>
<Input Universe="1" Channel="188"/>
<Function ID="8"/>
<Action>Toggle</Action>
<Intensity Adjust="False">100</Intensity>
</Button>
</SoloFrame>
<SpeedDial Caption="Speed" ID="3">
<WindowState Visible="True" X="988" Y="10" Width="100" Height="300"/>
+1
View File
@@ -0,0 +1 @@
"""Stage visualiser that listens for Art-Net."""
+177
View File
@@ -0,0 +1,177 @@
"""Stage simulator.
Loads a stage map, patches DMX addresses from a QLC+ show, and listens for
Art-Net. Open the printed URL and point QLC+ Art-Net output at this machine.
python -m simulator
python -m simulator --stage stage/map.json --show shows/templeoftechno.qxw
python -m simulator --demo
The show is optional: it only fills addresses the stage map leaves out, and
shows the QLC+ Art-Net output it sends to. The page can switch to any other
stage map in the same folder.
"""
from __future__ import annotations
import argparse
import math
import threading
import time
from pathlib import Path
from simulator.artnet import ArtNetNode
from simulator.server import Simulator, make_server
from simulator.stage import Fixture, apply_show, load_stage
ROOT = Path(__file__).resolve().parents[1]
def _hsv(hue: float) -> tuple[int, int, int]:
hue = hue % 1.0
i = int(hue * 6)
f = hue * 6 - i
q = int(255 * (1 - f))
t = int(255 * f)
segment = i % 6
if segment == 0:
return 255, t, 0
if segment == 1:
return q, 255, 0
if segment == 2:
return 0, 255, t
if segment == 3:
return 0, q, 255
if segment == 4:
return t, 0, 255
return 255, 0, q
def _slot(fixture: Fixture, name: str) -> int | None:
if fixture.address is None:
return None
for index, channel in enumerate(fixture.channel_names):
if channel.lower() == name.lower():
return fixture.address + index
return None
def _put(frame: bytearray, fixture: Fixture, name: str, value: int) -> None:
slot = _slot(fixture, name)
if slot is not None and 0 <= slot < len(frame):
frame[slot] = max(0, min(255, value))
def _demo_frame(fixtures: list[Fixture], elapsed: float) -> bytearray:
frame = bytearray(512)
cans = [fixture for fixture in fixtures if fixture.kind == "can" and fixture.address is not None]
cans.sort(key=lambda fixture: fixture.label)
# Walk the BCC145 macro: RGBW mix, colour jump, pulse, then gradient.
look = int(elapsed / 5) % 4
macro = (0, 120, 170, 220)[look]
speed = int(40 + (math.sin(elapsed * 0.7) * 0.5 + 0.5) * 180)
for index, fixture in enumerate(cans):
_put(frame, fixture, "Dimmer", 255)
_put(frame, fixture, "Macro", macro)
_put(frame, fixture, "Speed", speed)
if macro == 0:
red, green, blue = _hsv(elapsed * 0.05 + index / max(1, len(cans)))
_put(frame, fixture, "Red", red)
_put(frame, fixture, "Green", green)
_put(frame, fixture, "Blue", blue)
movers = [fixture for fixture in fixtures if fixture.kind == "mover" and fixture.address is not None]
for index, fixture in enumerate(movers):
pan = int(32768 + math.sin(elapsed * 0.6 + index * math.pi) * 9000)
pan = max(0, min(65535, pan))
tilt = 42000
_put(frame, fixture, "Pan", (pan >> 8) & 0xFF)
_put(frame, fixture, "Pan Fine", pan & 0xFF)
_put(frame, fixture, "Tilt", (tilt >> 8) & 0xFF)
_put(frame, fixture, "Tilt Fine", tilt & 0xFF)
_put(frame, fixture, "Zoom", 40)
_put(frame, fixture, "Center Brightness", 255)
color = (255, 40, 0) if index % 2 == 0 else (40, 80, 255)
for pixel in range(1, 8):
_put(frame, fixture, f"Red {pixel}", color[0])
_put(frame, fixture, f"Green {pixel}", color[1])
_put(frame, fixture, f"Blue {pixel}", color[2])
_put(frame, fixture, "Dynamic Effect", 30 if index % 2 == 0 else 160)
_put(frame, fixture, "Lens Rotate", 210 if index % 2 == 0 else 40)
return frame
def _demo_loop(node: ArtNetNode, fixtures: list[Fixture], stop: threading.Event) -> None:
started = time.monotonic()
while not stop.is_set():
frame = _demo_frame(fixtures, time.monotonic() - started)
node.write(0, frame)
stop.wait(0.05)
def _parse_host_port(value: str, default_port: int) -> tuple[str, int]:
if ":" not in value:
return value, default_port
host, port = value.rsplit(":", 1)
return host or "0.0.0.0", int(port)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--stage", type=Path, default=ROOT / "stage" / "map.json")
parser.add_argument("--show", type=Path, help="QLC+ workspace to fill addresses the stage map leaves out")
parser.add_argument("--no-show", action="store_true", help="Ignore --show (kept for older commands)")
parser.add_argument("--http", default="0.0.0.0:8765", help="Web view host:port")
parser.add_argument("--artnet", default="0.0.0.0:6454", help="Art-Net listen host:port")
parser.add_argument("--demo", action="store_true", help="Play a local look when you want to see the rig without QLC+")
args = parser.parse_args()
stage = load_stage(args.stage)
show = None if args.no_show else args.show
if show is not None:
if not show.is_file():
raise SystemExit(f"Show not found: {show}")
apply_show(stage, show)
http_host, http_port = _parse_host_port(args.http, 8765)
artnet_host, artnet_port = _parse_host_port(args.artnet, 6454)
node = ArtNetNode(artnet_host, artnet_port)
node.start()
server = make_server(Simulator(stage, node, show), http_host, http_port)
print("Stage simulator", flush=True)
print(f" stage: {args.stage}", flush=True)
if stage.show:
print(f" show: {args.show}", flush=True)
print(f" Art-Net {artnet_host}:{artnet_port}", flush=True)
print(f" view: http://127.0.0.1:{server.server_address[1]}", flush=True)
if stage.output_ip:
print(f" QLC+ Art-Net output in this show is {stage.output_ip}.", flush=True)
print(" Point that output at this computer (universe 0), or broadcast.", flush=True)
for fixture in stage.fixtures:
if fixture.dmx is None:
print(f" {fixture.label:<4} no address", flush=True)
else:
print(
f" {fixture.label:<4} {fixture.name:<16} universe {fixture.universe} DMX {fixture.dmx}",
flush=True,
)
for warning in stage.warnings:
print(f" warning: {warning}", flush=True)
stop = threading.Event()
if args.demo:
threading.Thread(target=_demo_loop, args=(node, stage.fixtures, stop), daemon=True).start()
print(" demo look is running", flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nStopping.", flush=True)
finally:
stop.set()
server.shutdown()
node.close()
if __name__ == "__main__":
main()
+214
View File
@@ -0,0 +1,214 @@
"""Art-Net receiver. Speaks ArtDMX and answers ArtPoll."""
from __future__ import annotations
import socket
import threading
import time
from collections import deque
ARTNET_PORT = 6454
HEADER = b"Art-Net\x00"
OP_POLL = 0x2000
OP_POLL_REPLY = 0x2100
OP_DMX = 0x5000
def build_artdmx(channels: bytes, universe: int = 0, sequence: int = 1) -> bytes:
"""ArtDMX packet. `channels` is the 0-based DMX frame (up to 512)."""
data = bytearray(channels)
n = len(data)
if n < 2:
data.extend(b"\x00" * (2 - n))
n = 2
if n & 1:
data.append(0)
n += 1
if n > 512:
data = data[:512]
n = 512
pkt = bytearray(18 + n)
pkt[0:8] = HEADER
pkt[8] = OP_DMX & 0xFF
pkt[9] = (OP_DMX >> 8) & 0xFF
pkt[11] = 14
pkt[12] = sequence & 0xFF
pkt[14] = universe & 0xFF
pkt[15] = (universe >> 8) & 0x7F
pkt[16] = (n >> 8) & 0xFF
pkt[17] = n & 0xFF
pkt[18 : 18 + n] = data
return bytes(pkt)
def parse_artdmx(packet: bytes) -> tuple[int, bytes] | None:
"""Return (port-address, dmx) for an ArtDMX packet, else None."""
if len(packet) < 18 or not packet.startswith(HEADER):
return None
opcode = packet[8] | (packet[9] << 8)
if opcode != OP_DMX:
return None
universe = packet[14] | ((packet[15] & 0x7F) << 8)
length = (packet[16] << 8) | packet[17]
if length < 2 or 18 + length > len(packet):
return None
return universe, packet[18 : 18 + length]
def parse_opcode(packet: bytes) -> int | None:
if len(packet) < 10 or not packet.startswith(HEADER):
return None
return packet[8] | (packet[9] << 8)
def poll_reply(ip: str) -> bytes:
"""Short ArtPollReply so QLC+ can list this node."""
pkt = bytearray(239)
pkt[0:8] = HEADER
pkt[8] = OP_POLL_REPLY & 0xFF
pkt[9] = (OP_POLL_REPLY >> 8) & 0xFF
pkt[11] = 14
parts = [int(part) for part in ip.split(".")]
if len(parts) != 4:
parts = [127, 0, 0, 1]
pkt[12:16] = bytes(parts)
pkt[16] = ARTNET_PORT & 0xFF
pkt[17] = (ARTNET_PORT >> 8) & 0xFF
pkt[19] = 1
pkt[25] = 0xD0
short = b"Stage sim"
pkt[28 : 28 + len(short)] = short
long = b"QLC+ stage Art-Net simulator"
pkt[46 : 46 + len(long)] = long
pkt[175] = 1
pkt[176] = 0x80
pkt[184] = 0x80
return bytes(pkt)
def local_ip_toward(peer: str) -> str:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.connect((peer, ARTNET_PORT))
return sock.getsockname()[0]
except OSError:
return "127.0.0.1"
finally:
sock.close()
class ArtNetNode:
"""Holds the latest DMX frame per Art-Net universe."""
def __init__(self, host: str = "0.0.0.0", port: int = ARTNET_PORT):
self.host = host
self.port = port
self._lock = threading.Lock()
self._universes: dict[int, bytearray] = {}
self.packets = 0
self._times: deque[float] = deque()
self.last_rx = 0.0
self.last_universe: int | None = None
self._sock: socket.socket | None = None
self._running = False
self._thread: threading.Thread | None = None
self._announced = False
def start(self) -> None:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if hasattr(socket, "SO_REUSEPORT"):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
try:
sock.bind((self.host, self.port))
except OSError as exc:
sock.close()
raise OSError(
f"Cannot listen for Art-Net on {self.host}:{self.port} ({exc}). "
"Close the other program using that port, or pass --artnet-port."
) from exc
sock.settimeout(0.5)
self._sock = sock
self._running = True
self._thread = threading.Thread(target=self._loop, name="artnet", daemon=True)
self._thread.start()
def close(self) -> None:
self._running = False
sock = self._sock
if sock is not None:
try:
sock.close()
except OSError:
pass
if self._thread is not None:
self._thread.join(timeout=1.5)
def write(self, universe: int, data: bytes) -> None:
with self._lock:
buf = self._universes.get(universe)
if buf is None:
buf = bytearray(512)
self._universes[universe] = buf
n = min(512, len(data))
buf[:n] = data[:n]
if n < 512:
buf[n:] = b"\x00" * (512 - n)
now = time.monotonic()
self.packets += 1
self.last_rx = now
self.last_universe = universe
self._times.append(now)
def snapshot(self) -> dict[int, bytes]:
with self._lock:
return {universe: bytes(buf) for universe, buf in self._universes.items()}
def stats(self) -> dict:
now = time.monotonic()
with self._lock:
while self._times and now - self._times[0] > 1.0:
self._times.popleft()
age = None if self.last_rx == 0 else now - self.last_rx
return {
"packets": self.packets,
"rate": len(self._times),
"age": None if age is None else round(age, 3),
"universe": self.last_universe,
"listen": f"{self.host}:{self.port}",
}
def _loop(self) -> None:
sock = self._sock
assert sock is not None
while self._running:
try:
packet, addr = sock.recvfrom(2048)
except TimeoutError:
continue
except OSError:
break
self._handle(packet, addr)
def _handle(self, packet: bytes, addr: tuple) -> None:
opcode = parse_opcode(packet)
if opcode == OP_DMX:
parsed = parse_artdmx(packet)
if parsed is None:
return
universe, data = parsed
self.write(universe, data)
if not self._announced:
self._announced = True
print(
f"Art-Net DMX from {addr[0]}:{addr[1]} "
f"universe {universe} ({len(data)} channels)",
flush=True,
)
return
if opcode == OP_POLL and self._sock is not None:
ip = local_ip_toward(addr[0])
try:
self._sock.sendto(poll_reply(ip), (addr[0], ARTNET_PORT))
except OSError:
pass
+430
View File
@@ -0,0 +1,430 @@
"""Turn a DMX frame into colours, beams, and strobe rates.
Channel order comes from the stage map's fixture definitions. Role names
such as Dimmer, Red, Pan, and Zoom select the slots.
"""
from __future__ import annotations
import re
from simulator.stage import Fixture, Stage
_PIXEL = re.compile(r"^(red|green|blue|white) (\d+)$", re.IGNORECASE)
PAN_DEGREES = 540.0
ZOOM_MIN = 5.0
ZOOM_MAX = 45.0
# BCC145 8ch: strobe 0–7 is open. Small Eye centre strobe 0–3 is open.
CAN_STROBE_OPEN = 7
MOVER_STROBE_OPEN = 3
# beamZ BCC145 8ch macro, matching fixtures/beamZ-BCC145.qxf.
# 0–50 RGBW mix, 51–100 fixed colour, 101–150 jump, 151–200 pulse,
# 201–250 gradient, 251–255 sound. Speed is slow to fast.
_PAR_PALETTE = (
(255, 0, 0),
(255, 96, 0),
(255, 200, 0),
(255, 255, 0),
(0, 255, 0),
(0, 255, 160),
(0, 64, 255),
(140, 0, 255),
(255, 0, 160),
(255, 255, 255),
)
# Small Eye 43ch colour macros, static masks, and dynamic chases.
# Ranges match fixtures/Small-Eye-7-Mover.qxf: 0–9 is no function.
_MOVER_MACROS = (
(255, 0, 0),
(255, 80, 0),
(255, 255, 0),
(0, 255, 0),
(0, 255, 255),
(0, 40, 255),
(160, 0, 255),
(255, 0, 180),
(255, 255, 255),
(255, 180, 80),
)
_STATIC_MASKS = (
("all", (1, 1, 1, 1, 1, 1, 1)),
("odds", (1, 0, 1, 0, 1, 0, 1)),
("evens", (0, 1, 0, 1, 0, 1, 0)),
("center", (0, 0, 0, 1, 0, 0, 0)),
("ends", (1, 0, 0, 0, 0, 0, 1)),
("left", (1, 1, 1, 1, 0, 0, 0)),
("right", (0, 0, 0, 1, 1, 1, 1)),
("one", None),
)
_DYNAMIC = ("chase", "reverse", "rainbow", "bounce", "pulse", "pairs")
_DYNAMIC_LABELS = {
"chase": "chase",
"reverse": "reverse chase",
"rainbow": "rainbow",
"bounce": "bounce",
"pulse": "pixel pulse",
"pairs": "pairs",
}
MOVER_43 = [
"Pan", "Pan Fine", "Tilt", "Tilt Fine", "Pan/Tilt Speed", "Lens Rotate", "Zoom", "Focus",
"Center Brightness", "Center Strobe",
"Red 1", "Green 1", "Blue 1", "White 1",
"Red 2", "Green 2", "Blue 2", "White 2",
"Red 3", "Green 3", "Blue 3", "White 3",
"Red 4", "Green 4", "Blue 4", "White 4",
"Red 5", "Green 5", "Blue 5", "White 5",
"Red 6", "Green 6", "Blue 6", "White 6",
"Red 7", "Green 7", "Blue 7", "White 7",
"Colour Temperature", "Colour Macro", "Static Effect", "Dynamic Effect", "Reset",
]
def _find(names: list[str], wanted: str) -> int | None:
wanted = wanted.lower()
for index, name in enumerate(names):
if name.lower() == wanted:
return index
return None
def _value(channels: list[int], names: list[str], wanted: str, default: int = 0) -> int:
index = _find(names, wanted)
if index is None or index >= len(channels):
return default
return channels[index]
def _pixels(channels: list[int], names: list[str], dimmer: int) -> list[list[int]]:
groups: dict[int, dict[str, int]] = {}
for index, name in enumerate(names):
match = _PIXEL.match(name.strip())
if match is None:
continue
groups.setdefault(int(match.group(2)), {})[match.group(1).lower()] = index
def at(group: dict[str, int], color: str) -> int:
index = group.get(color)
if index is None or index >= len(channels):
return 0
return channels[index]
return [
list(mix_rgbw(at(groups[number], "red"), at(groups[number], "green"), at(groups[number], "blue"), at(groups[number], "white"), dimmer))
for number in sorted(groups)
]
def slots_at(frame: bytes, address: int, count: int) -> list[int]:
out: list[int] = []
for offset in range(count):
index = address + offset
out.append(frame[index] if 0 <= index < len(frame) else 0)
return out
def mix_rgbw(red: int, green: int, blue: int, white: int, dimmer: int) -> tuple[int, int, int]:
"""White is a fourth emitter. Dimmer scales the whole mix."""
level = max(0, min(255, dimmer)) / 255.0
return (
int(round(min(255, red + white) * level)),
int(round(min(255, green + white) * level)),
int(round(min(255, blue + white) * level)),
)
def strobe_hz(value: int, open_max: int) -> float:
if value <= open_max:
return 0.0
span = max(1, 255 - open_max)
return round(1.0 + (value - open_max) / span * 18.0, 2)
def lens_angle(value: int) -> float:
"""Indexed lens position, 0–60°. Spin ranges are not an index."""
if value <= 127:
return round(value / 127.0 * 60.0, 1)
return 0.0
def lens_spin(value: int) -> float:
"""Degrees per second. Negative is counter-clockwise.
0–127 index, 128–188 CCW fast to slow, 189–193 stop, 194–255 CW slow to fast.
"""
if 128 <= value <= 188:
rate = (188 - value) / 60.0
return round(-(40.0 + rate * 320.0), 1)
if 194 <= value <= 255:
rate = (value - 194) / 61.0
return round(40.0 + rate * 320.0, 1)
return 0.0
def _beam_color(pixels: list[list[int]]) -> tuple[int, int, int]:
"""Brightness-weighted mix, so one lit pixel stays its own colour."""
red = green = blue = weight = 0.0
for pr, pg, pb in pixels:
w = pr + pg + pb
red += pr * w
green += pg * w
blue += pb * w
weight += w
if weight <= 0:
return 0, 0, 0
return int(round(red / weight)), int(round(green / weight)), int(round(blue / weight))
def _scale(colour: tuple[int, int, int], dimmer: int) -> tuple[int, int, int]:
level = max(0, min(255, dimmer)) / 255.0
return tuple(int(round(channel * level)) for channel in colour)
def _speed_hz(speed: int, *, slow: float = 0.35, fast: float = 8.0) -> float:
return round(slow + max(0, min(255, speed)) / 255.0 * (fast - slow), 2)
def _can_mode(macro: int) -> str:
if macro <= 50:
return "mix"
if macro <= 100:
return "fixed"
if macro <= 150:
return "jump"
if macro <= 200:
return "pulse"
if macro <= 250:
return "gradient"
return "sound"
def _range_pick(value: int, start: int, count: int) -> tuple[int, float] | None:
"""Map value onto `count` bands from `start` through 255. Returns index and 0–1 position."""
if value < start or count <= 0:
return None
span = 256 - start
index = min(count - 1, (value - start) * count // span)
band = span / count
frac = ((value - start) - index * band) / band
return index, max(0.0, min(0.999, frac))
def apply_cto(red: int, green: int, blue: int, amount: int) -> tuple[int, int, int]:
"""0 leaves the colour alone. Higher values warm it, the way a CTO does."""
if amount <= 0:
return red, green, blue
warm = max(0, min(255, amount)) / 255.0
return (
red,
int(round(green * (1 - 0.35 * warm))),
int(round(blue * (1 - 0.75 * warm))),
)
def _can_view(
dimmer: int,
strobe: int,
red: int,
green: int,
blue: int,
white: int,
macro: int,
speed: int,
channels: list[int],
) -> dict:
mode = _can_mode(macro)
mixed = mix_rgbw(red, green, blue, white, dimmer)
peak = mix_rgbw(red, green, blue, white, 255)
if peak == (0, 0, 0):
peak = (255, 255, 255)
shown = mixed
palette = None
sound = 0
hz = 0.0
if mode == "fixed":
span = 50
index = min(len(_PAR_PALETTE) - 1, max(0, macro - 51) * len(_PAR_PALETTE) // span)
shown = _scale(_PAR_PALETTE[index], dimmer)
elif mode == "pulse":
shown = _scale(peak, dimmer)
hz = _speed_hz(speed, slow=0.4, fast=6.0)
elif mode in ("jump", "gradient", "sound"):
palette = [list(colour) for colour in _PAR_PALETTE]
hz = _speed_hz(speed)
shown = _scale(_PAR_PALETTE[0], dimmer)
if mode == "sound":
sound = 2 if macro >= 254 else 1
labels = {
"mix": "RGBW",
"fixed": "fixed colour",
"jump": "colour jump",
"pulse": "colour pulse",
"gradient": "colour gradient",
"sound": "sound 2" if sound == 2 else "sound 1",
}
viewed = {
"r": shown[0],
"g": shown[1],
"b": shown[2],
"dimmer": dimmer,
"strobe_hz": strobe_hz(strobe, CAN_STROBE_OPEN),
"strobe_mode": "strobe" if strobe > CAN_STROBE_OPEN else "open",
"effect": mode != "mix",
"function": mode,
"function_label": labels[mode],
"speed_hz": hz,
"sound": sound,
"channels": channels,
}
if palette is not None:
viewed["palette"] = palette
return viewed
def decode_can(channels: list[int]) -> dict:
def at(index: int) -> int:
return channels[index] if index < len(channels) else 0
return _can_view(at(0), at(1), at(2), at(3), at(4), at(5), at(6), at(7), channels)
def decode_named(channels: list[int], names: list[str], *, kind: str) -> dict:
"""Read a fixture using the channel names from the stage map."""
if kind == "mover" or (_find(names, "Pan") is not None and _find(names, "Tilt") is not None):
return _decode_mover_named(channels, names)
return _decode_can_named(channels, names)
def _decode_can_named(channels: list[int], names: list[str]) -> dict:
dimmer = 255 if _find(names, "Dimmer") is None else _value(channels, names, "Dimmer")
return _can_view(
dimmer,
_value(channels, names, "Strobe"),
_value(channels, names, "Red"),
_value(channels, names, "Green"),
_value(channels, names, "Blue"),
_value(channels, names, "White"),
_value(channels, names, "Macro"),
_value(channels, names, "Speed"),
channels,
)
def _mover_strobe(value: int) -> tuple[float, str]:
"""Centre strobe: open, linear strobe, then three random-strobe bands."""
if value <= MOVER_STROBE_OPEN:
return 0.0, "open"
if value <= 200:
return strobe_hz(value, MOVER_STROBE_OPEN), "strobe"
if value <= 215:
return 6.0, "random"
if value <= 234:
return 12.0, "random"
return 18.0, "random"
def _decode_mover_named(channels: list[int], names: list[str]) -> dict:
pan = (_value(channels, names, "Pan") << 8) | _value(channels, names, "Pan Fine")
tilt = (_value(channels, names, "Tilt") << 8) | _value(channels, names, "Tilt Fine")
zoom = _value(channels, names, "Zoom")
rotate = _value(channels, names, "Lens Rotate")
dimmer = 255 if _find(names, "Center Brightness") is None else _value(channels, names, "Center Brightness")
strobe = _value(channels, names, "Center Strobe")
pixels = _pixels(channels, names, dimmer)
macro_value = _value(channels, names, "Colour Macro")
static_value = _value(channels, names, "Static Effect")
dynamic_value = _value(channels, names, "Dynamic Effect")
cto = _value(channels, names, "Colour Temperature")
macro = _range_pick(macro_value, 10, len(_MOVER_MACROS))
static = _range_pick(static_value, 10, len(_STATIC_MASKS))
dynamic = _range_pick(dynamic_value, 10, len(_DYNAMIC))
source = [list(pixel) for pixel in pixels]
function = "pixels"
label = "pixels"
dynamic_name = None
speed = 0.0
if macro is not None:
colour = list(_scale(_MOVER_MACROS[macro[0]], dimmer))
source = [colour[:] for _ in range(7)]
function = "macro"
label = "colour macro"
if static is not None or dynamic is not None:
if not any(sum(pixel) > 0 for pixel in source):
white = list(_scale((255, 255, 255), dimmer))
source = [white[:] for _ in range(7)]
if static is not None and dynamic is None:
name, mask = _STATIC_MASKS[static[0]]
if name == "one":
pixel = min(6, int(static[1] * 7))
mask = tuple(1 if index == pixel else 0 for index in range(7))
source = [pixel if mask[index] else [0, 0, 0] for index, pixel in enumerate(source)]
function = "static"
label = "one pixel" if name == "one" else f"static {name}"
if dynamic is not None:
dynamic_name = _DYNAMIC[dynamic[0]]
speed = round(0.4 + dynamic[1] * 6.0, 2)
function = "dynamic"
label = _DYNAMIC_LABELS[dynamic_name]
tinted = [list(apply_cto(pixel[0], pixel[1], pixel[2], cto)) for pixel in source]
red, green, blue = _beam_color(tinted)
rate, strobe_mode = _mover_strobe(strobe)
reset = _value(channels, names, "Reset")
pan_speed = _value(channels, names, "Pan/Tilt Speed")
pan_deg = (pan - 32768) / 65536.0 * PAN_DEGREES
zoom_deg = ZOOM_MIN + (zoom / 255.0) * (ZOOM_MAX - ZOOM_MIN)
# Long enough to read on the plan at tilt zero. Tilt stretches the throw.
beam_m = 2.2 + (tilt / 65535.0) * 2.5
return {
"r": red,
"g": green,
"b": blue,
"dimmer": dimmer,
"strobe_hz": rate,
"strobe_mode": strobe_mode,
"effect": function != "pixels",
"function": function,
"function_label": label,
"speed_hz": speed,
"dynamic": dynamic_name,
"pan_deg": round(pan_deg, 2),
"zoom_deg": round(zoom_deg, 2),
"beam_m": round(beam_m, 3),
"pixels": tinted,
"spin_dps": lens_spin(rotate),
"lens_deg": lens_angle(rotate),
"focus": round(_value(channels, names, "Focus") / 255.0, 3),
"move": round(1 - pan_speed / 255.0, 3),
"cto": cto,
"reset": 200 <= reset <= 205,
"channels": channels,
}
def decode_mover(channels: list[int]) -> dict:
return _decode_mover_named(channels, MOVER_43)
def view_fixture(fixture: Fixture, universes: dict[int, bytes]) -> dict:
if fixture.address is None or fixture.universe is None:
return {"patched": False, "r": 0, "g": 0, "b": 0, "dimmer": 0, "strobe_hz": 0, "channels": []}
count = len(fixture.channel_names) or fixture.channels or (43 if fixture.kind == "mover" else 8)
frame = universes.get(fixture.universe, bytes(512))
channels = slots_at(frame, fixture.address, count)
if fixture.channel_names:
viewed = decode_named(channels, fixture.channel_names, kind=fixture.kind)
elif fixture.kind == "mover":
viewed = decode_mover(channels)
else:
viewed = decode_can(channels)
viewed["patched"] = True
return viewed
def view_stage(stage: Stage, universes: dict[int, bytes]) -> dict[str, dict]:
return {fixture.id: view_fixture(fixture, universes) for fixture in stage.fixtures}
+147
View File
@@ -0,0 +1,147 @@
"""HTTP view of the stage. The page polls /api/state."""
from __future__ import annotations
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlparse
from simulator.artnet import ArtNetNode
from simulator.decode import view_stage
from simulator.stage import Stage, apply_show, load_stage, set_heading
STATIC = Path(__file__).resolve().parent / "static"
CONTENT_TYPES = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
}
class Simulator:
def __init__(self, stage: Stage, node: ArtNetNode, show: Path | None = None):
self.stage = stage
self.node = node
self.show = show
def state(self) -> dict:
stats = self.node.stats()
stats["fixtures"] = view_stage(self.stage, self.node.snapshot())
return stats
def stage_dir(self) -> Path | None:
return self.stage.path.parent if self.stage.path else None
def stages(self) -> dict:
"""The stage maps next to the current one, for the page's drop-down."""
folder = self.stage_dir()
files = sorted(path.name for path in folder.glob("*.json")) if folder else []
current = self.stage.path.name if self.stage.path else None
return {"current": current, "stages": files}
def switch(self, name: str) -> Stage:
"""Load another stage map from the same folder, with the same show."""
folder = self.stage_dir()
if folder is None or name not in self.stages()["stages"]:
raise KeyError(name)
stage = load_stage(folder / name)
if self.show is not None:
apply_show(stage, self.show)
self.stage = stage
return stage
def make_handler(sim: Simulator):
class Handler(BaseHTTPRequestHandler):
simulator = sim
def log_message(self, fmt: str, *args) -> None:
return
def do_POST(self) -> None:
path = urlparse(self.path).path
if path == "/api/stage":
self._switch_stage()
return
if path != "/api/heading":
self.send_error(404)
return
length = int(self.headers.get("Content-Length") or 0)
if length <= 0 or length > 4096:
self._json({"error": "bad heading"}, 400)
return
try:
payload = json.loads(self.rfile.read(length))
fixture = set_heading(
self.simulator.stage,
str(payload["id"]),
direction=payload.get("direction"),
zero=payload.get("zero"),
)
except (KeyError, TypeError, ValueError, json.JSONDecodeError):
self._json({"error": "bad heading"}, 400)
return
self._json({"id": fixture.id, "direction": fixture.direction, "zero": fixture.zero})
def do_GET(self) -> None:
path = urlparse(self.path).path
if path == "/api/state":
self._json(self.simulator.state())
return
if path == "/api/stage":
self._json(self.simulator.stage.to_json())
return
if path == "/api/stages":
self._json(self.simulator.stages())
return
if path in ("/", "/index.html"):
self._file(STATIC / "index.html")
return
if path.startswith("/static/"):
target = (STATIC / path.removeprefix("/static/")).resolve()
if STATIC.resolve() in target.parents or target == STATIC.resolve():
self._file(target)
return
self.send_error(404)
def _switch_stage(self) -> None:
length = int(self.headers.get("Content-Length") or 0)
if length <= 0 or length > 4096:
self._json({"error": "bad stage"}, 400)
return
try:
name = str(json.loads(self.rfile.read(length))["file"])
stage = self.simulator.switch(name)
except (KeyError, TypeError, ValueError, json.JSONDecodeError):
self._json({"error": "bad stage"}, 400)
return
self._json(stage.to_json())
def _json(self, payload: dict, status: int = 200) -> None:
body = json.dumps(payload).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _file(self, path: Path) -> None:
if not path.is_file():
self.send_error(404)
return
body = path.read_bytes()
self.send_response(200)
self.send_header("Content-Type", CONTENT_TYPES.get(path.suffix, "application/octet-stream"))
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return Handler
def make_server(sim: Simulator, host: str, port: int) -> ThreadingHTTPServer:
return ThreadingHTTPServer((host, port), make_handler(sim))
+283
View File
@@ -0,0 +1,283 @@
"""Load a stage map and patch it from a QLC+ workspace."""
from __future__ import annotations
import json
import re
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from pathlib import Path
_NUMBER = re.compile(r"#\s*0*(\d+)")
@dataclass
class FixtureDef:
name: str
manufacturer: str
model: str
mode: str
channels: list[str]
@dataclass
class Fixture:
id: str
label: str
kind: str
x: float
y: float
universe: int | None = None
address: int | None = None # 0-based, same as the QLC+ workspace file
channels: int = 0
mode: str = ""
name: str = ""
definition: str = ""
channel_names: list[str] = field(default_factory=list)
direction: float = 0.0 # cans: beam heading, degrees clockwise from +Y
zero: float = 0.0 # movers: heading at pan centre, same degrees
@property
def dmx(self) -> int | None:
"""1-based DMX start address."""
if self.address is None:
return None
return self.address + 1
def to_json(self) -> dict:
return {
"id": self.id,
"label": self.label,
"kind": self.kind,
"x": self.x,
"y": self.y,
"universe": self.universe,
"address": self.address,
"dmx": self.dmx,
"channels": self.channels,
"mode": self.mode,
"name": self.name or self.label,
"def": self.definition,
"channel_names": self.channel_names,
"direction": self.direction,
"zero": self.zero,
}
@dataclass
class Stage:
building_width: float
origin: str
fixtures: list[Fixture]
name: str = "xchc"
show: str | None = None
output_ip: str | None = None
path: Path | None = None
warnings: list[str] = field(default_factory=list)
def to_json(self) -> dict:
return {
"name": self.name,
"building_width": self.building_width,
"origin": self.origin,
"show": self.show,
"output_ip": self.output_ip,
"fixtures": [fixture.to_json() for fixture in self.fixtures],
"warnings": self.warnings,
}
def _local(tag: str) -> str:
return tag.rsplit("}", 1)[-1]
def _text(element: ET.Element, name: str, default: str = "") -> str:
for child in element:
if _local(child.tag) == name and child.text:
return child.text.strip()
return default
def _definitions(data: dict) -> dict[str, FixtureDef]:
found: dict[str, FixtureDef] = {}
for name, raw in data.get("definitions", {}).items():
found[str(name)] = FixtureDef(
name=str(name),
manufacturer=str(raw.get("manufacturer") or ""),
model=str(raw.get("model") or ""),
mode=str(raw.get("mode") or ""),
channels=[str(channel) for channel in raw.get("channels") or []],
)
return found
def load_stage(path: Path) -> Stage:
data = json.loads(path.read_text())
definitions = _definitions(data)
fixtures: list[Fixture] = []
for key, raw in data.get("fixtures", {}).items():
kind = raw.get("kind", "can")
if raw.get("address") is not None:
address = int(raw["address"])
elif raw.get("dmx") is not None:
address = int(raw["dmx"]) - 1
else:
address = None
definition = definitions.get(str(raw.get("def") or ""))
channel_names = list(definition.channels) if definition else []
channels = int(raw.get("channels") or 0) or len(channel_names)
if address is not None and channels == 0:
channels = 43 if kind == "mover" else 8
fixtures.append(
Fixture(
id=str(key),
label=str(raw.get("label", key)),
kind=kind,
x=float(raw["x"]),
y=float(raw["y"]),
universe=None if raw.get("universe") is None else int(raw["universe"]),
address=None if address is None else int(address),
channels=channels,
mode=str(raw.get("mode") or (definition.mode if definition else "")),
name=str(raw.get("name") or raw.get("label", key)),
definition=definition.name if definition else str(raw.get("def") or ""),
channel_names=channel_names,
direction=float(raw.get("direction") or 0),
zero=float(raw.get("zero") or 0),
)
)
return Stage(
building_width=float(data.get("building_width", 7.0)),
origin=str(data.get("origin", "")),
fixtures=fixtures,
name=str(data.get("name") or "xchc"),
path=Path(path),
)
def wrap_degrees(degrees: float) -> int:
"""Nearest degree in -179..180. 0 points toward +Y."""
return (round(float(degrees)) + 180) % 360 - 180
def set_heading(stage: Stage, fixture_id: str, *, direction: float | None = None, zero: float | None = None) -> Fixture:
"""Point a can's direction, or a mover's zero, and store it in the stage file."""
fixture = next((item for item in stage.fixtures if item.id == fixture_id), None)
if fixture is None:
raise KeyError(fixture_id)
if fixture.kind == "can":
if direction is None:
raise ValueError("direction required")
fixture.direction = wrap_degrees(direction)
_write_number(stage, fixture_id, "direction", fixture.direction)
else:
if zero is None:
raise ValueError("zero required")
fixture.zero = wrap_degrees(zero)
_write_number(stage, fixture_id, "zero", fixture.zero)
return fixture
def _write_number(stage: Stage, fixture_id: str, field_name: str, value: int) -> None:
if stage.path is None or not stage.path.is_file():
return
text = stage.path.read_text()
marker = f'"{fixture_id}": {{'
start = text.find(marker)
if start < 0:
return
end = text.find("\n }", start)
if end < 0:
return
block = text[start:end]
updated, count = re.subn(
rf'("{re.escape(field_name)}":\s*)-?\d+(?:\.\d+)?',
rf"\g<1>{value}",
block,
count=1,
)
if count == 0:
updated = block.rstrip() + f',\n "{field_name}": {value}'
stage.path.write_text(text[:start] + updated + text[end:])
def _qxw_fixtures(path: Path) -> tuple[list[dict], str | None]:
root = ET.parse(path).getroot()
output_ip = None
fixtures: list[dict] = []
for element in root.iter():
name = _local(element.tag)
if name == "PluginParameters" and output_ip is None:
output_ip = element.attrib.get("outputIP") or None
if name != "Engine":
continue
for child in element:
if _local(child.tag) != "Fixture":
continue
fixtures.append(
{
"name": _text(child, "Name"),
"mode": _text(child, "Mode"),
"model": _text(child, "Model"),
"manufacturer": _text(child, "Manufacturer"),
"universe": int(_text(child, "Universe", "0")),
"address": int(_text(child, "Address", "0")),
"channels": int(_text(child, "Channels", "0")),
}
)
return fixtures, output_ip
def _stage_id_for(patched: dict, stage_ids: set[str]) -> str | None:
name = patched["name"]
if name in stage_ids:
return name
match = _NUMBER.search(name)
number = int(match.group(1)) if match else None
blob = f"{patched['manufacturer']} {patched['model']} {name}".lower()
mover = "mover" in blob or "small eye" in blob
can = "bcc145" in blob or blob.strip().endswith("can")
if number is None:
lowered = name.lower()
if "front left" in lowered and "M1" in stage_ids:
return "M1"
if "front right" in lowered and "M2" in stage_ids:
return "M2"
if "back left" in lowered and "M3" in stage_ids:
return "M3"
if "back right" in lowered and "M4" in stage_ids:
return "M4"
return None
if mover:
key = f"M{number}"
if key in stage_ids:
return key
if can:
key = f"#{number}"
if key in stage_ids:
return key
return None
def apply_show(stage: Stage, show_path: Path) -> None:
"""Fill missing DMX addresses from a QLC+ workspace."""
patched, output_ip = _qxw_fixtures(show_path)
stage.show = show_path.name
stage.output_ip = output_ip
by_id = {fixture.id: fixture for fixture in stage.fixtures}
used: set[str] = set()
for item in patched:
key = _stage_id_for(item, set(by_id))
if key is None or key in used:
continue
fixture = by_id[key]
if fixture.address is None:
fixture.universe = item["universe"]
fixture.address = item["address"]
fixture.channels = item["channels"] or fixture.channels
fixture.mode = item["mode"]
fixture.name = item["name"]
used.add(key)
for fixture in stage.fixtures:
if fixture.address is None:
stage.warnings.append(f"{fixture.label} has no DMX address")
+645
View File
@@ -0,0 +1,645 @@
const canvas = document.getElementById("stage");
const ctx = canvas.getContext("2d");
const statusEl = document.getElementById("status");
const originEl = document.getElementById("origin");
const nameEl = document.getElementById("stage-name");
const patchEl = document.getElementById("patch");
const listEl = document.getElementById("fixtures");
const detailEl = document.getElementById("detail");
const detailTitle = document.getElementById("detail-title");
const detailMeta = document.getElementById("detail-meta");
const channelsEl = document.getElementById("channels");
const stageFileEl = document.getElementById("stage-file");
let stage = null;
let state = { fixtures: {}, age: null, rate: 0, universe: null, packets: 0 };
let selected = null;
let drag = null;
const rows = new Map();
function luma(r, g, b) {
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
function hsv(hue, value) {
const h = ((hue % 1) + 1) % 1;
const i = Math.floor(h * 6);
const f = h * 6 - i;
const q = value * (1 - f);
const t = value * f;
const map = [
[value, t, 0],
[q, value, 0],
[0, value, t],
[0, q, value],
[t, 0, value],
[value, 0, q],
];
const [r, g, b] = map[i % 6];
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}
const PAR_PALETTE = [
[255, 0, 0],
[255, 96, 0],
[255, 200, 0],
[255, 255, 0],
[0, 255, 0],
[0, 255, 160],
[0, 64, 255],
[140, 0, 255],
[255, 0, 160],
[255, 255, 255],
];
const aims = new Map();
function scaleColour(colour, dimmer) {
const level = (dimmer || 0) / 255;
return colour.map((channel) => Math.round(channel * level));
}
function paletteColour(live, gradient) {
const palette = live.palette && live.palette.length ? live.palette : PAR_PALETTE;
const speed = live.speed_hz || 0.35;
const phase = performance.now() / 1000 * speed;
const index = Math.floor(phase) % palette.length;
if (!gradient) return palette[index];
const next = palette[(index + 1) % palette.length];
const blend = phase - Math.floor(phase);
return palette[index].map((channel, slot) => Math.round(channel + (next[slot] - channel) * blend));
}
function canColour(live) {
const mode = live.function || "mix";
const dimmer = live.dimmer || 0;
if (mode === "jump" || mode === "gradient") return scaleColour(paletteColour(live, mode === "gradient"), dimmer);
if (mode === "pulse") {
const speed = live.speed_hz || 0.4;
const wave = 0.5 - 0.5 * Math.cos((performance.now() / 1000) * speed * Math.PI * 2);
const depth = 0.05 + 0.95 * wave;
return [live.r || 0, live.g || 0, live.b || 0].map((channel) => Math.round(channel * depth));
}
if (mode === "sound") {
const speed = live.speed_hz || 1;
const variant = live.sound === 2 ? 2 : 1;
const bpm = (variant === 2 ? 156 : 104) * (0.55 + Math.min(speed, 8) / 10);
const beat = ((performance.now() / 1000) * bpm / 60) % 1;
let hit = beat < 0.08 ? 1 : 0.04;
if (variant === 2 && beat > 0.5 && beat < 0.58) hit = 1;
const colour = (live.palette && live.palette[variant === 2 ? 4 : 0]) || PAR_PALETTE[variant === 2 ? 4 : 0];
return scaleColour(colour, dimmer).map((channel) => Math.round(channel * hit));
}
return [live.r || 0, live.g || 0, live.b || 0];
}
function effectPixels(live) {
const source = (live.pixels || []).map((pixel) => pixel.slice());
if (!live.dynamic || !source.length) return source;
const count = source.length;
const lit = source.find((pixel) => pixel[0] + pixel[1] + pixel[2] > 0);
const fallback = lit || scaleColour([255, 255, 255], live.dimmer || 0);
const speed = live.speed_hz || 1;
const t = (performance.now() / 1000) * speed;
return source.map((pixel, index) => {
const colour = pixel[0] + pixel[1] + pixel[2] > 0 ? pixel : fallback;
if (live.dynamic === "rainbow") {
return hsv((t * 0.2 + index / count) % 1, (live.dimmer || 0) / 255);
}
let level = 1;
if (live.dynamic === "chase") level = Math.floor(t) % count === index ? 1 : 0.08;
else if (live.dynamic === "reverse") level = Math.floor(t) % count === (count - 1 - index) ? 1 : 0.08;
else if (live.dynamic === "bounce") {
const span = Math.max(1, count - 1);
const tri = Math.abs((t % (2 * span)) - span);
level = Math.round(tri) === index ? 1 : 0.08;
} else if (live.dynamic === "pulse") level = 0.15 + 0.85 * (0.5 + 0.5 * Math.sin(t * Math.PI * 2));
else if (live.dynamic === "pairs") level = Math.floor(t) % 2 === index % 2 ? 1 : 0.08;
return colour.map((channel) => Math.round(channel * level));
});
}
function mixPixels(pixels) {
let red = 0;
let green = 0;
let blue = 0;
let weight = 0;
for (const pixel of pixels) {
const w = pixel[0] + pixel[1] + pixel[2];
red += pixel[0] * w;
green += pixel[1] * w;
blue += pixel[2] * w;
weight += w;
}
if (weight <= 0) return [0, 0, 0];
return [Math.round(red / weight), Math.round(green / weight), Math.round(blue / weight)];
}
function shutter(live) {
if (!live.strobe_hz) return 1;
const t = performance.now() / 1000;
if (live.strobe_mode === "random") {
const bucket = Math.floor(t * live.strobe_hz);
const noise = Math.abs(Math.sin(bucket * 12.9898) * 43758.5453) % 1;
return noise > 0.55 ? 1 : 0;
}
const period = 1 / live.strobe_hz;
return t % period < period * 0.42 ? 1 : 0;
}
function aimed(id, live, zero) {
const targetPan = (zero || 0) + (live.pan_deg || 0);
const targetBeam = live.beam_m || 0;
const now = performance.now() / 1000;
let state = aims.get(id);
if (!state) {
state = { pan: targetPan, beam: targetBeam, t: now };
aims.set(id, state);
return state;
}
const dt = Math.min(0.05, Math.max(0, now - state.t));
state.t = now;
const fast = live.move == null ? 1 : live.move;
if (fast > 0.97) {
state.pan = targetPan;
state.beam = targetBeam;
return state;
}
const tau = 0.05 + (1 - fast) * 1.8;
const k = 1 - Math.exp(-dt / tau);
state.pan += (targetPan - state.pan) * k;
state.beam += (targetBeam - state.beam) * k;
return state;
}
function appearance(fixture, live) {
const pixels = fixture.kind === "mover" ? effectPixels(live) : null;
let [r, g, b] = fixture.kind === "can" ? canColour(live) : pixels && live.dynamic ? mixPixels(pixels) : [live.r || 0, live.g || 0, live.b || 0];
const gate = shutter(live);
return {
r: Math.round(r * gate),
g: Math.round(g * gate),
b: Math.round(b * gate),
dimmer: live.dimmer || 0,
pixels: pixels && pixels.map((pixel) => pixel.map((channel) => Math.round(channel * gate))),
};
}
function layout(width, height) {
const ys = stage.fixtures.map((fixture) => fixture.y);
const backY = Math.min(0, ...ys);
const depth = Math.max(2.4, ...ys);
const padX = 0.85;
const padY = 0.7;
const x0 = -stage.building_width / 2 - padX;
const x1 = stage.building_width / 2 + padX;
const y0 = backY - padY;
const y1 = depth + padY;
const worldW = x1 - x0;
const worldH = y1 - y0;
const scale = Math.min(width / worldW, height / worldH);
const ox = (width - worldW * scale) / 2;
const oy = (height - worldH * scale) / 2;
return {
depth,
backY,
sx: (x) => ox + (x - x0) * scale,
sy: (y) => oy + (y1 - y) * scale,
mx: (px) => x0 + (px - ox) / scale,
my: (py) => y1 - (py - oy) / scale,
};
}
function draw() {
if (!stage) return;
const dpr = window.devicePixelRatio || 1;
const width = canvas.width;
const height = canvas.height;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
const cssW = width / dpr;
const cssH = height / dpr;
const view = layout(cssW, cssH);
const { sx, sy, depth, backY } = view;
ctx.clearRect(0, 0, cssW, cssH);
ctx.fillStyle = "#121216";
ctx.fillRect(0, 0, cssW, cssH);
const left = sx(-stage.building_width / 2);
const right = sx(stage.building_width / 2);
const front = sy(depth);
const back = sy(backY);
ctx.strokeStyle = "#5c5c66";
ctx.lineWidth = 2;
ctx.strokeRect(left, front, right - left, back - front);
ctx.strokeStyle = "#3a3a44";
ctx.lineWidth = 1;
ctx.setLineDash([4, 6]);
ctx.beginPath();
ctx.moveTo(sx(0), sy(backY - 0.2));
ctx.lineTo(sx(0), sy(depth + 0.25));
ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = "#9a9aa4";
ctx.font = "600 13px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.fillText("AUDIENCE", sx(0), sy(depth + 0.38));
ctx.font = "12px system-ui, sans-serif";
ctx.fillStyle = "#8d8d96";
ctx.fillText("row of 4", sx(0), sy(-0.28));
ctx.font = "11px system-ui, sans-serif";
ctx.fillText(`${stage.building_width.toFixed(1)} m`, sx(0), front - 8);
ctx.globalCompositeOperation = "lighter";
for (const fixture of stage.fixtures) {
const live = state.fixtures[fixture.id] || {};
const color = appearance(fixture, live);
const dragging = drag && drag.moved && drag.id === fixture.id;
const beamColor = dragging && color.r + color.g + color.b < 8 ? { ...color, r: 190, g: 190, b: 200 } : color;
if (fixture.kind === "mover") {
const fixed = dragging
? { pan: (fixture.zero || 0) + (live.pan_deg || 0), beam: Math.max(live.beam_m || 0, 1.6), zoom: live.zoom_deg || 18, focus: 1 - (live.focus || 0) }
: null;
drawBeam(sx, sy, fixture, live, beamColor, fixed);
} else {
drawBeam(sx, sy, fixture, live, beamColor, { pan: fixture.direction || 0, beam: 2.2, zoom: 25, focus: 0.35 });
}
drawGlow(sx, sy, fixture, color);
}
ctx.globalCompositeOperation = "source-over";
for (const fixture of stage.fixtures) {
const live = state.fixtures[fixture.id] || {};
drawBody(sx, sy, fixture, live, appearance(fixture, live));
}
}
function drawGlow(sx, sy, fixture, color) {
const level = (color.r + color.g + color.b) / (255 * 3);
if (level <= 0.01) return;
const x = sx(fixture.x);
const y = sy(fixture.y);
const radius = (fixture.kind === "mover" ? 70 : 54) * (0.45 + level);
const gradient = ctx.createRadialGradient(x, y, 2, x, y, radius);
gradient.addColorStop(0, `rgba(${color.r},${color.g},${color.b},${0.55 * level + 0.15})`);
gradient.addColorStop(1, `rgba(${color.r},${color.g},${color.b},0)`);
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fill();
}
function drawBeam(sx, sy, fixture, live, color, fixed) {
const level = (color.r + color.g + color.b) / 255;
const length = fixed ? fixed.beam : Math.max(live.beam_m || 0, fixture.kind === "mover" ? 2.2 : 0);
if (live.patched === false || level <= 0.02 || !length) return;
const aim = fixed || aimed(fixture.id, live, fixture.zero);
// DMX focus 0 is a wide wash. Focus 255 holds the zoom angle.
// Fixed beams pass spread directly, 0 tight and 1 wide.
const spread = fixed ? fixed.focus : 1 - (live.focus || 0);
const zoom = fixed ? fixed.zoom : live.zoom_deg || 8;
const tight = zoom / 2;
const wide = Math.max(tight, 40);
const rad = aim.pan * Math.PI / 180;
const half = (tight + (wide - tight) * spread) * Math.PI / 180;
const tip = [fixture.x + Math.sin(rad) * length, fixture.y + Math.cos(rad) * length];
const left = [fixture.x + Math.sin(rad - half) * length, fixture.y + Math.cos(rad - half) * length];
const right = [fixture.x + Math.sin(rad + half) * length, fixture.y + Math.cos(rad + half) * length];
ctx.beginPath();
ctx.moveTo(sx(fixture.x), sy(fixture.y));
ctx.lineTo(sx(left[0]), sy(left[1]));
ctx.lineTo(sx(right[0]), sy(right[1]));
ctx.closePath();
const gradient = ctx.createLinearGradient(sx(fixture.x), sy(fixture.y), sx(tip[0]), sy(tip[1]));
const alpha = 0.85 * (1 - spread * 0.35);
gradient.addColorStop(0, `rgba(${color.r},${color.g},${color.b},${alpha})`);
gradient.addColorStop(1, `rgba(${color.r},${color.g},${color.b},0)`);
ctx.fillStyle = gradient;
ctx.fill();
}
function lensRotation(live) {
if (live.spin_dps) return ((performance.now() / 1000) * live.spin_dps * Math.PI) / 180;
return ((live.lens_deg || 0) * Math.PI) / 180;
}
function drawBody(sx, sy, fixture, live, color) {
const x = sx(fixture.x);
const y = sy(fixture.y);
const pixels = color.pixels || [];
const head = fixture.kind === "mover" && pixels.length ? pixels[0] : [color.r, color.g, color.b];
const lit = head[0] + head[1] + head[2] > 8;
const size = fixture.kind === "mover" ? 15 : 13;
ctx.beginPath();
if (fixture.kind === "mover") {
ctx.rect(x - size, y - size, size * 2, size * 2);
} else {
ctx.arc(x, y, size, 0, Math.PI * 2);
}
ctx.fillStyle = lit ? `rgb(${head[0]},${head[1]},${head[2]})` : "#2a2a30";
ctx.fill();
ctx.lineWidth = fixture.id === selected ? 2.5 : 1.5;
ctx.strokeStyle = fixture.id === selected ? "#fff" : "#c8c8d0";
ctx.stroke();
if (fixture.kind === "mover" && pixels.length > 1) {
const ring = pixels.slice(1);
const spin = lensRotation(live);
ring.forEach((pixel, index) => {
const angle = spin + (index / ring.length) * Math.PI * 2 - Math.PI / 2;
const px = x + Math.cos(angle) * (size + 7);
const py = y + Math.sin(angle) * (size + 7);
ctx.beginPath();
ctx.arc(px, py, 3.5, 0, Math.PI * 2);
const on = pixel[0] + pixel[1] + pixel[2] > 0;
ctx.fillStyle = on ? `rgb(${pixel[0]},${pixel[1]},${pixel[2]})` : "#333";
ctx.fill();
});
}
ctx.fillStyle = lit && luma(head[0], head[1], head[2]) > 140 ? "#16161a" : "#f2f2f4";
ctx.font = "600 11px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(fixture.label, x, y);
ctx.textBaseline = "alphabetic";
}
function resize() {
const rect = canvas.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
canvas.width = Math.max(1, Math.floor(rect.width * dpr));
canvas.height = Math.max(1, Math.floor(rect.height * dpr));
draw();
}
function swatchColor(fixture, live) {
const color = appearance(fixture, live || {});
const head = fixture.kind === "mover" && color.pixels && color.pixels[0] ? color.pixels[0] : [color.r, color.g, color.b];
if (head[0] + head[1] + head[2] < 8) return "#2a2a30";
return `rgb(${head[0]},${head[1]},${head[2]})`;
}
function buildList() {
listEl.replaceChildren();
rows.clear();
for (const fixture of stage.fixtures) {
const li = document.createElement("li");
li.id = `fx-${fixture.id}`;
li.className = fixture.kind;
li.dataset.id = fixture.id;
li.title = fixture.label;
const swatch = document.createElement("span");
swatch.className = "swatch";
const name = document.createElement("span");
name.className = "name";
name.textContent = fixture.label;
const addr = document.createElement("span");
addr.className = "addr";
addr.textContent = fixture.dmx == null ? "no address" : `DMX ${fixture.dmx}`;
li.append(swatch, name, addr);
li.addEventListener("click", () => {
selected = fixture.id;
updateDetail();
draw();
});
listEl.append(li);
rows.set(fixture.id, { li, swatch, addr });
}
}
function updateList() {
for (const fixture of stage.fixtures) {
const row = rows.get(fixture.id);
const live = state.fixtures[fixture.id] || {};
row.swatch.style.background = swatchColor(fixture, live);
row.li.classList.toggle("selected", fixture.id === selected);
if (!live.patched) row.addr.textContent = "no address";
else if (live.function && live.function !== "mix" && live.function !== "pixels") {
row.addr.textContent = `DMX ${fixture.dmx} · ${live.function_label || live.function}`;
} else row.addr.textContent = `DMX ${fixture.dmx}`;
}
}
function updateDetail() {
const fixture = stage.fixtures.find((item) => item.id === selected);
if (!fixture) {
detailEl.hidden = true;
return;
}
const live = state.fixtures[fixture.id] || {};
detailEl.hidden = false;
detailTitle.textContent = fixture.name || fixture.label;
const bits = [];
if (fixture.dmx != null) bits.push(`DMX ${fixture.dmx}`);
if (fixture.def) bits.push(fixture.def);
else if (fixture.mode) bits.push(fixture.mode);
if (fixture.kind === "can") bits.push(`direction ${fixture.direction || 0}°`);
if (fixture.kind === "mover") bits.push(`zero ${fixture.zero || 0}°`);
if (live.function_label && live.function !== "mix" && live.function !== "pixels") bits.push(live.function_label);
if (live.speed_hz) bits.push(`${live.speed_hz.toFixed(1)} Hz`);
if (live.reset) bits.push("reset");
if (fixture.kind === "mover" && live.pan_deg != null) {
bits.push(`pan ${live.pan_deg.toFixed(0)}°`);
bits.push(`zoom ${(live.zoom_deg || 0).toFixed(0)}°`);
if (live.spin_dps) bits.push(`lens ${live.spin_dps > 0 ? "CW" : "CCW"}`);
else if (live.lens_deg) bits.push(`lens ${live.lens_deg.toFixed(0)}°`);
}
detailMeta.textContent = bits.join(" · ");
const channels = live.channels || [];
channelsEl.replaceChildren();
channels.forEach((value, index) => {
const row = document.createElement("div");
row.className = "channel";
const label = document.createElement("span");
label.textContent = String(index + 1);
const title = document.createElement("span");
title.className = "ch-name";
title.textContent = (fixture.channel_names && fixture.channel_names[index]) || "";
const bar = document.createElement("div");
bar.className = "bar";
const fill = document.createElement("span");
fill.style.width = `${(value / 255) * 100}%`;
bar.append(fill);
const num = document.createElement("span");
num.textContent = String(value);
row.append(label, title, bar, num);
channelsEl.append(row);
});
}
function updateStatus() {
const age = state.age;
const live = age != null && age < 1.5;
statusEl.classList.toggle("live", live);
if (!live) {
statusEl.textContent = state.packets ? "Art-Net idle" : "waiting for Art-Net";
return;
}
const universe = state.universe == null ? "" : ` · universe ${state.universe}`;
statusEl.textContent = `Art-Net ${state.rate} fps${universe}`;
}
async function poll() {
try {
state = await fetch("/api/state").then((response) => response.json());
updateStatus();
updateList();
if (selected) updateDetail();
} catch {
statusEl.classList.remove("live");
statusEl.textContent = "view disconnected";
}
}
function frame() {
draw();
if (stage) updateList();
requestAnimationFrame(frame);
}
function pointerMetres(event) {
const rect = canvas.getBoundingClientRect();
const view = layout(rect.width, rect.height);
return {
x: view.mx(event.clientX - rect.left),
y: view.my(event.clientY - rect.top),
};
}
function fixtureAt(x, y) {
let best = null;
let bestDist = 0.55;
for (const fixture of stage.fixtures) {
const dist = Math.hypot(fixture.x - x, fixture.y - y);
if (dist < bestDist) {
best = fixture;
bestDist = dist;
}
}
return best;
}
function wrapDegrees(degrees) {
return ((Math.round(degrees) + 180) % 360 + 360) % 360 - 180;
}
function aimDegrees(fixture, x, y) {
return wrapDegrees(Math.atan2(x - fixture.x, y - fixture.y) * 180 / Math.PI);
}
function saveHeading(fixture) {
const body = fixture.kind === "can"
? { id: fixture.id, direction: fixture.direction }
: { id: fixture.id, zero: fixture.zero };
fetch("/api/heading", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
}).catch(() => {});
}
canvas.addEventListener("pointerdown", (event) => {
if (!stage || event.button !== 0) return;
const { x, y } = pointerMetres(event);
const fixture = fixtureAt(x, y);
selected = fixture ? fixture.id : null;
drag = fixture ? { id: fixture.id, moved: false } : null;
if (drag) canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = fixture ? "grabbing" : "default";
updateList();
updateDetail();
});
canvas.addEventListener("pointermove", (event) => {
if (!stage) return;
const { x, y } = pointerMetres(event);
if (!drag) {
canvas.style.cursor = fixtureAt(x, y) ? "grab" : "default";
return;
}
const fixture = stage.fixtures.find((item) => item.id === drag.id);
if (!fixture) return;
if (!drag.moved && Math.hypot(x - fixture.x, y - fixture.y) < 0.2) return;
drag.moved = true;
const heading = aimDegrees(fixture, x, y);
if (fixture.kind === "can") fixture.direction = heading;
else {
const live = state.fixtures[fixture.id] || {};
fixture.zero = wrapDegrees(heading - (live.pan_deg || 0));
}
updateDetail();
});
canvas.addEventListener("pointerup", () => {
if (!drag) return;
const fixture = stage.fixtures.find((item) => item.id === drag.id);
const moved = drag.moved;
drag = null;
canvas.style.cursor = "grab";
if (fixture && moved) {
aims.delete(fixture.id);
saveHeading(fixture);
}
updateDetail();
});
canvas.addEventListener("pointercancel", () => {
drag = null;
canvas.style.cursor = "default";
});
window.addEventListener("resize", resize);
function showStage(loaded) {
stage = loaded;
selected = null;
detailEl.hidden = true;
nameEl.textContent = stage.name || "xchc";
document.title = stage.name || "xchc";
originEl.textContent = stage.origin || "";
const show = stage.show ? stage.show : "addresses from the stage map";
const target = stage.output_ip ? ` · QLC+ output ${stage.output_ip}` : "";
patchEl.textContent = `${show}${target}`;
buildList();
resize();
}
async function loadStageList() {
const { current, stages } = await fetch("/api/stages").then((response) => response.json());
stageFileEl.replaceChildren(
...stages.map((name) => new Option(name.replace(/\.json$/, ""), name, false, name === current)),
);
stageFileEl.disabled = stages.length < 2;
}
stageFileEl.addEventListener("change", async () => {
stageFileEl.disabled = true;
try {
const response = await fetch("/api/stage", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ file: stageFileEl.value }),
});
if (!response.ok) throw new Error("bad stage");
showStage(await response.json());
} catch {
statusEl.textContent = "could not load that stage";
}
await loadStageList().catch(() => {});
});
fetch("/api/stage")
.then((response) => response.json())
.then((loaded) => {
showStage(loaded);
loadStageList().catch(() => {});
poll();
setInterval(poll, 50);
requestAnimationFrame(frame);
})
.catch(() => {
statusEl.textContent = "could not load the stage";
});
+34
View File
@@ -0,0 +1,34 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>xchc</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<header>
<div class="titles">
<h1 id="stage-name">xchc</h1>
<p id="origin"></p>
</div>
<label class="stage-pick">Stage
<select id="stage-file" aria-label="Stage map"></select>
</label>
<p id="status" class="pill">waiting for Art-Net</p>
</header>
<main>
<canvas id="stage" aria-label="Stage plan"></canvas>
<aside>
<p id="patch" class="meta"></p>
<ul id="fixtures"></ul>
<section id="detail" hidden>
<h2 id="detail-title"></h2>
<p id="detail-meta" class="meta"></p>
<div id="channels"></div>
</section>
</aside>
</main>
<script src="/static/app.js"></script>
</body>
</html>
+203
View File
@@ -0,0 +1,203 @@
:root {
color-scheme: dark;
--bg: #0e0e10;
--panel: #141418;
--line: #2c2c34;
--text: #eee;
--muted: #8d8d96;
--live: #3dd68c;
--idle: #d7a13a;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
height: 100%;
background: var(--bg);
color: var(--text);
font-family: system-ui, sans-serif;
}
body {
display: grid;
grid-template-rows: auto minmax(0, 1fr);
height: 100vh;
height: 100dvh;
overflow: hidden;
}
header {
display: flex;
align-items: center;
flex-wrap: wrap;
justify-content: space-between;
gap: 8px 16px;
padding: 12px 16px;
border-bottom: 1px solid var(--line);
}
h1, h2 {
margin: 0;
font-size: 16px;
font-weight: 600;
}
h2 { font-size: 14px; }
.titles { flex: 1 1 240px; }
.titles p, .meta {
margin: 2px 0 0;
color: var(--muted);
font-size: 12px;
}
.stage-pick {
display: flex;
align-items: center;
gap: 6px;
margin-left: auto;
color: var(--muted);
font-size: 12px;
}
.stage-pick select {
padding: 3px 6px;
border: 1px solid var(--line);
border-radius: 6px;
background: var(--panel);
color: var(--text);
font: inherit;
}
.pill {
margin: 0;
padding: 4px 10px;
border-radius: 999px;
background: #2a2418;
color: var(--idle);
font-size: 12px;
font-variant-numeric: tabular-nums;
}
.pill.live {
background: #14281e;
color: var(--live);
}
main {
display: grid;
grid-template-columns: minmax(0, 1fr) 300px;
grid-template-rows: minmax(0, 1fr);
min-height: 0;
min-width: 0;
}
canvas {
width: 100%;
height: 100%;
display: block;
background: #121216;
touch-action: none;
}
aside {
border-left: 1px solid var(--line);
background: var(--panel);
overflow: hidden;
min-height: 0;
padding: 10px 14px;
display: flex;
flex-direction: column;
}
ul {
list-style: none;
margin: 10px 0 0;
padding: 0;
}
li {
display: grid;
grid-template-columns: 18px 1fr auto;
gap: 8px;
align-items: center;
padding: 4px 6px;
border-radius: 6px;
cursor: pointer;
}
li:hover, li.selected { background: #22222a; }
.swatch {
width: 18px;
height: 18px;
border-radius: 50%;
border: 1px solid #555;
background: #222;
}
li.mover .swatch { border-radius: 3px; }
.name { font-size: 13px; font-weight: 600; }
.addr { color: var(--muted); font-size: 11px; }
/* with a fixture open, or in a short window, collapse the list to swatches */
aside:has(#detail:not([hidden])) ul { display: flex; flex-wrap: wrap; gap: 4px; }
aside:has(#detail:not([hidden])) li { display: block; padding: 3px; }
aside:has(#detail:not([hidden])) li .name,
aside:has(#detail:not([hidden])) li .addr { display: none; }
@media (max-height: 760px) {
ul { display: flex; flex-wrap: wrap; gap: 4px; }
li { display: block; padding: 3px; }
li .name, li .addr { display: none; }
}
#detail {
margin-top: 12px;
min-height: 0;
overflow: hidden;
}
#channels {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
gap: 2px 10px;
margin-top: 8px;
}
.channel {
display: grid;
grid-template-columns: 22px minmax(72px, 1.2fr) 1fr 28px;
gap: 6px;
align-items: center;
font-size: 11px;
color: var(--muted);
font-variant-numeric: tabular-nums;
}
.ch-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.bar {
height: 6px;
background: #2a2a32;
border-radius: 99px;
overflow: hidden;
}
.bar span {
display: block;
height: 100%;
background: #d0d0d8;
}
@media (max-width: 800px) {
main { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(0, 1fr) auto; }
aside { border-left: 0; border-top: 1px solid var(--line); max-height: 42vh; }
}
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# Install the stage simulator as a systemd user service and start it.
#
# simulator/systemd/install.sh # install, enable, start
# simulator/systemd/install.sh --show shows/test.qxw # pass options to the simulator
# simulator/systemd/install.sh --no-enable # install only; start it with
# # systemctl --user start simulator
# simulator/systemd/install.sh --uninstall
#
# Logs: journalctl --user -u simulator -f
set -euo pipefail
UNIT=simulator.service
HERE="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(cd "$HERE/../.." && pwd)"
DEST="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"
if [[ "${1:-}" == "--uninstall" ]]; then
systemctl --user disable --now "$UNIT" 2>/dev/null || true
rm -f "$DEST/$UNIT"
systemctl --user daemon-reload
echo "Removed $UNIT."
exit 0
fi
PYTHON="$ROOT/.venv/bin/python"
[[ -x "$PYTHON" ]] || PYTHON="$(command -v python3)"
ENABLE=1
if [[ "${1:-}" == "--no-enable" ]]; then
ENABLE=
shift
fi
ARGS="$*"
mkdir -p "$DEST"
sed -e "s|@ROOT@|$ROOT|g" -e "s|@PYTHON@|$PYTHON|g" -e "s|@ARGS@|$ARGS|g" \
"$HERE/$UNIT" >"$DEST/$UNIT"
systemctl --user daemon-reload
if [[ -z "$ENABLE" ]]; then
# Undo an earlier enable, so it does not start at login here.
systemctl --user disable "$UNIT" 2>/dev/null || true
echo "Installed $DEST/$UNIT. It does not start at login."
echo "Start it with: systemctl --user start simulator"
exit 0
fi
systemctl --user enable "$UNIT"
systemctl --user restart "$UNIT"
echo "Installed $DEST/$UNIT and started it."
systemctl --user --no-pager status "$UNIT" | head -5 || true
+20
View File
@@ -0,0 +1,20 @@
# Stage simulator (python -m simulator) as a systemd user service.
# install.sh fills in @ROOT@, @PYTHON@ and @ARGS@ and copies it to
# ~/.config/systemd/user/.
[Unit]
Description=Stage simulator (Art-Net on 6454, view on http://127.0.0.1:8765)
After=network.target
[Service]
Type=simple
WorkingDirectory=@ROOT@
ExecStart=@PYTHON@ -m simulator @ARGS@
Environment=PYTHONUNBUFFERED=1
# The simulator shuts its server and Art-Net socket down on Ctrl+C.
KillSignal=SIGINT
Restart=on-failure
RestartSec=3
[Install]
WantedBy=default.target
+132 -26
View File
@@ -12,23 +12,36 @@ import {
/** Y=0 = row of 4; +Y toward audience. Side cans on walls at ±3.5 m. */
const WALL = 3.5;
const BEAM = 0.3;
const FAR = -8.0;
const FIXTURES: {
key: string;
label: string;
kind: "can" | "mover";
x: number;
y: number;
dmx: number;
channels: number;
}[] = [
{ key: "c3", label: "#3", kind: "can", x: -1.8, y: 0.0 },
{ key: "c4", label: "#4", kind: "can", x: -0.6, y: 0.0 },
{ key: "c5", label: "#5", kind: "can", x: 0.6, y: 0.0 },
{ key: "c6", label: "#6", kind: "can", x: 1.8, y: 0.0 },
{ key: "c2", label: "#2", kind: "can", x: -WALL, y: 1.2 },
{ key: "c7", label: "#7", kind: "can", x: WALL, y: 1.2 },
{ key: "m1", label: "M1", kind: "mover", x: -0.3, y: 1.1 },
{ key: "m2", label: "M2", kind: "mover", x: 0.3, y: 1.1 },
{ key: "c1", label: "#1", kind: "can", x: -WALL, y: 2.4 },
{ key: "c8", label: "#8", kind: "can", x: WALL, y: 2.4 },
{ key: "c3", label: "#3", kind: "can", x: -1.8, y: 0.0, dmx: 103, channels: 8 },
{ key: "c4", label: "#4", kind: "can", x: -0.6, y: 0.0, dmx: 111, channels: 8 },
{ key: "c5", label: "#5", kind: "can", x: 0.6, y: 0.0, dmx: 119, channels: 8 },
{ key: "c6", label: "#6", kind: "can", x: 1.8, y: 0.0, dmx: 127, channels: 8 },
{ key: "c2", label: "#2", kind: "can", x: -WALL, y: 1.2, dmx: 95, channels: 8 },
{ key: "c7", label: "#7", kind: "can", x: WALL, y: 1.2, dmx: 135, channels: 8 },
{ key: "m1", label: "M1", kind: "mover", x: -0.3, y: 1.1, dmx: 0, channels: 43 },
{ key: "m2", label: "M2", kind: "mover", x: 0.3, y: 1.1, dmx: 44, channels: 43 },
{ key: "c1", label: "#1", kind: "can", x: -WALL, y: 2.4, dmx: 87, channels: 8 },
{ key: "c8", label: "#8", kind: "can", x: WALL, y: 2.4, dmx: 143, channels: 8 },
{ key: "c9", label: "#9", kind: "can", x: -WALL, y: -0.8, dmx: 151, channels: 8 },
{ key: "c10", label: "#10", kind: "can", x: WALL, y: -0.8, dmx: 159, channels: 8 },
{ key: "c11", label: "#11", kind: "can", x: -WALL, y: -6.8, dmx: 167, channels: 8 },
{ key: "c12", label: "#12", kind: "can", x: WALL, y: -6.8, dmx: 175, channels: 8 },
{ key: "c13", label: "#13", kind: "can", x: -WALL, y: -7.65, dmx: 183, channels: 8 },
{ key: "c14", label: "#14", kind: "can", x: 0, y: -7.65, dmx: 191, channels: 8 },
{ key: "c15", label: "#15", kind: "can", x: WALL, y: -7.65, dmx: 199, channels: 8 },
{ key: "m3", label: "M3", kind: "mover", x: -1.75, y: -7.65, dmx: 257, channels: 43 },
{ key: "m4", label: "M4", kind: "mover", x: 1.75, y: -7.65, dmx: 300, channels: 43 },
];
const BUILDING_W = 7;
@@ -40,7 +53,7 @@ export default function StageMap() {
const pad = 0.55;
const x0 = -BUILDING_W / 2 - pad;
const x1 = BUILDING_W / 2 + pad;
const y0 = -0.45;
const y0 = FAR - 0.55;
const y1 = DEPTH + 0.55;
const vbW = x1 - x0;
const vbH = y1 - y0;
@@ -116,7 +129,7 @@ export default function StageMap() {
return (
<Stack gap={20} style={{ padding: 20, maxWidth: 960 }}>
<Stack gap={6}>
<H1>Stage map</H1>
<H1>xchc</H1>
<Text tone="secondary">
Building {BUILDING_W} m wide · walls at ±{WALL} m · Y = 0 at row of 4 ·
+Y toward audience
@@ -135,7 +148,7 @@ export default function StageMap() {
x={sx(-BUILDING_W / 2)}
y={sy(DEPTH)}
width={BUILDING_W * px}
height={DEPTH * px}
height={(DEPTH - FAR) * px}
fill="none"
stroke={stroke}
strokeWidth={2}
@@ -166,7 +179,7 @@ export default function StageMap() {
{DimH(0, WALL, 1.8, "3.5 m", "below")}
<line
x1={sx(0)}
y1={sy(-0.15)}
y1={sy(FAR - 0.15)}
x2={sx(0)}
y2={sy(DEPTH + 0.2)}
stroke={dim}
@@ -189,7 +202,7 @@ export default function StageMap() {
</text>
<text
x={sx(0)}
y={sy(-0.28)}
y={sy(-0.62)}
textAnchor="middle"
fontSize={11}
fill={dim}
@@ -207,6 +220,30 @@ export default function StageMap() {
{DimV(0, 1.1, 2.4, "1.1 m movers")}
{DimV(0, 1.2, 2.4, "1.2 m")}
{DimV(0, 2.4, -2.4, "2.4 m", "left")}
{DimV(-0.8, -6.8, -3.95, "6 m", "right")}
<rect
x={sx(-WALL)}
y={sy(-0.2)}
width={BUILDING_W * px}
height={BEAM * px}
fill={theme.fill.tertiary}
stroke={stroke}
/>
<rect
x={sx(-WALL)}
y={sy(-7.05)}
width={BUILDING_W * px}
height={BEAM * px}
fill={theme.fill.tertiary}
stroke={stroke}
/>
<text x={sx(-2.2)} y={sy(-0.32)} textAnchor="middle" fontSize={10} fill={dim} stroke="none">
beam
</text>
<text x={sx(-2.2)} y={sy(-7.17)} textAnchor="middle" fontSize={10} fill={dim} stroke="none">
beam
</text>
{FIXTURES.map((f) => {
const cx = sx(f.x);
@@ -246,6 +283,16 @@ export default function StageMap() {
>
{f.label}
</text>
<text
x={f.x < -3 ? cx + 18 : f.x > 3 ? cx - 18 : cx}
y={f.x < -3 || f.x > 3 ? cy + 4 : cy + r + 14}
textAnchor={f.x < -3 ? "start" : f.x > 3 ? "end" : "middle"}
fontSize={10}
fill={dim}
stroke="none"
>
{f.dmx}–{f.dmx + f.channels - 1}
</text>
</g>
);
})}
@@ -256,24 +303,83 @@ export default function StageMap() {
<Stack gap={12}>
<H2>Coordinates</H2>
<Table
headers={["Fixture", "Type", "X (m)", "Y (m)", "Notes"]}
headers={["Fixture", "Type", "Channels", "X (m)", "Y (m)", "Notes"]}
rows={[
["#3", "Can", "−1.8", "0.0", "Row of 4"],
["#4", "Can", "−0.6", "0.0", "Row of 4"],
["#5", "Can", "+0.6", "0.0", "Row of 4"],
["#6", "Can", "+1.8", "0.0", "Row of 4"],
["#2", "Can", "−3.5", "1.2", "Side · 3.5 m from centre · 1.2 m in front of the 4"],
["#7", "Can", "+3.5", "1.2", "Side · 3.5 m from centre · 1.2 m in front of the 4"],
["M1", "Mover", "−0.3", "1.1", "0.3 m off centre · 1.1 m in front of the 4"],
["M2", "Mover", "+0.3", "1.1", "0.3 m off centre · 1.1 m in front of the 4"],
["#1", "Can", "−3.5", "2.4", "Side · 3.5 m from centre · front left · 2.4 m in front"],
["#8", "Can", "+3.5", "2.4", "Side · 3.5 m from centre · front right · 2.4 m in front"],
["#3", "Can", "103–110", "−1.8", "0.0", "Row of 4"],
["#4", "Can", "111–118", "−0.6", "0.0", "Row of 4"],
["#5", "Can", "119–126", "+0.6", "0.0", "Row of 4"],
["#6", "Can", "127–134", "+1.8", "0.0", "Row of 4"],
["#2", "Can", "95–102", "−3.5", "1.2", "Side · 3.5 m from centre · 1.2 m in front of the 4"],
["#7", "Can", "135–142", "+3.5", "1.2", "Side · 3.5 m from centre · 1.2 m in front of the 4"],
["M1", "Mover", "0–42", "−0.3", "1.1", "Front left · 43ch"],
["M2", "Mover", "44–86", "+0.3", "1.1", "Front right · 43ch"],
["#1", "Can", "87–94", "−3.5", "2.4", "Side · 3.5 m from centre · front left · 2.4 m in front"],
["#8", "Can", "143–150", "+3.5", "2.4", "Side · 3.5 m from centre · front right · 2.4 m in front"],
["#9", "Can", "151–158", "−3.5", "−0.8", "Left corner · far side of the row-of-4 beam"],
["#10", "Can", "159–166", "+3.5", "−0.8", "Right corner · far side of the row-of-4 beam"],
["#11", "Can", "167–174", "−3.5", "−6.8", "6 m below #9 · audience side of the lower beam"],
["#12", "Can", "175–182", "+3.5", "−6.8", "6 m below #10 · audience side of the lower beam"],
["#13", "Can", "183–190", "−3.5", "−7.65", "Left corner · far side of the lower beam"],
["#14", "Can", "191–198", "0.0", "−7.65", "Halfway between #13 and #15"],
["#15", "Can", "199–206", "+3.5", "−7.65", "Right corner · far side of the lower beam"],
["M3", "Mover", "257–299", "−1.75", "−7.65", "Back left · between #13 and #14"],
["M4", "Mover", "300–342", "+1.75", "−7.65", "Back right · between #14 and #15"],
]}
/>
<Text tone="secondary" size="small">
Source: integrate_u_patterns.py LAYOUT_M
</Text>
</Stack>
<Stack gap={12}>
<H2>beamZ BCC145 · 8 Channel</H2>
<Text tone="secondary">Cans #1–#15. Channel 1 is the fixture’s start address.</Text>
<Table
headers={["Ch", "Name"]}
rows={[
["1", "Dimmer"],
["2", "Strobe"],
["3", "Red"],
["4", "Green"],
["5", "Blue"],
["6", "White"],
["7", "Macro"],
["8", "Speed"],
]}
/>
</Stack>
<Stack gap={12}>
<H2>Small Eye 7 Mover · 43 Channel</H2>
<Text tone="secondary">M1–M4. Channel 1 is the fixture’s start address.</Text>
<Table
headers={["Ch", "Name"]}
rows={[
["1", "Pan"],
["2", "Pan Fine"],
["3", "Tilt"],
["4", "Tilt Fine"],
["5", "Pan/Tilt Speed"],
["6", "Zoom"],
["7", "Lens Rotate"],
["8", "Focus"],
["9", "Center Brightness"],
["10", "Center Strobe"],
["11–14", "RGBW 1"],
["15–18", "RGBW 2"],
["19–22", "RGBW 3"],
["23–26", "RGBW 4"],
["27–30", "RGBW 5"],
["31–34", "RGBW 6"],
["35–38", "RGBW 7"],
["39", "Colour Temperature"],
["40", "Colour Macro"],
["41", "Static Effect"],
["42", "Dynamic Effect"],
["43", "Reset"],
]}
/>
</Stack>
</Stack>
);
}
+184 -11
View File
@@ -1,67 +1,240 @@
{
"name": "xchc",
"units": "metres",
"building_width": 7.0,
"origin": "Y=0 at row of 4; +Y toward audience; X=0 centre",
"origin": "Y=0 at row of 4; +Y toward audience; X=0 centre. Direction and zero are degrees clockwise from +Y, so 0 points at the audience. Two full-width beams. #9 and #10 are at the corners on the far side of the row-of-4 beam. #11 and #12 are 6 m below them, on the audience side of the lower beam. #13 and #15 are at the corners on the far side of that beam. #14 is halfway between #13 and #15.",
"definitions": {
"beamZ BCC145": {
"manufacturer": "beamZ",
"model": "BCC145",
"mode": "8 Channel",
"channels": ["Dimmer", "Strobe", "Red", "Green", "Blue", "White", "Macro", "Speed"]
},
"Small Eye 7 Mover": {
"manufacturer": "Small Eye 7",
"model": "Mover",
"mode": "43 Channel",
"channels": ["Pan", "Pan Fine", "Tilt", "Tilt Fine", "Pan/Tilt Speed", "Lens Rotate", "Zoom", "Focus", "Center Brightness", "Center Strobe", "Red 1", "Green 1", "Blue 1", "White 1", "Red 2", "Green 2", "Blue 2", "White 2", "Red 3", "Green 3", "Blue 3", "White 3", "Red 4", "Green 4", "Blue 4", "White 4", "Red 5", "Green 5", "Blue 5", "White 5", "Red 6", "Green 6", "Blue 6", "White 6", "Red 7", "Green 7", "Blue 7", "White 7", "Colour Temperature", "Colour Macro", "Static Effect", "Dynamic Effect", "Reset"]
}
},
"fixtures": {
"#1": {
"x": -3.5,
"y": 2.4,
"label": "#1",
"kind": "can"
"kind": "can",
"def": "beamZ BCC145",
"universe": 0,
"address": 87,
"channels": 8,
"direction": 90
},
"#2": {
"x": -3.5,
"y": 1.2,
"label": "#2",
"kind": "can"
"kind": "can",
"def": "beamZ BCC145",
"universe": 0,
"address": 95,
"channels": 8,
"direction": 90
},
"#3": {
"x": -1.8,
"y": 0.0,
"label": "#3",
"kind": "can"
"kind": "can",
"def": "beamZ BCC145",
"universe": 0,
"address": 103,
"channels": 8,
"direction": 0
},
"#4": {
"x": -0.6,
"y": 0.0,
"label": "#4",
"kind": "can"
"kind": "can",
"def": "beamZ BCC145",
"universe": 0,
"address": 111,
"channels": 8,
"direction": 0
},
"#5": {
"x": 0.6,
"y": 0.0,
"label": "#5",
"kind": "can"
"kind": "can",
"def": "beamZ BCC145",
"universe": 0,
"address": 119,
"channels": 8,
"direction": 0
},
"#6": {
"x": 1.8,
"y": 0.0,
"label": "#6",
"kind": "can"
"kind": "can",
"def": "beamZ BCC145",
"universe": 0,
"address": 127,
"channels": 8,
"direction": 0
},
"#7": {
"x": 3.5,
"y": 1.2,
"label": "#7",
"kind": "can"
"kind": "can",
"def": "beamZ BCC145",
"universe": 0,
"address": 135,
"channels": 8,
"direction": -72
},
"#8": {
"x": 3.5,
"y": 2.4,
"label": "#8",
"kind": "can"
"kind": "can",
"def": "beamZ BCC145",
"universe": 0,
"address": 143,
"channels": 8,
"direction": -90
},
"M1": {
"x": -0.3,
"y": 1.1,
"label": "M1",
"kind": "mover"
"kind": "mover",
"def": "Small Eye 7 Mover",
"universe": 0,
"address": 0,
"channels": 43,
"zero": 0
},
"M2": {
"x": 0.3,
"y": 1.1,
"label": "M2",
"kind": "mover"
"kind": "mover",
"def": "Small Eye 7 Mover",
"universe": 0,
"address": 44,
"channels": 43,
"zero": 0
},
"#9": {
"x": -3.5,
"y": -0.8,
"label": "#9",
"kind": "can",
"def": "beamZ BCC145",
"universe": 0,
"address": 151,
"channels": 8,
"note": "Left corner, far side of the row-of-4 beam",
"direction": 146
},
"#10": {
"x": 3.5,
"y": -0.8,
"label": "#10",
"kind": "can",
"def": "beamZ BCC145",
"universe": 0,
"address": 159,
"channels": 8,
"note": "Right corner, far side of the row-of-4 beam",
"direction": -142
},
"#11": {
"x": -3.5,
"y": -6.8,
"label": "#11",
"kind": "can",
"def": "beamZ BCC145",
"universe": 0,
"address": 167,
"channels": 8,
"note": "6 m below #9, audience side of the lower beam",
"direction": 41
},
"#12": {
"x": 3.5,
"y": -6.8,
"label": "#12",
"kind": "can",
"def": "beamZ BCC145",
"universe": 0,
"address": 175,
"channels": 8,
"note": "6 m below #10, audience side of the lower beam",
"direction": -36
},
"#13": {
"x": -3.5,
"y": -7.65,
"label": "#13",
"kind": "can",
"def": "beamZ BCC145",
"universe": 0,
"address": 183,
"channels": 8,
"note": "Left corner, far side of the lower beam from #11",
"direction": 161
},
"#14": {
"x": 0.0,
"y": -7.65,
"label": "#14",
"kind": "can",
"def": "beamZ BCC145",
"universe": 0,
"address": 191,
"channels": 8,
"note": "Halfway between #13 and #15",
"direction": -179
},
"#15": {
"x": 3.5,
"y": -7.65,
"label": "#15",
"kind": "can",
"def": "beamZ BCC145",
"universe": 0,
"address": 199,
"channels": 8,
"note": "Right corner, far side of the lower beam from #12",
"direction": -155
},
"M3": {
"x": -1.75,
"y": -7.65,
"label": "M3",
"kind": "mover",
"def": "Small Eye 7 Mover",
"universe": 0,
"address": 257,
"channels": 43,
"note": "Back left, between #13 and #14",
"zero": 0
},
"M4": {
"x": 1.75,
"y": -7.65,
"label": "M4",
"kind": "mover",
"def": "Small Eye 7 Mover",
"universe": 0,
"address": 300,
"channels": 43,
"note": "Back right, between #14 and #15",
"zero": 0
}
}
}
+67 -6
View File
@@ -1,13 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="840" height="350" viewBox="0 0 840.0 350.0">
<title>XCHC stage map — 7 m building</title>
<desc>Y=0 row of 4; +Y toward audience. Sides on walls ±3.5 m. Movers ±0.3 m, 1.1 m in front of row of 4.</desc>
<svg xmlns="http://www.w3.org/2000/svg" width="840" height="1280" viewBox="0 0 840.0 1280.0">
<title>xchc</title>
<desc>xchc. Two full-width beams. Row of 4 on the audience side of the first. #9 and #10 at the corners on the far side. #11 and #12 are 6 m below them. #13 and #15 are on the far side of the second beam from #11 and #12. #14 is halfway between #13 and #15.</desc>
<rect width="100%" height="100%" fill="#1a1a1a"/>
<rect x="70.0" y="60.0" width="700.0" height="240.0" fill="none" stroke="#888" stroke-width="2"/>
<line x1="420.0" y1="320.0" x2="420.0" y2="35.0" stroke="#555" stroke-dasharray="4 6"/>
<rect x="70.0" y="60.0" width="700.0" height="1040.0" fill="none" stroke="#888" stroke-width="2"/>
<line x1="420.0" y1="1130.0" x2="420.0" y2="35.0" stroke="#555" stroke-dasharray="4 6"/>
<text x="426.0" y="305.0" fill="#888" font-size="12" font-family="system-ui,sans-serif">centre</text>
<text x="8.0" y="16.0" fill="#eee" font-size="14" font-weight="600" font-family="system-ui,sans-serif">xchc</text>
<text x="420.0" y="20.0" text-anchor="middle" fill="#eee" font-size="14" font-weight="600" font-family="system-ui,sans-serif">AUDIENCE</text>
<text x="420.0" y="332.0" text-anchor="middle" fill="#888" font-size="12" font-family="system-ui,sans-serif">row of 4</text>
<text x="420.0" y="368.0" text-anchor="middle" fill="#888" font-size="12" font-family="system-ui,sans-serif">row of 4</text>
<g stroke="#888" fill="#888" stroke-width="1">
<line x1="70.0" y1="25.0" x2="770.0" y2="25.0"/>
<line x1="70.0" y1="21.0" x2="70.0" y2="29.0"/>
@@ -94,4 +95,64 @@
<text x="390.0" y="194.0" text-anchor="middle" fill="#fff" font-size="11" font-weight="600" font-family="system-ui,sans-serif">M1</text>
<rect x="436.0" y="176.0" width="28" height="28" rx="3" fill="#3b82f6" stroke="#ccc"/>
<text x="450.0" y="194.0" text-anchor="middle" fill="#fff" font-size="11" font-weight="600" font-family="system-ui,sans-serif">M2</text>
<g fill="#3a3a3a" stroke="#aaa" stroke-width="1">
<rect x="70.0" y="320.0" width="700.0" height="30.0"/>
<rect x="70.0" y="1005.0" width="700.0" height="30.0"/>
</g>
<g fill="#ccc" stroke="none" font-size="11" font-family="system-ui,sans-serif">
<text x="150.0" y="340.0" text-anchor="middle">beam</text>
<text x="150.0" y="1025.0" text-anchor="middle">beam</text>
</g>
<g stroke="#888" fill="#888" stroke-width="1">
<line x1="40.0" y1="380.0" x2="40.0" y2="980.0"/>
<line x1="36.0" y1="380.0" x2="44.0" y2="380.0"/>
<line x1="36.0" y1="980.0" x2="44.0" y2="980.0"/>
<text x="32.0" y="684.0" text-anchor="end" font-size="11" stroke="none" font-family="system-ui,sans-serif">6 m</text>
</g>
<circle cx="70.0" cy="380.0" r="12" fill="#333" stroke="#ccc" stroke-width="1.5"/>
<text x="70.0" y="384.0" text-anchor="middle" fill="#eee" font-size="11" font-weight="600" font-family="system-ui,sans-serif">#9</text>
<circle cx="770.0" cy="380.0" r="12" fill="#333" stroke="#ccc" stroke-width="1.5"/>
<text x="770.0" y="384.0" text-anchor="middle" fill="#eee" font-size="11" font-weight="600" font-family="system-ui,sans-serif">#10</text>
<circle cx="70.0" cy="980.0" r="12" fill="#333" stroke="#ccc" stroke-width="1.5"/>
<text x="70.0" y="984.0" text-anchor="middle" fill="#eee" font-size="11" font-weight="600" font-family="system-ui,sans-serif">#11</text>
<circle cx="770.0" cy="980.0" r="12" fill="#333" stroke="#ccc" stroke-width="1.5"/>
<text x="770.0" y="984.0" text-anchor="middle" fill="#eee" font-size="11" font-weight="600" font-family="system-ui,sans-serif">#12</text>
<circle cx="70.0" cy="1065.0" r="12" fill="#333" stroke="#ccc" stroke-width="1.5"/>
<text x="70.0" y="1069.0" text-anchor="middle" fill="#eee" font-size="11" font-weight="600" font-family="system-ui,sans-serif">#13</text>
<circle cx="420.0" cy="1065.0" r="12" fill="#333" stroke="#ccc" stroke-width="1.5"/>
<text x="420.0" y="1069.0" text-anchor="middle" fill="#eee" font-size="11" font-weight="600" font-family="system-ui,sans-serif">#14</text>
<circle cx="770.0" cy="1065.0" r="12" fill="#333" stroke="#ccc" stroke-width="1.5"/>
<text x="770.0" y="1069.0" text-anchor="middle" fill="#eee" font-size="11" font-weight="600" font-family="system-ui,sans-serif">#15</text>
<rect x="231.0" y="1051.0" width="28" height="28" rx="3" fill="#3b82f6" stroke="#ccc"/>
<text x="245.0" y="1069.0" text-anchor="middle" fill="#fff" font-size="11" font-weight="600" font-family="system-ui,sans-serif">M3</text>
<rect x="581.0" y="1051.0" width="28" height="28" rx="3" fill="#3b82f6" stroke="#ccc"/>
<text x="595.0" y="1069.0" text-anchor="middle" fill="#fff" font-size="11" font-weight="600" font-family="system-ui,sans-serif">M4</text>
<g fill="#bbb" font-size="10" font-family="system-ui,sans-serif">
<text x="86.0" y="64.0">87–94</text>
<text x="86.0" y="184.0">95–102</text>
<text x="240.0" y="326.0" text-anchor="middle">103–110</text>
<text x="360.0" y="326.0" text-anchor="middle">111–118</text>
<text x="480.0" y="326.0" text-anchor="middle">119–126</text>
<text x="600.0" y="326.0" text-anchor="middle">127–134</text>
<text x="754.0" y="184.0" text-anchor="end">135–142</text>
<text x="754.0" y="64.0" text-anchor="end">143–150</text>
<text x="390.0" y="218.0" text-anchor="middle">0–42</text>
<text x="450.0" y="218.0" text-anchor="middle">44–86</text>
<text x="86.0" y="384.0">151–158</text>
<text x="754.0" y="384.0" text-anchor="end">159–166</text>
<text x="86.0" y="984.0">167–174</text>
<text x="754.0" y="984.0" text-anchor="end">175–182</text>
<text x="86.0" y="1069.0">183–190</text>
<text x="420.0" y="1091.0" text-anchor="middle">191–198</text>
<text x="754.0" y="1069.0" text-anchor="end">199–206</text>
<text x="245.0" y="1093.0" text-anchor="middle">257–299</text>
<text x="595.0" y="1093.0" text-anchor="middle">300–342</text>
</g>
<g font-family="system-ui,sans-serif">
<text x="70.0" y="1148.0" fill="#eee" font-size="12" font-weight="600">beamZ BCC145 · 8 Channel</text>
<text x="70.0" y="1166.0" fill="#aaa" font-size="11">1 Dimmer · 2 Strobe · 3 Red · 4 Green · 5 Blue · 6 White · 7 Macro · 8 Speed</text>
<text x="70.0" y="1196.0" fill="#eee" font-size="12" font-weight="600">Small Eye 7 Mover · 43 Channel</text>
<text x="70.0" y="1214.0" fill="#aaa" font-size="11">1 Pan · 2 Pan Fine · 3 Tilt · 4 Tilt Fine · 5 Speed · 6 Zoom · 7 Lens Rotate · 8 Focus</text>
<text x="70.0" y="1230.0" fill="#aaa" font-size="11">9 Dimmer · 10 Strobe · 11–38 RGBW ×7 · 39 Colour Temp · 40 Macro · 41 Static · 42 Dynamic · 43 Reset</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 6.9 KiB

After

Width:  |  Height:  |  Size: 12 KiB

+3
View File
@@ -0,0 +1,3 @@
# test_small_eye.py is a hands-on Art-Net tester for the real Small Eye
# (scripts/shows/figure8_small_eye.py imports from it), not a test module.
collect_ignore = ["test_small_eye.py"]
Binary file not shown.
+62
View File
@@ -0,0 +1,62 @@
"""Chataigne export: channel mapping and the project file."""
from __future__ import annotations
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts" / "shows"))
import make_chataigne # noqa: E402
class ChataigneExportTest(unittest.TestCase):
def setUp(self) -> None:
self.show = json.loads((ROOT / "shows" / "test.show.json").read_text())
self.stage = json.loads((ROOT / self.show["stage"]).read_text())
def test_channels_are_one_based_dmx(self) -> None:
levels = make_chataigne.absolute_levels(self.show, self.stage, {"#1": {"0": 255, "2": 10}, "M1": {"8": 7}})
self.assertEqual(levels, {88: 255, 90: 10, 9: 7})
def test_groups_hold_pads_and_sliders(self) -> None:
groups = make_chataigne.collect(self.show, self.stage)
self.assertEqual(list(groups), ["Colour 1", "Colour 2"])
cans = groups["Colour 1"]
self.assertEqual([p["note"] for p in cans["pads"]][:2], [52, 53])
self.assertEqual([s["cc"] for s in cans["sliders"]], [30, 31, 32, 33, 34])
self.assertEqual(cans["pads"][0]["fade"], [1000, 1000])
def test_writes_project_and_script(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
subprocess.run(
[sys.executable, str(ROOT / "scripts" / "shows" / "make_chataigne.py"), str(ROOT / "shows" / "test.show.json"), tmp],
check=True,
capture_output=True,
)
project = json.loads((Path(tmp) / "test.noisette").read_text())
script = (Path(tmp) / "test.js").read_text()
settings = project["projectSettings"]["containers"]["dashboardSettings"]["parameters"]
self.assertIn({"value": True, "controlAddress": "/enableDashboardServer"}, settings)
board = project["dashboardManager"]["items"][0]["itemManager"]["items"]
targets = [item["controllable"] for item in board]
self.assertEqual(len(board), 32 * 2 + 10 + 2)
self.assertEqual(len(set(targets)), len(targets))
for item in board:
self.assertIn(item["controllable"].rsplit("/", 1)[1].removesuffix("Lamp"), script)
canvas = project["dashboardManager"]["items"][0]["itemManager"]["parameters"][0]
self.assertEqual((canvas["value"], canvas["enabled"]), ([1574.0, 953.0], True))
names = [m["niceName"] for m in project["modules"]["items"]]
self.assertEqual(names, ["Lights", "Preview", "Pad"])
self.assertEqual(project["modules"]["items"][1]["device"]["containers"]["output"]["parameters"][0]["value"], "127.0.0.1")
self.assertIn("var GROUPS", script)
self.assertNotIn("__DATA__", script)
if __name__ == "__main__":
unittest.main()
+131
View File
@@ -0,0 +1,131 @@
"""End to end: virtual pad -> padcontroller -> QLC+ (test show) -> Art-Net -> simulator.
Needs the rig up (CLAUDE.md): the padcontroller and simulator services, and
QLC+ running with shows/test.qxw open. It drives the live simulator, so it only
runs when asked:
PAD_E2E=1 .venv/bin/python -m unittest tests.test_e2e_pad -v
The helper tests at the bottom run offline every time.
"""
from __future__ import annotations
import json
import os
import sys
import tempfile
import time
import unittest
from pathlib import Path
from urllib.error import URLError
from urllib.request import urlopen
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from padcontroller.virtualpad import PAD_CHANNEL, VirtualPad, check_test_show, last_workspace, pad_note # noqa: E402
SIMULATOR = "http://127.0.0.1:8765/api/state"
SHOW = ROOT / "shows" / "test.show.json"
# Colour 1 (cans) is on notes 52-67; Play shifts them to 68-83, Colour 2 (movers).
RED, GREEN, BLUE, MAGENTA = 52, 57, 61, 63
RGB = {RED: (255, 0, 0), GREEN: (0, 255, 0), BLUE: (0, 0, 255), MAGENTA: (255, 0, 255)}
FADE_TIMEOUT = 4.0 # the colour scenes fade in over 1 s
def state() -> dict:
with urlopen(SIMULATOR, timeout=2) as r:
return json.load(r)
def scene_fixtures(key: str) -> list[str]:
"""The fixtures a scene in the test show sets, e.g. colour_1_1 -> ['#1', ..., '#15']."""
spec = json.loads(SHOW.read_text())
return sorted(next(f for f in spec["functions"] if f["key"] == key)["values"])
@unittest.skipUnless(os.environ.get("PAD_E2E") == "1", "set PAD_E2E=1 to drive the live rig")
class PadToSimulator(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
check_test_show()
try:
s = state()
except URLError as e:
raise AssertionError(f"Simulator not answering on {SIMULATOR}: {e}") from e
assert s["age"] < 1.0, f"Simulator has had no Art-Net for {s['age']:.1f} s; is QLC+ running?"
cls.pad = VirtualPad()
@classmethod
def tearDownClass(cls) -> None:
cls.pad.close()
def wait_for(self, fixtures: list[str], rgb: tuple[int, int, int]) -> None:
"""Poll the simulator until every fixture shows rgb, or fail with what it shows."""
deadline = time.monotonic() + FADE_TIMEOUT
while True:
got = {k: (v["r"], v["g"], v["b"]) for k, v in state()["fixtures"].items() if k in fixtures}
wrong = {k: v for k, v in got.items() if v != rgb}
if not wrong and len(got) == len(fixtures):
return
if time.monotonic() > deadline:
missing = sorted(set(fixtures) - set(got))
self.fail(f"wanted {rgb} on {fixtures}; wrong: {wrong}; missing: {missing}")
time.sleep(0.1)
def press(self, note: int, play: bool = False) -> None:
if play:
with self.pad.play():
self.pad.press(note, PAD_CHANNEL)
else:
self.pad.press(note, PAD_CHANNEL)
# Each test presses two different buttons in the solo frame. A tap on the
# button that's already on would turn it off, but the second press is always
# a different button, so it always turns on and sets the colour.
def test_bank2_pads_set_can_colour(self) -> None:
cans = scene_fixtures("colour_1_1")
self.assertTrue(cans and all(k.startswith("#") for k in cans))
self.press(RED)
self.press(BLUE)
self.wait_for(cans, RGB[BLUE])
self.press(GREEN)
self.wait_for(cans, RGB[GREEN])
def test_play_layer_sets_mover_colour(self) -> None:
movers = scene_fixtures("colour_2_1")
self.assertTrue(movers and all(k.startswith("M") for k in movers))
self.press(BLUE, play=True)
self.press(MAGENTA, play=True)
self.wait_for(movers, RGB[MAGENTA])
self.press(BLUE, play=True)
self.wait_for(movers, RGB[BLUE])
class Helpers(unittest.TestCase):
def test_last_workspace_reads_recent0(self) -> None:
with tempfile.TemporaryDirectory() as d:
conf = Path(d) / "qlc.conf"
conf.write_text("[workspace]\nrecent0=/x/shows/test.qxw\nrecent1=shows/other.qxw\n")
self.assertEqual(last_workspace(conf), Path("/x/shows/test.qxw"))
self.assertIsNone(last_workspace(Path(d) / "missing.conf"))
def test_check_test_show_refuses_other_shows(self) -> None:
with tempfile.TemporaryDirectory() as d:
conf = Path(d) / "qlc.conf"
conf.write_text(f"[workspace]\nrecent0={ROOT / 'shows' / 'cabaret.qxw'}\n")
with self.assertRaises(SystemExit):
check_test_show(conf)
conf.write_text(f"[workspace]\nrecent0={ROOT / 'shows' / 'test.qxw'}\n")
check_test_show(conf)
def test_pad_note_from_midi_map(self) -> None:
self.assertEqual(pad_note(1), (9, 36))
with self.assertRaises(SystemExit):
pad_note(999)
if __name__ == "__main__":
unittest.main()
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff. Show more