firmament: give effects normalized and cylindrical coordinates
Assisted-by: Claude Opus 5.5 via Claude Code
change xssrzvpvzprtwmpnumkpnovnztryyouy
commit 78e2098d71624bda838786629217e98b0a51e6b4
author Alpha Chen <alpha@kejadlen.dev>
date
parent onlvuysm
diff --git a/firmament/README.md b/firmament/README.md
index aab5682..ce29dab 100644
--- a/firmament/README.md
+++ b/firmament/README.md
@@ -39,14 +39,26 @@ uv run firmament light --host wled.local --leds 500 --strand 5
 
 An effect is a Python file that defines `color(led, t)`. It gets one LED and
 the time in seconds since the stream started, and returns `(r, g, b)` from 0
-to 255; values outside that range are clamped. `led` has `index`, `x`, `y`,
-`z` (meters, y up), and `views` (0 for an interpolated position).
+to 255; values outside that range are clamped.
 
 ```python
 def color(led, t):
-    return (255, 80, 0) if led.y < t % 2 else (0, 0, 0)
+    return (255, 80, 0) if led.h < t % 1 else (0, 0, 0)
 ```
 
+Directions are from where the capture started: x points right, y up, and z
+back toward the camera. `led` has the following fields:
+
+| Field | Meaning |
+| --- | --- |
+| `index` | The LED's index. |
+| `x`, `y`, `z` | Position in meters. |
+| `h` | Height, 0 at the lowest LED to 1 at the highest. |
+| `r` | Distance from a vertical axis through the middle of the LEDs, 0 to 1 at the farthest. |
+| `theta` | Angle around that axis in radians, -π to π. 0 faces where the capture started, and it increases to the right. |
+| `nx`, `ny`, `nz` | Position centered on the LEDs and scaled so the largest span is -1 to 1, keeping proportions. |
+| `views` | How many observations placed the LED; 0 means interpolated. |
+
 Stream it to WLED, to a 3D preview in [Rerun](https://rerun.io)'s viewer, or
 both, using a positions file in the [`leds.csv`](SPEC.md#led-positions)
 format:
diff --git a/firmament/src/firmament/cli.py b/firmament/src/firmament/cli.py
index dda1f96..1521818 100644
--- a/firmament/src/firmament/cli.py
+++ b/firmament/src/firmament/cli.py
@@ -12,7 +12,7 @@ from typing import TextIO
 
 from firmament.codes import MAX_LEDS
 from firmament.ddp import PORT, DdpSender
-from firmament.effects import LiveEffect, scale
+from firmament.effects import LiveEffect, effect_leds, scale
 from firmament.pattern import (
     ALL_OFF,
     MIN_LEDS,
@@ -103,6 +103,7 @@ def _stream(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
     except ValueError as e:
         parser.error(str(e))
 
+    placed = effect_leds(leds)
     effect = LiveEffect(
         args.effect, lambda message: print(f"firmament: {message}", file=sys.stderr)
     )
@@ -123,7 +124,7 @@ def _stream(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
 
         def frame_for_tick(k: int) -> bytes:
             t = k / args.fps
-            frame = effect.frame(leds, t)
+            frame = effect.frame(placed, t)
             if preview:
                 preview.show(t, frame)
             return scale(frame, args.brightness)
diff --git a/firmament/src/firmament/effects.py b/firmament/src/firmament/effects.py
index 6e64c78..7f4b3f2 100644
--- a/firmament/src/firmament/effects.py
+++ b/firmament/src/firmament/effects.py
@@ -4,11 +4,60 @@ import importlib.util
 import math
 import traceback
 from collections.abc import Callable, Sequence
+from dataclasses import dataclass
 from pathlib import Path
 
 from firmament.positions import Led
 
-type ColorFn = Callable[[Led, float], object]
+
+@dataclass(frozen=True)
+class EffectLed(Led):
+    """An LED as an effect sees it: its position, plus normalized and cylindrical coordinates.
+
+    Positions are in SPEC.md's start view: x right, y up, z back toward the starting camera.
+    The axis is vertical, through the middle of the map's horizontal bounding box.
+    """
+
+    h: float  # Height, 0 at the lowest LED to 1 at the highest.
+    r: float  # Distance from the axis, 0 to 1 at the farthest LED.
+    theta: float  # Around the axis, -pi to pi; 0 faces the start view, positive to its right.
+    nx: float  # nx, ny, nz: centered on the map, scaled so the largest span is -1 to 1.
+    ny: float
+    nz: float
+
+
+type ColorFn = Callable[[EffectLed, float], object]
+
+
+def effect_leds(leds: Sequence[Led]) -> list[EffectLed]:
+    lo = [min(getattr(led, a) for led in leds) for a in "xyz"]
+    hi = [max(getattr(led, a) for led in leds) for a in "xyz"]
+    center = [(a + b) / 2 for a, b in zip(lo, hi, strict=True)]
+    half_span = max((b - a) / 2 for a, b in zip(lo, hi, strict=True))
+    height = hi[1] - lo[1]
+    cx, cy, cz = center
+
+    def radius(led: Led) -> float:
+        return math.hypot(led.x - cx, led.z - cz)
+
+    farthest = max(radius(led) for led in leds)
+    # A map with no extent along some direction (all LEDs level, or on the axis) gets 0 there.
+    return [
+        EffectLed(
+            led.index,
+            led.x,
+            led.y,
+            led.z,
+            led.views,
+            h=(led.y - lo[1]) / height if height else 0.0,
+            r=radius(led) / farthest if farthest else 0.0,
+            theta=math.atan2(led.x - cx, led.z - cz),
+            nx=(led.x - cx) / half_span if half_span else 0.0,
+            ny=(led.y - cy) / half_span if half_span else 0.0,
+            nz=(led.z - cz) / half_span if half_span else 0.0,
+        )
+        for led in leds
+    ]
 
 
 class EffectError(Exception):
@@ -33,7 +82,7 @@ def load(path: Path) -> ColorFn:
     return color
 
 
-def render(color: ColorFn, leds: Sequence[Led], t: float, path: Path) -> bytes:
+def render(color: ColorFn, leds: Sequence[EffectLed], t: float, path: Path) -> bytes:
     """One RGB frame, clamping each channel to 0 to 255."""
     frame = bytearray()
     for led in leds:
@@ -59,7 +108,7 @@ class LiveEffect:
         self._current: ColorFn | None = None
         self._working: ColorFn | None = None
 
-    def frame(self, leds: Sequence[Led], t: float) -> bytes:
+    def frame(self, leds: Sequence[EffectLed], t: float) -> bytes:
         self._reload_if_changed()
         while self._current is not None:
             try:
diff --git a/firmament/tests/test_effects.py b/firmament/tests/test_effects.py
index 1ba72fd..729f531 100644
--- a/firmament/tests/test_effects.py
+++ b/firmament/tests/test_effects.py
@@ -1,11 +1,12 @@
+import math
 import os
 
 import pytest
 
-from firmament.effects import EffectError, LiveEffect, load, render, scale
+from firmament.effects import EffectError, LiveEffect, effect_leds, load, render, scale
 from firmament.positions import Led
 
-LEDS = [Led(0, 0.0, 0.0, 0.0, 1), Led(1, 0.0, 1.0, 0.0, 0)]
+LEDS = effect_leds([Led(0, 0.0, 0.0, 0.0, 1), Led(1, 0.0, 1.0, 0.0, 0)])
 
 
 def _effect(tmp_path, source, name="effect.py"):
@@ -67,6 +68,34 @@ def test_load_rejects_broken_files(tmp_path, source, match):
         load(_effect(tmp_path, source))
 
 
+def test_effect_leds_add_normalized_and_cylindrical_coordinates():
+    leds = [Led(0, 1, 0, 0, 1), Led(1, -1, 2, 0, 1), Led(2, 0, 1, -1, 0), Led(3, 0, 1, 1, 0)]
+    expected = [
+        (0.0, 1.0, math.pi / 2, 1.0, -1.0, 0.0),
+        (1.0, 1.0, -math.pi / 2, -1.0, 1.0, 0.0),
+        (0.5, 1.0, math.pi, 0.0, 0.0, -1.0),
+        (0.5, 1.0, 0.0, 0.0, 0.0, 1.0),
+    ]
+    for e, want in zip(effect_leds(leds), expected, strict=True):
+        assert (e.h, e.r, e.theta, e.nx, e.ny, e.nz) == pytest.approx(want)
+
+
+def test_effect_leds_keep_each_leds_position():
+    led = effect_leds([Led(0, 1, 2, 3, 4), Led(1, 5, 6, 7, 0)])[0]
+    assert (led.index, led.x, led.y, led.z, led.views) == (0, 1, 2, 3, 4)
+
+
+def test_normalized_positions_keep_proportions():
+    near, far = effect_leds([Led(0, 0, 0, 0, 1), Led(1, 4, 1, 0, 1)])
+    assert (near.nx, near.ny, near.nz) == pytest.approx((-1.0, -0.25, 0.0))
+    assert (far.nx, far.ny, far.nz) == pytest.approx((1.0, 0.25, 0.0))
+
+
+def test_a_map_with_no_extent_gets_zeros():
+    led = effect_leds([Led(0, 1, 1, 1, 1), Led(1, 1, 1, 1, 1)])[0]
+    assert (led.h, led.r, led.theta, led.nx, led.ny, led.nz) == (0, 0, 0, 0, 0, 0)
+
+
 def test_scale_applies_brightness():
     assert scale(bytes([255, 128, 0]), 64) == bytes([64, 32, 0])