Add Pattern Studio, SMC-PAD MIDI helpers, and the current venue workspaces.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
55a38478db
commit
12420bec93
19 files changed
+8954
No files matched your search
@@ -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"
|
||||
@@ -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())
|
||||
@@ -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}
|
||||
@@ -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}")
|
||||
@@ -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("&", "&").replace("<", "<").replace(">", ">").replace(""", '"').replace("'", "'")
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[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();
|
||||
})();
|
||||
@@ -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 & 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>
|
||||
@@ -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; }
|
||||
Reference in new issue
Block a user