Add a show compiler so QLC+ workspaces can be described and tested.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
fee1985e1a
commit
4374ffb430
14 files changed
+3739
No files matched your search
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"qlcplus-show": {
|
||||
"command": "python3",
|
||||
"args": ["-m", "showfile.mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Build QLC+ workspaces and play their animations."""
|
||||
|
||||
from .model import ArtNetOutput, MidiBinding, MidiInput, Show, midi_cc, midi_note
|
||||
from .play import frame_at, play
|
||||
from .spec import SpecError, from_spec, show_schema
|
||||
from .xmlutil import qlc_color
|
||||
|
||||
Show.from_spec = staticmethod(from_spec) # type: ignore[method-assign]
|
||||
|
||||
__all__ = [
|
||||
"ArtNetOutput",
|
||||
"MidiBinding",
|
||||
"MidiInput",
|
||||
"Show",
|
||||
"SpecError",
|
||||
"frame_at",
|
||||
"from_spec",
|
||||
"midi_cc",
|
||||
"midi_note",
|
||||
"play",
|
||||
"qlc_color",
|
||||
"show_schema",
|
||||
]
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Command line for the show tools. Each command prints one JSON object."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from .spec import PROJECT_ROOT
|
||||
from .tools import list_fixtures, run_script, sample_animation, show_schema, validate_show, write_show
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="showfile", description="Build and test QLC+ shows.")
|
||||
sub = parser.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
sub.add_parser("list-fixtures", help="List fixture modes and channel numbers.")
|
||||
sub.add_parser("schema", help="Print the show spec JSON Schema.")
|
||||
|
||||
validate = sub.add_parser("validate", help="Validate a show spec without writing.")
|
||||
validate.add_argument("spec")
|
||||
|
||||
write = sub.add_parser("write", help="Compile a show spec to a .qxw.")
|
||||
write.add_argument("spec")
|
||||
write.add_argument("-o", "--output", required=True)
|
||||
|
||||
sample = sub.add_parser("sample", help="Sample an efx or path block.")
|
||||
sample.add_argument("block")
|
||||
sample.add_argument("--steps", type=int, default=32)
|
||||
|
||||
run = sub.add_parser("run", help="Play a Python animation script or a JSON show.")
|
||||
run.add_argument("script")
|
||||
run.add_argument("--ip", help="Art-Net destination. Omit to print samples.")
|
||||
run.add_argument("--seconds", type=float)
|
||||
run.add_argument("--hz", type=float, default=40.0)
|
||||
run.add_argument("--universe", type=int, default=0)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
payload = _dispatch(args)
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
payload = {"ok": False, "errors": [{"path": "", "message": str(exc)}]}
|
||||
json.dump(payload, sys.stdout, indent=2)
|
||||
sys.stdout.write("\n")
|
||||
return 0 if payload.get("ok", True) else 1
|
||||
|
||||
|
||||
def _dispatch(args: argparse.Namespace) -> dict[str, Any]:
|
||||
if args.cmd == "list-fixtures":
|
||||
return list_fixtures()
|
||||
if args.cmd == "schema":
|
||||
return show_schema()
|
||||
if args.cmd == "validate":
|
||||
return validate_show(_load(args.spec))
|
||||
if args.cmd == "write":
|
||||
return write_show(_load(args.spec), args.output)
|
||||
if args.cmd == "sample":
|
||||
return sample_animation(_load(args.block), args.steps)
|
||||
if args.cmd == "run":
|
||||
return run_script(args.script, seconds=args.seconds, ip=args.ip, universe=args.universe, hz=args.hz)
|
||||
raise AssertionError(args.cmd)
|
||||
|
||||
|
||||
def _load(path: str) -> dict[str, Any]:
|
||||
source = Path(path)
|
||||
if not source.is_absolute():
|
||||
source = PROJECT_ROOT / source
|
||||
return json.loads(source.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,666 @@
|
||||
"""EFX, sequences, paths, and chasers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from patternstudio.efx import (
|
||||
ALGORITHMS,
|
||||
DIRECTIONS,
|
||||
PROPAGATIONS,
|
||||
RELATIVE_ZERO,
|
||||
RUN_ORDERS,
|
||||
Efx,
|
||||
EfxFixture,
|
||||
Path,
|
||||
PathFixture,
|
||||
PathPoint,
|
||||
clamp8,
|
||||
)
|
||||
|
||||
from .model import Show, blend_maps
|
||||
from .xmlutil import attr
|
||||
|
||||
Axis = tuple[int | None, int | None, int | None, int | None]
|
||||
|
||||
|
||||
def locate(
|
||||
steps: list[Any],
|
||||
elapsed_ms: float,
|
||||
run_order: str,
|
||||
direction: str,
|
||||
) -> tuple[int, float, int | None, float]:
|
||||
"""Return step index, fade progress, previous index, and ms into the step.
|
||||
|
||||
A looping timeline treats the last step as the fade source for the first,
|
||||
so a loop is seamless. Single Shot fades the first step up from black and
|
||||
holds the last step after the end.
|
||||
"""
|
||||
spans = [max(0, s.fade_ms) + max(0, s.hold_ms) + max(0, s.fade_out_ms) for s in steps]
|
||||
total = float(sum(spans))
|
||||
count = len(steps)
|
||||
if count == 0 or total <= 0:
|
||||
return 0, 1.0, None, 0.0
|
||||
elapsed = max(0.0, float(elapsed_ms))
|
||||
seamless = run_order != "SingleShot"
|
||||
if run_order == "SingleShot" and elapsed >= total:
|
||||
prev = count - 2 if count > 1 else None
|
||||
return count - 1, 1.0, prev, spans[-1]
|
||||
if run_order == "PingPong":
|
||||
cycle = int(elapsed // total)
|
||||
pos = elapsed % total
|
||||
if cycle % 2 == 1:
|
||||
pos = total - pos
|
||||
elif run_order == "SingleShot":
|
||||
pos = elapsed
|
||||
else:
|
||||
pos = elapsed % total
|
||||
if direction == "Backward":
|
||||
pos = total - pos
|
||||
if pos >= total:
|
||||
pos = total - 1e-6
|
||||
if pos < 0:
|
||||
pos = 0.0
|
||||
acc = 0.0
|
||||
for index, span in enumerate(spans):
|
||||
fade = max(0, steps[index].fade_ms)
|
||||
prev = None if index == 0 and not seamless else (index - 1) % count
|
||||
if pos < acc + fade or span == 0:
|
||||
prog = 1.0 if fade <= 0 else (pos - acc) / fade
|
||||
return index, min(1.0, max(0.0, prog)), prev, pos - acc
|
||||
if pos < acc + span or index == count - 1:
|
||||
return index, 1.0, prev, pos - acc
|
||||
acc += span
|
||||
return count - 1, 1.0, None, spans[-1]
|
||||
|
||||
|
||||
def _fixture(show: Show, item: Any) -> Any:
|
||||
if isinstance(item, str):
|
||||
return show.fixtures_by_key[item]
|
||||
if isinstance(item, int) and not isinstance(item, bool):
|
||||
return next(fx for fx in show.fixtures if fx.id == item)
|
||||
return item
|
||||
|
||||
|
||||
@dataclass
|
||||
class EfxFunction:
|
||||
id: int
|
||||
key: str
|
||||
name: str
|
||||
pattern: Efx
|
||||
homes: dict[int, tuple[int, int]]
|
||||
relative: bool
|
||||
axes: dict[int, Axis]
|
||||
preview: dict[int, dict[int, int]]
|
||||
primary: bool = True
|
||||
type: str = "EFX"
|
||||
|
||||
def duration_ms(self, _show: Show) -> int:
|
||||
return self.pattern.duration_ms
|
||||
|
||||
def apply(self, _show: Show, elapsed_ms: float, into: dict[int, dict[int, int]]) -> None:
|
||||
for serial, fx in enumerate(self.pattern.fixtures):
|
||||
bucket = into.setdefault(fx.id, {})
|
||||
for ch, val in self.preview.get(fx.id, {}).items():
|
||||
bucket.setdefault(ch, val)
|
||||
point = self.pattern.live_point(serial, elapsed_ms)
|
||||
if point is None:
|
||||
continue
|
||||
pan, tilt = point
|
||||
if self.relative:
|
||||
home_pan, home_tilt = self.homes.get(fx.id, (RELATIVE_ZERO, RELATIVE_ZERO))
|
||||
pan = home_pan + (pan - RELATIVE_ZERO)
|
||||
tilt = home_tilt + (tilt - RELATIVE_ZERO)
|
||||
pan_msb, pan_lsb, tilt_msb, tilt_lsb = self.axes[fx.id]
|
||||
_write_axis(bucket, pan_msb, pan_lsb, pan)
|
||||
_write_axis(bucket, tilt_msb, tilt_lsb, tilt)
|
||||
|
||||
def render(self) -> str:
|
||||
pattern = self.pattern
|
||||
fixtures = "\n".join(
|
||||
" <Fixture>\n"
|
||||
f" <ID>{fx.id}</ID>\n"
|
||||
f" <Head>{fx.head}</Head>\n"
|
||||
f" <Direction>{fx.direction}</Direction>\n"
|
||||
f" <StartOffset>{fx.start_offset}</StartOffset>\n"
|
||||
" </Fixture>"
|
||||
for fx in pattern.fixtures
|
||||
)
|
||||
return (
|
||||
f' <Function ID="{self.id}" Type="EFX" Name={attr(self.name)}>\n'
|
||||
f"{fixtures}\n"
|
||||
f" <PropagationMode>{pattern.propagation}</PropagationMode>\n"
|
||||
f' <Speed FadeIn="{pattern.fade_in_ms}" FadeOut="{pattern.fade_out_ms}" '
|
||||
f'Duration="{pattern.duration_ms}"/>\n'
|
||||
f" <Direction>{pattern.direction}</Direction>\n"
|
||||
f" <RunOrder>{pattern.run_order}</RunOrder>\n"
|
||||
f" <Algorithm>{pattern.algorithm}</Algorithm>\n"
|
||||
f" <Width>{pattern.width}</Width>\n"
|
||||
f" <Height>{pattern.height}</Height>\n"
|
||||
f" <Rotation>{pattern.rotation}</Rotation>\n"
|
||||
f" <StartOffset>{pattern.start_offset}</StartOffset>\n"
|
||||
f" <IsRelative>{1 if self.relative else 0}</IsRelative>\n"
|
||||
" <Axis Name=\"X\">\n"
|
||||
f" <Offset>{pattern.x_offset}</Offset>\n"
|
||||
f" <Frequency>{pattern.x_frequency}</Frequency>\n"
|
||||
f" <Phase>{pattern.x_phase}</Phase>\n"
|
||||
" </Axis>\n"
|
||||
" <Axis Name=\"Y\">\n"
|
||||
f" <Offset>{pattern.y_offset}</Offset>\n"
|
||||
f" <Frequency>{pattern.y_frequency}</Frequency>\n"
|
||||
f" <Phase>{pattern.y_phase}</Phase>\n"
|
||||
" </Axis>\n"
|
||||
" </Function>"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SequenceStep:
|
||||
values: dict[int, dict[int, int]]
|
||||
fade_ms: int = 0
|
||||
hold_ms: int = 0
|
||||
fade_out_ms: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class SequenceFunction:
|
||||
id: int
|
||||
key: str
|
||||
name: str
|
||||
bound_id: int
|
||||
steps: list[SequenceStep]
|
||||
direction: str = "Forward"
|
||||
run_order: str = "Loop"
|
||||
primary: bool = True
|
||||
type: str = "Sequence"
|
||||
|
||||
def duration_ms(self, _show: Show) -> int:
|
||||
return sum(step.fade_ms + step.hold_ms + step.fade_out_ms for step in self.steps)
|
||||
|
||||
def apply(self, _show: Show, elapsed_ms: float, into: dict[int, dict[int, int]]) -> None:
|
||||
index, prog, prev, _local = locate(self.steps, elapsed_ms, self.run_order, self.direction)
|
||||
if not self.steps:
|
||||
return
|
||||
current = self.steps[index].values
|
||||
previous = {} if prev is None else self.steps[prev].values
|
||||
blend_maps(into, previous, current, prog)
|
||||
|
||||
def render(self) -> str:
|
||||
lines = []
|
||||
for index, step in enumerate(self.steps):
|
||||
body, count = _step_values(step.values)
|
||||
lines.append(
|
||||
f' <Step Number="{index}" FadeIn="{step.fade_ms}" Hold="{step.hold_ms}" '
|
||||
f'FadeOut="{step.fade_out_ms}" Values="{count}">{body}</Step>'
|
||||
)
|
||||
first = self.steps[0] if self.steps else SequenceStep({})
|
||||
fade_mode, duration_mode = _speed_modes(self.steps)
|
||||
return (
|
||||
f' <Function ID="{self.id}" Type="Sequence" Name={attr(self.name)} '
|
||||
f'BoundScene="{self.bound_id}">\n'
|
||||
f' <Speed FadeIn="{first.fade_ms}" FadeOut="0" Duration="{first.fade_ms + first.hold_ms}"/>\n'
|
||||
f" <Direction>{self.direction}</Direction>\n"
|
||||
f" <RunOrder>{self.run_order}</RunOrder>\n"
|
||||
f' <SpeedModes FadeIn="{fade_mode}" FadeOut="Common" Duration="{duration_mode}"/>\n'
|
||||
+ "\n".join(lines)
|
||||
+ "\n </Function>"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ChaserStep:
|
||||
function_id: int
|
||||
fade_ms: int = 0
|
||||
hold_ms: int = 0
|
||||
fade_out_ms: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class ChaserFunction:
|
||||
id: int
|
||||
key: str
|
||||
name: str
|
||||
steps: list[ChaserStep]
|
||||
direction: str = "Forward"
|
||||
run_order: str = "Loop"
|
||||
primary: bool = True
|
||||
type: str = "Chaser"
|
||||
|
||||
def duration_ms(self, _show: Show) -> int:
|
||||
return sum(step.fade_ms + step.hold_ms + step.fade_out_ms for step in self.steps)
|
||||
|
||||
def apply(self, show: Show, elapsed_ms: float, into: dict[int, dict[int, int]]) -> None:
|
||||
from .model import Scene
|
||||
|
||||
if not self.steps:
|
||||
return
|
||||
index, prog, prev, local = locate(self.steps, elapsed_ms, self.run_order, self.direction)
|
||||
current = show.functions_by_id[self.steps[index].function_id]
|
||||
if isinstance(current, Scene):
|
||||
previous: dict[int, dict[int, int]] = {}
|
||||
if prev is not None:
|
||||
prev_fn = show.functions_by_id[self.steps[prev].function_id]
|
||||
if isinstance(prev_fn, Scene):
|
||||
previous = prev_fn.values
|
||||
else:
|
||||
prev_fn.apply(show, prev_fn.duration_ms(show), previous)
|
||||
blend_maps(into, previous, current.values, prog)
|
||||
return
|
||||
current.apply(show, local, into)
|
||||
|
||||
def render(self) -> str:
|
||||
lines = [
|
||||
f' <Step Number="{i}" FadeIn="{step.fade_ms}" Hold="{step.hold_ms}" '
|
||||
f'FadeOut="{step.fade_out_ms}">{step.function_id}</Step>'
|
||||
for i, step in enumerate(self.steps)
|
||||
]
|
||||
first = self.steps[0] if self.steps else ChaserStep(0)
|
||||
fade_mode, duration_mode = _speed_modes(self.steps)
|
||||
return (
|
||||
f' <Function ID="{self.id}" Type="Chaser" Name={attr(self.name)}>\n'
|
||||
f' <Speed FadeIn="{first.fade_ms}" FadeOut="0" Duration="{first.fade_ms + first.hold_ms}"/>\n'
|
||||
f" <Direction>{self.direction}</Direction>\n"
|
||||
f" <RunOrder>{self.run_order}</RunOrder>\n"
|
||||
f' <SpeedModes FadeIn="{fade_mode}" FadeOut="Common" Duration="{duration_mode}"/>\n'
|
||||
+ "\n".join(lines)
|
||||
+ "\n </Function>"
|
||||
)
|
||||
|
||||
|
||||
def add_efx(show: Show, name: str, fixtures: list[Any], **kwargs: Any) -> Any:
|
||||
key = kwargs.pop("key", None) or _auto_key(show, name)
|
||||
relative = bool(kwargs.pop("relative", False))
|
||||
homes_in = kwargs.pop("homes", None) or {}
|
||||
entries = [_efx_entry(show, item, homes_in) for item in fixtures]
|
||||
if not entries:
|
||||
raise ValueError("efx has no fixtures")
|
||||
for fixture, _direction, _offset, _pan, _tilt in entries:
|
||||
if fixture.pan_msb is None or fixture.tilt_msb is None:
|
||||
raise ValueError(f"{fixture.key} has no pan/tilt in mode {fixture.mode}")
|
||||
pattern = _build_efx(entries, relative=relative, **kwargs)
|
||||
homes = {fixture.id: (pan, tilt) for fixture, _d, _o, pan, tilt in entries}
|
||||
axes = {
|
||||
fixture.id: (fixture.pan_msb, fixture.pan_lsb, fixture.tilt_msb, fixture.tilt_lsb)
|
||||
for fixture, *_rest in entries
|
||||
}
|
||||
preview = {fixture.id: fixture.preview_channels() for fixture, *_rest in entries}
|
||||
if relative:
|
||||
home_values = {}
|
||||
for fixture, _d, _o, pan, tilt in entries:
|
||||
channels: dict[int, int] = {}
|
||||
if fixture.pan_msb is not None:
|
||||
channels[fixture.pan_msb] = pan
|
||||
if fixture.pan_lsb is not None:
|
||||
channels[fixture.pan_lsb] = 0
|
||||
if fixture.tilt_msb is not None:
|
||||
channels[fixture.tilt_msb] = tilt
|
||||
if fixture.tilt_lsb is not None:
|
||||
channels[fixture.tilt_lsb] = 0
|
||||
home_values[fixture.id] = channels
|
||||
show.scene(f"{name} (home)", home_values, key=f"{key}.home", primary=False)
|
||||
efx = EfxFunction(
|
||||
id=show.alloc_function(),
|
||||
key=f"{key}.efx",
|
||||
name=f"{name} (EFX)",
|
||||
pattern=pattern,
|
||||
homes=homes,
|
||||
relative=True,
|
||||
axes=axes,
|
||||
preview=preview,
|
||||
primary=False,
|
||||
)
|
||||
show._add_function(efx)
|
||||
return show.collection(name, [f"{key}.home", f"{key}.efx"], key=key, primary=True)
|
||||
efx = EfxFunction(
|
||||
id=show.alloc_function(),
|
||||
key=key,
|
||||
name=name,
|
||||
pattern=pattern,
|
||||
homes=homes,
|
||||
relative=False,
|
||||
axes=axes,
|
||||
preview=preview,
|
||||
)
|
||||
return show._add_function(efx)
|
||||
|
||||
|
||||
def add_sequence(
|
||||
show: Show,
|
||||
name: str,
|
||||
steps: list[Any],
|
||||
*,
|
||||
direction: str = "Forward",
|
||||
run_order: str = "Loop",
|
||||
key: str | None = None,
|
||||
primary: bool = True,
|
||||
) -> SequenceFunction:
|
||||
_check_choice("direction", direction, DIRECTIONS)
|
||||
_check_choice("run_order", run_order, RUN_ORDERS)
|
||||
fn_key = key or _auto_key(show, name)
|
||||
norm = [_sequence_step(show, step) for step in steps]
|
||||
if not norm:
|
||||
raise ValueError("sequence has no steps")
|
||||
show.scene(f"{name} (base)", norm[0].values, key=f"{fn_key}.base", primary=False)
|
||||
bound = show.functions_by_key[f"{fn_key}.base"]
|
||||
seq = SequenceFunction(
|
||||
id=show.alloc_function(),
|
||||
key=fn_key,
|
||||
name=name,
|
||||
bound_id=bound.id,
|
||||
steps=norm,
|
||||
direction=direction,
|
||||
run_order=run_order,
|
||||
primary=primary,
|
||||
)
|
||||
return show._add_function(seq)
|
||||
|
||||
|
||||
def add_path(
|
||||
show: Show,
|
||||
name: str,
|
||||
fixtures: list[Any],
|
||||
points: list[Any],
|
||||
*,
|
||||
smooth: bool = False,
|
||||
subdivisions: int = 6,
|
||||
closed: bool = True,
|
||||
run_order: str = "Loop",
|
||||
direction: str = "Forward",
|
||||
key: str | None = None,
|
||||
) -> SequenceFunction:
|
||||
entries = [_path_entry(show, item) for item in fixtures]
|
||||
if not entries:
|
||||
raise ValueError("path has no fixtures")
|
||||
path_points = [_path_point(point) for point in points]
|
||||
if len(path_points) < 1:
|
||||
raise ValueError("path has no points")
|
||||
for fixture, *_rest in entries:
|
||||
if fixture.pan_msb is None or fixture.tilt_msb is None:
|
||||
raise ValueError(f"{fixture.key} has no pan/tilt in mode {fixture.mode}")
|
||||
path = Path(
|
||||
points=path_points,
|
||||
smooth=smooth,
|
||||
subdivisions=int(subdivisions),
|
||||
closed=closed,
|
||||
run_order=run_order,
|
||||
direction=direction,
|
||||
fixtures=[
|
||||
PathFixture(
|
||||
id=fixture.id,
|
||||
pan_offset=pan_offset,
|
||||
tilt_offset=tilt_offset,
|
||||
mirror_pan=mirror_pan,
|
||||
mirror_tilt=mirror_tilt,
|
||||
)
|
||||
for fixture, pan_offset, tilt_offset, mirror_pan, mirror_tilt in entries
|
||||
],
|
||||
)
|
||||
resolved = path.steps()
|
||||
by_id = {fixture.id: fixture for fixture, *_rest in entries}
|
||||
steps = []
|
||||
for point in resolved:
|
||||
values: dict[int, dict[int, int]] = {}
|
||||
for cfg in path.fixtures:
|
||||
fixture = by_id[cfg.id]
|
||||
pan, tilt = cfg.apply(point.pan, point.tilt)
|
||||
channels: dict[int, int] = {}
|
||||
_write_axis(channels, fixture.pan_msb, fixture.pan_lsb, pan)
|
||||
_write_axis(channels, fixture.tilt_msb, fixture.tilt_lsb, tilt)
|
||||
values[fixture.id] = channels
|
||||
steps.append(SequenceStep(values, fade_ms=point.fade_ms, hold_ms=point.hold_ms))
|
||||
return add_sequence(show, name, steps, direction=direction, run_order=run_order, key=key)
|
||||
|
||||
|
||||
def add_chaser(
|
||||
show: Show,
|
||||
name: str,
|
||||
steps: list[Any],
|
||||
*,
|
||||
direction: str = "Forward",
|
||||
run_order: str = "Loop",
|
||||
key: str | None = None,
|
||||
primary: bool = True,
|
||||
) -> ChaserFunction:
|
||||
_check_choice("direction", direction, DIRECTIONS)
|
||||
_check_choice("run_order", run_order, RUN_ORDERS)
|
||||
norm = [_chaser_step(show, step) for step in steps]
|
||||
if not norm:
|
||||
raise ValueError("chaser has no steps")
|
||||
fn_key = key or _auto_key(show, name)
|
||||
chaser = ChaserFunction(
|
||||
id=show.alloc_function(),
|
||||
key=fn_key,
|
||||
name=name,
|
||||
steps=norm,
|
||||
direction=direction,
|
||||
run_order=run_order,
|
||||
primary=primary,
|
||||
)
|
||||
return show._add_function(chaser)
|
||||
|
||||
|
||||
def add_colour_chase(
|
||||
show: Show,
|
||||
name: str,
|
||||
fixtures: list[Any],
|
||||
channels: dict[str, int],
|
||||
frames: list[Any],
|
||||
*,
|
||||
fade_ms: int = 0,
|
||||
hold_ms: int = 0,
|
||||
run_order: str = "Loop",
|
||||
key: str | None = None,
|
||||
) -> ChaserFunction:
|
||||
if not frames:
|
||||
raise ValueError("colour chase has no frames")
|
||||
fn_key = key or _auto_key(show, name)
|
||||
names = list(channels)
|
||||
scene_keys = []
|
||||
for index, frame in enumerate(frames):
|
||||
if len(frame) != len(fixtures):
|
||||
raise ValueError(f"frame {index} has {len(frame)} colours for {len(fixtures)} fixtures")
|
||||
values: dict[int, dict[int, int]] = {}
|
||||
for fixture_item, colour in zip(fixtures, frame):
|
||||
fixture = _fixture(show, fixture_item)
|
||||
if isinstance(colour, dict):
|
||||
values[fixture.id] = {int(ch): int(val) for ch, val in colour.items()}
|
||||
else:
|
||||
if len(colour) != len(names):
|
||||
raise ValueError(
|
||||
f"frame {index} colour has {len(colour)} values for channels {names}"
|
||||
)
|
||||
values[fixture.id] = {int(channels[names[i]]): int(colour[i]) for i in range(len(names))}
|
||||
scene_key = f"{fn_key}.{index}"
|
||||
show.scene(f"{name} {index + 1}", values, key=scene_key, primary=False)
|
||||
scene_keys.append(scene_key)
|
||||
steps = [
|
||||
ChaserStep(show.functions_by_key[scene_key].id, fade_ms=int(fade_ms), hold_ms=int(hold_ms))
|
||||
for scene_key in scene_keys
|
||||
]
|
||||
return add_chaser(show, name, steps, run_order=run_order, key=fn_key)
|
||||
|
||||
|
||||
def _write_axis(bucket: dict[int, int], msb: int | None, lsb: int | None, value: float) -> None:
|
||||
if msb is not None:
|
||||
bucket[msb] = clamp8(value)
|
||||
if lsb is not None:
|
||||
bucket[lsb] = clamp8((value - int(value)) * 255)
|
||||
|
||||
|
||||
def _step_values(values: dict[int, dict[int, int]]) -> tuple[str, int]:
|
||||
chunks = []
|
||||
count = 0
|
||||
for fid, channels in sorted(values.items()):
|
||||
if not channels:
|
||||
continue
|
||||
count += len(channels)
|
||||
body = ",".join(f"{ch},{val}" for ch, val in sorted(channels.items()))
|
||||
chunks.append(f"{fid}:{body}")
|
||||
return ":".join(chunks), count
|
||||
|
||||
|
||||
def _speed_modes(steps: list[Any]) -> tuple[str, str]:
|
||||
if not steps:
|
||||
return "Common", "Common"
|
||||
first = (steps[0].fade_ms, steps[0].hold_ms, steps[0].fade_out_ms)
|
||||
if all((step.fade_ms, step.hold_ms, step.fade_out_ms) == first for step in steps):
|
||||
return "Common", "Common"
|
||||
return "PerStep", "PerStep"
|
||||
|
||||
|
||||
def _check_choice(label: str, value: str, allowed: tuple[str, ...]) -> None:
|
||||
if value not in allowed:
|
||||
raise ValueError(f"{label} must be one of {', '.join(allowed)}")
|
||||
|
||||
|
||||
def _check_range(label: str, value: int, lo: int, hi: int) -> int:
|
||||
number = int(value)
|
||||
if not lo <= number <= hi:
|
||||
raise ValueError(f"{label} must be {lo}–{hi}")
|
||||
return number
|
||||
|
||||
|
||||
def _build_efx(entries: list[tuple[Any, str, int, int, int]], *, relative: bool, **kwargs: Any) -> Efx:
|
||||
algorithm = kwargs.get("algorithm", "Circle")
|
||||
_check_choice("algorithm", algorithm, ALGORITHMS)
|
||||
direction = kwargs.get("direction", "Forward")
|
||||
run_order = kwargs.get("run_order", "Loop")
|
||||
propagation = kwargs.get("propagation", "Parallel")
|
||||
_check_choice("direction", direction, DIRECTIONS)
|
||||
_check_choice("run_order", run_order, RUN_ORDERS)
|
||||
_check_choice("propagation", propagation, PROPAGATIONS)
|
||||
duration = int(kwargs.get("duration_ms", 8000))
|
||||
if duration < 20:
|
||||
raise ValueError("duration_ms must be at least 20")
|
||||
x_offset = RELATIVE_ZERO if relative else _check_range("x_offset", kwargs.get("x_offset", 128), 0, 255)
|
||||
y_offset = RELATIVE_ZERO if relative else _check_range("y_offset", kwargs.get("y_offset", 128), 0, 255)
|
||||
return Efx(
|
||||
algorithm=algorithm,
|
||||
width=_check_range("width", kwargs.get("width", 40), 0, 127),
|
||||
height=_check_range("height", kwargs.get("height", 40), 0, 127),
|
||||
rotation=int(kwargs.get("rotation", 0)) % 360,
|
||||
start_offset=int(kwargs.get("start_offset", 0)) % 360,
|
||||
x_offset=x_offset,
|
||||
y_offset=y_offset,
|
||||
x_frequency=_check_range("x_frequency", kwargs.get("x_frequency", 1), 0, 5),
|
||||
y_frequency=_check_range("y_frequency", kwargs.get("y_frequency", 1), 0, 5),
|
||||
x_phase=int(kwargs.get("x_phase", 0)) % 360,
|
||||
y_phase=int(kwargs.get("y_phase", 0)) % 360,
|
||||
duration_ms=duration,
|
||||
fade_in_ms=max(0, int(kwargs.get("fade_in_ms", 0))),
|
||||
fade_out_ms=max(0, int(kwargs.get("fade_out_ms", 0))),
|
||||
direction=direction,
|
||||
run_order=run_order,
|
||||
propagation=propagation,
|
||||
relative=relative,
|
||||
fixtures=[
|
||||
EfxFixture(id=fixture.id, direction=direction, start_offset=offset, pan=pan, tilt=tilt)
|
||||
for fixture, direction, offset, pan, tilt in entries
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def _efx_entry(show: Show, item: Any, homes: dict[Any, Any]) -> tuple[Any, str, int, int, int]:
|
||||
if isinstance(item, str) or (isinstance(item, int) and not isinstance(item, bool)):
|
||||
fixture = _fixture(show, item)
|
||||
direction, offset, pan, tilt = "Forward", 0, 128, 128
|
||||
home_key: Any = item
|
||||
elif hasattr(item, "pan_msb"):
|
||||
fixture = item
|
||||
direction, offset, pan, tilt = "Forward", 0, 128, 128
|
||||
home_key = fixture.key
|
||||
else:
|
||||
fixture = _fixture(show, item["fixture"])
|
||||
direction = item.get("direction", "Forward")
|
||||
offset = int(item.get("start_offset", 0))
|
||||
pan = int(item.get("pan", 128))
|
||||
tilt = int(item.get("tilt", 128))
|
||||
home_key = item["fixture"]
|
||||
home = _home_for(homes, fixture, home_key)
|
||||
if home is not None:
|
||||
pan, tilt = int(home[0]), int(home[1])
|
||||
return fixture, direction, offset, pan, tilt
|
||||
|
||||
|
||||
def _home_for(homes: dict[Any, Any], fixture: Any, home_key: Any) -> Any:
|
||||
if not homes:
|
||||
return None
|
||||
for candidate in (home_key, fixture.key, fixture.id):
|
||||
if candidate in homes:
|
||||
return homes[candidate]
|
||||
for key, value in homes.items():
|
||||
if key is fixture:
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def _sequence_step(show: Show, step: Any) -> SequenceStep:
|
||||
if isinstance(step, SequenceStep):
|
||||
values = {
|
||||
show.fixture_id(fid): {int(ch): int(val) for ch, val in channels.items()}
|
||||
for fid, channels in step.values.items()
|
||||
}
|
||||
return SequenceStep(values, step.fade_ms, step.hold_ms, step.fade_out_ms)
|
||||
values = {
|
||||
show.fixture_id(fid): {int(ch): int(val) for ch, val in channels.items()}
|
||||
for fid, channels in step["values"].items()
|
||||
}
|
||||
return SequenceStep(
|
||||
values,
|
||||
fade_ms=int(step.get("fade_ms", 0)),
|
||||
hold_ms=int(step.get("hold_ms", 0)),
|
||||
fade_out_ms=int(step.get("fade_out_ms", 0)),
|
||||
)
|
||||
|
||||
|
||||
def _path_entry(show: Show, item: Any) -> tuple[Any, int, int, bool, bool]:
|
||||
if isinstance(item, str) or hasattr(item, "pan_msb"):
|
||||
return _fixture(show, item), 0, 0, False, False
|
||||
return (
|
||||
_fixture(show, item["fixture"]),
|
||||
int(item.get("pan_offset", 0)),
|
||||
int(item.get("tilt_offset", 0)),
|
||||
bool(item.get("mirror_pan", False)),
|
||||
bool(item.get("mirror_tilt", False)),
|
||||
)
|
||||
|
||||
|
||||
def _path_point(point: Any) -> PathPoint:
|
||||
if isinstance(point, PathPoint):
|
||||
return point
|
||||
return PathPoint(
|
||||
pan=float(point["pan"]),
|
||||
tilt=float(point["tilt"]),
|
||||
fade_ms=int(point.get("fade_ms", 1000)),
|
||||
hold_ms=int(point.get("hold_ms", 0)),
|
||||
)
|
||||
|
||||
|
||||
def _chaser_step(show: Show, step: Any) -> ChaserStep:
|
||||
if isinstance(step, ChaserStep):
|
||||
return ChaserStep(_function_id(show, step.function_id), step.fade_ms, step.hold_ms, step.fade_out_ms)
|
||||
if isinstance(step, tuple):
|
||||
function, fade, hold = step[0], step[1], step[2] if len(step) > 2 else 0
|
||||
fade_out = step[3] if len(step) > 3 else 0
|
||||
return ChaserStep(_function_id(show, function), int(fade), int(hold), int(fade_out))
|
||||
return ChaserStep(
|
||||
_function_id(show, step["function"] if isinstance(step, dict) else step),
|
||||
fade_ms=int(step.get("fade_ms", 0)) if isinstance(step, dict) else 0,
|
||||
hold_ms=int(step.get("hold_ms", 0)) if isinstance(step, dict) else 0,
|
||||
fade_out_ms=int(step.get("fade_out_ms", 0)) if isinstance(step, dict) else 0,
|
||||
)
|
||||
|
||||
|
||||
def _function_id(show: Show, function: Any) -> int:
|
||||
if isinstance(function, int) and not isinstance(function, bool):
|
||||
return function
|
||||
if isinstance(function, str):
|
||||
return show.functions_by_key[function].id
|
||||
return function.id
|
||||
|
||||
|
||||
def _auto_key(show: Show, name: str) -> str:
|
||||
from .model import _key_for
|
||||
|
||||
return _key_for(name, show.functions_by_key)
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
"""MCP stdio server for the show tools.
|
||||
|
||||
Cursor starts this with `python3 -m showfile.mcp`. The process speaks MCP
|
||||
over Content-Length framing and does not require the third-party mcp package.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
from .tools import list_fixtures, run_script, sample_animation, show_schema, validate_show, write_show
|
||||
|
||||
_TOOLS = [
|
||||
{
|
||||
"name": "list_fixtures",
|
||||
"description": (
|
||||
"List fixture definitions in fixtures/. Each mode includes channel index, name, "
|
||||
"preset, and which channels are pan and tilt. Use these channel numbers in a show spec."
|
||||
),
|
||||
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
|
||||
},
|
||||
{
|
||||
"name": "show_schema",
|
||||
"description": "Return the JSON Schema for a QLC+ show spec. Keys are strings; ids are assigned on write.",
|
||||
"inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
|
||||
},
|
||||
{
|
||||
"name": "validate_show",
|
||||
"description": (
|
||||
"Validate a show spec. Returns {ok, errors: [{path, message}]} and writes nothing. "
|
||||
"Error paths look like functions.eight.fixtures."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {"spec": {"type": "object", "description": "Show spec."}},
|
||||
"required": ["spec"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "write_show",
|
||||
"description": (
|
||||
"Write a show spec to a .qxw inside the project. Returns {ok, path, fixtures, functions, widgets} "
|
||||
"with the QLC+ ids that were assigned. Refuses paths outside the project."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"spec": {"type": "object"},
|
||||
"path": {"type": "string", "description": "Project-relative .qxw path, for example shows/look.qxw."},
|
||||
},
|
||||
"required": ["spec", "path"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "sample_animation",
|
||||
"description": (
|
||||
"Sample pan/tilt for one efx or path block so the shape can be checked before writing a show. "
|
||||
"Returns tracks of points. Relative EFX points are the fixture's real pan/tilt, including its home."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"block": {"type": "object", "description": "An efx or path function object."},
|
||||
"steps": {"type": "integer", "minimum": 1, "maximum": 128, "description": "EFX samples along one loop. Default 32."},
|
||||
},
|
||||
"required": ["block"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "run_animation",
|
||||
"description": (
|
||||
"Run an animation Python script (a file that defines build() -> Show) or a JSON show spec. "
|
||||
"Without ip, returns DMX samples for testing and sends nothing. "
|
||||
"With ip, streams Art-Net for `seconds` (or until the client cancels — prefer a short seconds value)."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {"type": "string", "description": "Project-relative .py script or .json spec."},
|
||||
"seconds": {"type": "number"},
|
||||
"ip": {"type": "string", "description": "Art-Net destination. Omit for a dry run."},
|
||||
"universe": {"type": "integer"},
|
||||
"hz": {"type": "number"},
|
||||
},
|
||||
"required": ["path"],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def serve() -> None:
|
||||
framed = False
|
||||
while True:
|
||||
message, framed = _read(framed)
|
||||
if message is None:
|
||||
return
|
||||
response = _handle(message)
|
||||
if response is not None:
|
||||
_write(response, framed)
|
||||
|
||||
|
||||
def _handle(message: dict[str, Any]) -> dict[str, Any] | None:
|
||||
method = message.get("method")
|
||||
mid = message.get("id")
|
||||
if method == "notifications/initialized" or method and method.startswith("notifications/"):
|
||||
return None
|
||||
if method == "initialize":
|
||||
return _result(
|
||||
mid,
|
||||
{
|
||||
"protocolVersion": "2024-11-05",
|
||||
"capabilities": {"tools": {"listChanged": False}},
|
||||
"serverInfo": {"name": "qlcplus-show", "version": "1.0.0"},
|
||||
},
|
||||
)
|
||||
if method == "ping":
|
||||
return _result(mid, {})
|
||||
if method == "tools/list":
|
||||
return _result(mid, {"tools": _TOOLS})
|
||||
if method == "tools/call":
|
||||
params = message.get("params") or {}
|
||||
try:
|
||||
payload = _call(str(params.get("name")), params.get("arguments") or {})
|
||||
return _result(mid, {"content": [{"type": "text", "text": json.dumps(payload, indent=2)}], "isError": False})
|
||||
except Exception as exc: # noqa: BLE001 — reported to the MCP client
|
||||
return _result(mid, {"content": [{"type": "text", "text": str(exc)}], "isError": True})
|
||||
if mid is not None:
|
||||
return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": f"unknown method {method}"}}
|
||||
return None
|
||||
|
||||
|
||||
def _call(name: str, arguments: dict[str, Any]) -> Any:
|
||||
if name == "list_fixtures":
|
||||
return list_fixtures()
|
||||
if name == "show_schema":
|
||||
return show_schema()
|
||||
if name == "validate_show":
|
||||
return validate_show(arguments["spec"])
|
||||
if name == "write_show":
|
||||
return write_show(arguments["spec"], arguments["path"])
|
||||
if name == "sample_animation":
|
||||
return sample_animation(arguments["block"], int(arguments.get("steps", 32)))
|
||||
if name == "run_animation":
|
||||
return run_script(
|
||||
arguments["path"],
|
||||
seconds=arguments.get("seconds"),
|
||||
ip=arguments.get("ip"),
|
||||
universe=int(arguments.get("universe", 0)),
|
||||
hz=float(arguments.get("hz", 40)),
|
||||
)
|
||||
raise KeyError(f"unknown tool {name}")
|
||||
|
||||
|
||||
def _result(mid: Any, result: Any) -> dict[str, Any]:
|
||||
return {"jsonrpc": "2.0", "id": mid, "result": result}
|
||||
|
||||
|
||||
def _read(framed: bool) -> tuple[dict[str, Any] | None, bool]:
|
||||
line = sys.stdin.buffer.readline()
|
||||
if not line:
|
||||
return None, framed
|
||||
if line.lower().startswith(b"content-length:"):
|
||||
length = int(line.split(b":", 1)[1].strip())
|
||||
while True:
|
||||
header = sys.stdin.buffer.readline()
|
||||
if header in (b"\r\n", b"\n", b""):
|
||||
break
|
||||
body = sys.stdin.buffer.read(length)
|
||||
return json.loads(body), True
|
||||
if not line.strip():
|
||||
return _read(framed)
|
||||
return json.loads(line), framed
|
||||
|
||||
|
||||
def _write(message: dict[str, Any], framed: bool) -> None:
|
||||
data = json.dumps(message).encode()
|
||||
if framed:
|
||||
sys.stdout.buffer.write(f"Content-Length: {len(data)}\r\n\r\n".encode() + data)
|
||||
else:
|
||||
sys.stdout.buffer.write(data + b"\n")
|
||||
sys.stdout.buffer.flush()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve()
|
||||
@@ -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=" ")
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Play a show's animations without QLC+.
|
||||
|
||||
Dry-run returns DMX samples. Pass an IP to send Art-Net. A Python script
|
||||
exposes this by defining build() -> Show and calling script_main(build).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import importlib.util
|
||||
import json
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from patternstudio.artnet import ARTNET_PORT, build_artdmx
|
||||
|
||||
from .model import Show
|
||||
from .spec import SpecError, from_spec
|
||||
|
||||
|
||||
def active_keys(show: Show, keys: list[str] | None = None) -> list[str]:
|
||||
if keys is not None:
|
||||
return list(keys)
|
||||
if show.playback:
|
||||
return list(show.playback)
|
||||
return [fn.key for fn in show.functions if getattr(fn, "primary", False)]
|
||||
|
||||
|
||||
def frame_at(show: Show, elapsed_ms: float, keys: list[str] | None = None) -> dict[str, dict[int, int]]:
|
||||
"""Fixture key → channel → value at `elapsed_ms` for the functions being played."""
|
||||
into: dict[int, dict[int, int]] = {}
|
||||
for key in active_keys(show, keys):
|
||||
show.functions_by_key[key].apply(show, elapsed_ms, into)
|
||||
names = {fx.id: fx.key for fx in show.fixtures}
|
||||
return {names[fid]: dict(channels) for fid, channels in into.items() if fid in names}
|
||||
|
||||
|
||||
def dmx_frames(show: Show, values: dict[str, dict[int, int]]) -> dict[int, bytearray]:
|
||||
"""QLC+ universe → 512-channel frame."""
|
||||
frames: dict[int, bytearray] = {}
|
||||
for key, channels in values.items():
|
||||
fixture = show.fixtures_by_key[key]
|
||||
frame = frames.setdefault(fixture.universe, bytearray(512))
|
||||
for channel, value in channels.items():
|
||||
slot = fixture.address + int(channel)
|
||||
if 0 <= slot < 512:
|
||||
frame[slot] = max(0, min(255, int(value)))
|
||||
return frames
|
||||
|
||||
|
||||
def sample_playback(show: Show, *, seconds: float | None = None, hz: float = 40.0) -> dict[str, Any]:
|
||||
keys = active_keys(show)
|
||||
if seconds is None:
|
||||
duration = max((show.functions_by_key[key].duration_ms(show) for key in keys), default=0)
|
||||
times = [0] if duration <= 0 else [int(duration * i / 4) for i in range(4)]
|
||||
if duration > 0:
|
||||
times.append(max(0, duration - 1))
|
||||
else:
|
||||
count = max(1, int(float(seconds) * hz))
|
||||
times = [int(i * (1000.0 / hz)) for i in range(min(count, 500))]
|
||||
duration = int(float(seconds) * 1000)
|
||||
return {
|
||||
"ok": True,
|
||||
"functions": keys,
|
||||
"duration_ms": duration,
|
||||
"samples": [{"time_ms": t, "values": frame_at(show, t, keys)} for t in times],
|
||||
}
|
||||
|
||||
|
||||
def play(
|
||||
show: Show,
|
||||
*,
|
||||
seconds: float | None = None,
|
||||
ip: str | None = None,
|
||||
universe: int = 0,
|
||||
hz: float = 40.0,
|
||||
) -> dict[str, Any]:
|
||||
"""Sample the running functions, or stream them as Art-Net when `ip` is set."""
|
||||
if not ip:
|
||||
return sample_playback(show, seconds=seconds, hz=hz)
|
||||
return _send(show, ip=ip, universe=universe, seconds=seconds, hz=hz)
|
||||
|
||||
|
||||
def load_show(path: Path | str) -> Show:
|
||||
"""Load a show from a build() script or a JSON spec."""
|
||||
source = Path(path).resolve()
|
||||
if source.suffix == ".json":
|
||||
return from_spec(json.loads(source.read_text(encoding="utf-8")))
|
||||
spec = importlib.util.spec_from_file_location(f"showfile_script_{source.stem}", source)
|
||||
if spec is None or spec.loader is None:
|
||||
raise SpecError([{"path": str(source), "message": "could not load the script"}])
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
if not hasattr(module, "build"):
|
||||
raise SpecError([{"path": str(source), "message": "script must define build() -> Show"}])
|
||||
show = module.build()
|
||||
if not isinstance(show, Show):
|
||||
raise SpecError([{"path": str(source), "message": "build() must return a Show"}])
|
||||
return show
|
||||
|
||||
|
||||
def script_main(build: Any, argv: list[str] | None = None) -> None:
|
||||
"""Entry point for `python animation.py`. Prints one JSON object."""
|
||||
args = _parser().parse_args(argv)
|
||||
_emit(play(build(), seconds=args.seconds, ip=args.ip, universe=args.universe, hz=args.hz))
|
||||
|
||||
|
||||
def _parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(description="Play this animation and print DMX samples, or send Art-Net.")
|
||||
parser.add_argument("--ip", help="Art-Net destination. Omit to print samples and exit.")
|
||||
parser.add_argument("--seconds", type=float, help="How long to play. Omit with --ip to run until Ctrl+C.")
|
||||
parser.add_argument("--hz", type=float, default=40.0)
|
||||
parser.add_argument("--universe", type=int, default=0, help="Art-Net universe for QLC+ universe 0.")
|
||||
return parser
|
||||
|
||||
|
||||
def _emit(payload: dict[str, Any]) -> None:
|
||||
json.dump(payload, sys.stdout, indent=2)
|
||||
sys.stdout.write("\n")
|
||||
|
||||
|
||||
def _send(show: Show, *, ip: str, universe: int, seconds: float | None, hz: float) -> dict[str, Any]:
|
||||
keys = active_keys(show)
|
||||
period = 1.0 / hz if hz > 0 else 0.025
|
||||
print(
|
||||
f"Art-Net {ip} universe {universe} {', '.join(keys) or '(no functions)'} (Ctrl+C to stop)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||
sequence = 1
|
||||
sent = 0
|
||||
stopped = False
|
||||
started = time.monotonic()
|
||||
try:
|
||||
while True:
|
||||
elapsed_ms = (time.monotonic() - started) * 1000.0
|
||||
if seconds is not None and elapsed_ms >= seconds * 1000.0:
|
||||
break
|
||||
frames = dmx_frames(show, frame_at(show, elapsed_ms, keys))
|
||||
if not frames:
|
||||
frames = {0: bytearray(512)}
|
||||
for qlc_universe, frame in frames.items():
|
||||
packet = build_artdmx(bytes(frame), universe + qlc_universe, sequence)
|
||||
sock.sendto(packet, (ip, ARTNET_PORT))
|
||||
sequence = 1 if sequence >= 255 else sequence + 1
|
||||
sent += 1
|
||||
time.sleep(period)
|
||||
except KeyboardInterrupt:
|
||||
stopped = True
|
||||
finally:
|
||||
for qlc_universe in dmx_frames(show, frame_at(show, 0, keys)) or {0: bytearray()}:
|
||||
for _ in range(3):
|
||||
sock.sendto(build_artdmx(bytes(512), universe + qlc_universe, sequence), (ip, ARTNET_PORT))
|
||||
sequence = 1 if sequence >= 255 else sequence + 1
|
||||
sock.close()
|
||||
return {"ok": True, "ip": ip, "universe": universe, "functions": keys, "frames": sent, "stopped": stopped}
|
||||
@@ -0,0 +1,862 @@
|
||||
"""JSON show spec: schema, validation, and Show.from_spec."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from patternstudio.efx import ALGORITHMS, DIRECTIONS, PROPAGATIONS, RUN_ORDERS
|
||||
from patternstudio.fixturedefs import FixtureLibrary
|
||||
|
||||
from .model import ArtNetOutput, MidiBinding, MidiInput, Show, midi_cc, midi_note
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class SpecError(Exception):
|
||||
def __init__(self, errors: list[dict[str, str]]):
|
||||
self.errors = errors
|
||||
detail = "; ".join(f"{item['path']}: {item['message']}" for item in errors)
|
||||
super().__init__(detail or "invalid show spec")
|
||||
|
||||
|
||||
def show_schema() -> dict[str, Any]:
|
||||
"""JSON Schema for the document accepted by validate_show and write_show."""
|
||||
return {
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "qlcplus://show",
|
||||
"title": "QLC+ show",
|
||||
"type": "object",
|
||||
"description": (
|
||||
"A QLC+ workspace. Fixture, function, and widget ids are assigned on write. "
|
||||
"Refer to fixtures and functions by their string keys. Channel numbers come from list_fixtures. "
|
||||
"Addresses are 0-based, matching QLC+ (address 87 is DMX channel 88). "
|
||||
"Set stage to a stage map path to patch that rig; fixture keys are the map ids."
|
||||
),
|
||||
"properties": {
|
||||
"stage": {
|
||||
"type": "string",
|
||||
"description": "Stage map inside the project, for example stage/map.json. Patches every fixture before fixtures.",
|
||||
},
|
||||
"author": {"type": "string"},
|
||||
"vc_size": {
|
||||
"type": "array",
|
||||
"items": {"type": "integer"},
|
||||
"minItems": 2,
|
||||
"maxItems": 2,
|
||||
"description": "Virtual console width and height. Omitted means fit the widgets plus a 16px margin.",
|
||||
},
|
||||
"run": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Function keys to play when the show is run as a script. Defaults to every top-level function.",
|
||||
},
|
||||
"universes": {"type": "array", "items": {"$ref": "#/$defs/universe"}},
|
||||
"fixtures": {"type": "array", "items": {"$ref": "#/$defs/fixture"}},
|
||||
"groups": {"type": "array", "items": {"$ref": "#/$defs/group"}},
|
||||
"functions": {"type": "array", "items": {"$ref": "#/$defs/function"}},
|
||||
"vc": {"type": "array", "items": {"$ref": "#/$defs/widget"}},
|
||||
},
|
||||
"$defs": {
|
||||
"universe": {
|
||||
"type": "object",
|
||||
"required": ["id"],
|
||||
"properties": {
|
||||
"id": {"type": "integer", "minimum": 0},
|
||||
"name": {"type": "string"},
|
||||
"output": {
|
||||
"type": "object",
|
||||
"required": ["uid", "ip"],
|
||||
"properties": {
|
||||
"plugin": {"const": "ArtNet"},
|
||||
"uid": {"type": "string"},
|
||||
"ip": {"type": "string"},
|
||||
"universe": {"type": "integer"},
|
||||
"line": {"type": "integer"},
|
||||
},
|
||||
},
|
||||
"input": {
|
||||
"type": "object",
|
||||
"required": ["uid", "profile"],
|
||||
"properties": {
|
||||
"plugin": {"const": "MIDI"},
|
||||
"uid": {"type": "string"},
|
||||
"profile": {"type": "string"},
|
||||
"channel": {"type": "integer", "description": "QLC+ MIDI plugin channel. 16 is omni."},
|
||||
"line": {"type": "integer"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"fixture": {
|
||||
"type": "object",
|
||||
"required": ["key", "manufacturer", "model", "mode", "address"],
|
||||
"properties": {
|
||||
"key": {"type": "string"},
|
||||
"manufacturer": {"type": "string"},
|
||||
"model": {"type": "string"},
|
||||
"mode": {"type": "string"},
|
||||
"name": {"type": "string"},
|
||||
"universe": {"type": "integer"},
|
||||
"address": {"type": "integer", "minimum": 0},
|
||||
"channels": {"type": "integer", "minimum": 1, "description": "Required only when the fixture is not in the library."},
|
||||
},
|
||||
},
|
||||
"group": {
|
||||
"type": "object",
|
||||
"required": ["name", "fixtures"],
|
||||
"properties": {
|
||||
"name": {"type": "string"},
|
||||
"fixtures": {"type": "array", "items": {"type": "string"}},
|
||||
"columns": {"type": "integer", "minimum": 1},
|
||||
},
|
||||
},
|
||||
"function": {
|
||||
"type": "object",
|
||||
"required": ["key", "type", "name"],
|
||||
"description": "type is scene, efx, sequence, path, chaser, colour_chase, or collection.",
|
||||
"properties": {
|
||||
"key": {"type": "string"},
|
||||
"type": {"enum": ["scene", "efx", "sequence", "path", "chaser", "colour_chase", "collection"]},
|
||||
"name": {"type": "string"},
|
||||
},
|
||||
},
|
||||
"widget": {
|
||||
"type": "object",
|
||||
"required": ["type", "caption", "x", "y", "w", "h"],
|
||||
"properties": {
|
||||
"type": {"enum": ["slider", "button", "xypad", "frame", "solo"]},
|
||||
"caption": {"type": "string"},
|
||||
"x": {"type": "integer"},
|
||||
"y": {"type": "integer"},
|
||||
"w": {"type": "integer"},
|
||||
"h": {"type": "integer"},
|
||||
"fg": {"$ref": "#/$defs/colour"},
|
||||
"bg": {"$ref": "#/$defs/colour"},
|
||||
"function": {"type": "string", "description": "Function key for a button."},
|
||||
"fixture": {"type": "string", "description": "Fixture key for an XY pad."},
|
||||
"channels": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "array",
|
||||
"prefixItems": [{"type": "string"}, {"type": "integer"}],
|
||||
"minItems": 2,
|
||||
"maxItems": 2,
|
||||
},
|
||||
},
|
||||
"input": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"universe": {"type": "integer"},
|
||||
"note": {"type": "array", "items": {"type": "integer"}, "minItems": 2, "maxItems": 2},
|
||||
"cc": {"type": "array", "items": {"type": "integer"}, "minItems": 2, "maxItems": 2},
|
||||
"channel": {"type": "integer"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"colour": {
|
||||
"description": "[r, g, b], or the string Default, or a QLC+ ARGB decimal.",
|
||||
"oneOf": [
|
||||
{"type": "array", "items": {"type": "integer"}, "minItems": 3, "maxItems": 3},
|
||||
{"type": "string"},
|
||||
{"type": "integer"},
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def validate(data: Any, *, root: Path | None = None) -> None:
|
||||
errors = collect_errors(data, root=root)
|
||||
if errors:
|
||||
raise SpecError(errors)
|
||||
|
||||
|
||||
def collect_errors(data: Any, *, root: Path | None = None) -> list[dict[str, str]]:
|
||||
errors: list[dict[str, str]] = []
|
||||
if not isinstance(data, dict):
|
||||
return [{"path": "", "message": "show spec must be an object"}]
|
||||
project = root or PROJECT_ROOT
|
||||
library = FixtureLibrary(project)
|
||||
_check_universes(data.get("universes", []), errors)
|
||||
fixtures = _check_stage(data.get("stage", None), project, library, errors)
|
||||
for key, info in _check_fixtures(data.get("fixtures", []), library, errors).items():
|
||||
if key in fixtures:
|
||||
_err(errors, f"fixtures.{key}", "duplicate fixture key")
|
||||
else:
|
||||
fixtures[key] = info
|
||||
keys = set(fixtures)
|
||||
_check_groups(data.get("groups", []), keys, errors)
|
||||
functions = data.get("functions", [])
|
||||
fn_keys = _check_functions(functions, fixtures, errors)
|
||||
_check_widgets(data.get("vc", []), keys, fn_keys, fixtures, errors, "vc")
|
||||
run = data.get("run", [])
|
||||
if run is not None and not isinstance(run, list):
|
||||
_err(errors, "run", "must be a list of function keys")
|
||||
elif isinstance(run, list):
|
||||
for index, key in enumerate(run):
|
||||
if key not in fn_keys:
|
||||
_err(errors, f"run.{index}", f"unknown function {key!r}")
|
||||
if "vc_size" in data:
|
||||
size = data["vc_size"]
|
||||
if not (isinstance(size, list) and len(size) == 2 and all(isinstance(n, int) for n in size)):
|
||||
_err(errors, "vc_size", "must be [width, height]")
|
||||
return errors
|
||||
|
||||
|
||||
def from_spec(data: dict[str, Any], *, root: Path | None = None) -> Show:
|
||||
validate(data, root=root)
|
||||
try:
|
||||
return _build(data, root=root)
|
||||
except SpecError:
|
||||
raise
|
||||
except (ValueError, KeyError) as exc:
|
||||
raise SpecError([{"path": "", "message": str(exc)}]) from exc
|
||||
|
||||
|
||||
def _build(data: dict[str, Any], *, root: Path | None) -> Show:
|
||||
show = Show(author=str(data.get("author") or "Jimmy"), root=root)
|
||||
if "vc_size" in data:
|
||||
show.vc_size = (int(data["vc_size"][0]), int(data["vc_size"][1]))
|
||||
universes = data.get("universes")
|
||||
if not universes:
|
||||
for index in range(4):
|
||||
show.universe(index, f"Universe {index + 1}")
|
||||
else:
|
||||
for uni in universes:
|
||||
output = None
|
||||
midi = None
|
||||
if uni.get("output"):
|
||||
out = uni["output"]
|
||||
output = ArtNetOutput(
|
||||
uid=str(out["uid"]),
|
||||
ip=str(out["ip"]),
|
||||
universe=int(out.get("universe", 0)),
|
||||
line=int(out.get("line", 0)),
|
||||
)
|
||||
if uni.get("input"):
|
||||
inp = uni["input"]
|
||||
midi = MidiInput(
|
||||
uid=str(inp["uid"]),
|
||||
profile=str(inp["profile"]),
|
||||
channel=int(inp.get("channel", 0)),
|
||||
line=int(inp.get("line", 0)),
|
||||
)
|
||||
show.universe(int(uni["id"]), uni.get("name"), output=output, midi=midi)
|
||||
if data.get("stage"):
|
||||
show.patch_stage(data["stage"])
|
||||
for fx in data.get("fixtures", []):
|
||||
show.patch(
|
||||
fx["manufacturer"],
|
||||
fx["model"],
|
||||
fx["mode"],
|
||||
address=int(fx["address"]),
|
||||
name=fx.get("name"),
|
||||
universe=int(fx.get("universe", 0)),
|
||||
channels=int(fx["channels"]) if "channels" in fx else None,
|
||||
key=fx["key"],
|
||||
)
|
||||
for group in data.get("groups", []):
|
||||
show.group(group["name"], list(group["fixtures"]), columns=group.get("columns"))
|
||||
pending = []
|
||||
for fn in data.get("functions", []):
|
||||
if fn["type"] in ("chaser", "collection"):
|
||||
pending.append(fn)
|
||||
else:
|
||||
_add_function(show, fn)
|
||||
while pending:
|
||||
ready = [fn for fn in pending if _refs_ready(show, fn)]
|
||||
if not ready:
|
||||
missing = pending[0]
|
||||
raise SpecError([{"path": f"functions.{missing['key']}", "message": "references a function that is not defined"}])
|
||||
for fn in ready:
|
||||
_add_function(show, fn)
|
||||
pending = [fn for fn in pending if fn not in ready]
|
||||
_add_widgets(show, show.vc, data.get("vc", []))
|
||||
if data.get("run"):
|
||||
show.run(*data["run"])
|
||||
return show
|
||||
|
||||
|
||||
Show.from_spec = staticmethod(from_spec) # type: ignore[method-assign]
|
||||
|
||||
|
||||
def _refs_ready(show: Show, fn: dict[str, Any]) -> bool:
|
||||
if fn["type"] == "collection":
|
||||
return all(key in show.functions_by_key for key in fn.get("members", []))
|
||||
return all(step["function"] in show.functions_by_key for step in fn.get("steps", []))
|
||||
|
||||
|
||||
def _add_function(show: Show, fn: dict[str, Any]) -> None:
|
||||
kind = fn["type"]
|
||||
key = fn["key"]
|
||||
name = fn["name"]
|
||||
if kind == "scene":
|
||||
show.scene(name, fn.get("values") or {}, key=key, fade_in=int(fn.get("fade_in", 0)), fade_out=int(fn.get("fade_out", 0)), duration=int(fn.get("duration", 0)))
|
||||
elif kind == "efx":
|
||||
show.efx(name, fn.get("fixtures") or [], key=key, **_efx_kwargs(fn))
|
||||
elif kind == "sequence":
|
||||
show.sequence(name, fn.get("steps") or [], key=key, direction=fn.get("direction", "Forward"), run_order=fn.get("run_order", "Loop"))
|
||||
elif kind == "path":
|
||||
show.path_sequence(
|
||||
name,
|
||||
fn.get("fixtures") or [],
|
||||
fn.get("points") or [],
|
||||
key=key,
|
||||
smooth=bool(fn.get("smooth", False)),
|
||||
subdivisions=int(fn.get("subdivisions", 6)),
|
||||
closed=bool(fn.get("closed", True)),
|
||||
direction=fn.get("direction", "Forward"),
|
||||
run_order=fn.get("run_order", "Loop"),
|
||||
)
|
||||
elif kind == "colour_chase":
|
||||
show.colour_chase(
|
||||
name,
|
||||
fn.get("fixtures") or [],
|
||||
fn.get("channels") or {},
|
||||
fn.get("frames") or [],
|
||||
key=key,
|
||||
fade_ms=int(fn.get("fade_ms", 0)),
|
||||
hold_ms=int(fn.get("hold_ms", 0)),
|
||||
run_order=fn.get("run_order", "Loop"),
|
||||
)
|
||||
elif kind == "chaser":
|
||||
show.chaser(name, fn.get("steps") or [], key=key, direction=fn.get("direction", "Forward"), run_order=fn.get("run_order", "Loop"))
|
||||
elif kind == "collection":
|
||||
show.collection(name, list(fn.get("members") or []), key=key)
|
||||
|
||||
|
||||
def _efx_kwargs(fn: dict[str, Any]) -> dict[str, Any]:
|
||||
fields = (
|
||||
"algorithm", "width", "height", "rotation", "start_offset",
|
||||
"x_offset", "y_offset", "x_frequency", "y_frequency", "x_phase", "y_phase",
|
||||
"duration_ms", "fade_in_ms", "fade_out_ms", "direction", "run_order", "propagation",
|
||||
"relative", "homes",
|
||||
)
|
||||
return {field: fn[field] for field in fields if field in fn}
|
||||
|
||||
|
||||
def _add_widgets(show: Show, frame: Any, widgets: list[dict[str, Any]]) -> None:
|
||||
for widget in widgets:
|
||||
kind = widget["type"]
|
||||
box = dict(x=int(widget["x"]), y=int(widget["y"]), w=int(widget["w"]), h=int(widget["h"]))
|
||||
binding = _binding(widget["input"]) if widget.get("input") else None
|
||||
if kind == "slider":
|
||||
frame.slider(
|
||||
widget["caption"],
|
||||
[(pair[0], int(pair[1])) for pair in widget.get("channels", [])],
|
||||
value=int(widget.get("value", 0)),
|
||||
fg=widget.get("fg", "Default"),
|
||||
cng=str(widget.get("cng", "None")),
|
||||
inverted=bool(widget.get("inverted", False)),
|
||||
input=binding,
|
||||
**box,
|
||||
)
|
||||
elif kind == "button":
|
||||
frame.button(
|
||||
widget["caption"],
|
||||
widget["function"],
|
||||
fg=widget.get("fg", "4294967295"),
|
||||
bg=widget.get("bg", "Default"),
|
||||
action=str(widget.get("action", "Toggle")),
|
||||
input=binding,
|
||||
**box,
|
||||
)
|
||||
elif kind == "xypad":
|
||||
frame.xypad(
|
||||
widget["caption"],
|
||||
widget["fixture"],
|
||||
reverse_pan=bool(widget.get("reverse_pan", False)),
|
||||
reverse_tilt=bool(widget.get("reverse_tilt", False)),
|
||||
pan=int(widget.get("pan", 128)),
|
||||
tilt=int(widget.get("tilt", 128)),
|
||||
input=binding,
|
||||
**box,
|
||||
)
|
||||
else:
|
||||
child = frame.frame(
|
||||
widget["caption"],
|
||||
solo=kind == "solo" or bool(widget.get("solo", False)),
|
||||
header=bool(widget.get("header", True)),
|
||||
**box,
|
||||
)
|
||||
_add_widgets(show, child, widget.get("children") or [])
|
||||
|
||||
|
||||
def _binding(raw: dict[str, Any]) -> MidiBinding:
|
||||
if "channel" in raw:
|
||||
channel = int(raw["channel"])
|
||||
elif "note" in raw:
|
||||
channel = midi_note(int(raw["note"][0]), int(raw["note"][1]))
|
||||
else:
|
||||
channel = midi_cc(int(raw["cc"][0]), int(raw["cc"][1]))
|
||||
return MidiBinding(int(raw["universe"]), channel)
|
||||
|
||||
|
||||
def _check_universes(universes: Any, errors: list[dict[str, str]]) -> None:
|
||||
if not isinstance(universes, list):
|
||||
_err(errors, "universes", "must be a list")
|
||||
return
|
||||
for index, uni in enumerate(universes):
|
||||
path = f"universes.{index}"
|
||||
if not isinstance(uni, dict) or not isinstance(uni.get("id"), int):
|
||||
_err(errors, path, "must be an object with an integer id")
|
||||
continue
|
||||
output = uni.get("output")
|
||||
if output is not None:
|
||||
if not isinstance(output, dict) or "uid" not in output or "ip" not in output:
|
||||
_err(errors, f"{path}.output", "Art-Net output needs uid and ip")
|
||||
midi = uni.get("input")
|
||||
if midi is not None:
|
||||
if not isinstance(midi, dict) or "uid" not in midi or "profile" not in midi:
|
||||
_err(errors, f"{path}.input", "MIDI input needs uid and profile")
|
||||
|
||||
|
||||
def _check_stage(
|
||||
stage: Any,
|
||||
root: Path,
|
||||
library: FixtureLibrary,
|
||||
errors: list[dict[str, str]],
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
found: dict[str, dict[str, Any]] = {}
|
||||
if stage is None:
|
||||
return found
|
||||
if not isinstance(stage, str) or not stage.strip():
|
||||
_err(errors, "stage", "must be a path to a stage map")
|
||||
return found
|
||||
target = _stage_file(stage, root, errors)
|
||||
if target is None:
|
||||
return found
|
||||
try:
|
||||
document = json.loads(target.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError as exc:
|
||||
_err(errors, "stage", f"invalid JSON: {exc}")
|
||||
return found
|
||||
if not isinstance(document, dict):
|
||||
_err(errors, "stage", "stage map must be an object")
|
||||
return found
|
||||
definitions = document.get("definitions")
|
||||
fixtures = document.get("fixtures")
|
||||
if not isinstance(definitions, dict) or not isinstance(fixtures, dict):
|
||||
_err(errors, "stage", "stage map needs definitions and fixtures")
|
||||
return found
|
||||
for key, raw in fixtures.items():
|
||||
path = f"stage.fixtures.{key}"
|
||||
if not isinstance(raw, dict):
|
||||
_err(errors, path, "must be an object")
|
||||
continue
|
||||
defin = definitions.get(raw.get("def"))
|
||||
if not isinstance(defin, dict):
|
||||
_err(errors, f"{path}.def", "unknown definition")
|
||||
continue
|
||||
if not isinstance(raw.get("address"), int) or raw["address"] < 0:
|
||||
_err(errors, f"{path}.address", "must be an address of 0 or more")
|
||||
continue
|
||||
manufacturer = defin.get("manufacturer")
|
||||
model = defin.get("model")
|
||||
mode = defin.get("mode")
|
||||
if not all(isinstance(item, str) and item for item in (manufacturer, model, mode)):
|
||||
_err(errors, f"{path}.def", "definition needs manufacturer, model, and mode")
|
||||
continue
|
||||
definition = library.find(manufacturer, model)
|
||||
mode_info = definition.mode(mode) if definition is not None else None
|
||||
if mode_info is None:
|
||||
_err(errors, path, f"unknown fixture {manufacturer} {model} mode {mode!r}")
|
||||
continue
|
||||
count = len(mode_info.channels)
|
||||
if raw["address"] + count > 512:
|
||||
_err(errors, f"{path}.address", "fixture extends past DMX channel 512")
|
||||
if key in found:
|
||||
_err(errors, path, "duplicate fixture key")
|
||||
continue
|
||||
found[key] = {"channels": count, "mover": mode_info.is_mover}
|
||||
return found
|
||||
|
||||
|
||||
def _stage_file(stage: str, root: Path, errors: list[dict[str, str]]) -> Path | None:
|
||||
candidate = Path(stage)
|
||||
base = root.resolve()
|
||||
target = candidate.resolve() if candidate.is_absolute() else (base / candidate).resolve()
|
||||
if target != base and base not in target.parents:
|
||||
_err(errors, "stage", f"{stage} is outside the project")
|
||||
return None
|
||||
if not target.is_file():
|
||||
_err(errors, "stage", f"stage map not found: {stage}")
|
||||
return None
|
||||
return target
|
||||
|
||||
|
||||
def _check_fixtures(fixtures: Any, library: FixtureLibrary, errors: list[dict[str, str]]) -> dict[str, dict[str, Any]]:
|
||||
found: dict[str, dict[str, Any]] = {}
|
||||
if not isinstance(fixtures, list):
|
||||
_err(errors, "fixtures", "must be a list")
|
||||
return found
|
||||
for index, fx in enumerate(fixtures):
|
||||
path = f"fixtures.{index}"
|
||||
if not isinstance(fx, dict):
|
||||
_err(errors, path, "must be an object")
|
||||
continue
|
||||
key = fx.get("key")
|
||||
if not isinstance(key, str) or not key:
|
||||
_err(errors, f"{path}.key", "must be a non-empty string")
|
||||
continue
|
||||
path = f"fixtures.{key}"
|
||||
if key in found:
|
||||
_err(errors, path, "duplicate fixture key")
|
||||
continue
|
||||
for field in ("manufacturer", "model", "mode"):
|
||||
if not isinstance(fx.get(field), str) or not fx[field]:
|
||||
_err(errors, f"{path}.{field}", "must be a non-empty string")
|
||||
if not isinstance(fx.get("address"), int) or fx["address"] < 0:
|
||||
_err(errors, f"{path}.address", "must be an address of 0 or more")
|
||||
continue
|
||||
definition = None
|
||||
if isinstance(fx.get("manufacturer"), str) and isinstance(fx.get("model"), str):
|
||||
definition = library.find(fx["manufacturer"], fx["model"])
|
||||
mode_info = definition.mode(fx["mode"]) if definition is not None and isinstance(fx.get("mode"), str) else None
|
||||
if definition is None and "channels" not in fx:
|
||||
_err(errors, path, "unknown fixture; add it under fixtures/ or set channels")
|
||||
elif definition is not None and mode_info is None:
|
||||
_err(errors, f"{path}.mode", f"unknown mode {fx.get('mode')!r}")
|
||||
count = None
|
||||
if mode_info is not None:
|
||||
count = len(mode_info.channels)
|
||||
if "channels" in fx and fx["channels"] != count:
|
||||
_err(errors, f"{path}.channels", f"mode {fx['mode']} has {count} channels")
|
||||
elif isinstance(fx.get("channels"), int) and fx["channels"] > 0:
|
||||
count = fx["channels"]
|
||||
elif "channels" in fx:
|
||||
_err(errors, f"{path}.channels", "must be a positive integer")
|
||||
if count is not None and fx["address"] + count > 512:
|
||||
_err(errors, f"{path}.address", "fixture extends past DMX channel 512")
|
||||
mover = bool(mode_info and mode_info.pan_msb is not None and mode_info.tilt_msb is not None)
|
||||
found[key] = {"channels": count or 0, "mover": mover}
|
||||
return found
|
||||
|
||||
|
||||
def _check_groups(groups: Any, fixtures: set[str], errors: list[dict[str, str]]) -> None:
|
||||
if not isinstance(groups, list):
|
||||
_err(errors, "groups", "must be a list")
|
||||
return
|
||||
for index, group in enumerate(groups):
|
||||
path = f"groups.{index}"
|
||||
if not isinstance(group, dict) or not isinstance(group.get("name"), str):
|
||||
_err(errors, path, "must be an object with a name")
|
||||
continue
|
||||
members = group.get("fixtures")
|
||||
if not isinstance(members, list) or not members:
|
||||
_err(errors, f"{path}.fixtures", "must list fixture keys")
|
||||
continue
|
||||
for member in members:
|
||||
if member not in fixtures:
|
||||
_err(errors, f"{path}.fixtures", f"unknown fixture {member!r}")
|
||||
|
||||
|
||||
def _check_functions(
|
||||
functions: Any,
|
||||
fixtures: dict[str, dict[str, Any]],
|
||||
errors: list[dict[str, str]],
|
||||
) -> set[str]:
|
||||
keys: set[str] = set()
|
||||
if not isinstance(functions, list):
|
||||
_err(errors, "functions", "must be a list")
|
||||
return keys
|
||||
for index, fn in enumerate(functions):
|
||||
path = f"functions.{index}"
|
||||
if not isinstance(fn, dict):
|
||||
_err(errors, path, "must be an object")
|
||||
continue
|
||||
key = fn.get("key")
|
||||
if not isinstance(key, str) or not key:
|
||||
_err(errors, f"{path}.key", "must be a non-empty string")
|
||||
continue
|
||||
path = f"functions.{key}"
|
||||
if key in keys:
|
||||
_err(errors, path, "duplicate function key")
|
||||
continue
|
||||
keys.add(key)
|
||||
kind = fn.get("type")
|
||||
if kind not in ("scene", "efx", "sequence", "path", "chaser", "colour_chase", "collection"):
|
||||
_err(errors, f"{path}.type", "must be scene, efx, sequence, path, chaser, colour_chase, or collection")
|
||||
continue
|
||||
if not isinstance(fn.get("name"), str) or not fn["name"]:
|
||||
_err(errors, f"{path}.name", "must be a non-empty string")
|
||||
if kind == "scene":
|
||||
_check_values(fn.get("values") or {}, fixtures, errors, f"{path}.values")
|
||||
elif kind == "efx":
|
||||
_check_efx(fn, fixtures, errors, path)
|
||||
elif kind == "sequence":
|
||||
_check_sequence(fn, fixtures, errors, path)
|
||||
elif kind == "path":
|
||||
_check_path(fn, fixtures, errors, path)
|
||||
elif kind == "colour_chase":
|
||||
_check_chase(fn, fixtures, errors, path)
|
||||
elif kind == "chaser":
|
||||
_check_chaser_steps(fn.get("steps"), errors, path)
|
||||
elif kind == "collection":
|
||||
members = fn.get("members")
|
||||
if not isinstance(members, list) or not members:
|
||||
_err(errors, f"{path}.members", "must list function keys")
|
||||
for fn in functions if isinstance(functions, list) else []:
|
||||
if not isinstance(fn, dict) or fn.get("type") not in ("chaser", "collection"):
|
||||
continue
|
||||
path = f"functions.{fn.get('key')}"
|
||||
if fn["type"] == "collection":
|
||||
for member in fn.get("members") or []:
|
||||
if member not in keys:
|
||||
_err(errors, f"{path}.members", f"unknown function {member!r}")
|
||||
else:
|
||||
for index, step in enumerate(fn.get("steps") or []):
|
||||
if isinstance(step, dict) and step.get("function") not in keys:
|
||||
_err(errors, f"{path}.steps.{index}.function", f"unknown function {step.get('function')!r}")
|
||||
return keys
|
||||
|
||||
|
||||
def _check_values(values: Any, fixtures: dict[str, dict[str, Any]], errors: list[dict[str, str]], path: str) -> None:
|
||||
if not isinstance(values, dict):
|
||||
_err(errors, path, "must map fixture keys to channel values")
|
||||
return
|
||||
for key, channels in values.items():
|
||||
if key not in fixtures:
|
||||
_err(errors, f"{path}.{key}", f"unknown fixture {key!r}")
|
||||
continue
|
||||
if not isinstance(channels, dict):
|
||||
_err(errors, f"{path}.{key}", "must map channel numbers to values")
|
||||
continue
|
||||
count = fixtures[key]["channels"]
|
||||
for ch, val in channels.items():
|
||||
try:
|
||||
index = int(ch)
|
||||
number = int(val)
|
||||
except (TypeError, ValueError):
|
||||
_err(errors, f"{path}.{key}.{ch}", "channel and value must be integers")
|
||||
continue
|
||||
if count and not 0 <= index < count:
|
||||
_err(errors, f"{path}.{key}.{ch}", f"channel {index} is outside 0–{count - 1}")
|
||||
if not 0 <= number <= 255:
|
||||
_err(errors, f"{path}.{key}.{ch}", "value must be 0–255")
|
||||
|
||||
|
||||
def _check_efx(fn: dict[str, Any], fixtures: dict[str, dict[str, Any]], errors: list[dict[str, str]], path: str) -> None:
|
||||
entries = fn.get("fixtures")
|
||||
if not isinstance(entries, list) or not entries:
|
||||
_err(errors, f"{path}.fixtures", "must list fixture keys")
|
||||
return
|
||||
for item in entries:
|
||||
key = item if isinstance(item, str) else item.get("fixture") if isinstance(item, dict) else None
|
||||
if key not in fixtures:
|
||||
_err(errors, f"{path}.fixtures", f"unknown fixture {key!r}")
|
||||
elif not fixtures[key]["mover"]:
|
||||
_err(errors, f"{path}.fixtures", f"{key} has no pan/tilt in this mode")
|
||||
algorithm = fn.get("algorithm", "Circle")
|
||||
if algorithm not in ALGORITHMS:
|
||||
_err(errors, f"{path}.algorithm", f"must be one of {', '.join(ALGORITHMS)}")
|
||||
_choice(errors, fn, "direction", DIRECTIONS, path, "Forward")
|
||||
_choice(errors, fn, "run_order", RUN_ORDERS, path, "Loop")
|
||||
_choice(errors, fn, "propagation", PROPAGATIONS, path, "Parallel")
|
||||
_range(errors, fn, "width", 0, 127, path)
|
||||
_range(errors, fn, "height", 0, 127, path)
|
||||
_range(errors, fn, "x_offset", 0, 255, path)
|
||||
_range(errors, fn, "y_offset", 0, 255, path)
|
||||
_range(errors, fn, "x_frequency", 0, 5, path)
|
||||
_range(errors, fn, "y_frequency", 0, 5, path)
|
||||
if "duration_ms" in fn and (not isinstance(fn["duration_ms"], int) or fn["duration_ms"] < 20):
|
||||
_err(errors, f"{path}.duration_ms", "must be at least 20")
|
||||
homes = fn.get("homes") or {}
|
||||
if homes and not isinstance(homes, dict):
|
||||
_err(errors, f"{path}.homes", "must map fixture keys to [pan, tilt]")
|
||||
elif isinstance(homes, dict):
|
||||
for key, home in homes.items():
|
||||
if key not in fixtures:
|
||||
_err(errors, f"{path}.homes.{key}", f"unknown fixture {key!r}")
|
||||
elif not (isinstance(home, list) and len(home) == 2 and all(isinstance(n, int) and 0 <= n <= 255 for n in home)):
|
||||
_err(errors, f"{path}.homes.{key}", "must be [pan, tilt] in 0–255")
|
||||
|
||||
|
||||
def _check_sequence(fn: dict[str, Any], fixtures: dict[str, dict[str, Any]], errors: list[dict[str, str]], path: str) -> None:
|
||||
steps = fn.get("steps")
|
||||
if not isinstance(steps, list) or not steps:
|
||||
_err(errors, f"{path}.steps", "must be a list of steps")
|
||||
return
|
||||
_choice(errors, fn, "direction", DIRECTIONS, path, "Forward")
|
||||
_choice(errors, fn, "run_order", RUN_ORDERS, path, "Loop")
|
||||
for index, step in enumerate(steps):
|
||||
if not isinstance(step, dict):
|
||||
_err(errors, f"{path}.steps.{index}", "must be an object")
|
||||
continue
|
||||
_check_values(step.get("values") or {}, fixtures, errors, f"{path}.steps.{index}.values")
|
||||
for field in ("fade_ms", "hold_ms", "fade_out_ms"):
|
||||
if field in step and (not isinstance(step[field], int) or step[field] < 0):
|
||||
_err(errors, f"{path}.steps.{index}.{field}", "must be 0 or more")
|
||||
|
||||
|
||||
def _check_path(fn: dict[str, Any], fixtures: dict[str, dict[str, Any]], errors: list[dict[str, str]], path: str) -> None:
|
||||
entries = fn.get("fixtures")
|
||||
points = fn.get("points")
|
||||
if not isinstance(entries, list) or not entries:
|
||||
_err(errors, f"{path}.fixtures", "must list fixtures")
|
||||
else:
|
||||
for item in entries:
|
||||
key = item if isinstance(item, str) else item.get("fixture") if isinstance(item, dict) else None
|
||||
if key not in fixtures:
|
||||
_err(errors, f"{path}.fixtures", f"unknown fixture {key!r}")
|
||||
elif not fixtures[key]["mover"]:
|
||||
_err(errors, f"{path}.fixtures", f"{key} has no pan/tilt in this mode")
|
||||
if not isinstance(points, list) or not points:
|
||||
_err(errors, f"{path}.points", "must list pan/tilt points")
|
||||
else:
|
||||
for index, point in enumerate(points):
|
||||
if not isinstance(point, dict) or "pan" not in point or "tilt" not in point:
|
||||
_err(errors, f"{path}.points.{index}", "must have pan and tilt")
|
||||
_choice(errors, fn, "direction", DIRECTIONS, path, "Forward")
|
||||
_choice(errors, fn, "run_order", RUN_ORDERS, path, "Loop")
|
||||
|
||||
|
||||
def _check_chase(fn: dict[str, Any], fixtures: dict[str, dict[str, Any]], errors: list[dict[str, str]], path: str) -> None:
|
||||
members = fn.get("fixtures")
|
||||
frames = fn.get("frames")
|
||||
channels = fn.get("channels")
|
||||
if not isinstance(members, list) or not members:
|
||||
_err(errors, f"{path}.fixtures", "must list fixture keys")
|
||||
members = []
|
||||
else:
|
||||
for key in members:
|
||||
if key not in fixtures:
|
||||
_err(errors, f"{path}.fixtures", f"unknown fixture {key!r}")
|
||||
if not isinstance(channels, dict) or not channels:
|
||||
_err(errors, f"{path}.channels", "must map names such as r, g, b to channel numbers")
|
||||
channels = {}
|
||||
if not isinstance(frames, list) or not frames:
|
||||
_err(errors, f"{path}.frames", "must list colour frames")
|
||||
return
|
||||
for index, frame in enumerate(frames):
|
||||
if not isinstance(frame, list) or len(frame) != len(members):
|
||||
_err(errors, f"{path}.frames.{index}", f"must have one colour for each of {len(members)} fixtures")
|
||||
continue
|
||||
for colour in frame:
|
||||
if isinstance(colour, dict):
|
||||
continue
|
||||
if not isinstance(colour, list) or len(colour) != len(channels):
|
||||
_err(errors, f"{path}.frames.{index}", f"colour must have {len(channels)} values")
|
||||
break
|
||||
if any(not isinstance(n, int) or not 0 <= n <= 255 for n in colour):
|
||||
_err(errors, f"{path}.frames.{index}", "colour values must be 0–255")
|
||||
|
||||
|
||||
def _check_chaser_steps(steps: Any, errors: list[dict[str, str]], path: str) -> None:
|
||||
if not isinstance(steps, list) or not steps:
|
||||
_err(errors, f"{path}.steps", "must list steps")
|
||||
return
|
||||
for index, step in enumerate(steps):
|
||||
if not isinstance(step, dict) or not isinstance(step.get("function"), str):
|
||||
_err(errors, f"{path}.steps.{index}.function", "must name a function key")
|
||||
for field in ("fade_ms", "hold_ms", "fade_out_ms"):
|
||||
if isinstance(step, dict) and field in step and (not isinstance(step[field], int) or step[field] < 0):
|
||||
_err(errors, f"{path}.steps.{index}.{field}", "must be 0 or more")
|
||||
|
||||
|
||||
def _check_widgets(
|
||||
widgets: Any,
|
||||
fixtures: set[str],
|
||||
functions: set[str],
|
||||
fixture_info: dict[str, dict[str, Any]],
|
||||
errors: list[dict[str, str]],
|
||||
path: str,
|
||||
) -> None:
|
||||
if not isinstance(widgets, list):
|
||||
_err(errors, path, "must be a list")
|
||||
return
|
||||
for index, widget in enumerate(widgets):
|
||||
here = f"{path}.{index}"
|
||||
if not isinstance(widget, dict):
|
||||
_err(errors, here, "must be an object")
|
||||
continue
|
||||
kind = widget.get("type")
|
||||
if kind not in ("slider", "button", "xypad", "frame", "solo"):
|
||||
_err(errors, f"{here}.type", "must be slider, button, xypad, frame, or solo")
|
||||
continue
|
||||
if not isinstance(widget.get("caption"), str):
|
||||
_err(errors, f"{here}.caption", "must be a string")
|
||||
for field in ("x", "y", "w", "h"):
|
||||
if not isinstance(widget.get(field), int):
|
||||
_err(errors, f"{here}.{field}", "must be an integer")
|
||||
if kind == "slider":
|
||||
channels = widget.get("channels")
|
||||
if not isinstance(channels, list) or not channels:
|
||||
_err(errors, f"{here}.channels", "must list [fixture, channel] pairs")
|
||||
else:
|
||||
for pair in channels:
|
||||
if not (isinstance(pair, list) and len(pair) == 2 and isinstance(pair[1], int)):
|
||||
_err(errors, f"{here}.channels", "each entry is [fixture key, channel]")
|
||||
continue
|
||||
if pair[0] not in fixtures:
|
||||
_err(errors, f"{here}.channels", f"unknown fixture {pair[0]!r}")
|
||||
elif fixture_info[pair[0]]["channels"] and not 0 <= pair[1] < fixture_info[pair[0]]["channels"]:
|
||||
_err(errors, f"{here}.channels", f"channel {pair[1]} is outside {pair[0]}")
|
||||
elif kind == "button":
|
||||
if widget.get("function") not in functions:
|
||||
_err(errors, f"{here}.function", f"unknown function {widget.get('function')!r}")
|
||||
if "action" in widget and widget["action"] not in ("Toggle", "Flash"):
|
||||
_err(errors, f"{here}.action", "must be Toggle or Flash")
|
||||
elif kind == "xypad":
|
||||
if widget.get("fixture") not in fixtures:
|
||||
_err(errors, f"{here}.fixture", f"unknown fixture {widget.get('fixture')!r}")
|
||||
elif not fixture_info[widget["fixture"]]["mover"]:
|
||||
_err(errors, f"{here}.fixture", f"{widget['fixture']} has no pan/tilt in this mode")
|
||||
else:
|
||||
_check_widgets(widget.get("children") or [], fixtures, functions, fixture_info, errors, f"{here}.children")
|
||||
if "input" in widget:
|
||||
_check_input(widget["input"], errors, f"{here}.input")
|
||||
for field in ("fg", "bg"):
|
||||
if field in widget:
|
||||
_check_colour(widget[field], errors, f"{here}.{field}")
|
||||
|
||||
|
||||
def _check_input(raw: Any, errors: list[dict[str, str]], path: str) -> None:
|
||||
if not isinstance(raw, dict) or not isinstance(raw.get("universe"), int):
|
||||
_err(errors, path, "must have a universe")
|
||||
return
|
||||
kinds = [name for name in ("note", "cc", "channel") if name in raw]
|
||||
if len(kinds) != 1:
|
||||
_err(errors, path, "set one of note, cc, or channel")
|
||||
return
|
||||
if "note" in raw:
|
||||
pair = raw["note"]
|
||||
if not (isinstance(pair, list) and len(pair) == 2 and all(isinstance(n, int) for n in pair)):
|
||||
_err(errors, f"{path}.note", "must be [channel 0–15, note 0–127]")
|
||||
elif not 0 <= pair[0] <= 15 or not 0 <= pair[1] <= 127:
|
||||
_err(errors, f"{path}.note", "must be [channel 0–15, note 0–127]")
|
||||
elif "cc" in raw:
|
||||
pair = raw["cc"]
|
||||
if not (isinstance(pair, list) and len(pair) == 2 and all(isinstance(n, int) for n in pair)):
|
||||
_err(errors, f"{path}.cc", "must be [channel 0–15, cc 0–127]")
|
||||
elif not 0 <= pair[0] <= 15 or not 0 <= pair[1] <= 127:
|
||||
_err(errors, f"{path}.cc", "must be [channel 0–15, cc 0–127]")
|
||||
|
||||
|
||||
def _check_colour(value: Any, errors: list[dict[str, str]], path: str) -> None:
|
||||
if isinstance(value, str) or isinstance(value, int):
|
||||
return
|
||||
if isinstance(value, list) and len(value) == 3 and all(isinstance(n, int) and 0 <= n <= 255 for n in value):
|
||||
return
|
||||
_err(errors, path, "must be [r, g, b], Default, or an ARGB decimal")
|
||||
|
||||
|
||||
def _choice(errors: list[dict[str, str]], fn: dict[str, Any], field: str, allowed: tuple[str, ...], path: str, default: str) -> None:
|
||||
value = fn.get(field, default)
|
||||
if value not in allowed:
|
||||
_err(errors, f"{path}.{field}", f"must be one of {', '.join(allowed)}")
|
||||
|
||||
|
||||
def _range(errors: list[dict[str, str]], fn: dict[str, Any], field: str, lo: int, hi: int, path: str) -> None:
|
||||
if field not in fn:
|
||||
return
|
||||
value = fn[field]
|
||||
if not isinstance(value, int) or not lo <= value <= hi:
|
||||
_err(errors, f"{path}.{field}", f"must be {lo}–{hi}")
|
||||
|
||||
|
||||
def _err(errors: list[dict[str, str]], path: str, message: str) -> None:
|
||||
errors.append({"path": path, "message": message})
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Patch a Show from a stage map."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from .model import Fixture, Show
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@dataclass
|
||||
class StageRig:
|
||||
path: Path
|
||||
name: str
|
||||
cans: list[Fixture] = field(default_factory=list)
|
||||
movers: list[Fixture] = field(default_factory=list)
|
||||
|
||||
def __getitem__(self, key: str) -> Fixture:
|
||||
for fixture in (*self.cans, *self.movers):
|
||||
if fixture.key == key:
|
||||
return fixture
|
||||
raise KeyError(key)
|
||||
|
||||
|
||||
def patch_stage(show: Show, path: str | Path | None = None) -> StageRig:
|
||||
"""Patch every fixture in the stage map and group cans and movers."""
|
||||
source = _map_path(path, show.root or PROJECT_ROOT)
|
||||
document = json.loads(source.read_text(encoding="utf-8"))
|
||||
definitions = document.get("definitions")
|
||||
fixtures = document.get("fixtures")
|
||||
if not isinstance(definitions, dict) or not isinstance(fixtures, dict):
|
||||
raise ValueError(f"{source} needs definitions and fixtures")
|
||||
rig = StageRig(path=source, name=str(document.get("name") or source.stem))
|
||||
for key, raw in fixtures.items():
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError(f"{key} is not a fixture")
|
||||
defin = definitions.get(raw.get("def"))
|
||||
if not isinstance(defin, dict):
|
||||
raise ValueError(f"{key} has no definition {raw.get('def')!r}")
|
||||
fixture = show.patch(
|
||||
str(defin["manufacturer"]),
|
||||
str(defin["model"]),
|
||||
str(defin["mode"]),
|
||||
address=int(raw["address"]),
|
||||
universe=int(raw.get("universe", 0)),
|
||||
name=str(raw.get("label") or key),
|
||||
key=str(key),
|
||||
)
|
||||
listed = raw.get("channels")
|
||||
if isinstance(listed, int) and listed != fixture.channels:
|
||||
raise ValueError(f"{key} says {listed} channels; {defin['mode']} has {fixture.channels}")
|
||||
fixture.x = float(raw["x"]) if "x" in raw else None
|
||||
fixture.y = float(raw["y"]) if "y" in raw else None
|
||||
fixture.direction = float(raw["direction"]) if "direction" in raw else None
|
||||
fixture.zero = float(raw["zero"]) if "zero" in raw else None
|
||||
fixture.kind = str(raw.get("kind") or "")
|
||||
if fixture.kind == "mover":
|
||||
rig.movers.append(fixture)
|
||||
else:
|
||||
rig.cans.append(fixture)
|
||||
if rig.cans:
|
||||
show.group("Cans", rig.cans, columns=len(rig.cans))
|
||||
if rig.movers:
|
||||
show.group("Movers", rig.movers, columns=len(rig.movers))
|
||||
return rig
|
||||
|
||||
|
||||
def _map_path(path: str | Path | None, root: Path) -> Path:
|
||||
source = Path(path) if path is not None else root / "stage" / "map.json"
|
||||
base = root.resolve()
|
||||
target = source.resolve() if source.is_absolute() else (base / source).resolve()
|
||||
if target != base and base not in target.parents:
|
||||
raise ValueError(f"{path} is outside the project")
|
||||
if not target.is_file():
|
||||
raise ValueError(f"stage map not found: {path or target}")
|
||||
return target
|
||||
@@ -0,0 +1,252 @@
|
||||
"""Operations behind the CLI and the MCP server."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from patternstudio.efx import (
|
||||
ALGORITHMS,
|
||||
DIRECTIONS,
|
||||
PROPAGATIONS,
|
||||
RUN_ORDERS,
|
||||
Efx,
|
||||
EfxFixture,
|
||||
Path as EfxPath,
|
||||
PathFixture,
|
||||
PathPoint,
|
||||
)
|
||||
from patternstudio.fixturedefs import load_fixture_def
|
||||
|
||||
from .play import load_show, play
|
||||
from .spec import PROJECT_ROOT, SpecError, collect_errors, from_spec, show_schema
|
||||
|
||||
__all__ = [
|
||||
"list_fixtures",
|
||||
"sample_animation",
|
||||
"show_schema",
|
||||
"validate_show",
|
||||
"write_show",
|
||||
"run_script",
|
||||
]
|
||||
|
||||
|
||||
def list_fixtures(root: Path | None = None) -> dict[str, Any]:
|
||||
"""Manufacturer, model, modes, and channel maps from the project's fixtures/ directory."""
|
||||
folder = (root or PROJECT_ROOT) / "fixtures"
|
||||
fixtures = []
|
||||
if folder.is_dir():
|
||||
for path in sorted(folder.glob("*.qxf")):
|
||||
definition = load_fixture_def(str(path))
|
||||
fixtures.append(
|
||||
{
|
||||
"manufacturer": definition.manufacturer,
|
||||
"model": definition.model,
|
||||
"type": definition.type,
|
||||
"modes": [
|
||||
{
|
||||
"name": mode.name,
|
||||
"pan_msb": mode.pan_msb,
|
||||
"pan_lsb": mode.pan_lsb,
|
||||
"tilt_msb": mode.tilt_msb,
|
||||
"tilt_lsb": mode.tilt_lsb,
|
||||
"channels": [
|
||||
{"index": ch.index, "name": ch.name, "preset": ch.preset, "group": ch.group}
|
||||
for ch in mode.channels
|
||||
],
|
||||
}
|
||||
for mode in definition.modes.values()
|
||||
],
|
||||
}
|
||||
)
|
||||
return {"fixtures": fixtures}
|
||||
|
||||
|
||||
def validate_show(spec: dict[str, Any], root: Path | None = None) -> dict[str, Any]:
|
||||
"""Check a show spec. Writes nothing."""
|
||||
errors = collect_errors(spec, root=root)
|
||||
return {"ok": not errors, "errors": errors}
|
||||
|
||||
|
||||
def write_show(spec: dict[str, Any], path: str, root: Path | None = None) -> dict[str, Any]:
|
||||
"""Write a .qxw inside the project and return the ids that were assigned."""
|
||||
base = (root or PROJECT_ROOT).resolve()
|
||||
try:
|
||||
target = _inside(base, path)
|
||||
show = from_spec(spec, root=base)
|
||||
except SpecError as exc:
|
||||
return {"ok": False, "errors": exc.errors}
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
show.write(target)
|
||||
return {"ok": True, "path": str(target.relative_to(base)), **show.summary()}
|
||||
|
||||
|
||||
def sample_animation(block: dict[str, Any], steps: int = 32) -> dict[str, Any]:
|
||||
"""Pan/tilt samples for one efx or path block, before it is written into a show."""
|
||||
if not isinstance(block, dict) or block.get("type") not in ("efx", "path"):
|
||||
return {"ok": False, "errors": [{"path": "type", "message": "sample an efx or path block"}]}
|
||||
count = max(1, min(128, int(steps)))
|
||||
try:
|
||||
if block["type"] == "efx":
|
||||
return {"ok": True, **_sample_efx(block, count)}
|
||||
return {"ok": True, **_sample_path(block)}
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
return {"ok": False, "errors": [{"path": "", "message": str(exc)}]}
|
||||
|
||||
|
||||
def run_script(
|
||||
path: str,
|
||||
*,
|
||||
seconds: float | None = None,
|
||||
ip: str | None = None,
|
||||
universe: int = 0,
|
||||
hz: float = 40.0,
|
||||
root: Path | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Play a Python build() script, or a JSON spec, and return samples or send Art-Net."""
|
||||
base = (root or PROJECT_ROOT).resolve()
|
||||
try:
|
||||
source = _inside(base, path)
|
||||
show = load_show(source)
|
||||
return play(show, seconds=seconds, ip=ip, universe=universe, hz=hz)
|
||||
except SpecError as exc:
|
||||
return {"ok": False, "errors": exc.errors}
|
||||
|
||||
|
||||
def _inside(root: Path, rel: str) -> Path:
|
||||
candidate = Path(rel)
|
||||
target = candidate.resolve() if candidate.is_absolute() else (root / candidate).resolve()
|
||||
if target != root and root not in target.parents:
|
||||
raise SpecError([{"path": "path", "message": f"{rel} is outside the project"}])
|
||||
return target
|
||||
|
||||
|
||||
def _sample_efx(block: dict[str, Any], steps: int) -> dict[str, Any]:
|
||||
algorithm = block.get("algorithm", "Circle")
|
||||
if algorithm not in ALGORITHMS:
|
||||
raise ValueError(f"unknown algorithm {algorithm!r}")
|
||||
_choice(block.get("direction", "Forward"), DIRECTIONS, "direction")
|
||||
_choice(block.get("run_order", "Loop"), RUN_ORDERS, "run_order")
|
||||
_choice(block.get("propagation", "Parallel"), PROPAGATIONS, "propagation")
|
||||
entries = block.get("fixtures") or []
|
||||
if not entries:
|
||||
raise ValueError("efx has no fixtures")
|
||||
relative = bool(block.get("relative"))
|
||||
homes = block.get("homes") or {}
|
||||
fixtures = []
|
||||
keys = []
|
||||
for index, item in enumerate(entries):
|
||||
if isinstance(item, str):
|
||||
key, direction, offset = item, "Forward", 0
|
||||
pan = tilt = 128
|
||||
elif isinstance(item, dict) and "fixture" in item:
|
||||
key = str(item["fixture"])
|
||||
direction = item.get("direction", "Forward")
|
||||
offset = int(item.get("start_offset", 0))
|
||||
pan = int(item.get("pan", 128))
|
||||
tilt = int(item.get("tilt", 128))
|
||||
else:
|
||||
raise ValueError("each efx fixture is a key or {fixture, ...}")
|
||||
if key in homes:
|
||||
pan, tilt = int(homes[key][0]), int(homes[key][1])
|
||||
keys.append(key)
|
||||
fixtures.append(EfxFixture(id=index, direction=direction, start_offset=offset, pan=pan, tilt=tilt))
|
||||
width = _bounded(block.get("width", 40), 0, 127, "width")
|
||||
height = _bounded(block.get("height", 40), 0, 127, "height")
|
||||
duration = int(block.get("duration_ms", 8000))
|
||||
if duration < 20:
|
||||
raise ValueError("duration_ms must be at least 20")
|
||||
pattern = Efx(
|
||||
algorithm=algorithm,
|
||||
width=width,
|
||||
height=height,
|
||||
rotation=int(block.get("rotation", 0)) % 360,
|
||||
start_offset=int(block.get("start_offset", 0)) % 360,
|
||||
x_offset=127 if relative else _bounded(block.get("x_offset", 128), 0, 255, "x_offset"),
|
||||
y_offset=127 if relative else _bounded(block.get("y_offset", 128), 0, 255, "y_offset"),
|
||||
x_frequency=_bounded(block.get("x_frequency", 1), 0, 5, "x_frequency"),
|
||||
y_frequency=_bounded(block.get("y_frequency", 1), 0, 5, "y_frequency"),
|
||||
x_phase=int(block.get("x_phase", 0)) % 360,
|
||||
y_phase=int(block.get("y_phase", 0)) % 360,
|
||||
duration_ms=duration,
|
||||
direction=block.get("direction", "Forward"),
|
||||
run_order=block.get("run_order", "Loop"),
|
||||
propagation=block.get("propagation", "Parallel"),
|
||||
relative=relative,
|
||||
fixtures=fixtures,
|
||||
)
|
||||
sampled = pattern.sample(steps=steps)
|
||||
for track, fx in zip(sampled["tracks"], fixtures):
|
||||
track["key"] = keys[fx.id]
|
||||
if relative:
|
||||
track["points"] = [
|
||||
[
|
||||
round(max(0.0, min(255.0, fx.pan + (x - 127))), 2),
|
||||
round(max(0.0, min(255.0, fx.tilt + (y - 127))), 2),
|
||||
]
|
||||
for x, y in track["points"]
|
||||
]
|
||||
return sampled
|
||||
|
||||
|
||||
def _sample_path(block: dict[str, Any]) -> dict[str, Any]:
|
||||
entries = block.get("fixtures") or []
|
||||
points = block.get("points") or []
|
||||
if not entries or not points:
|
||||
raise ValueError("path needs fixtures and points")
|
||||
fixtures = []
|
||||
keys = []
|
||||
for index, item in enumerate(entries):
|
||||
if isinstance(item, str):
|
||||
key, pan_offset, tilt_offset, mirror_pan, mirror_tilt = item, 0, 0, False, False
|
||||
elif isinstance(item, dict):
|
||||
key = str(item["fixture"])
|
||||
pan_offset = int(item.get("pan_offset", 0))
|
||||
tilt_offset = int(item.get("tilt_offset", 0))
|
||||
mirror_pan = bool(item.get("mirror_pan", False))
|
||||
mirror_tilt = bool(item.get("mirror_tilt", False))
|
||||
else:
|
||||
raise ValueError("each path fixture is a key or {fixture, mirror_pan}")
|
||||
keys.append(key)
|
||||
fixtures.append(
|
||||
PathFixture(
|
||||
id=index,
|
||||
pan_offset=pan_offset,
|
||||
tilt_offset=tilt_offset,
|
||||
mirror_pan=mirror_pan,
|
||||
mirror_tilt=mirror_tilt,
|
||||
)
|
||||
)
|
||||
path = EfxPath(
|
||||
points=[
|
||||
PathPoint(
|
||||
pan=float(point["pan"]),
|
||||
tilt=float(point["tilt"]),
|
||||
fade_ms=int(point.get("fade_ms", 1000)),
|
||||
hold_ms=int(point.get("hold_ms", 0)),
|
||||
)
|
||||
for point in points
|
||||
],
|
||||
smooth=bool(block.get("smooth", False)),
|
||||
subdivisions=int(block.get("subdivisions", 6)),
|
||||
closed=bool(block.get("closed", True)),
|
||||
run_order=block.get("run_order", "Loop"),
|
||||
direction=block.get("direction", "Forward"),
|
||||
fixtures=fixtures,
|
||||
)
|
||||
sampled = path.sample()
|
||||
for track in sampled["tracks"]:
|
||||
track["key"] = keys[track["id"]]
|
||||
return sampled
|
||||
|
||||
|
||||
def _choice(value: str, allowed: tuple[str, ...], label: str) -> None:
|
||||
if value not in allowed:
|
||||
raise ValueError(f"{label} must be one of {', '.join(allowed)}")
|
||||
|
||||
|
||||
def _bounded(value: Any, lo: int, hi: int, label: str) -> int:
|
||||
number = int(value)
|
||||
if not lo <= number <= hi:
|
||||
raise ValueError(f"{label} must be {lo}–{hi}")
|
||||
return number
|
||||
+300
@@ -0,0 +1,300 @@
|
||||
"""Virtual console widgets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from .model import INVALID_FUNCTION, MidiBinding
|
||||
from .xmlutil import appearance, attr
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .model import Show
|
||||
|
||||
|
||||
@dataclass
|
||||
class Slider:
|
||||
id: int
|
||||
caption: str
|
||||
channels: list[tuple[int, int]]
|
||||
x: int
|
||||
y: int
|
||||
w: int
|
||||
h: int
|
||||
value: int = 0
|
||||
fg: Any = "Default"
|
||||
cng: str = "None"
|
||||
inverted: bool = False
|
||||
binding: MidiBinding | None = None
|
||||
type_name: str = "Slider"
|
||||
|
||||
def render(self, indent: str = " ") -> str:
|
||||
inner = indent + " "
|
||||
inv = "true" if self.inverted else "false"
|
||||
channels = "\n".join(
|
||||
f'{inner} <Channel Fixture="{fid}">{ch}</Channel>' for fid, ch in self.channels
|
||||
)
|
||||
extra = _input_xml(self.binding, inner)
|
||||
return (
|
||||
f"{indent}<Slider Caption={attr(self.caption)} ID=\"{self.id}\" "
|
||||
f'WidgetStyle="Slider" InvertedAppearance="{inv}">\n'
|
||||
f'{inner}<WindowState Visible="True" X="{self.x}" Y="{self.y}" '
|
||||
f'Width="{self.w}" Height="{self.h}"/>\n'
|
||||
f"{appearance(fg=self.fg, indent=inner)}\n"
|
||||
f'{inner}<SliderMode ValueDisplayStyle="Exact" ClickAndGoType={attr(self.cng)} '
|
||||
f'Monitor="true">Level</SliderMode>\n'
|
||||
f"{inner}<Reset/>\n"
|
||||
f'{inner}<Level LowLimit="0" HighLimit="255" Value="{self.value}">\n'
|
||||
f"{channels}\n"
|
||||
f"{inner}</Level>\n"
|
||||
f"{inner}<Playback>\n"
|
||||
f"{inner} <Function>{INVALID_FUNCTION}</Function>\n"
|
||||
f"{inner}</Playback>{extra}\n"
|
||||
f"{indent}</Slider>"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Button:
|
||||
id: int
|
||||
caption: str
|
||||
function_id: int
|
||||
x: int
|
||||
y: int
|
||||
w: int
|
||||
h: int
|
||||
fg: Any = "4294967295"
|
||||
bg: Any = "Default"
|
||||
action: str = "Toggle"
|
||||
binding: MidiBinding | None = None
|
||||
type_name: str = "Button"
|
||||
|
||||
def render(self, indent: str = " ") -> str:
|
||||
inner = indent + " "
|
||||
extra = _input_xml(self.binding, inner)
|
||||
return (
|
||||
f"{indent}<Button Caption={attr(self.caption)} ID=\"{self.id}\" Icon=\"\">\n"
|
||||
f'{inner}<WindowState Visible="True" X="{self.x}" Y="{self.y}" '
|
||||
f'Width="{self.w}" Height="{self.h}"/>\n'
|
||||
f"{appearance(fg=self.fg, bg=self.bg, frame='None', indent=inner)}\n"
|
||||
f'{inner}<Function ID="{self.function_id}"/>\n'
|
||||
f"{inner}<Action>{self.action}</Action>\n"
|
||||
f'{inner}<Intensity Adjust="False">100</Intensity>{extra}\n'
|
||||
f"{indent}</Button>"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class XYPad:
|
||||
id: int
|
||||
caption: str
|
||||
fixture_id: int
|
||||
x: int
|
||||
y: int
|
||||
w: int
|
||||
h: int
|
||||
reverse_pan: bool = False
|
||||
reverse_tilt: bool = False
|
||||
pan: int = 128
|
||||
tilt: int = 128
|
||||
binding: MidiBinding | None = None
|
||||
type_name: str = "XYPad"
|
||||
|
||||
def render(self, indent: str = " ") -> str:
|
||||
inner = indent + " "
|
||||
pan_rev = "True" if self.reverse_pan else "False"
|
||||
tilt_rev = "True" if self.reverse_tilt else "False"
|
||||
extra = _input_xml(self.binding, inner)
|
||||
return (
|
||||
f"{indent}<XYPad Caption={attr(self.caption)} ID=\"{self.id}\" InvertedAppearance=\"0\">\n"
|
||||
f'{inner}<WindowState Visible="True" X="{self.x}" Y="{self.y}" '
|
||||
f'Width="{self.w}" Height="{self.h}"/>\n'
|
||||
f"{appearance(indent=inner)}\n"
|
||||
f'{inner}<Fixture ID="{self.fixture_id}" Head="0">\n'
|
||||
f'{inner} <Axis ID="X" LowLimit="0" HighLimit="1" Reverse="{pan_rev}"/>\n'
|
||||
f'{inner} <Axis ID="Y" LowLimit="0" HighLimit="1" Reverse="{tilt_rev}"/>\n'
|
||||
f"{inner}</Fixture>\n"
|
||||
f'{inner}<Window hMin="0" hMax="255" vMin="0" vMax="255"/>\n'
|
||||
f'{inner}<Pan Position="{self.pan}"/>\n'
|
||||
f'{inner}<Tilt Position="{self.tilt}"/>{extra}\n'
|
||||
f"{indent}</XYPad>"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Frame:
|
||||
show: Show
|
||||
caption: str
|
||||
x: int = 0
|
||||
y: int = 0
|
||||
w: int = 0
|
||||
h: int = 0
|
||||
solo: bool = False
|
||||
root: bool = False
|
||||
show_header: bool = True
|
||||
children: list[Any] = field(default_factory=list)
|
||||
id: int | None = None
|
||||
type_name: str = "Frame"
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self.type_name = "SoloFrame" if self.solo else "Frame"
|
||||
if not self.root and self.id is None:
|
||||
self.id = self.show.alloc_widget()
|
||||
|
||||
def slider(
|
||||
self,
|
||||
caption: str,
|
||||
channels: list[tuple[Any, int]],
|
||||
*,
|
||||
x: int,
|
||||
y: int,
|
||||
w: int,
|
||||
h: int,
|
||||
value: int = 0,
|
||||
fg: Any = "Default",
|
||||
cng: str = "None",
|
||||
inverted: bool = False,
|
||||
input: MidiBinding | None = None,
|
||||
) -> Slider:
|
||||
widget = Slider(
|
||||
id=self.show.alloc_widget(),
|
||||
caption=caption,
|
||||
channels=[(self.show.fixture_id(fx), int(ch)) for fx, ch in channels],
|
||||
x=x,
|
||||
y=y,
|
||||
w=w,
|
||||
h=h,
|
||||
value=int(value),
|
||||
fg=fg,
|
||||
cng=cng,
|
||||
inverted=inverted,
|
||||
binding=input,
|
||||
)
|
||||
self.children.append(widget)
|
||||
return widget
|
||||
|
||||
def button(
|
||||
self,
|
||||
caption: str,
|
||||
function: Any,
|
||||
*,
|
||||
x: int,
|
||||
y: int,
|
||||
w: int,
|
||||
h: int,
|
||||
fg: Any = "4294967295",
|
||||
bg: Any = "Default",
|
||||
action: str = "Toggle",
|
||||
input: MidiBinding | None = None,
|
||||
) -> Button:
|
||||
if isinstance(function, int):
|
||||
fid = function
|
||||
elif isinstance(function, str):
|
||||
fid = self.show.functions_by_key[function].id
|
||||
else:
|
||||
fid = function.id
|
||||
widget = Button(
|
||||
id=self.show.alloc_widget(),
|
||||
caption=caption,
|
||||
function_id=fid,
|
||||
x=x,
|
||||
y=y,
|
||||
w=w,
|
||||
h=h,
|
||||
fg=fg,
|
||||
bg=bg,
|
||||
action=action,
|
||||
binding=input,
|
||||
)
|
||||
self.children.append(widget)
|
||||
return widget
|
||||
|
||||
def xypad(
|
||||
self,
|
||||
caption: str,
|
||||
fixture: Any,
|
||||
*,
|
||||
x: int,
|
||||
y: int,
|
||||
w: int,
|
||||
h: int,
|
||||
reverse_pan: bool = False,
|
||||
reverse_tilt: bool = False,
|
||||
pan: int = 128,
|
||||
tilt: int = 128,
|
||||
input: MidiBinding | None = None,
|
||||
) -> XYPad:
|
||||
widget = XYPad(
|
||||
id=self.show.alloc_widget(),
|
||||
caption=caption,
|
||||
fixture_id=self.show.fixture_id(fixture),
|
||||
x=x,
|
||||
y=y,
|
||||
w=w,
|
||||
h=h,
|
||||
reverse_pan=reverse_pan,
|
||||
reverse_tilt=reverse_tilt,
|
||||
pan=int(pan),
|
||||
tilt=int(tilt),
|
||||
binding=input,
|
||||
)
|
||||
self.children.append(widget)
|
||||
return widget
|
||||
|
||||
def frame(
|
||||
self,
|
||||
caption: str,
|
||||
*,
|
||||
x: int,
|
||||
y: int,
|
||||
w: int,
|
||||
h: int,
|
||||
solo: bool = False,
|
||||
header: bool = True,
|
||||
) -> Frame:
|
||||
child = Frame(self.show, caption, x, y, w, h, solo=solo, show_header=header)
|
||||
self.children.append(child)
|
||||
return child
|
||||
|
||||
def solo_frame(self, caption: str, *, x: int, y: int, w: int, h: int) -> Frame:
|
||||
return self.frame(caption, x=x, y=y, w=w, h=h, solo=True)
|
||||
|
||||
def render(self, indent: str = " ") -> str:
|
||||
inner = indent + " "
|
||||
if self.root:
|
||||
body = "\n".join(child.render(inner) for child in self.children)
|
||||
parts = [
|
||||
f"{indent}<Frame Caption=\"\">",
|
||||
appearance(frame="None", indent=inner),
|
||||
]
|
||||
if body:
|
||||
parts.append(body)
|
||||
parts.append(f"{indent}</Frame>")
|
||||
return "\n".join(parts)
|
||||
tag = "SoloFrame" if self.solo else "Frame"
|
||||
flags = [
|
||||
f"{inner}<AllowChildren>True</AllowChildren>",
|
||||
f"{inner}<AllowResize>True</AllowResize>",
|
||||
f"{inner}<ShowHeader>{'True' if self.show_header else 'False'}</ShowHeader>",
|
||||
f"{inner}<ShowEnableButton>False</ShowEnableButton>",
|
||||
]
|
||||
if not self.solo:
|
||||
flags.append(f"{inner}<ShowIntensityButton>False</ShowIntensityButton>")
|
||||
flags.append(f"{inner}<Mixing>False</Mixing>")
|
||||
nested = "\n".join(child.render(inner) for child in self.children)
|
||||
parts = [
|
||||
f"{indent}<{tag} Caption={attr(self.caption)} ID=\"{self.id}\">",
|
||||
appearance(indent=inner),
|
||||
f'{inner}<WindowState Visible="True" X="{self.x}" Y="{self.y}" Width="{self.w}" Height="{self.h}"/>',
|
||||
*flags,
|
||||
]
|
||||
if nested:
|
||||
parts.append(nested)
|
||||
parts.append(f"{indent}</{tag}>")
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def _input_xml(binding: MidiBinding | None, indent: str) -> str:
|
||||
if binding is None:
|
||||
return ""
|
||||
return f'\n{indent}<Input Universe="{binding.universe}" Channel="{binding.channel}"/>'
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Serialize a Show to a QLC+ 4.12 workspace."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .model import Show, Universe, fixture_xml, group_xml, universe_xml
|
||||
|
||||
|
||||
def render_show(show: Show) -> str:
|
||||
universes = list(show.universes) or [Universe(i, f"Universe {i + 1}") for i in range(4)]
|
||||
universes.sort(key=lambda uni: uni.id)
|
||||
width, height = show.size()
|
||||
engine = [" <InputOutputMap>"]
|
||||
engine.extend(universe_xml(uni) for uni in universes)
|
||||
engine.append(" </InputOutputMap>")
|
||||
engine.extend(fixture_xml(fx) for fx in show.fixtures)
|
||||
engine.extend(group_xml(group) for group in show.groups)
|
||||
engine.extend(fn.render() for fn in show.functions)
|
||||
widgets = show.vc.render(" ")
|
||||
return (
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
"<!DOCTYPE Workspace>\n"
|
||||
'<Workspace xmlns="http://www.qlcplus.org/Workspace" CurrentWindow="VirtualConsole">\n'
|
||||
" <Creator>\n"
|
||||
" <Name>Q Light Controller Plus</Name>\n"
|
||||
f" <Version>{show.version}</Version>\n"
|
||||
f" <Author>{_author(show.author)}</Author>\n"
|
||||
" </Creator>\n"
|
||||
" <Engine>\n"
|
||||
+ "\n".join(engine)
|
||||
+ "\n </Engine>\n"
|
||||
" <VirtualConsole>\n"
|
||||
+ widgets
|
||||
+ "\n <Properties>\n"
|
||||
f' <Size Width="{width}" Height="{height}"/>\n'
|
||||
' <GrandMaster ChannelMode="Intensity" ValueMode="Reduce" SliderMode="Normal"/>\n'
|
||||
" </Properties>\n"
|
||||
" </VirtualConsole>\n"
|
||||
" <SimpleDesk>\n"
|
||||
" <Engine/>\n"
|
||||
" </SimpleDesk>\n"
|
||||
"</Workspace>\n"
|
||||
)
|
||||
|
||||
|
||||
def _author(name: str) -> str:
|
||||
from .xmlutil import text
|
||||
|
||||
return text(name)
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Small XML helpers shared by the workspace writer."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from xml.sax.saxutils import escape, quoteattr
|
||||
|
||||
|
||||
def attr(value: object) -> str:
|
||||
return quoteattr(str(value))
|
||||
|
||||
|
||||
def text(value: object) -> str:
|
||||
return escape(str(value))
|
||||
|
||||
|
||||
def qlc_color(r: int, g: int, b: int) -> str:
|
||||
"""QLC+ widget colour as a decimal ARGB word."""
|
||||
return str((0xFF << 24) | ((int(r) & 255) << 16) | ((int(g) & 255) << 8) | (int(b) & 255))
|
||||
|
||||
|
||||
def colour(value: object, default: str = "Default") -> str:
|
||||
if value is None:
|
||||
return default
|
||||
if isinstance(value, str):
|
||||
return value
|
||||
if isinstance(value, int) and not isinstance(value, bool):
|
||||
return str(value)
|
||||
if isinstance(value, (list, tuple)) and len(value) == 3:
|
||||
return qlc_color(int(value[0]), int(value[1]), int(value[2]))
|
||||
raise TypeError(f"colour must be 'Default', an ARGB decimal, or [r, g, b], not {value!r}")
|
||||
|
||||
|
||||
def appearance(
|
||||
fg: object = "Default",
|
||||
bg: object = "Default",
|
||||
frame: str = "Sunken",
|
||||
indent: str = " ",
|
||||
) -> str:
|
||||
inner = indent + " "
|
||||
return (
|
||||
f"{indent}<Appearance>\n"
|
||||
f"{inner}<FrameStyle>{text(frame)}</FrameStyle>\n"
|
||||
f"{inner}<ForegroundColor>{text(colour(fg))}</ForegroundColor>\n"
|
||||
f"{inner}<BackgroundColor>{text(colour(bg))}</BackgroundColor>\n"
|
||||
f"{inner}<BackgroundImage>None</BackgroundImage>\n"
|
||||
f"{inner}<Font>Default</Font>\n"
|
||||
f"{indent}</Appearance>"
|
||||
)
|
||||
@@ -0,0 +1,448 @@
|
||||
"""Show engine: workspace XML, spec validation, animations, and the agent tools."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
|
||||
from showfile import Show, midi_note
|
||||
from showfile.play import load_show
|
||||
from showfile.tools import list_fixtures, sample_animation, show_schema, validate_show, write_show
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
NS = {"q": "http://www.qlcplus.org/Workspace"}
|
||||
|
||||
|
||||
def _xml(spec: dict) -> ET.Element:
|
||||
show = Show.from_spec(spec)
|
||||
return ET.fromstring(show.xml())
|
||||
|
||||
|
||||
def _text(root: ET.Element, path: str) -> list[str]:
|
||||
return [el.text or "" for el in root.findall(path, NS)]
|
||||
|
||||
|
||||
class ShowFileTest(unittest.TestCase):
|
||||
def spec(self) -> dict:
|
||||
return {
|
||||
"author": "Jimmy",
|
||||
"universes": [
|
||||
{
|
||||
"id": 0,
|
||||
"name": "Universe 1",
|
||||
"output": {
|
||||
"plugin": "ArtNet",
|
||||
"uid": "192.168.1.92",
|
||||
"ip": "192.168.1.228",
|
||||
"universe": 0,
|
||||
"line": 7,
|
||||
},
|
||||
}
|
||||
],
|
||||
"fixtures": [
|
||||
{
|
||||
"key": "m1",
|
||||
"manufacturer": "Small Eye 7",
|
||||
"model": "Mover",
|
||||
"mode": "43 Channel",
|
||||
"name": "Small Eye 7 #1",
|
||||
"address": 0,
|
||||
},
|
||||
{
|
||||
"key": "m2",
|
||||
"manufacturer": "Small Eye 7",
|
||||
"model": "Mover",
|
||||
"mode": "43 Channel",
|
||||
"name": "Small Eye 7 #2",
|
||||
"address": 44,
|
||||
},
|
||||
{
|
||||
"key": "can1",
|
||||
"manufacturer": "beamZ",
|
||||
"model": "BCC145",
|
||||
"mode": "8 Channel",
|
||||
"address": 87,
|
||||
},
|
||||
],
|
||||
"functions": [
|
||||
{
|
||||
"key": "eight",
|
||||
"type": "efx",
|
||||
"name": "Figure of 8",
|
||||
"algorithm": "Eight",
|
||||
"fixtures": ["m1", "m2"],
|
||||
"width": 40,
|
||||
"height": 30,
|
||||
"x_offset": 128,
|
||||
"y_offset": 140,
|
||||
"duration_ms": 8000,
|
||||
},
|
||||
{
|
||||
"key": "rel",
|
||||
"type": "efx",
|
||||
"name": "Rel",
|
||||
"algorithm": "Circle",
|
||||
"fixtures": ["m1"],
|
||||
"width": 20,
|
||||
"height": 0,
|
||||
"relative": True,
|
||||
"homes": {"m1": [100, 140]},
|
||||
"duration_ms": 4000,
|
||||
},
|
||||
{
|
||||
"key": "focus",
|
||||
"type": "sequence",
|
||||
"name": "Colour Focus",
|
||||
"run_order": "SingleShot",
|
||||
"steps": [
|
||||
{"fade_ms": 100, "values": {"m1": {"10": 0}}},
|
||||
{"fade_ms": 100, "values": {"m1": {"10": 255}}},
|
||||
],
|
||||
},
|
||||
{
|
||||
"key": "sweep",
|
||||
"type": "path",
|
||||
"name": "Sweep",
|
||||
"closed": False,
|
||||
"fixtures": [{"fixture": "m2", "mirror_pan": True}],
|
||||
"points": [
|
||||
{"pan": 80, "tilt": 160, "fade_ms": 1000},
|
||||
{"pan": 180, "tilt": 40, "fade_ms": 1000},
|
||||
],
|
||||
},
|
||||
{"key": "red", "type": "scene", "name": "Red", "values": {"can1": {"2": 255, "4": 0}}},
|
||||
{"key": "blue", "type": "scene", "name": "Blue", "values": {"can1": {"2": 0, "4": 255}}},
|
||||
{
|
||||
"key": "collapse",
|
||||
"type": "chaser",
|
||||
"name": "Ring Collapse",
|
||||
"run_order": "SingleShot",
|
||||
"steps": [
|
||||
{"function": "red", "fade_ms": 100, "hold_ms": 0},
|
||||
{"function": "blue", "fade_ms": 100, "hold_ms": 0},
|
||||
],
|
||||
},
|
||||
{
|
||||
"key": "cols",
|
||||
"type": "colour_chase",
|
||||
"name": "Can Chase",
|
||||
"fixtures": ["can1"],
|
||||
"channels": {"r": 2, "g": 3, "b": 4},
|
||||
"fade_ms": 0,
|
||||
"hold_ms": 100,
|
||||
"frames": [[[255, 0, 0]], [[0, 0, 255]]],
|
||||
},
|
||||
],
|
||||
"vc": [
|
||||
{
|
||||
"type": "slider",
|
||||
"caption": "Dim",
|
||||
"channels": [["can1", 0]],
|
||||
"x": 10,
|
||||
"y": 28,
|
||||
"w": 44,
|
||||
"h": 240,
|
||||
"value": 255,
|
||||
"fg": [255, 255, 255],
|
||||
},
|
||||
{
|
||||
"type": "button",
|
||||
"caption": "Red",
|
||||
"function": "red",
|
||||
"x": 20,
|
||||
"y": 300,
|
||||
"w": 110,
|
||||
"h": 60,
|
||||
"bg": [255, 0, 0],
|
||||
"input": {"universe": 1, "note": [9, 36]},
|
||||
},
|
||||
{
|
||||
"type": "xypad",
|
||||
"caption": "M1",
|
||||
"fixture": "m1",
|
||||
"x": 10,
|
||||
"y": 28,
|
||||
"w": 240,
|
||||
"h": 240,
|
||||
},
|
||||
{
|
||||
"type": "solo",
|
||||
"caption": "Looks",
|
||||
"x": 0,
|
||||
"y": 400,
|
||||
"w": 200,
|
||||
"h": 80,
|
||||
"children": [
|
||||
{
|
||||
"type": "button",
|
||||
"caption": "Blue",
|
||||
"function": "blue",
|
||||
"x": 4,
|
||||
"y": 24,
|
||||
"w": 60,
|
||||
"h": 40,
|
||||
}
|
||||
],
|
||||
},
|
||||
],
|
||||
"run": ["eight"],
|
||||
}
|
||||
|
||||
def test_workspace_xml_has_patch_widgets_and_animations(self):
|
||||
show = Show.from_spec(self.spec())
|
||||
root = ET.fromstring(show.xml())
|
||||
addresses = [int(el.text or "0") for el in root.findall(".//q:Fixture/q:Address", NS)]
|
||||
self.assertEqual(addresses, [0, 44, 87])
|
||||
output = root.find(".//q:Output", NS)
|
||||
self.assertEqual(output.get("Plugin"), "ArtNet")
|
||||
self.assertEqual(output.get("Line"), "7")
|
||||
self.assertEqual(output.find("q:PluginParameters", NS).get("outputIP"), "192.168.1.228")
|
||||
self.assertEqual(_text(root, ".//q:Algorithm"), ["Eight", "Circle"])
|
||||
self.assertEqual(_text(root, ".//q:IsRelative"), ["0", "1"])
|
||||
self.assertIn("127", _text(root, ".//q:Axis/q:Offset"))
|
||||
self.assertIn("0,100", "".join(_text(root, ".//q:FixtureVal")))
|
||||
steps = root.findall(".//q:Function[@Type='Sequence']/q:Step", NS)
|
||||
joined = " ".join(step.text or "" for step in steps)
|
||||
self.assertIn("0,175", joined)
|
||||
self.assertIn("10,255", joined)
|
||||
chaser = root.find(".//q:Function[@Name='Ring Collapse']", NS)
|
||||
self.assertEqual(
|
||||
[step.text for step in chaser.findall("q:Step", NS)],
|
||||
[str(show.functions_by_key["red"].id), str(show.functions_by_key["blue"].id)],
|
||||
)
|
||||
self.assertEqual(show.summary()["functions"]["rel"]["type"], "Collection")
|
||||
self.assertIsNotNone(root.find(".//q:SoloFrame", NS))
|
||||
button = root.find(".//q:Button[@Caption='Red']", NS)
|
||||
self.assertEqual(button.find("q:Input", NS).get("Channel"), str(midi_note(9, 36)))
|
||||
self.assertEqual(button.find("q:Function", NS).get("ID"), str(show.functions_by_key["red"].id))
|
||||
slider = root.find(".//q:Slider", NS)
|
||||
self.assertEqual(slider.find("q:Level", NS).get("Value"), "255")
|
||||
self.assertEqual(slider.find("q:Level/q:Channel", NS).text, "0")
|
||||
|
||||
def test_playback_moves_and_fades(self):
|
||||
show = Show.from_spec(self.spec())
|
||||
pans = {show_frame(show, t, ["eight"])["m1"][0] for t in range(0, 8000, 500)}
|
||||
self.assertGreater(len(pans), 1)
|
||||
self.assertEqual(show_frame(show, 0, ["eight"])["m1"][8], 255)
|
||||
relative = {show_frame(show, t, ["rel"])["m1"][0] for t in range(0, 4000, 250)}
|
||||
self.assertIn(100, relative)
|
||||
self.assertGreater(len(relative), 1)
|
||||
self.assertEqual(show_frame(show, 0, ["collapse"])["can1"][2], 0)
|
||||
self.assertEqual(show_frame(show, 100, ["collapse"])["can1"][2], 255)
|
||||
self.assertEqual(show_frame(show, 150, ["collapse"])["can1"], {2: 128, 4: 128})
|
||||
self.assertEqual(show_frame(show, 200, ["collapse"])["can1"], {2: 0, 4: 255})
|
||||
self.assertEqual(show_frame(show, 0, ["cols"])["can1"][2], 255)
|
||||
self.assertEqual(show_frame(show, 100, ["cols"])["can1"][2], 0)
|
||||
self.assertEqual(show_frame(show, 50, ["focus"])["m1"][10], 0)
|
||||
self.assertEqual(show_frame(show, 150, ["focus"])["m1"][10], 128)
|
||||
|
||||
def test_validation_names_the_key_and_write_stays_inside_the_project(self):
|
||||
result = validate_show(
|
||||
{
|
||||
"fixtures": [
|
||||
{"key": "can1", "manufacturer": "beamZ", "model": "BCC145", "mode": "nope", "address": 0}
|
||||
],
|
||||
"functions": [{"key": "eight", "type": "efx", "name": "E", "fixtures": ["missing"]}],
|
||||
}
|
||||
)
|
||||
self.assertFalse(result["ok"])
|
||||
self.assertIn("fixtures.can1.mode", [item["path"] for item in result["errors"]])
|
||||
self.assertIn("functions.eight.fixtures", [item["path"] for item in result["errors"]])
|
||||
refused = write_show({}, "/tmp/showfile-outside.qxw")
|
||||
self.assertFalse(refused["ok"])
|
||||
self.assertFalse(Path("/tmp/showfile-outside.qxw").exists())
|
||||
|
||||
def test_tools_list_schema_sample_and_write(self):
|
||||
fixtures = list_fixtures()
|
||||
bcc = next(item for item in fixtures["fixtures"] if item["model"] == "BCC145")
|
||||
mode = next(item for item in bcc["modes"] if item["name"] == "8 Channel")
|
||||
self.assertEqual(mode["channels"][0]["name"], "Dimmer")
|
||||
self.assertIn("fixtures", show_schema()["properties"])
|
||||
sample = sample_animation(
|
||||
{
|
||||
"type": "efx",
|
||||
"algorithm": "Eight",
|
||||
"fixtures": ["m1", "m2"],
|
||||
"width": 40,
|
||||
"height": 30,
|
||||
"duration_ms": 8000,
|
||||
"relative": True,
|
||||
"homes": {"m1": [128, 140], "m2": [100, 140]},
|
||||
},
|
||||
steps=8,
|
||||
)
|
||||
self.assertTrue(sample["ok"])
|
||||
self.assertEqual([track["key"] for track in sample["tracks"]], ["m1", "m2"])
|
||||
self.assertGreater(len({point[0] for point in sample["tracks"][0]["points"]}), 1)
|
||||
target = ROOT / "shows" / "_showfile_test.qxw"
|
||||
try:
|
||||
written = write_show(self.spec(), "shows/_showfile_test.qxw")
|
||||
self.assertTrue(written["ok"])
|
||||
self.assertEqual(written["fixtures"]["can1"]["address"], 87)
|
||||
self.assertEqual(written["functions"]["eight"]["type"], "EFX")
|
||||
self.assertEqual(written["functions"]["rel"]["type"], "Collection")
|
||||
self.assertTrue(target.is_file())
|
||||
finally:
|
||||
target.unlink(missing_ok=True)
|
||||
|
||||
def test_animation_script_dry_run(self):
|
||||
show = load_show(ROOT / "scripts" / "anim_eight.py")
|
||||
frames = [show_frame(show, t) for t in (0, 2000)]
|
||||
self.assertNotEqual(frames[0]["m1"][2], frames[1]["m1"][2])
|
||||
self.assertEqual(frames[0]["m1"][8], 255)
|
||||
completed = subprocess.run(
|
||||
[sys.executable, "-m", "showfile", "run", "scripts/anim_eight.py", "--seconds", "0.1"],
|
||||
cwd=ROOT,
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
self.assertEqual(completed.returncode, 0, completed.stderr)
|
||||
payload = json.loads(completed.stdout)
|
||||
self.assertTrue(payload["ok"])
|
||||
self.assertEqual(payload["functions"], ["eight"])
|
||||
self.assertGreaterEqual(len(payload["samples"]), 1)
|
||||
|
||||
def test_simple_board_matches_the_stage_patch(self):
|
||||
spec = json.loads((ROOT / "shows" / "simple.show.json").read_text(encoding="utf-8"))
|
||||
show = Show.from_spec(spec)
|
||||
root = ET.fromstring(show.xml())
|
||||
addresses = [int(el.text or "0") for el in root.findall(".//q:Fixture/q:Address", NS)]
|
||||
self.assertEqual(addresses, [87, 95, 103, 111, 119, 127, 135, 143, 0, 44])
|
||||
captions = [el.get("Caption") for el in root.findall(".//q:XYPad", NS)]
|
||||
self.assertEqual(captions, ["M1 Position", "M2 Position"])
|
||||
sliders = root.findall(".//q:Slider", NS)
|
||||
self.assertEqual(len(sliders), 50)
|
||||
dim = next(el for el in sliders if el.get("Caption") == "C Dim")
|
||||
self.assertEqual(dim.find("q:Level", NS).get("Value"), "255")
|
||||
self.assertEqual(len(dim.findall("q:Level/q:Channel", NS)), 8)
|
||||
self.assertEqual(
|
||||
[el.get("Caption") for el in root.findall(".//q:Frame", NS) if el.get("Caption")],
|
||||
["Cans individual RGBW", "Movers individual RGBW"],
|
||||
)
|
||||
size = root.find(".//q:Properties/q:Size", NS)
|
||||
self.assertEqual((size.get("Width"), size.get("Height")), ("1654", "480"))
|
||||
|
||||
def test_stage_map_drives_the_whole_rig(self):
|
||||
stage = json.loads((ROOT / "stage" / "map.json").read_text(encoding="utf-8"))
|
||||
show = load_show(ROOT / "scripts" / "anim_stage.py")
|
||||
self.assertEqual([fx.key for fx in show.fixtures], list(stage["fixtures"]))
|
||||
for key, raw in stage["fixtures"].items():
|
||||
fixture = show.fixtures_by_key[key]
|
||||
self.assertEqual(fixture.address, raw["address"])
|
||||
self.assertEqual(fixture.x, raw["x"])
|
||||
self.assertEqual(fixture.y, raw["y"])
|
||||
if "direction" in raw:
|
||||
self.assertEqual(fixture.direction, raw["direction"])
|
||||
if "zero" in raw:
|
||||
self.assertEqual(fixture.zero, raw["zero"])
|
||||
self.assertEqual(show.fixtures_by_key["#1"].channel("Red"), 2)
|
||||
self.assertEqual(len(show.fixtures_by_key["M1"].named("Red")), 7)
|
||||
self.assertEqual([group.name for group in show.groups], ["Cans", "Movers"])
|
||||
from showfile.play import dmx_frames
|
||||
|
||||
frame = show_frame(show, 100)
|
||||
dmx = dmx_frames(show, frame)
|
||||
self.assertEqual(dmx[0][87], 255)
|
||||
self.assertEqual(dmx[0][300 + 8], 255)
|
||||
self.assertEqual(frame["M1"][show.fixtures_by_key["M1"].channel("Zoom")], 40)
|
||||
colour = sum(
|
||||
frame[key][2] + frame[key][3] + frame[key][4]
|
||||
for key, raw in stage["fixtures"].items()
|
||||
if raw["kind"] == "can"
|
||||
)
|
||||
self.assertGreater(colour, 0)
|
||||
tracks = []
|
||||
for key in ("M1", "M3"):
|
||||
tracks.append([(show_frame(show, t)[key][0], show_frame(show, t)[key][2]) for t in range(0, 3000, 250)])
|
||||
self.assertGreater(len(set(tracks[0])), 1)
|
||||
self.assertNotEqual(tracks[0], tracks[1])
|
||||
spec = Show.from_spec({"stage": "stage/map.json", "run": []})
|
||||
self.assertEqual(spec.fixtures_by_key["M4"].address, 300)
|
||||
self.assertEqual(spec.fixtures_by_key["#15"].address, 199)
|
||||
missing = validate_show({"stage": "stage/no-such.json"})
|
||||
self.assertFalse(missing["ok"])
|
||||
self.assertEqual(missing["errors"][0]["path"], "stage")
|
||||
outside = validate_show({"stage": "/etc/passwd"})
|
||||
self.assertFalse(outside["ok"])
|
||||
completed = subprocess.run(
|
||||
[sys.executable, "-m", "showfile", "run", "scripts/anim_stage.py", "--seconds", "0.1"],
|
||||
cwd=ROOT,
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
self.assertEqual(completed.returncode, 0, completed.stderr)
|
||||
payload = json.loads(completed.stdout)
|
||||
self.assertTrue(payload["ok"])
|
||||
self.assertEqual(payload["functions"], ["stage"])
|
||||
|
||||
def test_mcp_lists_and_calls_a_tool(self):
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-m", "showfile.mcp"],
|
||||
cwd=ROOT,
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
)
|
||||
assert proc.stdin and proc.stdout
|
||||
try:
|
||||
_mcp(proc, {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}})
|
||||
_mcp(proc, {"jsonrpc": "2.0", "method": "notifications/initialized"})
|
||||
listed = _mcp(proc, {"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
|
||||
names = [tool["name"] for tool in listed["result"]["tools"]]
|
||||
self.assertEqual(
|
||||
names,
|
||||
["list_fixtures", "show_schema", "validate_show", "write_show", "sample_animation", "run_animation"],
|
||||
)
|
||||
called = _mcp(
|
||||
proc,
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 3,
|
||||
"method": "tools/call",
|
||||
"params": {"name": "list_fixtures", "arguments": {}},
|
||||
},
|
||||
)
|
||||
body = json.loads(called["result"]["content"][0]["text"])
|
||||
self.assertIn("BCC145", [item["model"] for item in body["fixtures"]])
|
||||
finally:
|
||||
if proc.stdin:
|
||||
proc.stdin.close()
|
||||
try:
|
||||
proc.wait(timeout=2)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait(timeout=5)
|
||||
if proc.stdout:
|
||||
proc.stdout.close()
|
||||
|
||||
|
||||
def show_frame(show: Show, elapsed: float, keys: list[str] | None = None) -> dict:
|
||||
from showfile import frame_at
|
||||
|
||||
return frame_at(show, elapsed, keys)
|
||||
|
||||
|
||||
def _mcp(proc: subprocess.Popen, message: dict) -> dict:
|
||||
data = json.dumps(message).encode()
|
||||
assert proc.stdin and proc.stdout
|
||||
proc.stdin.write(f"Content-Length: {len(data)}\r\n\r\n".encode() + data)
|
||||
proc.stdin.flush()
|
||||
if "id" not in message:
|
||||
return {}
|
||||
headers = {}
|
||||
while True:
|
||||
line = proc.stdout.readline()
|
||||
if line in (b"\r\n", b"\n"):
|
||||
break
|
||||
key, _, value = line.decode().partition(":")
|
||||
headers[key.strip().lower()] = value.strip()
|
||||
return json.loads(proc.stdout.read(int(headers["content-length"])))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user