"""Pattern maths. `EFX*` is a faithful port of QLC+ 4.12 `EFX::calculatePoint` / `rotateAndScale` / `EFXFixture::timeOffset`, so the preview here matches what QLC+ renders. `Path*` samples a list of waypoints (optionally Catmull-Rom smoothed) into keyframes that become a QLC+ Sequence. Both produce the same output shape — a list of per-fixture keyframe tracks — so the browser preview and the live Art-Net preview share one code path. """ from __future__ import annotations import math from dataclasses import dataclass, field from typing import Any ALGORITHMS = ( "Circle", "Eight", "Line", "Line2", "Diamond", "Square", "SquareChoppy", "Leaf", "Lissajous", ) DIRECTIONS = ("Forward", "Backward") RUN_ORDERS = ("Loop", "SingleShot", "PingPong") PROPAGATIONS = ("Parallel", "Serial", "Asymmetric") RELATIVE_ZERO = 127 PREVIEW_STEPS = 128 # same as EFX::preview def clamp(v: float, lo: float = 0, hi: float = 255) -> float: return max(lo, min(hi, v)) def clamp8(v: float) -> int: return int(clamp(round(v))) # --------------------------------------------------------------------------- EFX @dataclass class EfxFixture: id: int head: int = 0 direction: str = "Forward" start_offset: int = 0 # Only used when `relative` is on: absolute home aim written to the base Scene. pan: int = 128 tilt: int = 128 @classmethod def from_dict(cls, d: dict[str, Any]) -> "EfxFixture": return cls( id=int(d["id"]), head=int(d.get("head", 0)), direction="Backward" if d.get("direction") == "Backward" else "Forward", start_offset=int(d.get("start_offset", 0)) % 360, pan=clamp8(d.get("pan", 128)), tilt=clamp8(d.get("tilt", 128)), ) @dataclass class Efx: algorithm: str = "Circle" width: int = 40 height: int = 40 rotation: int = 0 start_offset: int = 0 x_offset: int = 128 y_offset: int = 128 x_frequency: int = 1 y_frequency: int = 1 x_phase: int = 0 y_phase: int = 0 duration_ms: int = 8000 fade_in_ms: int = 0 fade_out_ms: int = 0 direction: str = "Forward" run_order: str = "Loop" propagation: str = "Parallel" relative: bool = False fixtures: list[EfxFixture] = field(default_factory=list) @classmethod def from_dict(cls, d: dict[str, Any]) -> "Efx": alg = d.get("algorithm", "Circle") if alg not in ALGORITHMS: raise ValueError(f"unknown algorithm {alg!r}") return cls( algorithm=alg, width=int(clamp(int(d.get("width", 40)), 0, 127)), height=int(clamp(int(d.get("height", 40)), 0, 127)), rotation=int(d.get("rotation", 0)) % 360, start_offset=int(d.get("start_offset", 0)) % 360, x_offset=clamp8(d.get("x_offset", 128)), y_offset=clamp8(d.get("y_offset", 128)), x_frequency=int(clamp(int(d.get("x_frequency", 1)), 0, 5)), y_frequency=int(clamp(int(d.get("y_frequency", 1)), 0, 5)), x_phase=int(d.get("x_phase", 0)) % 360, y_phase=int(d.get("y_phase", 0)) % 360, duration_ms=max(20, int(d.get("duration_ms", 8000))), fade_in_ms=max(0, int(d.get("fade_in_ms", 0))), fade_out_ms=max(0, int(d.get("fade_out_ms", 0))), direction=d.get("direction") if d.get("direction") in DIRECTIONS else "Forward", run_order=d.get("run_order") if d.get("run_order") in RUN_ORDERS else "Loop", propagation=d.get("propagation") if d.get("propagation") in PROPAGATIONS else "Parallel", relative=bool(d.get("relative", False)), fixtures=[EfxFixture.from_dict(f) for f in d.get("fixtures", [])], ) # -- QLC+ port --------------------------------------------------------- def _direction_iterator(self, fixture_dir: str, it: float) -> float: if fixture_dir == self.direction: return it if self.algorithm == "Line": return it - math.pi if it > math.pi else it + math.pi return 2.0 * math.pi - it def _raw_point(self, it: float) -> tuple[float, float]: a = self.algorithm if a == "Circle": return math.cos(it + math.pi / 2), math.cos(it) if a == "Eight": return math.cos(it * 2 + math.pi / 2), math.cos(it) if a == "Line": return math.cos(it), math.cos(it) if a == "Line2": v = it / math.pi - 1 return v, v if a == "Diamond": return math.cos(it - math.pi / 2) ** 3, math.cos(it) ** 3 if a == "Square": h = math.pi / 2 if it < h: return (it * 2 / math.pi) * 2 - 1, 1.0 if it < math.pi: return 1.0, (1 - (it - h) * 2 / math.pi) * 2 - 1 if it < math.pi * 1.5: return (1 - (it - math.pi) * 2 / math.pi) * 2 - 1, -1.0 return -1.0, ((it - math.pi * 1.5) * 2 / math.pi) * 2 - 1 if a == "SquareChoppy": return float(round(math.cos(it))), float(round(math.sin(it))) if a == "Leaf": return math.cos(it + math.pi / 2) ** 5, math.cos(it) if a == "Lissajous": return ( self._lissajous_axis(it, self.x_frequency, math.radians(self.x_phase)), self._lissajous_axis(it, self.y_frequency, math.radians(self.y_phase)), ) raise ValueError(a) @staticmethod def _lissajous_axis(it: float, freq: int, phase: float) -> float: if freq > 0: return math.cos(freq * it - phase) # Frequency 0 = triangle wave (QLC+ "linear" axis). it0 = (it + phase) / math.pi fff = int(it0) it0 -= fff - fff % 2 forward = 1 - math.floor(it0) backward = 1 - forward it0 -= math.floor(it0) return (forward * it0 + backward * (1 - it0)) * 2 - 1 def point(self, fixture_dir: str, fixture_offset: int, it: float) -> tuple[float, float]: """Pan/tilt (0–255 float) for iterator `it` in 0..2π — EFX::calculatePoint.""" it = self._direction_iterator(fixture_dir, it) it += math.radians((fixture_offset + self.start_offset) % 360) if it >= 2 * math.pi: it -= 2 * math.pi x, y = self._raw_point(it) r = math.radians(self.rotation) c, s = math.cos(r), math.sin(r) px = self.x_offset + x * c * self.width + y * s * self.height py = self.y_offset + -x * s * self.width + y * c * self.height return clamp(px), clamp(py) def time_offset_ms(self, serial: int) -> int: if self.propagation in ("Serial", "Asymmetric"): return self.duration_ms // (len(self.fixtures) + 1) * serial return 0 def sample(self, steps: int = PREVIEW_STEPS) -> dict[str, Any]: tracks = [] for serial, fx in enumerate(self.fixtures): pts = [] for i in range(steps): it = 2 * math.pi * i / steps px, py = self.point(fx.direction, fx.start_offset, it) pts.append([round(px, 2), round(py, 2)]) tracks.append( { "id": fx.id, "head": fx.head, "points": pts, # Asymmetric: shifted in phase, starts immediately. # Serial: shifted in phase AND waits before starting. "time_offset_ms": self.time_offset_ms(serial), "start_delay_ms": self.time_offset_ms(serial) if self.propagation == "Serial" else 0, } ) return { "kind": "efx", "loop_ms": self.duration_ms, "run_order": self.run_order, "relative": self.relative, "tracks": tracks, } def live_point(self, serial: int, elapsed_ms: float) -> tuple[float, float] | None: """Pan/tilt for a running fixture at wall time — EFXFixture::nextStep.""" fx = self.fixtures[serial] loop = self.duration_ms off = self.time_offset_ms(serial) if self.propagation == "Serial" and elapsed_ms < off: return None cycles, pos = divmod(elapsed_ms, loop) if self.run_order == "SingleShot" and cycles >= 1: return None d = fx.direction if self.run_order == "PingPong" and int(cycles) % 2 == 1: d = "Backward" if d == "Forward" else "Forward" pos = (pos + off) % loop it = 2 * math.pi * pos / loop return self.point(d, fx.start_offset, it) # --------------------------------------------------------------------------- Path @dataclass class PathPoint: pan: float tilt: float fade_ms: int = 1000 hold_ms: int = 0 @classmethod def from_dict(cls, d: dict[str, Any]) -> "PathPoint": return cls( pan=clamp(float(d["pan"])), tilt=clamp(float(d["tilt"])), fade_ms=max(0, int(d.get("fade_ms", 1000))), hold_ms=max(0, int(d.get("hold_ms", 0))), ) @dataclass class PathFixture: id: int head: int = 0 pan_offset: int = 0 tilt_offset: int = 0 mirror_pan: bool = False # head hung the other way round: pan = 255 - pan mirror_tilt: bool = False @classmethod def from_dict(cls, d: dict[str, Any]) -> "PathFixture": return cls( id=int(d["id"]), head=int(d.get("head", 0)), pan_offset=int(d.get("pan_offset", 0)), tilt_offset=int(d.get("tilt_offset", 0)), mirror_pan=bool(d.get("mirror_pan", False)), mirror_tilt=bool(d.get("mirror_tilt", False)), ) def apply(self, pan: float, tilt: float) -> tuple[float, float]: if self.mirror_pan: pan = 255 - pan if self.mirror_tilt: tilt = 255 - tilt return clamp(pan + self.pan_offset), clamp(tilt + self.tilt_offset) @dataclass class Path: points: list[PathPoint] = field(default_factory=list) smooth: bool = False subdivisions: int = 6 # extra steps per segment when smoothing closed: bool = True # last point flows back into the first run_order: str = "Loop" direction: str = "Forward" fixtures: list[PathFixture] = field(default_factory=list) @classmethod def from_dict(cls, d: dict[str, Any]) -> "Path": return cls( points=[PathPoint.from_dict(p) for p in d.get("points", [])], smooth=bool(d.get("smooth", False)), subdivisions=int(clamp(int(d.get("subdivisions", 6)), 1, 32)), closed=bool(d.get("closed", True)), run_order=d.get("run_order") if d.get("run_order") in RUN_ORDERS else "Loop", direction=d.get("direction") if d.get("direction") in DIRECTIONS else "Forward", fixtures=[PathFixture.from_dict(f) for f in d.get("fixtures", [])], ) # -- steps ---------------------------------------------------------------- def steps(self) -> list[PathPoint]: """Resolved step list (smoothing expanded), in the pattern's base frame.""" pts = self.points if len(pts) < 2 or not self.smooth: return list(pts) # A waypoint's fade_ms is the travel time *into* it. When the segment # before it is split into `sub` sub-steps, each sub-step (and the # waypoint itself) gets fade_ms / sub so the total travel time holds. out: list[PathPoint] = [] n = len(pts) sub = self.subdivisions seg_count = n if self.closed else n - 1 def split_fade(p: PathPoint) -> int: return max(1, p.fade_ms // sub) for i in range(seg_count): p0 = pts[(i - 1) % n] if (self.closed or i > 0) else pts[0] p1 = pts[i] p2 = pts[(i + 1) % n] p3 = pts[(i + 2) % n] if (self.closed or i + 2 < n) else pts[-1] arrive = split_fade(p1) if (self.closed or i > 0) else p1.fade_ms out.append(PathPoint(p1.pan, p1.tilt, fade_ms=arrive, hold_ms=p1.hold_ms)) for k in range(1, sub): t = k / sub pan = _catmull(p0.pan, p1.pan, p2.pan, p3.pan, t) tilt = _catmull(p0.tilt, p1.tilt, p2.tilt, p3.tilt, t) out.append(PathPoint(clamp(pan), clamp(tilt), fade_ms=split_fade(p2), hold_ms=0)) if not self.closed: last = pts[-1] out.append(PathPoint(last.pan, last.tilt, fade_ms=split_fade(last), hold_ms=last.hold_ms)) return out def loop_ms(self) -> int: return sum(s.fade_ms + s.hold_ms for s in self.steps()) def sample(self) -> dict[str, Any]: steps = self.steps() tracks = [] for fx in self.fixtures: keys = [] t = 0 for s in steps: pan, tilt = fx.apply(s.pan, s.tilt) t += s.fade_ms keys.append([t, round(pan, 2), round(tilt, 2)]) if s.hold_ms: t += s.hold_ms keys.append([t, round(pan, 2), round(tilt, 2)]) tracks.append({"id": fx.id, "head": fx.head, "keys": keys}) return { "kind": "path", "loop_ms": self.loop_ms(), "run_order": self.run_order, "direction": self.direction, "tracks": tracks, "step_count": len(steps), } def live_point(self, serial: int, elapsed_ms: float) -> tuple[float, float] | None: steps = self.steps() if not steps: return None loop = self.loop_ms() if loop <= 0: pan, tilt = steps[0].pan, steps[0].tilt return self.fixtures[serial].apply(pan, tilt) cycles, pos = divmod(elapsed_ms, loop) if self.run_order == "SingleShot" and cycles >= 1: pos = loop reverse = self.direction == "Backward" if self.run_order == "PingPong" and int(cycles) % 2 == 1: reverse = not reverse order = list(reversed(steps)) if reverse else steps t = 0.0 prev = order[-1] for s in order: if pos <= t + s.fade_ms: f = (pos - t) / s.fade_ms if s.fade_ms else 1.0 pan = prev.pan + (s.pan - prev.pan) * f tilt = prev.tilt + (s.tilt - prev.tilt) * f return self.fixtures[serial].apply(pan, tilt) t += s.fade_ms if pos <= t + s.hold_ms: return self.fixtures[serial].apply(s.pan, s.tilt) t += s.hold_ms prev = s last = order[-1] return self.fixtures[serial].apply(last.pan, last.tilt) def _catmull(p0: float, p1: float, p2: float, p3: float, t: float) -> float: t2, t3 = t * t, t * t * t return 0.5 * ( 2 * p1 + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3 ) # --------------------------------------------------------------------------- entry def pattern_from_dict(d: dict[str, Any]) -> Efx | Path: kind = d.get("type", "efx") if kind == "efx": return Efx.from_dict({**d.get("efx", {}), "fixtures": d.get("fixtures", [])}) if kind == "path": return Path.from_dict({**d.get("path", {}), "fixtures": d.get("fixtures", [])}) raise ValueError(f"unknown pattern type {kind!r}")