laser-dac 0.10.0

Unified laser DAC abstraction supporting multiple protocols
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//! PresentationEngine and ColorDelayLine — core frame lifecycle internals.

use crate::types::LaserPoint;

use super::{Frame, TransitionFn, TransitionPlan};

// =============================================================================
// PresentationEngine
// =============================================================================

/// Core frame lifecycle manager.
///
/// Manages the current and pending frames, cursor position, and transition
/// point insertion. Provides two delivery modes:
///
/// - [`fill_chunk`](Self::fill_chunk): FIFO delivery for queue-based DACs.
///   Traverses the drawable, inserting transition points at frame boundaries.
/// - [`compose_hardware_frame`](Self::compose_hardware_frame): Frame-swap
///   delivery. Returns a complete composed frame with transition points.
pub(crate) struct PresentationEngine {
    /// The currently playing frame.
    pub(crate) current_base: Option<Frame>,
    /// The next frame to promote (latest-wins).
    pub(crate) pending_base: Option<Frame>,
    /// Working buffer: base-only frame points (FIFO) or composed frame (FrameSwap).
    drawable: Vec<LaserPoint>,
    /// Whether the drawable needs to be rebuilt from current_base.
    drawable_dirty: bool,
    /// Current read cursor within `drawable`.
    cursor: usize,
    /// Transition function for generating blanking between frames.
    transition_fn: TransitionFn,
    /// Buffer for transition points injected between frames.
    transition_buf: Vec<LaserPoint>,
    /// Read cursor within transition_buf.
    transition_cursor: usize,
    /// True when transition_buf holds self-loop points (can be discarded if
    /// a pending frame arrives before they are fully drained).
    transition_is_self_loop: bool,
    /// Length of the transition prefix in the last composed frame-swap drawable.
    frame_swap_transition_len: usize,
    /// Maximum hardware frame capacity (frame-swap only). When set, composed
    /// frames are clamped by truncating the transition prefix.
    frame_capacity: Option<usize>,
}

impl PresentationEngine {
    /// Create a new engine with the given transition function.
    pub fn new(transition_fn: TransitionFn) -> Self {
        Self {
            current_base: None,
            pending_base: None,
            drawable: Vec::new(),
            drawable_dirty: true,
            cursor: 0,
            transition_fn,
            transition_buf: Vec::new(),
            transition_cursor: 0,
            transition_is_self_loop: false,
            frame_swap_transition_len: 0,
            frame_capacity: None,
        }
    }

    /// Set the maximum hardware frame capacity for frame-swap clamping.
    pub fn set_frame_capacity(&mut self, cap: Option<usize>) {
        self.frame_capacity = cap;
    }

    /// Reset all runtime state. Preserves the transition_fn and frame_capacity.
    pub fn reset(&mut self) {
        self.current_base = None;
        self.pending_base = None;
        self.drawable.clear();
        self.drawable_dirty = true;
        self.cursor = 0;
        self.transition_buf.clear();
        self.transition_cursor = 0;
        self.transition_is_self_loop = false;
        self.frame_swap_transition_len = 0;
    }

    /// Submit a new frame. Latest-wins: multiple calls before consumption
    /// keep only the most recent frame.
    ///
    /// If no current frame exists, the pending is immediately promoted.
    pub fn set_pending(&mut self, frame: Frame) {
        if self.current_base.is_none() {
            self.current_base = Some(frame);
            self.drawable_dirty = true;
            self.cursor = 0;
        } else {
            self.pending_base = Some(frame);
            // Don't mark dirty yet — we compose on promotion
        }
    }

    /// FIFO delivery: fill `buffer[..max_points]` from the current frame.
    ///
    /// Traverses the base frame points cyclically. At each seam (cursor
    /// wrap), the transition function is called dynamically against the
    /// latest pending frame (if any) or the current frame (self-loop).
    /// This ensures the seam always reflects the most recent state — no
    /// stale self-loop transition is emitted before a real frame change.
    ///
    /// Returns the number of points written (always `max_points` if a
    /// frame is available, 0 if no frame has been submitted).
    pub fn fill_chunk(&mut self, buffer: &mut [LaserPoint], max_points: usize) -> usize {
        let max_points = max_points.min(buffer.len());

        // Before first frame: output blanked at origin
        if self.current_base.is_none() {
            for p in &mut buffer[..max_points] {
                *p = LaserPoint::blanked(0.0, 0.0);
            }
            return max_points;
        }

        // Rebuild drawable if dirty
        if self.drawable_dirty {
            self.refresh_drawable();
        }

        if self.drawable.is_empty() {
            for p in &mut buffer[..max_points] {
                *p = LaserPoint::blanked(0.0, 0.0);
            }
            return max_points;
        }

        let mut written = 0;
        while written < max_points {
            // Drain pending transition points — but if they are stale
            // self-loop points and a pending frame has arrived, discard
            // them and promote immediately.
            if self.transition_cursor < self.transition_buf.len() {
                if self.transition_is_self_loop && self.pending_base.is_some() {
                    // Stale self-loop transition: discard and promote now
                    self.transition_buf.clear();
                    self.transition_cursor = 0;
                    self.transition_is_self_loop = false;
                    self.promote_pending();

                    if self.drawable.is_empty() {
                        for p in &mut buffer[written..max_points] {
                            *p = LaserPoint::blanked(0.0, 0.0);
                        }
                        return max_points;
                    }
                    continue;
                }

                buffer[written] = self.transition_buf[self.transition_cursor];
                self.transition_cursor += 1;
                written += 1;
                continue;
            }

            // Output current frame point
            buffer[written] = self.drawable[self.cursor];
            written += 1;
            self.cursor += 1;

            // At the seam: compute transition dynamically against pending or self
            if self.cursor >= self.drawable.len() {
                if self.pending_base.is_some() {
                    self.promote_pending();

                    if self.drawable.is_empty() {
                        for p in &mut buffer[written..max_points] {
                            *p = LaserPoint::blanked(0.0, 0.0);
                        }
                        return max_points;
                    }
                } else {
                    // Self-loop: compute seam dynamically (current.last → current.first)
                    let outgoing_last = self
                        .current_base
                        .as_ref()
                        .and_then(|f| f.last_point())
                        .copied();
                    let incoming_first = self
                        .current_base
                        .as_ref()
                        .and_then(|f| f.first_point())
                        .copied();

                    match (outgoing_last, incoming_first) {
                        (Some(last), Some(first)) => match (self.transition_fn)(&last, &first) {
                            TransitionPlan::Transition(points) => {
                                self.transition_buf = points;
                                self.transition_cursor = 0;
                                self.transition_is_self_loop = true;
                                self.cursor = 0;
                            }
                            TransitionPlan::Coalesce => {
                                self.transition_buf.clear();
                                self.cursor = if self.drawable.len() > 1 { 1 } else { 0 };
                            }
                        },
                        _ => {
                            self.cursor = 0;
                        }
                    }
                }
            }
        }

        written
    }

    /// Frame-swap delivery: compose and return a complete hardware frame.
    ///
    /// On frame change (A→B): computes `transition_fn(A.last, B.first)`,
    /// composes `[transition | B_points]`, then promotes B to current.
    /// The next call without a pending frame will recompute the self-loop.
    ///
    /// On self-loop (no pending): computes `transition_fn(A.last, A.first)`,
    /// composes `[transition | A_points]` (or coalesced).
    pub fn compose_hardware_frame(&mut self) -> &[LaserPoint] {
        if let Some(pending) = self.pending_base.take() {
            // Frame change: A→B transition.
            // Compute transition from current (A) to pending (B) BEFORE promoting.
            let plan = match &self.current_base {
                Some(current) => match (current.last_point(), pending.first_point()) {
                    (Some(last), Some(first)) => (self.transition_fn)(last, first),
                    _ => TransitionPlan::Transition(vec![]),
                },
                None => TransitionPlan::Transition(vec![]),
            };

            self.drawable.clear();
            match plan {
                TransitionPlan::Transition(transition) => {
                    self.frame_swap_transition_len = transition.len();
                    self.drawable.extend_from_slice(&transition);
                    self.drawable.extend_from_slice(pending.points());
                }
                TransitionPlan::Coalesce => {
                    self.frame_swap_transition_len = 0;
                    // A.last ≈ B.first — skip B's first point to avoid a
                    // duplicate logical seam sample in the hardware frame.
                    let pts = pending.points();
                    if pts.len() > 1 {
                        self.drawable.extend_from_slice(&pts[1..]);
                    } else {
                        self.drawable.extend_from_slice(pts);
                    }
                }
            }

            // Empty frame submitted: send a blanked point to clear the display
            if self.drawable.is_empty() {
                self.drawable.push(LaserPoint::blanked(0.0, 0.0));
            }

            self.clamp_to_capacity();

            // Promote B to current. Mark dirty so next call builds self-loop.
            self.current_base = Some(pending);
            self.drawable_dirty = true;

            return &self.drawable;
        }

        // No pending: self-loop for current frame.
        if self.drawable_dirty {
            self.refresh_drawable_for_frame_swap();
        }

        &self.drawable
    }

    /// Rebuild drawable for frame-swap: includes self-loop transition.
    ///
    /// Frame-swap DACs send the entire drawable as one atomic frame, so the
    /// transition from last→first point is included for clean looping.
    /// For nearly-closed shapes (circles), `Coalesce` omits the last base
    /// point so the frame loops seamlessly without a duplicate seam point.
    fn refresh_drawable_for_frame_swap(&mut self) {
        self.drawable.clear();
        self.drawable_dirty = false;

        let Some(current) = &self.current_base else {
            self.frame_swap_transition_len = 0;
            return;
        };

        if current.is_empty() {
            self.frame_swap_transition_len = 0;
            self.drawable.push(LaserPoint::blanked(0.0, 0.0));
            return;
        }

        let points = current.points();
        self.frame_swap_transition_len =
            build_self_loop_drawable(&self.transition_fn, points, &mut self.drawable, true);
        self.clamp_to_capacity();
    }

    /// Truncate the transition prefix so the drawable fits within frame_capacity.
    /// Never removes authored frame points — only the leading transition.
    fn clamp_to_capacity(&mut self) {
        if let Some(cap) = self.frame_capacity {
            if self.drawable.len() > cap {
                let excess = self.drawable.len() - cap;
                let trim = excess.min(self.frame_swap_transition_len);
                self.drawable.drain(..trim);
                self.frame_swap_transition_len -= trim;
            }
        }
    }

    /// Promote pending frame to current for FIFO delivery.
    ///
    /// Computes the A→B transition, promotes the pending frame, rebuilds
    /// the drawable, and sets the cursor appropriately.
    fn promote_pending(&mut self) {
        let pending = self.pending_base.take().unwrap();

        let outgoing_last = self
            .current_base
            .as_ref()
            .and_then(|f| f.last_point())
            .copied();
        let mut coalesce = false;

        if let (Some(last), Some(first)) = (outgoing_last.as_ref(), pending.first_point()) {
            match (self.transition_fn)(last, first) {
                TransitionPlan::Transition(points) => {
                    self.transition_buf = points;
                    self.transition_cursor = 0;
                    self.transition_is_self_loop = false;
                }
                TransitionPlan::Coalesce => {
                    self.transition_buf.clear();
                    coalesce = true;
                }
            }
        }

        self.current_base = Some(pending);
        self.refresh_drawable();

        if coalesce {
            self.cursor = if self.drawable.len() > 1 { 1 } else { 0 };
        } else {
            self.cursor = 0;
        }
    }

    /// Rebuild the FIFO drawable from the current base frame.
    ///
    /// Contains only the base frame points. Transition points are computed
    /// dynamically at seam time in `fill_chunk`.
    fn refresh_drawable(&mut self) {
        self.drawable.clear();
        self.drawable_dirty = false;

        let Some(current) = &self.current_base else {
            return;
        };

        if current.is_empty() {
            return;
        }

        self.drawable.extend_from_slice(current.points());
    }
}

/// Build a seam-adjusted drawable for a self-loop, applying the transition
/// function to the seam between the frame's last and first points.
///
/// For `Transition(points)`: places transition as prefix (frame-swap) or
/// suffix (FIFO) depending on `prefix_mode`.
///
/// For `Coalesce`: omits the last base point so the loop represents the
/// seam point once. Single-point frames are kept unchanged.
///
/// Returns the number of transition points in the drawable.
fn build_self_loop_drawable(
    transition_fn: &TransitionFn,
    base: &[LaserPoint],
    drawable: &mut Vec<LaserPoint>,
    prefix_mode: bool,
) -> usize {
    let last = base.last().unwrap();
    let first = base.first().unwrap();
    let plan = transition_fn(last, first);

    match plan {
        TransitionPlan::Transition(pts) => {
            let transition_len = pts.len();
            if prefix_mode {
                drawable.extend_from_slice(&pts);
                drawable.extend_from_slice(base);
            } else {
                drawable.extend_from_slice(base);
                drawable.extend_from_slice(&pts);
            }
            transition_len
        }
        TransitionPlan::Coalesce => {
            if base.len() > 1 {
                // Omit the last base point — on wrap, cursor returns to
                // first which is the same logical point.
                drawable.extend_from_slice(&base[..base.len() - 1]);
            } else {
                drawable.extend_from_slice(base);
            }
            0
        }
    }
}

// =============================================================================
// ColorDelayLine
// =============================================================================

/// Stateful color delay that carries across chunk boundaries.
///
/// For FIFO DACs, color delay is applied per-chunk. Without carry-over state,
/// the first `delay` points of every chunk get blanked, causing periodic
/// micro-brightness drops at chunk boundaries. This struct maintains a ring
/// buffer of the last `delay` color values so they carry into the next chunk.
pub(crate) struct ColorDelayLine {
    delay: usize,
    /// Ring buffer of the last `delay` colors from the previous chunk.
    carry: Vec<(u16, u16, u16, u16)>,
    /// Pre-allocated buffer for current chunk colors (avoids per-chunk allocation).
    scratch: Vec<(u16, u16, u16, u16)>,
}

impl ColorDelayLine {
    pub fn new(delay: usize) -> Self {
        Self {
            delay,
            carry: vec![(0, 0, 0, 0); delay],
            scratch: Vec::new(),
        }
    }

    /// Reset the carry buffer (e.g., after reconnect).
    pub fn reset(&mut self) {
        self.carry.fill((0, 0, 0, 0));
    }

    /// Apply color delay to a chunk, using carried state from the previous chunk.
    pub fn apply(&mut self, points: &mut [LaserPoint]) {
        if self.delay == 0 || points.is_empty() {
            return;
        }

        // Collect current colors into pre-allocated scratch buffer
        self.scratch.clear();
        self.scratch
            .extend(points.iter().map(|p| (p.r, p.g, p.b, p.intensity)));

        // Apply delay: for the first `delay` points, use the carry buffer;
        // for the rest, use colors from earlier in this chunk.
        for (i, point) in points.iter_mut().enumerate() {
            let (r, g, b, intensity) = if i < self.delay {
                // Use carried colors from previous chunk
                let carry_idx = self.carry.len() - self.delay + i;
                self.carry[carry_idx]
            } else {
                self.scratch[i - self.delay]
            };
            point.r = r;
            point.g = g;
            point.b = b;
            point.intensity = intensity;
        }

        // Update carry buffer: keep the last `delay` colors from this chunk
        let n = self.scratch.len();
        if n >= self.delay {
            self.carry.clear();
            self.carry
                .extend_from_slice(&self.scratch[n - self.delay..]);
        } else {
            // Chunk smaller than delay: shift carry and append
            self.carry.drain(..n);
            self.carry.extend_from_slice(&self.scratch);
            debug_assert_eq!(self.carry.len(), self.delay);
        }
    }
}