Add a show compiler so QLC+ workspaces can be described and tested.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
jimmyandCursor committed 2026-10-21 17:39:13 +13:00
1 parent fee1985e1a
commit 4374ffb430
14 files changed
+3739

No files matched your search

+584
View File
@@ -0,0 +1,584 @@
"""QLC+ show model: universes, fixtures, scenes, and the virtual-console root."""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from patternstudio.fixturedefs import FixtureLibrary, ModeInfo
from .xmlutil import appearance, attr, text
QLC_VERSION = "4.12.7"
INVALID_FUNCTION = 4294967295
def midi_note(channel: int, note: int) -> int:
"""QLC+ input channel for a MIDI note. Channel is 0–15."""
return (int(channel) << 12) | (128 + int(note))
def midi_cc(channel: int, cc: int) -> int:
"""QLC+ input channel for a MIDI control change. Channel is 0–15."""
return (int(channel) << 12) | int(cc)
def blend_maps(
into: dict[int, dict[int, int]],
prev: dict[int, dict[int, int]],
curr: dict[int, dict[int, int]],
prog: float,
) -> None:
"""Write prev→curr into `into`. Channels fade up from 0 when prev lacks them."""
prog = max(0.0, min(1.0, prog))
for fid in set(prev) | set(curr):
bucket = into.setdefault(fid, {})
channels = set(prev.get(fid, {})) | set(curr.get(fid, {}))
for ch in channels:
start = prev.get(fid, {}).get(ch, 0)
end = curr.get(fid, {}).get(ch, 0)
bucket[ch] = int(round(start + (end - start) * prog))
@dataclass
class MidiBinding:
universe: int
channel: int
@dataclass
class ArtNetOutput:
uid: str
ip: str
universe: int = 0
line: int = 0
@dataclass
class MidiInput:
uid: str
profile: str
channel: int = 0
line: int = 0
@dataclass
class Universe:
id: int
name: str
output: ArtNetOutput | None = None
midi: MidiInput | None = None
@dataclass
class Fixture:
id: int
key: str
manufacturer: str
model: str
mode: str
name: str
universe: int
address: int
channels: int
mode_info: ModeInfo | None = None
x: float | None = None
y: float | None = None
direction: float | None = None
zero: float | None = None
kind: str = ""
def named(self, name: str) -> list[int]:
"""Channel indexes for a name. "Red" is Red, or Red 1 … Red N when those exist."""
if self.mode_info is None:
raise ValueError(f"{self.key} has no channel map")
query = name.strip().lower()
exact: list[int] = []
numbered: list[tuple[int, int]] = []
for channel in self.mode_info.channels:
label = channel.name.strip()
if label.lower() == query:
exact.append(channel.index)
continue
head, sep, tail = label.rpartition(" ")
if sep and head.lower() == query and tail.isdigit():
numbered.append((int(tail), channel.index))
if exact:
return exact
if numbered:
numbered.sort()
return [index for _, index in numbered]
raise KeyError(f"{self.key} has no channel {name!r}")
def channel(self, name: str) -> int:
return self.named(name)[0]
@property
def pan_msb(self) -> int | None:
return None if self.mode_info is None else self.mode_info.pan_msb
@property
def pan_lsb(self) -> int | None:
return None if self.mode_info is None else self.mode_info.pan_lsb
@property
def tilt_msb(self) -> int | None:
return None if self.mode_info is None else self.mode_info.tilt_msb
@property
def tilt_lsb(self) -> int | None:
return None if self.mode_info is None else self.mode_info.tilt_lsb
def preview_channels(self) -> dict[int, int]:
if self.mode_info is None:
return {}
return self.mode_info.preview_channels()
@dataclass
class FixtureGroup:
id: int
name: str
columns: int
fixture_ids: list[int]
head: int = 0
@dataclass
class Scene:
id: int
key: str
name: str
values: dict[int, dict[int, int]]
fade_in: int = 0
fade_out: int = 0
duration: int = 0
primary: bool = True
type: str = "Scene"
def duration_ms(self, _show: Show) -> int:
return max(0, self.fade_in) + max(0, self.duration)
def apply(self, _show: Show, elapsed_ms: float, into: dict[int, dict[int, int]]) -> None:
prog = 1.0 if self.fade_in <= 0 else min(1.0, elapsed_ms / self.fade_in)
blend_maps(into, {}, self.values, prog)
def render(self) -> str:
vals = []
for fid, channels in sorted(self.values.items()):
if not channels:
continue
body = ",".join(f"{ch},{val}" for ch, val in sorted(channels.items()))
vals.append(f' <FixtureVal ID="{fid}">{body}</FixtureVal>')
inner = ("\n" + "\n".join(vals)) if vals else ""
return (
f' <Function ID="{self.id}" Type="Scene" Name={attr(self.name)}>\n'
f' <Speed FadeIn="{self.fade_in}" FadeOut="{self.fade_out}" Duration="{self.duration}"/>'
f"{inner}\n"
f" </Function>"
)
@dataclass
class Collection:
id: int
key: str
name: str
members: list[int]
primary: bool = True
type: str = "Collection"
def duration_ms(self, show: Show) -> int:
return max((show.functions_by_id[mid].duration_ms(show) for mid in self.members), default=0)
def apply(self, show: Show, elapsed_ms: float, into: dict[int, dict[int, int]]) -> None:
for mid in self.members:
show.functions_by_id[mid].apply(show, elapsed_ms, into)
def render(self) -> str:
steps = "\n".join(f' <Step Number="{i}">{mid}</Step>' for i, mid in enumerate(self.members))
return (
f' <Function ID="{self.id}" Type="Collection" Name={attr(self.name)}>\n'
f"{steps}\n"
f" </Function>"
)
@dataclass
class RawFunction:
id: int
key: str
name: str
xml: str
primary: bool = True
type: str = "Raw"
def duration_ms(self, _show: Show) -> int:
return 0
def apply(self, _show: Show, _elapsed_ms: float, _into: dict[int, dict[int, int]]) -> None:
return None
def render(self) -> str:
return self.xml
@dataclass
class Show:
author: str = "Jimmy"
version: str = QLC_VERSION
root: Path | None = None
universes: list[Universe] = field(default_factory=list)
fixtures: list[Fixture] = field(default_factory=list)
groups: list[FixtureGroup] = field(default_factory=list)
functions: list[Any] = field(default_factory=list)
playback: list[str] = field(default_factory=list)
vc_size: tuple[int, int] | None = None
def __post_init__(self) -> None:
from .vc import Frame
self._fixture_seq = 0
self._function_seq = 0
self._widget_seq = 0
self._group_seq = 0
self.fixtures_by_key: dict[str, Fixture] = {}
self.functions_by_key: dict[str, Any] = {}
self.functions_by_id: dict[int, Any] = {}
project = self.root or Path(__file__).resolve().parents[1]
self.library = FixtureLibrary(project)
self.vc = Frame(self, "", root=True)
# -- allocation -------------------------------------------------------
def alloc_fixture(self) -> int:
value = self._fixture_seq
self._fixture_seq += 1
return value
def alloc_function(self) -> int:
value = self._function_seq
self._function_seq += 1
return value
def alloc_widget(self) -> int:
value = self._widget_seq
self._widget_seq += 1
return value
def _add_function(self, fn: Any) -> Any:
if fn.key in self.functions_by_key:
raise ValueError(f"duplicate function key {fn.key!r}")
self.functions.append(fn)
self.functions_by_key[fn.key] = fn
self.functions_by_id[fn.id] = fn
return fn
def fixture_id(self, fx: Fixture | int | str) -> int:
if isinstance(fx, Fixture):
return fx.id
if isinstance(fx, int) and not isinstance(fx, bool):
return fx
try:
return self.fixtures_by_key[str(fx)].id
except KeyError as exc:
raise KeyError(f"no fixture {fx!r}") from exc
# -- patch ------------------------------------------------------------
def universe(
self,
uid: int,
name: str | None = None,
*,
output: ArtNetOutput | None = None,
midi: MidiInput | None = None,
) -> Universe:
uni = Universe(int(uid), name or f"Universe {int(uid) + 1}", output, midi)
self.universes.append(uni)
return uni
def patch(
self,
manufacturer: str,
model: str,
mode: str,
*,
address: int,
name: str | None = None,
universe: int = 0,
channels: int | None = None,
key: str | None = None,
) -> Fixture:
definition = self.library.find(manufacturer, model)
mode_info = definition.mode(mode) if definition is not None else None
if channels is None:
if mode_info is None:
raise ValueError(
f"no fixture definition for {manufacturer} {model} mode {mode!r}; pass channels="
)
channels = len(mode_info.channels)
elif mode_info is not None and channels != len(mode_info.channels):
mode_info = None
fid = self.alloc_fixture()
fx_key = key or f"fixture{fid}"
if fx_key in self.fixtures_by_key:
raise ValueError(f"duplicate fixture key {fx_key!r}")
fixture = Fixture(
id=fid,
key=fx_key,
manufacturer=manufacturer,
model=model,
mode=mode,
name=name or f"{model} #{fid + 1}",
universe=int(universe),
address=int(address),
channels=int(channels),
mode_info=mode_info,
)
self.fixtures.append(fixture)
self.fixtures_by_key[fx_key] = fixture
return fixture
def group(self, name: str, fixtures: list[Fixture | str | int], *, columns: int | None = None) -> FixtureGroup:
ids = [self.fixture_id(fx) for fx in fixtures]
group = FixtureGroup(
id=self._group_seq,
name=name,
columns=columns or max(1, len(ids)),
fixture_ids=ids,
)
self._group_seq += 1
self.groups.append(group)
return group
def patch_stage(self, path: str | Path | None = None) -> Any:
"""Patch every fixture in a stage map. Keys are the map ids, such as "#1" and "M1"."""
from .stage import patch_stage
return patch_stage(self, path)
def scene(
self,
name: str,
values: dict[Any, dict[Any, int]],
*,
key: str | None = None,
fade_in: int = 0,
fade_out: int = 0,
duration: int = 0,
primary: bool = True,
) -> Scene:
norm = _channel_map(self, values)
fn_key = key or _key_for(name, self.functions_by_key)
scene = Scene(
id=self.alloc_function(),
key=fn_key,
name=name,
values=norm,
fade_in=int(fade_in),
fade_out=int(fade_out),
duration=int(duration),
primary=primary,
)
return self._add_function(scene)
def collection(
self,
name: str,
members: list[Any],
*,
key: str | None = None,
primary: bool = True,
) -> Collection:
ids = []
for member in members:
if isinstance(member, int) and not isinstance(member, bool):
ids.append(member)
elif isinstance(member, str):
ids.append(self.functions_by_key[member].id)
else:
ids.append(member.id)
fn_key = key or _key_for(name, self.functions_by_key)
coll = Collection(
id=self.alloc_function(),
key=fn_key,
name=name,
members=ids,
primary=primary,
)
return self._add_function(coll)
def function_xml(self, xml: str, *, key: str | None = None, name: str = "Function") -> RawFunction:
fid = self.alloc_function()
fn_key = key or f"function{fid}"
stamped = _stamp_function_id(xml.strip(), fid)
raw = RawFunction(id=fid, key=fn_key, name=name, xml=stamped)
return self._add_function(raw)
def run(self, *keys: str) -> None:
missing = [key for key in keys if key not in self.functions_by_key]
if missing:
raise KeyError(f"no function {missing[0]!r}")
self.playback = list(keys)
def efx(self, name: str, fixtures: list[Any], **kwargs: Any) -> Any:
from .animate import add_efx
return add_efx(self, name, fixtures, **kwargs)
def sequence(self, name: str, steps: list[Any], **kwargs: Any) -> Any:
from .animate import add_sequence
return add_sequence(self, name, steps, **kwargs)
def path_sequence(self, name: str, fixtures: list[Any], points: list[Any], **kwargs: Any) -> Any:
from .animate import add_path
return add_path(self, name, fixtures, points, **kwargs)
def chaser(self, name: str, steps: list[Any], **kwargs: Any) -> Any:
from .animate import add_chaser
return add_chaser(self, name, steps, **kwargs)
def colour_chase(self, name: str, fixtures: list[Any], channels: dict[str, int], frames: list[Any], **kwargs: Any) -> Any:
from .animate import add_colour_chase
return add_colour_chase(self, name, fixtures, channels, frames, **kwargs)
# -- output -----------------------------------------------------------
def size(self) -> tuple[int, int]:
if self.vc_size is not None:
return self.vc_size
max_x = max_y = 0
for widget in self.vc.children:
max_x = max(max_x, widget.x + widget.w)
max_y = max(max_y, widget.y + widget.h)
return max_x + 16, max_y + 16
def xml(self) -> str:
from .xml import render_show
return render_show(self)
def write(self, path: Path | str) -> Path:
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(self.xml(), encoding="utf-8")
return target
def summary(self) -> dict[str, Any]:
return {
"fixtures": {
fx.key: {
"id": fx.id,
"name": fx.name,
"address": fx.address,
"channels": fx.channels,
"universe": fx.universe,
}
for fx in self.fixtures
},
"functions": {
fn.key: {"id": fn.id, "type": fn.type, "name": fn.name}
for fn in self.functions
},
"widgets": _widgets(self.vc),
}
def _channel_map(show: Show, values: Any) -> dict[int, dict[int, int]]:
pairs = values if isinstance(values, list) else values.items()
norm: dict[int, dict[int, int]] = {}
for fx, channels in pairs:
norm[show.fixture_id(fx)] = {int(ch): int(val) for ch, val in channels.items()}
return norm
def _widgets(frame: Any) -> list[dict[str, Any]]:
found: list[dict[str, Any]] = []
for child in frame.children:
found.append({"id": child.id, "type": child.type_name, "caption": child.caption})
if child.type_name in ("Frame", "SoloFrame"):
found.extend(_widgets(child))
return found
def _key_for(name: str, existing: dict[str, Any]) -> str:
base = "".join(ch.lower() if ch.isalnum() else "-" for ch in name).strip("-") or "function"
key = base
n = 2
while key in existing:
key = f"{base}-{n}"
n += 1
return key
def _stamp_function_id(xml: str, fid: int) -> str:
import re
if re.search(r"\bID=\"\d+\"", xml):
return re.sub(r"\bID=\"\d+\"", f'ID="{fid}"', xml, count=1)
return xml.replace("<Function ", f'<Function ID="{fid}" ', 1)
def fixture_xml(fx: Fixture) -> str:
return (
" <Fixture>\n"
f" <Manufacturer>{text(fx.manufacturer)}</Manufacturer>\n"
f" <Model>{text(fx.model)}</Model>\n"
f" <Mode>{text(fx.mode)}</Mode>\n"
f" <ID>{fx.id}</ID>\n"
f" <Name>{text(fx.name)}</Name>\n"
f" <Universe>{fx.universe}</Universe>\n"
f" <Address>{fx.address}</Address>\n"
f" <Channels>{fx.channels}</Channels>\n"
" </Fixture>"
)
def group_xml(group: FixtureGroup) -> str:
columns = max(1, group.columns)
rows = max(1, (len(group.fixture_ids) + columns - 1) // columns)
heads = []
for index, fid in enumerate(group.fixture_ids):
heads.append(
f' <Head X="{index % columns}" Y="{index // columns}" Fixture="{fid}">{group.head}</Head>'
)
body = "\n".join(heads)
return (
f' <FixtureGroup ID="{group.id}">\n'
f" <Name>{text(group.name)}</Name>\n"
f' <Size X="{columns}" Y="{rows}"/>\n'
f"{body}\n"
" </FixtureGroup>"
)
def universe_xml(uni: Universe) -> str:
if uni.output is None and uni.midi is None:
return f' <Universe Name={attr(uni.name)} ID="{uni.id}"/>'
parts = [f' <Universe Name={attr(uni.name)} ID="{uni.id}">']
if uni.output is not None:
out = uni.output
parts.append(
f' <Output Plugin="ArtNet" UID={attr(out.uid)} Line="{out.line}">\n'
f' <PluginParameters outputIP={attr(out.ip)} outputUni="{out.universe}"/>\n'
" </Output>"
)
if uni.midi is not None:
midi = uni.midi
parts.append(
f' <Input Plugin="MIDI" UID={attr(midi.uid)} Line="{midi.line}" Profile={attr(midi.profile)}>\n'
f' <PluginParameters midichannel="{midi.channel}"/>\n'
" </Input>"
)
parts.append(" </Universe>")
return "\n".join(parts)
def root_appearance() -> str:
return appearance(frame="None", indent=" ")