diff --git a/simulator/__init__.py b/simulator/__init__.py new file mode 100644 index 0000000..72476bc --- /dev/null +++ b/simulator/__init__.py @@ -0,0 +1 @@ +"""Stage visualiser that listens for Art-Net.""" diff --git a/simulator/__main__.py b/simulator/__main__.py new file mode 100644 index 0000000..b481911 --- /dev/null +++ b/simulator/__main__.py @@ -0,0 +1,172 @@ +"""Stage simulator. + +Loads a stage map, patches DMX addresses from a QLC+ show, and listens for +Art-Net. Open the printed URL and point QLC+ Art-Net output at this machine. + + python -m simulator + python -m simulator --stage stage/map.json --show shows/templeoftechno.qxw + python -m simulator --demo +""" + +from __future__ import annotations + +import argparse +import math +import threading +import time +from pathlib import Path + +from simulator.artnet import ArtNetNode +from simulator.server import Simulator, make_server +from simulator.stage import Fixture, apply_show, load_stage + +ROOT = Path(__file__).resolve().parents[1] + + +def _hsv(hue: float) -> tuple[int, int, int]: + hue = hue % 1.0 + i = int(hue * 6) + f = hue * 6 - i + q = int(255 * (1 - f)) + t = int(255 * f) + segment = i % 6 + if segment == 0: + return 255, t, 0 + if segment == 1: + return q, 255, 0 + if segment == 2: + return 0, 255, t + if segment == 3: + return 0, q, 255 + if segment == 4: + return t, 0, 255 + return 255, 0, q + + +def _slot(fixture: Fixture, name: str) -> int | None: + if fixture.address is None: + return None + for index, channel in enumerate(fixture.channel_names): + if channel.lower() == name.lower(): + return fixture.address + index + return None + + +def _put(frame: bytearray, fixture: Fixture, name: str, value: int) -> None: + slot = _slot(fixture, name) + if slot is not None and 0 <= slot < len(frame): + frame[slot] = max(0, min(255, value)) + + +def _demo_frame(fixtures: list[Fixture], elapsed: float) -> bytearray: + frame = bytearray(512) + cans = [fixture for fixture in fixtures if fixture.kind == "can" and fixture.address is not None] + cans.sort(key=lambda fixture: fixture.label) + # Walk the BCC145 macro: RGBW mix, colour jump, pulse, then gradient. + look = int(elapsed / 5) % 4 + macro = (0, 120, 170, 220)[look] + speed = int(40 + (math.sin(elapsed * 0.7) * 0.5 + 0.5) * 180) + for index, fixture in enumerate(cans): + _put(frame, fixture, "Dimmer", 255) + _put(frame, fixture, "Macro", macro) + _put(frame, fixture, "Speed", speed) + if macro == 0: + red, green, blue = _hsv(elapsed * 0.05 + index / max(1, len(cans))) + _put(frame, fixture, "Red", red) + _put(frame, fixture, "Green", green) + _put(frame, fixture, "Blue", blue) + movers = [fixture for fixture in fixtures if fixture.kind == "mover" and fixture.address is not None] + for index, fixture in enumerate(movers): + pan = int(32768 + math.sin(elapsed * 0.6 + index * math.pi) * 9000) + pan = max(0, min(65535, pan)) + tilt = 42000 + _put(frame, fixture, "Pan", (pan >> 8) & 0xFF) + _put(frame, fixture, "Pan Fine", pan & 0xFF) + _put(frame, fixture, "Tilt", (tilt >> 8) & 0xFF) + _put(frame, fixture, "Tilt Fine", tilt & 0xFF) + _put(frame, fixture, "Zoom", 40) + _put(frame, fixture, "Center Brightness", 255) + color = (255, 40, 0) if index % 2 == 0 else (40, 80, 255) + for pixel in range(1, 8): + _put(frame, fixture, f"Red {pixel}", color[0]) + _put(frame, fixture, f"Green {pixel}", color[1]) + _put(frame, fixture, f"Blue {pixel}", color[2]) + _put(frame, fixture, "Dynamic Effect", 30 if index % 2 == 0 else 160) + _put(frame, fixture, "Lens Rotate", 210 if index % 2 == 0 else 40) + return frame + + +def _demo_loop(node: ArtNetNode, fixtures: list[Fixture], stop: threading.Event) -> None: + started = time.monotonic() + while not stop.is_set(): + frame = _demo_frame(fixtures, time.monotonic() - started) + node.write(0, frame) + stop.wait(0.05) + + +def _parse_host_port(value: str, default_port: int) -> tuple[str, int]: + if ":" not in value: + return value, default_port + host, port = value.rsplit(":", 1) + return host or "0.0.0.0", int(port) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--stage", type=Path, default=ROOT / "stage" / "map.json") + parser.add_argument("--show", type=Path, default=ROOT / "shows" / "templeoftechno.qxw") + parser.add_argument("--no-show", action="store_true", help="Use addresses stored in the stage file only") + parser.add_argument("--http", default="0.0.0.0:8765", help="Web view host:port") + parser.add_argument("--artnet", default="0.0.0.0:6454", help="Art-Net listen host:port") + parser.add_argument("--demo", action="store_true", help="Play a local look when you want to see the rig without QLC+") + args = parser.parse_args() + + stage = load_stage(args.stage) + if not args.no_show: + if not args.show.is_file(): + raise SystemExit(f"Show not found: {args.show}") + apply_show(stage, args.show) + + http_host, http_port = _parse_host_port(args.http, 8765) + artnet_host, artnet_port = _parse_host_port(args.artnet, 6454) + node = ArtNetNode(artnet_host, artnet_port) + node.start() + server = make_server(Simulator(stage, node), http_host, http_port) + + print("Stage simulator", flush=True) + print(f" stage: {args.stage}", flush=True) + if stage.show: + print(f" show: {args.show}", flush=True) + print(f" Art-Net {artnet_host}:{artnet_port}", flush=True) + print(f" view: http://127.0.0.1:{server.server_address[1]}", flush=True) + if stage.output_ip: + print(f" QLC+ Art-Net output in this show is {stage.output_ip}.", flush=True) + print(" Point that output at this computer (universe 0), or broadcast.", flush=True) + for fixture in stage.fixtures: + if fixture.dmx is None: + print(f" {fixture.label:<4} no address", flush=True) + else: + print( + f" {fixture.label:<4} {fixture.name:<16} universe {fixture.universe} DMX {fixture.dmx}", + flush=True, + ) + for warning in stage.warnings: + print(f" warning: {warning}", flush=True) + + stop = threading.Event() + if args.demo: + threading.Thread(target=_demo_loop, args=(node, stage.fixtures, stop), daemon=True).start() + print(" demo look is running", flush=True) + + try: + server.serve_forever() + except KeyboardInterrupt: + print("\nStopping.", flush=True) + finally: + stop.set() + server.shutdown() + node.close() + + +if __name__ == "__main__": + main() diff --git a/simulator/artnet.py b/simulator/artnet.py new file mode 100644 index 0000000..c75c15d --- /dev/null +++ b/simulator/artnet.py @@ -0,0 +1,214 @@ +"""Art-Net receiver. Speaks ArtDMX and answers ArtPoll.""" + +from __future__ import annotations + +import socket +import threading +import time +from collections import deque + +ARTNET_PORT = 6454 +HEADER = b"Art-Net\x00" +OP_POLL = 0x2000 +OP_POLL_REPLY = 0x2100 +OP_DMX = 0x5000 + + +def build_artdmx(channels: bytes, universe: int = 0, sequence: int = 1) -> bytes: + """ArtDMX packet. `channels` is the 0-based DMX frame (up to 512).""" + data = bytearray(channels) + n = len(data) + if n < 2: + data.extend(b"\x00" * (2 - n)) + n = 2 + if n & 1: + data.append(0) + n += 1 + if n > 512: + data = data[:512] + n = 512 + pkt = bytearray(18 + n) + pkt[0:8] = HEADER + pkt[8] = OP_DMX & 0xFF + pkt[9] = (OP_DMX >> 8) & 0xFF + pkt[11] = 14 + pkt[12] = sequence & 0xFF + pkt[14] = universe & 0xFF + pkt[15] = (universe >> 8) & 0x7F + pkt[16] = (n >> 8) & 0xFF + pkt[17] = n & 0xFF + pkt[18 : 18 + n] = data + return bytes(pkt) + + +def parse_artdmx(packet: bytes) -> tuple[int, bytes] | None: + """Return (port-address, dmx) for an ArtDMX packet, else None.""" + if len(packet) < 18 or not packet.startswith(HEADER): + return None + opcode = packet[8] | (packet[9] << 8) + if opcode != OP_DMX: + return None + universe = packet[14] | ((packet[15] & 0x7F) << 8) + length = (packet[16] << 8) | packet[17] + if length < 2 or 18 + length > len(packet): + return None + return universe, packet[18 : 18 + length] + + +def parse_opcode(packet: bytes) -> int | None: + if len(packet) < 10 or not packet.startswith(HEADER): + return None + return packet[8] | (packet[9] << 8) + + +def poll_reply(ip: str) -> bytes: + """Short ArtPollReply so QLC+ can list this node.""" + pkt = bytearray(239) + pkt[0:8] = HEADER + pkt[8] = OP_POLL_REPLY & 0xFF + pkt[9] = (OP_POLL_REPLY >> 8) & 0xFF + pkt[11] = 14 + parts = [int(part) for part in ip.split(".")] + if len(parts) != 4: + parts = [127, 0, 0, 1] + pkt[12:16] = bytes(parts) + pkt[16] = ARTNET_PORT & 0xFF + pkt[17] = (ARTNET_PORT >> 8) & 0xFF + pkt[19] = 1 + pkt[25] = 0xD0 + short = b"Stage sim" + pkt[28 : 28 + len(short)] = short + long = b"QLC+ stage Art-Net simulator" + pkt[46 : 46 + len(long)] = long + pkt[175] = 1 + pkt[176] = 0x80 + pkt[184] = 0x80 + return bytes(pkt) + + +def local_ip_toward(peer: str) -> str: + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + sock.connect((peer, ARTNET_PORT)) + return sock.getsockname()[0] + except OSError: + return "127.0.0.1" + finally: + sock.close() + + +class ArtNetNode: + """Holds the latest DMX frame per Art-Net universe.""" + + def __init__(self, host: str = "0.0.0.0", port: int = ARTNET_PORT): + self.host = host + self.port = port + self._lock = threading.Lock() + self._universes: dict[int, bytearray] = {} + self.packets = 0 + self._times: deque[float] = deque() + self.last_rx = 0.0 + self.last_universe: int | None = None + self._sock: socket.socket | None = None + self._running = False + self._thread: threading.Thread | None = None + self._announced = False + + def start(self) -> None: + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if hasattr(socket, "SO_REUSEPORT"): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + try: + sock.bind((self.host, self.port)) + except OSError as exc: + sock.close() + raise OSError( + f"Cannot listen for Art-Net on {self.host}:{self.port} ({exc}). " + "Close the other program using that port, or pass --artnet-port." + ) from exc + sock.settimeout(0.5) + self._sock = sock + self._running = True + self._thread = threading.Thread(target=self._loop, name="artnet", daemon=True) + self._thread.start() + + def close(self) -> None: + self._running = False + sock = self._sock + if sock is not None: + try: + sock.close() + except OSError: + pass + if self._thread is not None: + self._thread.join(timeout=1.5) + + def write(self, universe: int, data: bytes) -> None: + with self._lock: + buf = self._universes.get(universe) + if buf is None: + buf = bytearray(512) + self._universes[universe] = buf + n = min(512, len(data)) + buf[:n] = data[:n] + if n < 512: + buf[n:] = b"\x00" * (512 - n) + now = time.monotonic() + self.packets += 1 + self.last_rx = now + self.last_universe = universe + self._times.append(now) + + def snapshot(self) -> dict[int, bytes]: + with self._lock: + return {universe: bytes(buf) for universe, buf in self._universes.items()} + + def stats(self) -> dict: + now = time.monotonic() + with self._lock: + while self._times and now - self._times[0] > 1.0: + self._times.popleft() + age = None if self.last_rx == 0 else now - self.last_rx + return { + "packets": self.packets, + "rate": len(self._times), + "age": None if age is None else round(age, 3), + "universe": self.last_universe, + "listen": f"{self.host}:{self.port}", + } + + def _loop(self) -> None: + sock = self._sock + assert sock is not None + while self._running: + try: + packet, addr = sock.recvfrom(2048) + except TimeoutError: + continue + except OSError: + break + self._handle(packet, addr) + + def _handle(self, packet: bytes, addr: tuple) -> None: + opcode = parse_opcode(packet) + if opcode == OP_DMX: + parsed = parse_artdmx(packet) + if parsed is None: + return + universe, data = parsed + self.write(universe, data) + if not self._announced: + self._announced = True + print( + f"Art-Net DMX from {addr[0]}:{addr[1]} " + f"universe {universe} ({len(data)} channels)", + flush=True, + ) + return + if opcode == OP_POLL and self._sock is not None: + ip = local_ip_toward(addr[0]) + try: + self._sock.sendto(poll_reply(ip), (addr[0], ARTNET_PORT)) + except OSError: + pass diff --git a/simulator/decode.py b/simulator/decode.py new file mode 100644 index 0000000..e0237a3 --- /dev/null +++ b/simulator/decode.py @@ -0,0 +1,430 @@ +"""Turn a DMX frame into colours, beams, and strobe rates. + +Channel order comes from the stage map's fixture definitions. Role names +such as Dimmer, Red, Pan, and Zoom select the slots. +""" + +from __future__ import annotations + +import re + +from simulator.stage import Fixture, Stage + +_PIXEL = re.compile(r"^(red|green|blue|white) (\d+)$", re.IGNORECASE) + +PAN_DEGREES = 540.0 +ZOOM_MIN = 5.0 +ZOOM_MAX = 45.0 + +# BCC145 8ch: strobe 0–7 is open. Small Eye centre strobe 0–3 is open. +CAN_STROBE_OPEN = 7 +MOVER_STROBE_OPEN = 3 + +# beamZ BCC145 8ch macro, matching fixtures/beamZ-BCC145.qxf. +# 0–50 RGBW mix, 51–100 fixed colour, 101–150 jump, 151–200 pulse, +# 201–250 gradient, 251–255 sound. Speed is slow to fast. +_PAR_PALETTE = ( + (255, 0, 0), + (255, 96, 0), + (255, 200, 0), + (255, 255, 0), + (0, 255, 0), + (0, 255, 160), + (0, 64, 255), + (140, 0, 255), + (255, 0, 160), + (255, 255, 255), +) + +# Small Eye 43ch colour macros, static masks, and dynamic chases. +# Ranges match fixtures/Small-Eye-7-Mover.qxf: 0–9 is no function. +_MOVER_MACROS = ( + (255, 0, 0), + (255, 80, 0), + (255, 255, 0), + (0, 255, 0), + (0, 255, 255), + (0, 40, 255), + (160, 0, 255), + (255, 0, 180), + (255, 255, 255), + (255, 180, 80), +) +_STATIC_MASKS = ( + ("all", (1, 1, 1, 1, 1, 1, 1)), + ("odds", (1, 0, 1, 0, 1, 0, 1)), + ("evens", (0, 1, 0, 1, 0, 1, 0)), + ("center", (0, 0, 0, 1, 0, 0, 0)), + ("ends", (1, 0, 0, 0, 0, 0, 1)), + ("left", (1, 1, 1, 1, 0, 0, 0)), + ("right", (0, 0, 0, 1, 1, 1, 1)), + ("one", None), +) +_DYNAMIC = ("chase", "reverse", "rainbow", "bounce", "pulse", "pairs") +_DYNAMIC_LABELS = { + "chase": "chase", + "reverse": "reverse chase", + "rainbow": "rainbow", + "bounce": "bounce", + "pulse": "pixel pulse", + "pairs": "pairs", +} + +MOVER_43 = [ + "Pan", "Pan Fine", "Tilt", "Tilt Fine", "Pan/Tilt Speed", "Lens Rotate", "Zoom", "Focus", + "Center Brightness", "Center Strobe", + "Red 1", "Green 1", "Blue 1", "White 1", + "Red 2", "Green 2", "Blue 2", "White 2", + "Red 3", "Green 3", "Blue 3", "White 3", + "Red 4", "Green 4", "Blue 4", "White 4", + "Red 5", "Green 5", "Blue 5", "White 5", + "Red 6", "Green 6", "Blue 6", "White 6", + "Red 7", "Green 7", "Blue 7", "White 7", + "Colour Temperature", "Colour Macro", "Static Effect", "Dynamic Effect", "Reset", +] + + +def _find(names: list[str], wanted: str) -> int | None: + wanted = wanted.lower() + for index, name in enumerate(names): + if name.lower() == wanted: + return index + return None + + +def _value(channels: list[int], names: list[str], wanted: str, default: int = 0) -> int: + index = _find(names, wanted) + if index is None or index >= len(channels): + return default + return channels[index] + + +def _pixels(channels: list[int], names: list[str], dimmer: int) -> list[list[int]]: + groups: dict[int, dict[str, int]] = {} + for index, name in enumerate(names): + match = _PIXEL.match(name.strip()) + if match is None: + continue + groups.setdefault(int(match.group(2)), {})[match.group(1).lower()] = index + + def at(group: dict[str, int], color: str) -> int: + index = group.get(color) + if index is None or index >= len(channels): + return 0 + return channels[index] + + return [ + list(mix_rgbw(at(groups[number], "red"), at(groups[number], "green"), at(groups[number], "blue"), at(groups[number], "white"), dimmer)) + for number in sorted(groups) + ] + + +def slots_at(frame: bytes, address: int, count: int) -> list[int]: + out: list[int] = [] + for offset in range(count): + index = address + offset + out.append(frame[index] if 0 <= index < len(frame) else 0) + return out + + +def mix_rgbw(red: int, green: int, blue: int, white: int, dimmer: int) -> tuple[int, int, int]: + """White is a fourth emitter. Dimmer scales the whole mix.""" + level = max(0, min(255, dimmer)) / 255.0 + return ( + int(round(min(255, red + white) * level)), + int(round(min(255, green + white) * level)), + int(round(min(255, blue + white) * level)), + ) + + +def strobe_hz(value: int, open_max: int) -> float: + if value <= open_max: + return 0.0 + span = max(1, 255 - open_max) + return round(1.0 + (value - open_max) / span * 18.0, 2) + + +def lens_angle(value: int) -> float: + """Indexed lens position, 0–60°. Spin ranges are not an index.""" + if value <= 127: + return round(value / 127.0 * 60.0, 1) + return 0.0 + + +def lens_spin(value: int) -> float: + """Degrees per second. Negative is counter-clockwise. + + 0–127 index, 128–188 CCW fast to slow, 189–193 stop, 194–255 CW slow to fast. + """ + if 128 <= value <= 188: + rate = (188 - value) / 60.0 + return round(-(40.0 + rate * 320.0), 1) + if 194 <= value <= 255: + rate = (value - 194) / 61.0 + return round(40.0 + rate * 320.0, 1) + return 0.0 + + +def _beam_color(pixels: list[list[int]]) -> tuple[int, int, int]: + """Brightness-weighted mix, so one lit pixel stays its own colour.""" + red = green = blue = weight = 0.0 + for pr, pg, pb in pixels: + w = pr + pg + pb + red += pr * w + green += pg * w + blue += pb * w + weight += w + if weight <= 0: + return 0, 0, 0 + return int(round(red / weight)), int(round(green / weight)), int(round(blue / weight)) + + +def _scale(colour: tuple[int, int, int], dimmer: int) -> tuple[int, int, int]: + level = max(0, min(255, dimmer)) / 255.0 + return tuple(int(round(channel * level)) for channel in colour) + + +def _speed_hz(speed: int, *, slow: float = 0.35, fast: float = 8.0) -> float: + return round(slow + max(0, min(255, speed)) / 255.0 * (fast - slow), 2) + + +def _can_mode(macro: int) -> str: + if macro <= 50: + return "mix" + if macro <= 100: + return "fixed" + if macro <= 150: + return "jump" + if macro <= 200: + return "pulse" + if macro <= 250: + return "gradient" + return "sound" + + +def _range_pick(value: int, start: int, count: int) -> tuple[int, float] | None: + """Map value onto `count` bands from `start` through 255. Returns index and 0–1 position.""" + if value < start or count <= 0: + return None + span = 256 - start + index = min(count - 1, (value - start) * count // span) + band = span / count + frac = ((value - start) - index * band) / band + return index, max(0.0, min(0.999, frac)) + + +def apply_cto(red: int, green: int, blue: int, amount: int) -> tuple[int, int, int]: + """0 leaves the colour alone. Higher values warm it, the way a CTO does.""" + if amount <= 0: + return red, green, blue + warm = max(0, min(255, amount)) / 255.0 + return ( + red, + int(round(green * (1 - 0.35 * warm))), + int(round(blue * (1 - 0.75 * warm))), + ) + + +def _can_view( + dimmer: int, + strobe: int, + red: int, + green: int, + blue: int, + white: int, + macro: int, + speed: int, + channels: list[int], +) -> dict: + mode = _can_mode(macro) + mixed = mix_rgbw(red, green, blue, white, dimmer) + peak = mix_rgbw(red, green, blue, white, 255) + if peak == (0, 0, 0): + peak = (255, 255, 255) + shown = mixed + palette = None + sound = 0 + hz = 0.0 + if mode == "fixed": + span = 50 + index = min(len(_PAR_PALETTE) - 1, max(0, macro - 51) * len(_PAR_PALETTE) // span) + shown = _scale(_PAR_PALETTE[index], dimmer) + elif mode == "pulse": + shown = _scale(peak, dimmer) + hz = _speed_hz(speed, slow=0.4, fast=6.0) + elif mode in ("jump", "gradient", "sound"): + palette = [list(colour) for colour in _PAR_PALETTE] + hz = _speed_hz(speed) + shown = _scale(_PAR_PALETTE[0], dimmer) + if mode == "sound": + sound = 2 if macro >= 254 else 1 + labels = { + "mix": "RGBW", + "fixed": "fixed colour", + "jump": "colour jump", + "pulse": "colour pulse", + "gradient": "colour gradient", + "sound": "sound 2" if sound == 2 else "sound 1", + } + viewed = { + "r": shown[0], + "g": shown[1], + "b": shown[2], + "dimmer": dimmer, + "strobe_hz": strobe_hz(strobe, CAN_STROBE_OPEN), + "strobe_mode": "strobe" if strobe > CAN_STROBE_OPEN else "open", + "effect": mode != "mix", + "function": mode, + "function_label": labels[mode], + "speed_hz": hz, + "sound": sound, + "channels": channels, + } + if palette is not None: + viewed["palette"] = palette + return viewed + + +def decode_can(channels: list[int]) -> dict: + def at(index: int) -> int: + return channels[index] if index < len(channels) else 0 + + return _can_view(at(0), at(1), at(2), at(3), at(4), at(5), at(6), at(7), channels) + + +def decode_named(channels: list[int], names: list[str], *, kind: str) -> dict: + """Read a fixture using the channel names from the stage map.""" + if kind == "mover" or (_find(names, "Pan") is not None and _find(names, "Tilt") is not None): + return _decode_mover_named(channels, names) + return _decode_can_named(channels, names) + + +def _decode_can_named(channels: list[int], names: list[str]) -> dict: + dimmer = 255 if _find(names, "Dimmer") is None else _value(channels, names, "Dimmer") + return _can_view( + dimmer, + _value(channels, names, "Strobe"), + _value(channels, names, "Red"), + _value(channels, names, "Green"), + _value(channels, names, "Blue"), + _value(channels, names, "White"), + _value(channels, names, "Macro"), + _value(channels, names, "Speed"), + channels, + ) + + +def _mover_strobe(value: int) -> tuple[float, str]: + """Centre strobe: open, linear strobe, then three random-strobe bands.""" + if value <= MOVER_STROBE_OPEN: + return 0.0, "open" + if value <= 200: + return strobe_hz(value, MOVER_STROBE_OPEN), "strobe" + if value <= 215: + return 6.0, "random" + if value <= 234: + return 12.0, "random" + return 18.0, "random" + + +def _decode_mover_named(channels: list[int], names: list[str]) -> dict: + pan = (_value(channels, names, "Pan") << 8) | _value(channels, names, "Pan Fine") + tilt = (_value(channels, names, "Tilt") << 8) | _value(channels, names, "Tilt Fine") + zoom = _value(channels, names, "Zoom") + rotate = _value(channels, names, "Lens Rotate") + dimmer = 255 if _find(names, "Center Brightness") is None else _value(channels, names, "Center Brightness") + strobe = _value(channels, names, "Center Strobe") + pixels = _pixels(channels, names, dimmer) + macro_value = _value(channels, names, "Colour Macro") + static_value = _value(channels, names, "Static Effect") + dynamic_value = _value(channels, names, "Dynamic Effect") + cto = _value(channels, names, "Colour Temperature") + macro = _range_pick(macro_value, 10, len(_MOVER_MACROS)) + static = _range_pick(static_value, 10, len(_STATIC_MASKS)) + dynamic = _range_pick(dynamic_value, 10, len(_DYNAMIC)) + + source = [list(pixel) for pixel in pixels] + function = "pixels" + label = "pixels" + dynamic_name = None + speed = 0.0 + if macro is not None: + colour = list(_scale(_MOVER_MACROS[macro[0]], dimmer)) + source = [colour[:] for _ in range(7)] + function = "macro" + label = "colour macro" + if static is not None or dynamic is not None: + if not any(sum(pixel) > 0 for pixel in source): + white = list(_scale((255, 255, 255), dimmer)) + source = [white[:] for _ in range(7)] + if static is not None and dynamic is None: + name, mask = _STATIC_MASKS[static[0]] + if name == "one": + pixel = min(6, int(static[1] * 7)) + mask = tuple(1 if index == pixel else 0 for index in range(7)) + source = [pixel if mask[index] else [0, 0, 0] for index, pixel in enumerate(source)] + function = "static" + label = "one pixel" if name == "one" else f"static {name}" + if dynamic is not None: + dynamic_name = _DYNAMIC[dynamic[0]] + speed = round(0.4 + dynamic[1] * 6.0, 2) + function = "dynamic" + label = _DYNAMIC_LABELS[dynamic_name] + + tinted = [list(apply_cto(pixel[0], pixel[1], pixel[2], cto)) for pixel in source] + red, green, blue = _beam_color(tinted) + rate, strobe_mode = _mover_strobe(strobe) + reset = _value(channels, names, "Reset") + pan_speed = _value(channels, names, "Pan/Tilt Speed") + pan_deg = (pan - 32768) / 65536.0 * PAN_DEGREES + zoom_deg = ZOOM_MIN + (zoom / 255.0) * (ZOOM_MAX - ZOOM_MIN) + # Long enough to read on the plan at tilt zero. Tilt stretches the throw. + beam_m = 2.2 + (tilt / 65535.0) * 2.5 + return { + "r": red, + "g": green, + "b": blue, + "dimmer": dimmer, + "strobe_hz": rate, + "strobe_mode": strobe_mode, + "effect": function != "pixels", + "function": function, + "function_label": label, + "speed_hz": speed, + "dynamic": dynamic_name, + "pan_deg": round(pan_deg, 2), + "zoom_deg": round(zoom_deg, 2), + "beam_m": round(beam_m, 3), + "pixels": tinted, + "spin_dps": lens_spin(rotate), + "lens_deg": lens_angle(rotate), + "focus": round(_value(channels, names, "Focus") / 255.0, 3), + "move": round(1 - pan_speed / 255.0, 3), + "cto": cto, + "reset": 200 <= reset <= 205, + "channels": channels, + } + + +def decode_mover(channels: list[int]) -> dict: + return _decode_mover_named(channels, MOVER_43) + + +def view_fixture(fixture: Fixture, universes: dict[int, bytes]) -> dict: + if fixture.address is None or fixture.universe is None: + return {"patched": False, "r": 0, "g": 0, "b": 0, "dimmer": 0, "strobe_hz": 0, "channels": []} + count = len(fixture.channel_names) or fixture.channels or (43 if fixture.kind == "mover" else 8) + frame = universes.get(fixture.universe, bytes(512)) + channels = slots_at(frame, fixture.address, count) + if fixture.channel_names: + viewed = decode_named(channels, fixture.channel_names, kind=fixture.kind) + elif fixture.kind == "mover": + viewed = decode_mover(channels) + else: + viewed = decode_can(channels) + viewed["patched"] = True + return viewed + + +def view_stage(stage: Stage, universes: dict[int, bytes]) -> dict[str, dict]: + return {fixture.id: view_fixture(fixture, universes) for fixture in stage.fixtures} diff --git a/simulator/server.py b/simulator/server.py new file mode 100644 index 0000000..1fd7cbe --- /dev/null +++ b/simulator/server.py @@ -0,0 +1,106 @@ +"""HTTP view of the stage. The page polls /api/state.""" + +from __future__ import annotations + +import json +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import urlparse + +from simulator.artnet import ArtNetNode +from simulator.decode import view_stage +from simulator.stage import Stage, set_heading + +STATIC = Path(__file__).resolve().parent / "static" + +CONTENT_TYPES = { + ".html": "text/html; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".css": "text/css; charset=utf-8", +} + + +class Simulator: + def __init__(self, stage: Stage, node: ArtNetNode): + self.stage = stage + self.node = node + + def state(self) -> dict: + stats = self.node.stats() + stats["fixtures"] = view_stage(self.stage, self.node.snapshot()) + return stats + + +def make_handler(sim: Simulator): + class Handler(BaseHTTPRequestHandler): + simulator = sim + + def log_message(self, fmt: str, *args) -> None: + return + + def do_POST(self) -> None: + path = urlparse(self.path).path + if path != "/api/heading": + self.send_error(404) + return + length = int(self.headers.get("Content-Length") or 0) + if length <= 0 or length > 4096: + self._json({"error": "bad heading"}, 400) + return + try: + payload = json.loads(self.rfile.read(length)) + fixture = set_heading( + self.simulator.stage, + str(payload["id"]), + direction=payload.get("direction"), + zero=payload.get("zero"), + ) + except (KeyError, TypeError, ValueError, json.JSONDecodeError): + self._json({"error": "bad heading"}, 400) + return + self._json({"id": fixture.id, "direction": fixture.direction, "zero": fixture.zero}) + + def do_GET(self) -> None: + path = urlparse(self.path).path + if path == "/api/state": + self._json(self.simulator.state()) + return + if path == "/api/stage": + self._json(self.simulator.stage.to_json()) + return + if path in ("/", "/index.html"): + self._file(STATIC / "index.html") + return + if path.startswith("/static/"): + target = (STATIC / path.removeprefix("/static/")).resolve() + if STATIC.resolve() in target.parents or target == STATIC.resolve(): + self._file(target) + return + self.send_error(404) + + def _json(self, payload: dict, status: int = 200) -> None: + body = json.dumps(payload).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Cache-Control", "no-store") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _file(self, path: Path) -> None: + if not path.is_file(): + self.send_error(404) + return + body = path.read_bytes() + self.send_response(200) + self.send_header("Content-Type", CONTENT_TYPES.get(path.suffix, "application/octet-stream")) + self.send_header("Cache-Control", "no-store") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + return Handler + + +def make_server(sim: Simulator, host: str, port: int) -> ThreadingHTTPServer: + return ThreadingHTTPServer((host, port), make_handler(sim)) diff --git a/simulator/stage.py b/simulator/stage.py new file mode 100644 index 0000000..93ba306 --- /dev/null +++ b/simulator/stage.py @@ -0,0 +1,283 @@ +"""Load a stage map and patch it from a QLC+ workspace.""" + +from __future__ import annotations + +import json +import re +import xml.etree.ElementTree as ET +from dataclasses import dataclass, field +from pathlib import Path + +_NUMBER = re.compile(r"#\s*0*(\d+)") + + +@dataclass +class FixtureDef: + name: str + manufacturer: str + model: str + mode: str + channels: list[str] + + +@dataclass +class Fixture: + id: str + label: str + kind: str + x: float + y: float + universe: int | None = None + address: int | None = None # 0-based, same as the QLC+ workspace file + channels: int = 0 + mode: str = "" + name: str = "" + definition: str = "" + channel_names: list[str] = field(default_factory=list) + direction: float = 0.0 # cans: beam heading, degrees clockwise from +Y + zero: float = 0.0 # movers: heading at pan centre, same degrees + + @property + def dmx(self) -> int | None: + """1-based DMX start address.""" + if self.address is None: + return None + return self.address + 1 + + def to_json(self) -> dict: + return { + "id": self.id, + "label": self.label, + "kind": self.kind, + "x": self.x, + "y": self.y, + "universe": self.universe, + "address": self.address, + "dmx": self.dmx, + "channels": self.channels, + "mode": self.mode, + "name": self.name or self.label, + "def": self.definition, + "channel_names": self.channel_names, + "direction": self.direction, + "zero": self.zero, + } + + +@dataclass +class Stage: + building_width: float + origin: str + fixtures: list[Fixture] + name: str = "xchc" + show: str | None = None + output_ip: str | None = None + path: Path | None = None + warnings: list[str] = field(default_factory=list) + + def to_json(self) -> dict: + return { + "name": self.name, + "building_width": self.building_width, + "origin": self.origin, + "show": self.show, + "output_ip": self.output_ip, + "fixtures": [fixture.to_json() for fixture in self.fixtures], + "warnings": self.warnings, + } + + +def _local(tag: str) -> str: + return tag.rsplit("}", 1)[-1] + + +def _text(element: ET.Element, name: str, default: str = "") -> str: + for child in element: + if _local(child.tag) == name and child.text: + return child.text.strip() + return default + + +def _definitions(data: dict) -> dict[str, FixtureDef]: + found: dict[str, FixtureDef] = {} + for name, raw in data.get("definitions", {}).items(): + found[str(name)] = FixtureDef( + name=str(name), + manufacturer=str(raw.get("manufacturer") or ""), + model=str(raw.get("model") or ""), + mode=str(raw.get("mode") or ""), + channels=[str(channel) for channel in raw.get("channels") or []], + ) + return found + + +def load_stage(path: Path) -> Stage: + data = json.loads(path.read_text()) + definitions = _definitions(data) + fixtures: list[Fixture] = [] + for key, raw in data.get("fixtures", {}).items(): + kind = raw.get("kind", "can") + if raw.get("address") is not None: + address = int(raw["address"]) + elif raw.get("dmx") is not None: + address = int(raw["dmx"]) - 1 + else: + address = None + definition = definitions.get(str(raw.get("def") or "")) + channel_names = list(definition.channels) if definition else [] + channels = int(raw.get("channels") or 0) or len(channel_names) + if address is not None and channels == 0: + channels = 43 if kind == "mover" else 8 + fixtures.append( + Fixture( + id=str(key), + label=str(raw.get("label", key)), + kind=kind, + x=float(raw["x"]), + y=float(raw["y"]), + universe=None if raw.get("universe") is None else int(raw["universe"]), + address=None if address is None else int(address), + channels=channels, + mode=str(raw.get("mode") or (definition.mode if definition else "")), + name=str(raw.get("name") or raw.get("label", key)), + definition=definition.name if definition else str(raw.get("def") or ""), + channel_names=channel_names, + direction=float(raw.get("direction") or 0), + zero=float(raw.get("zero") or 0), + ) + ) + return Stage( + building_width=float(data.get("building_width", 7.0)), + origin=str(data.get("origin", "")), + fixtures=fixtures, + name=str(data.get("name") or "xchc"), + path=Path(path), + ) + + +def wrap_degrees(degrees: float) -> int: + """Nearest degree in -179..180. 0 points toward +Y.""" + return (round(float(degrees)) + 180) % 360 - 180 + + +def set_heading(stage: Stage, fixture_id: str, *, direction: float | None = None, zero: float | None = None) -> Fixture: + """Point a can's direction, or a mover's zero, and store it in the stage file.""" + fixture = next((item for item in stage.fixtures if item.id == fixture_id), None) + if fixture is None: + raise KeyError(fixture_id) + if fixture.kind == "can": + if direction is None: + raise ValueError("direction required") + fixture.direction = wrap_degrees(direction) + _write_number(stage, fixture_id, "direction", fixture.direction) + else: + if zero is None: + raise ValueError("zero required") + fixture.zero = wrap_degrees(zero) + _write_number(stage, fixture_id, "zero", fixture.zero) + return fixture + + +def _write_number(stage: Stage, fixture_id: str, field_name: str, value: int) -> None: + if stage.path is None or not stage.path.is_file(): + return + text = stage.path.read_text() + marker = f'"{fixture_id}": {{' + start = text.find(marker) + if start < 0: + return + end = text.find("\n }", start) + if end < 0: + return + block = text[start:end] + updated, count = re.subn( + rf'("{re.escape(field_name)}":\s*)-?\d+(?:\.\d+)?', + rf"\g<1>{value}", + block, + count=1, + ) + if count == 0: + updated = block.rstrip() + f',\n "{field_name}": {value}' + stage.path.write_text(text[:start] + updated + text[end:]) + + +def _qxw_fixtures(path: Path) -> tuple[list[dict], str | None]: + root = ET.parse(path).getroot() + output_ip = None + fixtures: list[dict] = [] + for element in root.iter(): + name = _local(element.tag) + if name == "PluginParameters" and output_ip is None: + output_ip = element.attrib.get("outputIP") or None + if name != "Engine": + continue + for child in element: + if _local(child.tag) != "Fixture": + continue + fixtures.append( + { + "name": _text(child, "Name"), + "mode": _text(child, "Mode"), + "model": _text(child, "Model"), + "manufacturer": _text(child, "Manufacturer"), + "universe": int(_text(child, "Universe", "0")), + "address": int(_text(child, "Address", "0")), + "channels": int(_text(child, "Channels", "0")), + } + ) + return fixtures, output_ip + + +def _stage_id_for(patched: dict, stage_ids: set[str]) -> str | None: + name = patched["name"] + if name in stage_ids: + return name + match = _NUMBER.search(name) + number = int(match.group(1)) if match else None + blob = f"{patched['manufacturer']} {patched['model']} {name}".lower() + mover = "mover" in blob or "small eye" in blob + can = "bcc145" in blob or blob.strip().endswith("can") + if number is None: + lowered = name.lower() + if "front left" in lowered and "M1" in stage_ids: + return "M1" + if "front right" in lowered and "M2" in stage_ids: + return "M2" + if "back left" in lowered and "M3" in stage_ids: + return "M3" + if "back right" in lowered and "M4" in stage_ids: + return "M4" + return None + if mover: + key = f"M{number}" + if key in stage_ids: + return key + if can: + key = f"#{number}" + if key in stage_ids: + return key + return None + + +def apply_show(stage: Stage, show_path: Path) -> None: + """Fill missing DMX addresses from a QLC+ workspace.""" + patched, output_ip = _qxw_fixtures(show_path) + stage.show = show_path.name + stage.output_ip = output_ip + by_id = {fixture.id: fixture for fixture in stage.fixtures} + used: set[str] = set() + for item in patched: + key = _stage_id_for(item, set(by_id)) + if key is None or key in used: + continue + fixture = by_id[key] + if fixture.address is None: + fixture.universe = item["universe"] + fixture.address = item["address"] + fixture.channels = item["channels"] or fixture.channels + fixture.mode = item["mode"] + fixture.name = item["name"] + used.add(key) + for fixture in stage.fixtures: + if fixture.address is None: + stage.warnings.append(f"{fixture.label} has no DMX address") diff --git a/simulator/static/app.js b/simulator/static/app.js new file mode 100644 index 0000000..6d9a42f --- /dev/null +++ b/simulator/static/app.js @@ -0,0 +1,612 @@ +const canvas = document.getElementById("stage"); +const ctx = canvas.getContext("2d"); +const statusEl = document.getElementById("status"); +const originEl = document.getElementById("origin"); +const nameEl = document.getElementById("stage-name"); +const patchEl = document.getElementById("patch"); +const listEl = document.getElementById("fixtures"); +const detailEl = document.getElementById("detail"); +const detailTitle = document.getElementById("detail-title"); +const detailMeta = document.getElementById("detail-meta"); +const channelsEl = document.getElementById("channels"); + +let stage = null; +let state = { fixtures: {}, age: null, rate: 0, universe: null, packets: 0 }; +let selected = null; +let drag = null; +const rows = new Map(); + +function luma(r, g, b) { + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +} + +function hsv(hue, value) { + const h = ((hue % 1) + 1) % 1; + const i = Math.floor(h * 6); + const f = h * 6 - i; + const q = value * (1 - f); + const t = value * f; + const map = [ + [value, t, 0], + [q, value, 0], + [0, value, t], + [0, q, value], + [t, 0, value], + [value, 0, q], + ]; + const [r, g, b] = map[i % 6]; + return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; +} + +const PAR_PALETTE = [ + [255, 0, 0], + [255, 96, 0], + [255, 200, 0], + [255, 255, 0], + [0, 255, 0], + [0, 255, 160], + [0, 64, 255], + [140, 0, 255], + [255, 0, 160], + [255, 255, 255], +]; + +const aims = new Map(); + +function scaleColour(colour, dimmer) { + const level = (dimmer || 0) / 255; + return colour.map((channel) => Math.round(channel * level)); +} + +function paletteColour(live, gradient) { + const palette = live.palette && live.palette.length ? live.palette : PAR_PALETTE; + const speed = live.speed_hz || 0.35; + const phase = performance.now() / 1000 * speed; + const index = Math.floor(phase) % palette.length; + if (!gradient) return palette[index]; + const next = palette[(index + 1) % palette.length]; + const blend = phase - Math.floor(phase); + return palette[index].map((channel, slot) => Math.round(channel + (next[slot] - channel) * blend)); +} + +function canColour(live) { + const mode = live.function || "mix"; + const dimmer = live.dimmer || 0; + if (mode === "jump" || mode === "gradient") return scaleColour(paletteColour(live, mode === "gradient"), dimmer); + if (mode === "pulse") { + const speed = live.speed_hz || 0.4; + const wave = 0.5 - 0.5 * Math.cos((performance.now() / 1000) * speed * Math.PI * 2); + const depth = 0.05 + 0.95 * wave; + return [live.r || 0, live.g || 0, live.b || 0].map((channel) => Math.round(channel * depth)); + } + if (mode === "sound") { + const speed = live.speed_hz || 1; + const variant = live.sound === 2 ? 2 : 1; + const bpm = (variant === 2 ? 156 : 104) * (0.55 + Math.min(speed, 8) / 10); + const beat = ((performance.now() / 1000) * bpm / 60) % 1; + let hit = beat < 0.08 ? 1 : 0.04; + if (variant === 2 && beat > 0.5 && beat < 0.58) hit = 1; + const colour = (live.palette && live.palette[variant === 2 ? 4 : 0]) || PAR_PALETTE[variant === 2 ? 4 : 0]; + return scaleColour(colour, dimmer).map((channel) => Math.round(channel * hit)); + } + return [live.r || 0, live.g || 0, live.b || 0]; +} + +function effectPixels(live) { + const source = (live.pixels || []).map((pixel) => pixel.slice()); + if (!live.dynamic || !source.length) return source; + const count = source.length; + const lit = source.find((pixel) => pixel[0] + pixel[1] + pixel[2] > 0); + const fallback = lit || scaleColour([255, 255, 255], live.dimmer || 0); + const speed = live.speed_hz || 1; + const t = (performance.now() / 1000) * speed; + return source.map((pixel, index) => { + const colour = pixel[0] + pixel[1] + pixel[2] > 0 ? pixel : fallback; + if (live.dynamic === "rainbow") { + return hsv((t * 0.2 + index / count) % 1, (live.dimmer || 0) / 255); + } + let level = 1; + if (live.dynamic === "chase") level = Math.floor(t) % count === index ? 1 : 0.08; + else if (live.dynamic === "reverse") level = Math.floor(t) % count === (count - 1 - index) ? 1 : 0.08; + else if (live.dynamic === "bounce") { + const span = Math.max(1, count - 1); + const tri = Math.abs((t % (2 * span)) - span); + level = Math.round(tri) === index ? 1 : 0.08; + } else if (live.dynamic === "pulse") level = 0.15 + 0.85 * (0.5 + 0.5 * Math.sin(t * Math.PI * 2)); + else if (live.dynamic === "pairs") level = Math.floor(t) % 2 === index % 2 ? 1 : 0.08; + return colour.map((channel) => Math.round(channel * level)); + }); +} + +function mixPixels(pixels) { + let red = 0; + let green = 0; + let blue = 0; + let weight = 0; + for (const pixel of pixels) { + const w = pixel[0] + pixel[1] + pixel[2]; + red += pixel[0] * w; + green += pixel[1] * w; + blue += pixel[2] * w; + weight += w; + } + if (weight <= 0) return [0, 0, 0]; + return [Math.round(red / weight), Math.round(green / weight), Math.round(blue / weight)]; +} + +function shutter(live) { + if (!live.strobe_hz) return 1; + const t = performance.now() / 1000; + if (live.strobe_mode === "random") { + const bucket = Math.floor(t * live.strobe_hz); + const noise = Math.abs(Math.sin(bucket * 12.9898) * 43758.5453) % 1; + return noise > 0.55 ? 1 : 0; + } + const period = 1 / live.strobe_hz; + return t % period < period * 0.42 ? 1 : 0; +} + +function aimed(id, live, zero) { + const targetPan = (zero || 0) + (live.pan_deg || 0); + const targetBeam = live.beam_m || 0; + const now = performance.now() / 1000; + let state = aims.get(id); + if (!state) { + state = { pan: targetPan, beam: targetBeam, t: now }; + aims.set(id, state); + return state; + } + const dt = Math.min(0.05, Math.max(0, now - state.t)); + state.t = now; + const fast = live.move == null ? 1 : live.move; + if (fast > 0.97) { + state.pan = targetPan; + state.beam = targetBeam; + return state; + } + const tau = 0.05 + (1 - fast) * 1.8; + const k = 1 - Math.exp(-dt / tau); + state.pan += (targetPan - state.pan) * k; + state.beam += (targetBeam - state.beam) * k; + return state; +} + +function appearance(fixture, live) { + const pixels = fixture.kind === "mover" ? effectPixels(live) : null; + let [r, g, b] = fixture.kind === "can" ? canColour(live) : pixels && live.dynamic ? mixPixels(pixels) : [live.r || 0, live.g || 0, live.b || 0]; + const gate = shutter(live); + return { + r: Math.round(r * gate), + g: Math.round(g * gate), + b: Math.round(b * gate), + dimmer: live.dimmer || 0, + pixels: pixels && pixels.map((pixel) => pixel.map((channel) => Math.round(channel * gate))), + }; +} + +function layout(width, height) { + const ys = stage.fixtures.map((fixture) => fixture.y); + const backY = Math.min(0, ...ys); + const depth = Math.max(2.4, ...ys); + const padX = 0.85; + const padY = 0.7; + const x0 = -stage.building_width / 2 - padX; + const x1 = stage.building_width / 2 + padX; + const y0 = backY - padY; + const y1 = depth + padY; + const worldW = x1 - x0; + const worldH = y1 - y0; + const scale = Math.min(width / worldW, height / worldH); + const ox = (width - worldW * scale) / 2; + const oy = (height - worldH * scale) / 2; + return { + depth, + backY, + sx: (x) => ox + (x - x0) * scale, + sy: (y) => oy + (y1 - y) * scale, + mx: (px) => x0 + (px - ox) / scale, + my: (py) => y1 - (py - oy) / scale, + }; +} + +function draw() { + if (!stage) return; + const dpr = window.devicePixelRatio || 1; + const width = canvas.width; + const height = canvas.height; + ctx.setTransform(dpr, 0, 0, dpr, 0, 0); + const cssW = width / dpr; + const cssH = height / dpr; + const view = layout(cssW, cssH); + const { sx, sy, depth, backY } = view; + + ctx.clearRect(0, 0, cssW, cssH); + ctx.fillStyle = "#121216"; + ctx.fillRect(0, 0, cssW, cssH); + + const left = sx(-stage.building_width / 2); + const right = sx(stage.building_width / 2); + const front = sy(depth); + const back = sy(backY); + ctx.strokeStyle = "#5c5c66"; + ctx.lineWidth = 2; + ctx.strokeRect(left, front, right - left, back - front); + + ctx.strokeStyle = "#3a3a44"; + ctx.lineWidth = 1; + ctx.setLineDash([4, 6]); + ctx.beginPath(); + ctx.moveTo(sx(0), sy(backY - 0.2)); + ctx.lineTo(sx(0), sy(depth + 0.25)); + ctx.stroke(); + ctx.setLineDash([]); + + ctx.fillStyle = "#9a9aa4"; + ctx.font = "600 13px system-ui, sans-serif"; + ctx.textAlign = "center"; + ctx.fillText("AUDIENCE", sx(0), sy(depth + 0.38)); + ctx.font = "12px system-ui, sans-serif"; + ctx.fillStyle = "#8d8d96"; + ctx.fillText("row of 4", sx(0), sy(-0.28)); + ctx.font = "11px system-ui, sans-serif"; + ctx.fillText(`${stage.building_width.toFixed(1)} m`, sx(0), front - 8); + + ctx.globalCompositeOperation = "lighter"; + for (const fixture of stage.fixtures) { + const live = state.fixtures[fixture.id] || {}; + const color = appearance(fixture, live); + const dragging = drag && drag.moved && drag.id === fixture.id; + const beamColor = dragging && color.r + color.g + color.b < 8 ? { ...color, r: 190, g: 190, b: 200 } : color; + if (fixture.kind === "mover") { + const fixed = dragging + ? { pan: (fixture.zero || 0) + (live.pan_deg || 0), beam: Math.max(live.beam_m || 0, 1.6), zoom: live.zoom_deg || 18, focus: 1 - (live.focus || 0) } + : null; + drawBeam(sx, sy, fixture, live, beamColor, fixed); + } else { + drawBeam(sx, sy, fixture, live, beamColor, { pan: fixture.direction || 0, beam: 2.2, zoom: 25, focus: 0.35 }); + } + drawGlow(sx, sy, fixture, color); + } + ctx.globalCompositeOperation = "source-over"; + + for (const fixture of stage.fixtures) { + const live = state.fixtures[fixture.id] || {}; + drawBody(sx, sy, fixture, live, appearance(fixture, live)); + } +} + +function drawGlow(sx, sy, fixture, color) { + const level = (color.r + color.g + color.b) / (255 * 3); + if (level <= 0.01) return; + const x = sx(fixture.x); + const y = sy(fixture.y); + const radius = (fixture.kind === "mover" ? 70 : 54) * (0.45 + level); + const gradient = ctx.createRadialGradient(x, y, 2, x, y, radius); + gradient.addColorStop(0, `rgba(${color.r},${color.g},${color.b},${0.55 * level + 0.15})`); + gradient.addColorStop(1, `rgba(${color.r},${color.g},${color.b},0)`); + ctx.fillStyle = gradient; + ctx.beginPath(); + ctx.arc(x, y, radius, 0, Math.PI * 2); + ctx.fill(); +} + +function drawBeam(sx, sy, fixture, live, color, fixed) { + const level = (color.r + color.g + color.b) / 255; + const length = fixed ? fixed.beam : Math.max(live.beam_m || 0, fixture.kind === "mover" ? 2.2 : 0); + if (live.patched === false || level <= 0.02 || !length) return; + const aim = fixed || aimed(fixture.id, live, fixture.zero); + // DMX focus 0 is a wide wash. Focus 255 holds the zoom angle. + // Fixed beams pass spread directly, 0 tight and 1 wide. + const spread = fixed ? fixed.focus : 1 - (live.focus || 0); + const zoom = fixed ? fixed.zoom : live.zoom_deg || 8; + const tight = zoom / 2; + const wide = Math.max(tight, 40); + const rad = aim.pan * Math.PI / 180; + const half = (tight + (wide - tight) * spread) * Math.PI / 180; + const tip = [fixture.x + Math.sin(rad) * length, fixture.y + Math.cos(rad) * length]; + const left = [fixture.x + Math.sin(rad - half) * length, fixture.y + Math.cos(rad - half) * length]; + const right = [fixture.x + Math.sin(rad + half) * length, fixture.y + Math.cos(rad + half) * length]; + ctx.beginPath(); + ctx.moveTo(sx(fixture.x), sy(fixture.y)); + ctx.lineTo(sx(left[0]), sy(left[1])); + ctx.lineTo(sx(right[0]), sy(right[1])); + ctx.closePath(); + const gradient = ctx.createLinearGradient(sx(fixture.x), sy(fixture.y), sx(tip[0]), sy(tip[1])); + const alpha = 0.85 * (1 - spread * 0.35); + gradient.addColorStop(0, `rgba(${color.r},${color.g},${color.b},${alpha})`); + gradient.addColorStop(1, `rgba(${color.r},${color.g},${color.b},0)`); + ctx.fillStyle = gradient; + ctx.fill(); +} + +function lensRotation(live) { + if (live.spin_dps) return ((performance.now() / 1000) * live.spin_dps * Math.PI) / 180; + return ((live.lens_deg || 0) * Math.PI) / 180; +} + +function drawBody(sx, sy, fixture, live, color) { + const x = sx(fixture.x); + const y = sy(fixture.y); + const pixels = color.pixels || []; + const head = fixture.kind === "mover" && pixels.length ? pixels[0] : [color.r, color.g, color.b]; + const lit = head[0] + head[1] + head[2] > 8; + const size = fixture.kind === "mover" ? 15 : 13; + ctx.beginPath(); + if (fixture.kind === "mover") { + ctx.rect(x - size, y - size, size * 2, size * 2); + } else { + ctx.arc(x, y, size, 0, Math.PI * 2); + } + ctx.fillStyle = lit ? `rgb(${head[0]},${head[1]},${head[2]})` : "#2a2a30"; + ctx.fill(); + ctx.lineWidth = fixture.id === selected ? 2.5 : 1.5; + ctx.strokeStyle = fixture.id === selected ? "#fff" : "#c8c8d0"; + ctx.stroke(); + + if (fixture.kind === "mover" && pixels.length > 1) { + const ring = pixels.slice(1); + const spin = lensRotation(live); + ring.forEach((pixel, index) => { + const angle = spin + (index / ring.length) * Math.PI * 2 - Math.PI / 2; + const px = x + Math.cos(angle) * (size + 7); + const py = y + Math.sin(angle) * (size + 7); + ctx.beginPath(); + ctx.arc(px, py, 3.5, 0, Math.PI * 2); + const on = pixel[0] + pixel[1] + pixel[2] > 0; + ctx.fillStyle = on ? `rgb(${pixel[0]},${pixel[1]},${pixel[2]})` : "#333"; + ctx.fill(); + }); + } + + ctx.fillStyle = lit && luma(head[0], head[1], head[2]) > 140 ? "#16161a" : "#f2f2f4"; + ctx.font = "600 11px system-ui, sans-serif"; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.fillText(fixture.label, x, y); + ctx.textBaseline = "alphabetic"; +} + +function resize() { + const rect = canvas.getBoundingClientRect(); + const dpr = window.devicePixelRatio || 1; + canvas.width = Math.max(1, Math.floor(rect.width * dpr)); + canvas.height = Math.max(1, Math.floor(rect.height * dpr)); + draw(); +} + +function swatchColor(fixture, live) { + const color = appearance(fixture, live || {}); + const head = fixture.kind === "mover" && color.pixels && color.pixels[0] ? color.pixels[0] : [color.r, color.g, color.b]; + if (head[0] + head[1] + head[2] < 8) return "#2a2a30"; + return `rgb(${head[0]},${head[1]},${head[2]})`; +} + +function buildList() { + listEl.replaceChildren(); + rows.clear(); + for (const fixture of stage.fixtures) { + const li = document.createElement("li"); + li.id = `fx-${fixture.id}`; + li.className = fixture.kind; + li.dataset.id = fixture.id; + const swatch = document.createElement("span"); + swatch.className = "swatch"; + const name = document.createElement("span"); + name.className = "name"; + name.textContent = fixture.label; + const addr = document.createElement("span"); + addr.className = "addr"; + addr.textContent = fixture.dmx == null ? "no address" : `DMX ${fixture.dmx}`; + li.append(swatch, name, addr); + li.addEventListener("click", () => { + selected = fixture.id; + updateDetail(); + draw(); + }); + listEl.append(li); + rows.set(fixture.id, { li, swatch, addr }); + } +} + +function updateList() { + for (const fixture of stage.fixtures) { + const row = rows.get(fixture.id); + const live = state.fixtures[fixture.id] || {}; + row.swatch.style.background = swatchColor(fixture, live); + row.li.classList.toggle("selected", fixture.id === selected); + if (!live.patched) row.addr.textContent = "no address"; + else if (live.function && live.function !== "mix" && live.function !== "pixels") { + row.addr.textContent = `DMX ${fixture.dmx} · ${live.function_label || live.function}`; + } else row.addr.textContent = `DMX ${fixture.dmx}`; + } +} + +function updateDetail() { + const fixture = stage.fixtures.find((item) => item.id === selected); + if (!fixture) { + detailEl.hidden = true; + return; + } + const live = state.fixtures[fixture.id] || {}; + detailEl.hidden = false; + detailTitle.textContent = fixture.name || fixture.label; + const bits = []; + if (fixture.dmx != null) bits.push(`DMX ${fixture.dmx}`); + if (fixture.def) bits.push(fixture.def); + else if (fixture.mode) bits.push(fixture.mode); + if (fixture.kind === "can") bits.push(`direction ${fixture.direction || 0}°`); + if (fixture.kind === "mover") bits.push(`zero ${fixture.zero || 0}°`); + if (live.function_label && live.function !== "mix" && live.function !== "pixels") bits.push(live.function_label); + if (live.speed_hz) bits.push(`${live.speed_hz.toFixed(1)} Hz`); + if (live.reset) bits.push("reset"); + if (fixture.kind === "mover" && live.pan_deg != null) { + bits.push(`pan ${live.pan_deg.toFixed(0)}°`); + bits.push(`zoom ${(live.zoom_deg || 0).toFixed(0)}°`); + if (live.spin_dps) bits.push(`lens ${live.spin_dps > 0 ? "CW" : "CCW"}`); + else if (live.lens_deg) bits.push(`lens ${live.lens_deg.toFixed(0)}°`); + } + detailMeta.textContent = bits.join(" · "); + const channels = live.channels || []; + channelsEl.replaceChildren(); + channels.forEach((value, index) => { + const row = document.createElement("div"); + row.className = "channel"; + const label = document.createElement("span"); + label.textContent = String(index + 1); + const title = document.createElement("span"); + title.className = "ch-name"; + title.textContent = (fixture.channel_names && fixture.channel_names[index]) || ""; + const bar = document.createElement("div"); + bar.className = "bar"; + const fill = document.createElement("span"); + fill.style.width = `${(value / 255) * 100}%`; + bar.append(fill); + const num = document.createElement("span"); + num.textContent = String(value); + row.append(label, title, bar, num); + channelsEl.append(row); + }); +} + +function updateStatus() { + const age = state.age; + const live = age != null && age < 1.5; + statusEl.classList.toggle("live", live); + if (!live) { + statusEl.textContent = state.packets ? "Art-Net idle" : "waiting for Art-Net"; + return; + } + const universe = state.universe == null ? "" : ` · universe ${state.universe}`; + statusEl.textContent = `Art-Net ${state.rate} fps${universe}`; +} + +async function poll() { + try { + state = await fetch("/api/state").then((response) => response.json()); + updateStatus(); + updateList(); + if (selected) updateDetail(); + } catch { + statusEl.classList.remove("live"); + statusEl.textContent = "view disconnected"; + } +} + +function frame() { + draw(); + if (stage) updateList(); + requestAnimationFrame(frame); +} + +function pointerMetres(event) { + const rect = canvas.getBoundingClientRect(); + const view = layout(rect.width, rect.height); + return { + x: view.mx(event.clientX - rect.left), + y: view.my(event.clientY - rect.top), + }; +} + +function fixtureAt(x, y) { + let best = null; + let bestDist = 0.55; + for (const fixture of stage.fixtures) { + const dist = Math.hypot(fixture.x - x, fixture.y - y); + if (dist < bestDist) { + best = fixture; + bestDist = dist; + } + } + return best; +} + +function wrapDegrees(degrees) { + return ((Math.round(degrees) + 180) % 360 + 360) % 360 - 180; +} + +function aimDegrees(fixture, x, y) { + return wrapDegrees(Math.atan2(x - fixture.x, y - fixture.y) * 180 / Math.PI); +} + +function saveHeading(fixture) { + const body = fixture.kind === "can" + ? { id: fixture.id, direction: fixture.direction } + : { id: fixture.id, zero: fixture.zero }; + fetch("/api/heading", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }).catch(() => {}); +} + +canvas.addEventListener("pointerdown", (event) => { + if (!stage || event.button !== 0) return; + const { x, y } = pointerMetres(event); + const fixture = fixtureAt(x, y); + selected = fixture ? fixture.id : null; + drag = fixture ? { id: fixture.id, moved: false } : null; + if (drag) canvas.setPointerCapture(event.pointerId); + canvas.style.cursor = fixture ? "grabbing" : "default"; + updateList(); + updateDetail(); +}); + +canvas.addEventListener("pointermove", (event) => { + if (!stage) return; + const { x, y } = pointerMetres(event); + if (!drag) { + canvas.style.cursor = fixtureAt(x, y) ? "grab" : "default"; + return; + } + const fixture = stage.fixtures.find((item) => item.id === drag.id); + if (!fixture) return; + if (!drag.moved && Math.hypot(x - fixture.x, y - fixture.y) < 0.2) return; + drag.moved = true; + const heading = aimDegrees(fixture, x, y); + if (fixture.kind === "can") fixture.direction = heading; + else { + const live = state.fixtures[fixture.id] || {}; + fixture.zero = wrapDegrees(heading - (live.pan_deg || 0)); + } + updateDetail(); +}); + +canvas.addEventListener("pointerup", () => { + if (!drag) return; + const fixture = stage.fixtures.find((item) => item.id === drag.id); + const moved = drag.moved; + drag = null; + canvas.style.cursor = "grab"; + if (fixture && moved) { + aims.delete(fixture.id); + saveHeading(fixture); + } + updateDetail(); +}); + +canvas.addEventListener("pointercancel", () => { + drag = null; + canvas.style.cursor = "default"; +}); + +window.addEventListener("resize", resize); + +fetch("/api/stage") + .then((response) => response.json()) + .then((loaded) => { + stage = loaded; + nameEl.textContent = stage.name || "xchc"; + document.title = stage.name || "xchc"; + originEl.textContent = stage.origin || ""; + const show = stage.show ? stage.show : "stage file"; + const target = stage.output_ip ? ` · QLC+ output ${stage.output_ip}` : ""; + patchEl.textContent = `${show}${target}`; + buildList(); + resize(); + poll(); + setInterval(poll, 50); + requestAnimationFrame(frame); + }) + .catch(() => { + statusEl.textContent = "could not load the stage"; + }); diff --git a/simulator/static/index.html b/simulator/static/index.html new file mode 100644 index 0000000..25a76ba --- /dev/null +++ b/simulator/static/index.html @@ -0,0 +1,31 @@ + + + + + + xchc + + + +
+
+

xchc

+

+
+

waiting for Art-Net

+
+
+ + +
+ + + diff --git a/simulator/static/style.css b/simulator/static/style.css new file mode 100644 index 0000000..0a5f613 --- /dev/null +++ b/simulator/static/style.css @@ -0,0 +1,158 @@ +:root { + color-scheme: dark; + --bg: #0e0e10; + --panel: #141418; + --line: #2c2c34; + --text: #eee; + --muted: #8d8d96; + --live: #3dd68c; + --idle: #d7a13a; +} + +* { box-sizing: border-box; } + +html, body { + margin: 0; + height: 100%; + background: var(--bg); + color: var(--text); + font-family: system-ui, sans-serif; +} + +body { + display: grid; + grid-template-rows: auto 1fr; + min-height: 100%; +} + +header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 12px 16px; + border-bottom: 1px solid var(--line); +} + +h1, h2 { + margin: 0; + font-size: 16px; + font-weight: 600; +} + +h2 { font-size: 14px; } + +.titles p, .meta { + margin: 2px 0 0; + color: var(--muted); + font-size: 12px; +} + +.pill { + margin: 0; + padding: 4px 10px; + border-radius: 999px; + background: #2a2418; + color: var(--idle); + font-size: 12px; + font-variant-numeric: tabular-nums; +} + +.pill.live { + background: #14281e; + color: var(--live); +} + +main { + display: grid; + grid-template-columns: 1fr 300px; + min-height: 0; +} + +canvas { + width: 100%; + height: 100%; + display: block; + background: #121216; + touch-action: none; +} + +aside { + border-left: 1px solid var(--line); + background: var(--panel); + overflow: auto; + padding: 12px 14px 24px; +} + +ul { + list-style: none; + margin: 10px 0 0; + padding: 0; +} + +li { + display: grid; + grid-template-columns: 18px 1fr auto; + gap: 8px; + align-items: center; + padding: 7px 6px; + border-radius: 6px; + cursor: pointer; +} + +li:hover, li.selected { background: #22222a; } + +.swatch { + width: 18px; + height: 18px; + border-radius: 50%; + border: 1px solid #555; + background: #222; +} + +li.mover .swatch { border-radius: 3px; } + +.name { font-size: 13px; font-weight: 600; } +.addr { color: var(--muted); font-size: 11px; } + +#detail { margin-top: 16px; } + +#channels { + display: grid; + gap: 3px; + margin-top: 8px; +} + +.channel { + display: grid; + grid-template-columns: 22px minmax(72px, 1.2fr) 1fr 28px; + gap: 6px; + align-items: center; + font-size: 11px; + color: var(--muted); + font-variant-numeric: tabular-nums; +} + +.ch-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.bar { + height: 6px; + background: #2a2a32; + border-radius: 99px; + overflow: hidden; +} + +.bar span { + display: block; + height: 100%; + background: #d0d0d8; +} + +@media (max-width: 800px) { + main { grid-template-columns: 1fr; grid-template-rows: minmax(280px, 1fr) auto; } + aside { border-left: 0; border-top: 1px solid var(--line); max-height: 42vh; } +} diff --git a/tests/test_simulator.py b/tests/test_simulator.py new file mode 100644 index 0000000..b1f6069 --- /dev/null +++ b/tests/test_simulator.py @@ -0,0 +1,230 @@ +"""Stage simulator: Art-Net decode and the XCHC patch.""" + +from __future__ import annotations + +import json +import threading +from pathlib import Path +from urllib.request import urlopen + +from simulator.artnet import ArtNetNode, build_artdmx, parse_artdmx, parse_opcode +from simulator.decode import apply_cto, decode_can, decode_mover, lens_angle, lens_spin, mix_rgbw, view_stage +from simulator.server import Simulator, make_server +from simulator.stage import apply_show, load_stage, set_heading, wrap_degrees + +ROOT = Path(__file__).resolve().parents[1] + + +def test_artdmx_roundtrip(): + frame = bytearray(512) + frame[87] = 255 + frame[89] = 200 + packet = build_artdmx(frame, universe=0, sequence=3) + parsed = parse_artdmx(packet) + assert parsed is not None + universe, data = parsed + assert universe == 0 + assert data[87] == 255 + assert data[89] == 200 + assert parse_opcode(packet) == 0x5000 + + +def test_poll_is_not_dmx(): + packet = b"Art-Net\x00" + bytes([0x00, 0x20]) + bytes(10) + assert parse_opcode(packet) == 0x2000 + assert parse_artdmx(packet) is None + + +def test_xchc_patch_matches_the_stage_map(): + stage = load_stage(ROOT / "stage" / "map.json") + apply_show(stage, ROOT / "shows" / "xchc.qxw") + by_id = {fixture.id: fixture for fixture in stage.fixtures} + assert by_id["#1"].address == 87 + assert by_id["#1"].dmx == 88 + assert by_id["#8"].address == 143 + assert by_id["M1"].address == 0 + assert by_id["M1"].dmx == 1 + assert by_id["M2"].address == 44 + assert by_id["M1"].channels == 43 + assert by_id["#3"].kind == "can" + assert stage.output_ip == "192.168.1.228" + assert stage.name == "xchc" + assert by_id["#9"].x == -3.5 and by_id["#9"].y == -0.8 + assert by_id["#11"].y == -6.8 and by_id["#12"].x == 3.5 + assert by_id["#13"].x == -3.5 and by_id["#15"].x == 3.5 + assert by_id["#14"].x == 0.0 and by_id["#14"].y == -7.65 + assert by_id["#1"].address == 87 and by_id["#9"].address == 151 + assert by_id["#15"].address == 199 and by_id["M1"].address == 0 + assert by_id["M2"].address == 44 and by_id["#15"].channels == 8 + assert by_id["M3"].address == 257 and by_id["M3"].channels == 43 + assert by_id["M3"].x == -1.75 and by_id["M3"].y == -7.65 + assert by_id["M4"].address == 300 and by_id["M4"].x == 1.75 + assert by_id["#1"].direction == 90 and by_id["#8"].direction == -90 + assert by_id["#3"].direction == 0 and by_id["#14"].direction == 0 + assert by_id["M1"].zero == 0 and by_id["M4"].zero == 0 + assert stage.warnings == [] + + +def test_can_red_and_white(): + assert mix_rgbw(0, 0, 0, 255, 255) == (255, 255, 255) + viewed = decode_can([255, 0, 255, 0, 0, 0, 0, 0]) + assert (viewed["r"], viewed["g"], viewed["b"]) == (255, 0, 0) + assert viewed["function"] == "mix" + assert viewed["strobe_hz"] == 0 + assert decode_can([255, 255, 255, 0, 0, 0, 0, 0])["strobe_hz"] > 0 + assert decode_can([128, 0, 0, 0, 0, 0, 120, 0])["effect"] is True + + +def test_can_macro_functions(): + assert decode_can([255, 0, 0, 0, 0, 0, 51, 0])["function"] == "fixed" + assert decode_can([255, 0, 0, 0, 0, 0, 51, 0])["r"] == 255 + assert decode_can([0, 0, 0, 0, 0, 0, 80, 0])["r"] == 0 + jump = decode_can([255, 0, 0, 0, 0, 0, 120, 200]) + assert jump["function"] == "jump" + assert jump["speed_hz"] > 1 + assert jump["palette"][0] == [255, 0, 0] + pulse = decode_can([255, 0, 255, 80, 0, 0, 170, 0]) + assert pulse["function"] == "pulse" + assert pulse["r"] == 255 and pulse["g"] == 80 + assert decode_can([255, 0, 0, 0, 0, 0, 220, 0])["function"] == "gradient" + sound = decode_can([255, 0, 0, 0, 0, 0, 255, 0]) + assert sound["function"] == "sound" and sound["sound"] == 2 + + +def test_mover_home_points_at_the_audience(): + channels = [0] * 43 + channels[0] = 128 # pan coarse, fine 0 → 32768, the centre of 540° + channels[2] = 160 + channels[8] = 255 + channels[10] = 255 # red on the first pixel + viewed = decode_mover(channels) + assert viewed["pan_deg"] == 0 + assert viewed["r"] == 255 + assert viewed["beam_m"] > 2 + parked = [0] * 43 + parked[8] = 255 + assert decode_mover(parked)["beam_m"] >= 2.2 + assert lens_spin(0) == 0 + assert lens_spin(160) < 0 + assert lens_spin(230) > 0 + assert lens_angle(0) == 0 + assert 25 < lens_angle(64) < 35 + + +def test_mover_functions(): + channels = [0] * 43 + channels[5] = 230 + channels[6] = 255 + channels[8] = 255 + channels[39] = 20 + macro = decode_mover(channels) + assert macro["function"] == "macro" + assert macro["r"] == 255 and macro["b"] == 0 + assert macro["zoom_deg"] == 45 + assert macro["spin_dps"] > 0 + + channels[40] = 103 + static = decode_mover(channels) + assert static["function"] == "static" + assert static["pixels"][3][0] == 255 + assert static["pixels"][0] == [0, 0, 0] + + channels[41] = 30 + dynamic = decode_mover(channels) + assert dynamic["function"] == "dynamic" + assert dynamic["dynamic"] == "chase" + assert dynamic["pixels"][0][0] == 255 + assert dynamic["speed_hz"] > 0 + + warm = [0] * 43 + warm[8] = 255 + warm[10] = warm[11] = warm[12] = 255 + warm[38] = 255 + tinted = decode_mover(warm) + assert tinted["r"] == 255 + assert tinted["b"] < apply_cto(255, 255, 255, 0)[2] + assert tinted["b"] < 100 + + strobe = [0] * 43 + strobe[9] = 240 + assert decode_mover(strobe)["strobe_mode"] == "random" + assert decode_mover([0] * 43)["strobe_mode"] == "open" + + +def test_map_definition_selects_the_channels(): + stage = load_stage(ROOT / "stage" / "map.json") + mover = next(fixture for fixture in stage.fixtures if fixture.id == "M1") + can = next(fixture for fixture in stage.fixtures if fixture.id == "#1") + assert can.channel_names[:3] == ["Dimmer", "Strobe", "Red"] + assert mover.channel_names[5] == "Lens Rotate" + assert mover.channel_names[6] == "Zoom" + assert mover.mode == "43 Channel" + + frame = bytearray(512) + frame[mover.address + mover.channel_names.index("Pan")] = 128 + frame[mover.address + mover.channel_names.index("Zoom")] = 255 + frame[mover.address + mover.channel_names.index("Center Brightness")] = 255 + frame[mover.address + mover.channel_names.index("Red 1")] = 255 + frame[mover.address + mover.channel_names.index("Lens Rotate")] = 230 + live = view_stage(stage, {0: bytes(frame)})["M1"] + assert live["zoom_deg"] == 45 + assert live["spin_dps"] > 0 + assert live["r"] == 255 + assert live["pan_deg"] == 0 + + +def test_view_reads_universe_bytes(): + stage = load_stage(ROOT / "stage" / "map.json") + apply_show(stage, ROOT / "shows" / "xchc.qxw") + frame = bytearray(512) + frame[87] = 255 + frame[89] = 0 + frame[90] = 255 + live = view_stage(stage, {0: bytes(frame)}) + assert (live["#1"]["r"], live["#1"]["g"], live["#1"]["b"]) == (0, 255, 0) + assert live["#2"]["dimmer"] == 0 + + +def test_http_state_follows_artnet(): + stage = load_stage(ROOT / "stage" / "map.json") + apply_show(stage, ROOT / "shows" / "xchc.qxw") + node = ArtNetNode("127.0.0.1", 0) + node.start() + server = make_server(Simulator(stage, node), "127.0.0.1", 0) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + frame = bytearray(512) + frame[0] = 128 + frame[8] = 255 + frame[10] = 255 + node.write(0, frame) + port = server.server_address[1] + with urlopen(f"http://127.0.0.1:{port}/api/state") as response: + payload = json.load(response) + assert payload["packets"] == 1 + assert payload["fixtures"]["M1"]["r"] == 255 + with urlopen(f"http://127.0.0.1:{port}/api/stage") as response: + described = json.load(response) + assert described["fixtures"][0]["x"] == -3.5 + finally: + server.shutdown() + node.close() + + +def test_heading_is_stored_in_the_map(tmp_path): + target = tmp_path / "map.json" + target.write_text((ROOT / "stage" / "map.json").read_text()) + stage = load_stage(target) + assert wrap_degrees(270) == -90 + set_heading(stage, "#1", direction=45) + set_heading(stage, "M1", zero=-30) + saved = json.loads(target.read_text()) + assert saved["fixtures"]["#1"]["direction"] == 45 + assert saved["fixtures"]["#2"]["direction"] == 90 + assert saved["fixtures"]["M1"]["zero"] == -30 + assert saved["fixtures"]["M2"]["zero"] == 0 + again = load_stage(target) + by_id = {fixture.id: fixture for fixture in again.fixtures} + assert by_id["#1"].direction == 45 + assert by_id["M1"].zero == -30