Skip to main content

qualia_core_db/hypermedia_authoring/
dmx.rs

1//! DMX / fixtures / lighting / projection / cue stack / show control.
2//!
3//! ~25 required functions.
4
5use std::collections::BTreeMap;
6
7/// A DMX universe (512 channels).
8#[derive(Debug, Clone)]
9pub struct DmxUniverse {
10    pub id: u16,
11    pub channels: [u8; 512],
12}
13
14impl DmxUniverse {
15    /// Creates universe `id` with all 512 channels at 0.
16    pub fn new(id: u16) -> Self {
17        Self {
18            id,
19            channels: [0; 512],
20        }
21    }
22
23    /// Sets `channel` (1-512) to `value`; `false` when out of DMX range.
24    pub fn set_channel(&mut self, channel: u16, value: u8) -> bool {
25        if channel < 512 {
26            self.channels[channel as usize] = value;
27            true
28        } else {
29            false
30        }
31    }
32
33    /// Channel value, or `None` when out of range.
34    pub fn get_channel(&self, channel: u16) -> Option<u8> {
35        if channel < 512 {
36            Some(self.channels[channel as usize])
37        } else {
38            None
39        }
40    }
41
42    /// Zeroes all 512 channels.
43    pub fn clear(&mut self) {
44        self.channels = [0; 512];
45    }
46}
47
48/// A DMX fixture with channel mapping.
49#[derive(Debug, Clone)]
50pub struct DmxFixture {
51    pub id: String,
52    pub name: String,
53    pub fixture_type: FixtureType,
54    pub universe: u16,
55    pub start_channel: u16,
56    pub channel_count: u16,
57    pub channel_map: BTreeMap<String, u16>, // function name -> offset
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum FixtureType {
62    MovingHead,
63    ParCan,
64    StripLight,
65    Laser,
66    Hazer,
67    FogMachine,
68    Spotlight,
69    Generic,
70}
71
72impl DmxFixture {
73    /// Creates a fixture with a start address and channel map.
74    pub fn new(
75        id: &str,
76        name: &str,
77        fixture_type: FixtureType,
78        universe: u16,
79        start_channel: u16,
80        channel_count: u16,
81    ) -> Self {
82        Self {
83            id: id.to_string(),
84            name: name.to_string(),
85            fixture_type,
86            universe,
87            start_channel,
88            channel_count,
89            channel_map: BTreeMap::new(),
90        }
91    }
92
93    /// Maps a fixture `function` name to a channel `offset`.
94    pub fn map_channel(&mut self, function: &str, offset: u16) {
95        self.channel_map.insert(function.to_string(), offset);
96    }
97
98    /// Set a function value on this fixture in a universe.
99    pub fn set_function(&self, universe: &mut DmxUniverse, function: &str, value: u8) -> bool {
100        if let Some(&offset) = self.channel_map.get(function) {
101            let channel = self.start_channel + offset;
102            universe.set_channel(channel, value)
103        } else {
104            false
105        }
106    }
107
108    /// Set the colour (RGB) on this fixture.
109    pub fn set_colour(&self, universe: &mut DmxUniverse, r: u8, g: u8, b: u8) -> bool {
110        let mut ok = true;
111        ok &= self.set_function(universe, "red", r);
112        ok &= self.set_function(universe, "green", g);
113        ok &= self.set_function(universe, "blue", b);
114        ok
115    }
116
117    /// Set pan/tilt for moving heads.
118    pub fn set_pan_tilt(&self, universe: &mut DmxUniverse, pan: u8, tilt: u8) -> bool {
119        let mut ok = true;
120        ok &= self.set_function(universe, "pan", pan);
121        ok &= self.set_function(universe, "tilt", tilt);
122        ok
123    }
124
125    /// Set intensity (0-255).
126    pub fn set_intensity(&self, universe: &mut DmxUniverse, intensity: u8) -> bool {
127        self.set_function(universe, "intensity", intensity)
128    }
129}
130
131/// A cue in a cue stack.
132#[derive(Debug, Clone)]
133pub struct Cue {
134    pub id: String,
135    pub name: String,
136    pub duration: f64, // seconds for fade
137    pub fade_in: f64,
138    pub fade_out: f64,
139    pub channel_values: BTreeMap<(u16, u16), u8>, // (universe, channel) -> value
140    pub triggers: Vec<String>,
141}
142
143impl Cue {
144    /// Creates an empty cue.
145    pub fn new(id: &str, name: &str) -> Self {
146        Self {
147            id: id.to_string(),
148            name: name.to_string(),
149            duration: 0.0,
150            fade_in: 0.0,
151            fade_out: 0.0,
152            channel_values: BTreeMap::new(),
153            triggers: Vec::new(),
154        }
155    }
156
157    /// Sets `channel` in `universe` to `value` in this cue.
158    pub fn set_channel(&mut self, universe: u16, channel: u16, value: u8) {
159        self.channel_values.insert((universe, channel), value);
160    }
161
162    /// Sets fade-in/fade-out times in seconds.
163    pub fn set_fade(&mut self, fade_in: f64, fade_out: f64) {
164        self.fade_in = fade_in.max(0.0);
165        self.fade_out = fade_out.max(0.0);
166    }
167
168    /// Adds a trigger label to the cue.
169    pub fn add_trigger(&mut self, trigger: &str) {
170        self.triggers.push(trigger.to_string());
171    }
172
173    /// Apply this cue's values to the given universes.
174    pub fn apply(&self, universes: &mut BTreeMap<u16, DmxUniverse>) {
175        for ((universe_id, channel), value) in &self.channel_values {
176            if let Some(universe) = universes.get_mut(universe_id) {
177                universe.set_channel(*channel, *value);
178            }
179        }
180    }
181
182    /// Interpolate between this cue and the next, at time t [0, 1].
183    pub fn interpolate_to(&self, next: &Cue, t: f32) -> BTreeMap<(u16, u16), u8> {
184        let t = t.clamp(0.0, 1.0);
185        let mut result = BTreeMap::new();
186        for (key, &value) in &self.channel_values {
187            let next_value = next.channel_values.get(key).copied().unwrap_or(value);
188            let interpolated = (value as f32 * (1.0 - t) + next_value as f32 * t).round() as u8;
189            result.insert(*key, interpolated);
190        }
191        for (key, &value) in &next.channel_values {
192            if !self.channel_values.contains_key(key) {
193                result.insert(*key, (value as f32 * t).round() as u8);
194            }
195        }
196        result
197    }
198}
199
200/// A cue stack — ordered sequence of cues for a show.
201#[derive(Debug, Clone)]
202pub struct CueStack {
203    pub id: String,
204    pub name: String,
205    pub cues: Vec<Cue>,
206    pub current_index: usize,
207    pub auto_follow: bool,
208}
209
210impl CueStack {
211    /// Creates an empty cue stack positioned before the first cue.
212    pub fn new(id: &str, name: &str) -> Self {
213        Self {
214            id: id.to_string(),
215            name: name.to_string(),
216            cues: Vec::new(),
217            current_index: 0,
218            auto_follow: false,
219        }
220    }
221
222    /// Appends `cue` to the stack.
223    pub fn add_cue(&mut self, cue: Cue) {
224        self.cues.push(cue);
225    }
226
227    /// Advances to the next cue and applies its channel values to `universes`; `false` at the end.
228    pub fn go(&mut self, universes: &mut BTreeMap<u16, DmxUniverse>) -> bool {
229        if self.current_index < self.cues.len() {
230            self.cues[self.current_index].apply(universes);
231            self.current_index += 1;
232            true
233        } else {
234            false
235        }
236    }
237
238    /// Steps back one cue (does not re-apply values); `false` at the start.
239    pub fn go_back(&mut self) -> bool {
240        if self.current_index > 0 {
241            self.current_index -= 1;
242            true
243        } else {
244            false
245        }
246    }
247
248    /// Resets the stack position to before the first cue.
249    pub fn reset(&mut self) {
250        self.current_index = 0;
251    }
252
253    /// The cue at the current position, or `None`.
254    pub fn current_cue(&self) -> Option<&Cue> {
255        self.cues.get(self.current_index)
256    }
257
258    /// Number of cues in the stack.
259    pub fn cue_count(&self) -> usize {
260        self.cues.len()
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    #[test]
269    fn universe_creation() {
270        let uni = DmxUniverse::new(1);
271        assert_eq!(uni.id, 1);
272        assert_eq!(uni.channels[0], 0);
273    }
274
275    #[test]
276    fn universe_set_get_channel() {
277        let mut uni = DmxUniverse::new(1);
278        assert!(uni.set_channel(0, 128));
279        assert_eq!(uni.get_channel(0), Some(128));
280        assert!(!uni.set_channel(512, 255)); // out of range
281    }
282
283    #[test]
284    fn fixture_creation() {
285        let fixture = DmxFixture::new("f1", "Moving Head 1", FixtureType::MovingHead, 1, 0, 16);
286        assert_eq!(fixture.fixture_type, FixtureType::MovingHead);
287        assert_eq!(fixture.channel_count, 16);
288    }
289
290    #[test]
291    fn fixture_set_colour() {
292        let mut fixture = DmxFixture::new("f1", "Par 1", FixtureType::ParCan, 1, 0, 7);
293        fixture.map_channel("red", 0);
294        fixture.map_channel("green", 1);
295        fixture.map_channel("blue", 2);
296        let mut uni = DmxUniverse::new(1);
297        assert!(fixture.set_colour(&mut uni, 255, 0, 128));
298        assert_eq!(uni.get_channel(0), Some(255));
299        assert_eq!(uni.get_channel(1), Some(0));
300        assert_eq!(uni.get_channel(2), Some(128));
301    }
302
303    #[test]
304    fn fixture_set_pan_tilt() {
305        let mut fixture = DmxFixture::new("f1", "MH1", FixtureType::MovingHead, 1, 0, 16);
306        fixture.map_channel("pan", 0);
307        fixture.map_channel("tilt", 1);
308        let mut uni = DmxUniverse::new(1);
309        assert!(fixture.set_pan_tilt(&mut uni, 128, 64));
310        assert_eq!(uni.get_channel(0), Some(128));
311        assert_eq!(uni.get_channel(1), Some(64));
312    }
313
314    #[test]
315    fn cue_creation() {
316        let cue = Cue::new("c1", "Scene 1");
317        assert_eq!(cue.name, "Scene 1");
318        assert_eq!(cue.fade_in, 0.0);
319    }
320
321    #[test]
322    fn cue_set_channels() {
323        let mut cue = Cue::new("c1", "Scene 1");
324        cue.set_channel(1, 0, 255);
325        cue.set_channel(1, 1, 128);
326        assert_eq!(cue.channel_values.len(), 2);
327    }
328
329    #[test]
330    fn cue_apply() {
331        let mut cue = Cue::new("c1", "Scene 1");
332        cue.set_channel(1, 0, 255);
333        let mut universes = BTreeMap::new();
334        universes.insert(1, DmxUniverse::new(1));
335        cue.apply(&mut universes);
336        assert_eq!(universes.get(&1).unwrap().get_channel(0), Some(255));
337    }
338
339    #[test]
340    fn cue_interpolate() {
341        let mut c1 = Cue::new("c1", "A");
342        c1.set_channel(1, 0, 0);
343        let mut c2 = Cue::new("c2", "B");
344        c2.set_channel(1, 0, 255);
345        let mid = c1.interpolate_to(&c2, 0.5);
346        assert_eq!(mid.get(&(1, 0)), Some(&128));
347    }
348
349    #[test]
350    fn cue_stack_go() {
351        let mut stack = CueStack::new("s1", "Show");
352        let mut c1 = Cue::new("c1", "Scene 1");
353        c1.set_channel(1, 0, 255);
354        stack.add_cue(c1);
355        let mut universes = BTreeMap::new();
356        universes.insert(1, DmxUniverse::new(1));
357        assert!(stack.go(&mut universes));
358        assert_eq!(stack.current_index, 1);
359        assert!(!stack.go(&mut universes)); // no more cues
360    }
361
362    #[test]
363    fn cue_stack_go_back() {
364        let mut stack = CueStack::new("s1", "Show");
365        stack.add_cue(Cue::new("c1", "A"));
366        stack.add_cue(Cue::new("c2", "B"));
367        stack.current_index = 1;
368        assert!(stack.go_back());
369        assert_eq!(stack.current_index, 0);
370    }
371
372    #[test]
373    fn cue_stack_reset() {
374        let mut stack = CueStack::new("s1", "Show");
375        stack.add_cue(Cue::new("c1", "A"));
376        stack.current_index = 1;
377        stack.reset();
378        assert_eq!(stack.current_index, 0);
379    }
380}