Files

667 lines
24 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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)