gled 2.1.0

gled is an application for creating animations and effects on artnet or wled light installations
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
//! Save the list of LEDs, a position for color measurement and the current color for groups.

use super::{Led, Parameter, ParsedSvg};
use crate::pipeline::{
    constants::UNIVERSES,
    group::Group,
    texture_to_output::positions::{Lamp, Positions, Universe},
};
use egui::{Pos2, Rect};
use kurbo::{ParamCurve, ParamCurveArclen};
use log::debug;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use tiny_skia::{Path, PathSegment, Point};
use usvg::Node;

pub type Universes = BTreeSet<u16>;

#[derive(Clone, Debug, Default)]
pub struct MeasurementPoints {
    /// points for each group
    points: BTreeMap<Group, Vec<MeasurementPoint>>,
    /// Positions of each individual led
    preview_positions: Positions,
    uv: Option<Option<Rect>>,
}

impl MeasurementPoints {
    pub const fn new() -> Self {
        Self {
            points: BTreeMap::new(),
            preview_positions: Positions::new(),
            uv: None,
        }
    }

    pub fn universes(&self) -> Universes {
        self.points
            .values()
            .flat_map(|points| points.iter())
            .flat_map(|point| point.leds.iter())
            .map(|led| led.universe)
            .collect()
    }

    pub fn positions(&self, group: &Group) -> Positions {
        let mut positions = Positions::default();

        if let Some(points) = self.points.get(group) {
            let mut universes = BTreeMap::new();
            for point in points.iter() {
                let lamp = Lamp::Position {
                    x: point.x,
                    y: point.y,
                };

                for led in point.leds.iter() {
                    let i = led.num;

                    let universe = universes
                        .entry(led.universe)
                        .or_insert_with(|| Universe::new(Some(led.universe)));
                    universe.lamps[i] = lamp;
                }
            }

            for (i, universe) in self
                .universes()
                .into_iter()
                .enumerate()
                .take(UNIVERSES as usize)
            {
                if let Some(universe) = universes.remove(&universe) {
                    positions.universes[i] = universe;
                }
            }
        }

        positions
    }

    pub fn preview_positions(&self) -> Positions {
        self.preview_positions.clone()
    }

    pub fn preview_uv(&mut self) -> Option<Rect> {
        *self.uv.get_or_insert_with(|| {
            self.preview_positions
                .universes
                .iter()
                .flat_map(|universe| universe.lamps.iter())
                .fold(None, |uv, lamp| match (uv, lamp) {
                    (uv, Lamp::None) => uv,
                    (None, Lamp::Position { x, y }) => {
                        Some(Rect::from_min_max(Pos2::new(*x, *y), Pos2::new(*x, *y)))
                    }
                    (Some(mut uv), Lamp::Position { x, y }) => {
                        if uv.min.x > *x {
                            uv.min.x = *x;
                        }
                        if uv.min.y > *y {
                            uv.min.y = *y;
                        }
                        if uv.max.x < *x {
                            uv.max.x = *x;
                        }
                        if uv.max.y < *y {
                            uv.max.y = *y;
                        }
                        Some(uv)
                    }
                })
                .map(|mut uv| {
                    const BORDER: f32 = 0.03;

                    uv.min.y = (uv.min.y - BORDER).max(0.0);
                    uv.min.x = (uv.min.x - BORDER).max(0.0);
                    uv.max.x = (uv.max.x + BORDER).min(1.0);
                    uv.max.y = (uv.max.y + BORDER).min(1.0);

                    uv
                })
        })
    }

    pub fn groups(&self) -> Vec<Group> {
        self.points.keys().cloned().collect()
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct MeasurementPoint {
    leds: Vec<Led>,
    x: f32,
    y: f32,
}

fn traverse_nodes(group: &usvg::Group) -> Vec<&Node> {
    let mut nodes = vec![];
    for child in group.children() {
        nodes.push(child);
        if let Node::Group(group) = child {
            nodes.extend(traverse_nodes(group));
        }
    }
    nodes
}

impl From<&ParsedSvg> for MeasurementPoints {
    fn from(svg: &ParsedSvg) -> Self {
        debug!("find measurement points");

        let size = svg.tree.size();
        let max = size.width().max(size.height());
        let mut points = BTreeMap::new();

        traverse_nodes(svg.tree.root())
            .into_iter()
            .for_each(|node| {
                if let Some(parameter) = svg.parameters.get(node.id()) {
                    parameter.groups.iter().cloned().for_each(|group| {
                        let measurement_points = points.entry(group).or_insert_with(Vec::new);
                        match node {
                            Node::Path(path) if parameter.count > 1 => {
                                let path_data = path
                                    .data()
                                    .clone()
                                    .transform(node.abs_transform())
                                    .unwrap_or_else(|| path.data().clone());
                                leds_on_path(
                                    max,
                                    parameter.count,
                                    path_data,
                                    parameter,
                                    measurement_points,
                                );
                            }
                            _ => {
                                let rect = &node.abs_bounding_box();
                                let x = (rect.x() + rect.width() / 2.0) / max;
                                let y = (rect.y() + rect.height() / 2.0) / max;
                                measurement_points.push(MeasurementPoint {
                                    leds: parameter.leds.clone(),
                                    x,
                                    y,
                                });
                            }
                        }
                    });
                }
            });

        debug!("Done finding measurement points");
        debug!("Determining preview positions");

        let mut measurement_points = MeasurementPoints {
            points,
            preview_positions: Positions::default(),
            uv: None,
        };
        let universes: BTreeMap<u16, usize> = measurement_points
            .universes()
            .into_iter()
            .enumerate()
            .map(|(index, universe)| (universe, index))
            .collect();

        for measurement_point in measurement_points
            .points
            .values()
            .flat_map(|measurement_points| measurement_points.iter())
        {
            if measurement_point.leds.len() == 1 {
                let led = measurement_point
                    .leds
                    .first()
                    .expect("Could not find first led");
                let num = led.num;
                if let Some(universe_index) = universes.get(&led.universe) {
                    measurement_points.preview_positions.universes[*universe_index].lamps[num] =
                        Lamp::Position {
                            x: measurement_point.x,
                            y: measurement_point.y,
                        }
                }
            }
        }

        debug!("Done determining preview positions");

        measurement_points
    }
}

fn leds_on_path(
    max: f32,
    leds: usize,
    path_data: Path,
    parameter: &Parameter,
    measurement_points: &mut Vec<MeasurementPoint>,
) {
    assert_eq!(leds, parameter.leds.len());
    let path_length = path_length(&path_data) as f32;
    let led_distance = path_length / f64::from(leds as i32 - 1) as f32;
    let mut leds_added: usize = 0;
    let mut path_position: f32 = 0.0;
    let mut prev_x = 0.0;
    let mut prev_y = 0.0;
    path_data.segments().for_each(|segment| match segment {
        PathSegment::MoveTo(Point { x, y }) => {
            measurement_points.push(MeasurementPoint {
                leds: vec![parameter
                    .leds
                    .get(leds_added)
                    .expect("Could not find led")
                    .clone()],
                x: x / max,
                y: y / max,
            });
            leds_added += 1;

            prev_x = x;
            prev_y = y;
        }
        PathSegment::LineTo(Point { x, y }) => {
            let delta_x = x - prev_x;
            let delta_y = y - prev_y;
            let mut segment_position =
                led_distance * f64::from(leds_added as i32) as f32 - path_position;
            let segment_length = (delta_x.powi(2) + delta_y.powi(2)).sqrt();

            while segment_position <= segment_length {
                let x = prev_x + delta_x * segment_position / segment_length;
                let y = prev_y + delta_y * segment_position / segment_length;
                measurement_points.push(MeasurementPoint {
                    leds: vec![parameter
                        .leds
                        .get(leds_added)
                        .expect("Could not find led")
                        .clone()],
                    x: x / max,
                    y: y / max,
                });
                leds_added += 1;
                segment_position += led_distance;
            }

            prev_x = x;
            prev_y = y;
            path_position += segment_length;
        }
        PathSegment::CubicTo(Point { x: x1, y: y1 }, Point { x: x2, y: y2 }, Point { x, y }) => {
            let curve = kurbo::CubicBez::new(
                (prev_x as f64, prev_y as f64),
                (x1 as f64, y1 as f64),
                (x2 as f64, y2 as f64),
                (x as f64, y as f64),
            );
            let n = ((10.0 * curve.arclen(1.0)).ln() / 2_f64.ln()).ceil() as usize;
            let mut curves = vec![curve];
            { 0..n }.for_each(|_| {
                curves = curves
                    .iter()
                    .flat_map(|curve| {
                        let curves = curve.subdivide();
                        std::iter::once(curves.0).chain(std::iter::once(curves.1))
                    })
                    .collect();
            });
            curves.drain(..).for_each(|curve| {
                path_position += curve.arclen(1.0) as f32;
                if path_position >= led_distance * f64::from(leds_added as i32) as f32 {
                    let end = curve.end();
                    measurement_points.push(MeasurementPoint {
                        leds: vec![parameter
                            .leds
                            .get(leds_added)
                            .expect("Could not find led")
                            .clone()],
                        x: end.x as f32 / max,
                        y: end.y as f32 / max,
                    });
                    leds_added += 1;
                }
            });
            prev_x = x;
            prev_y = y;
        }
        PathSegment::QuadTo(Point { x: x1, y: y1 }, Point { x, y }) => {
            let curve = kurbo::QuadBez::new(
                kurbo::Point::new(prev_x as f64, prev_y as f64),
                kurbo::Point::new(x1 as f64, y1 as f64),
                kurbo::Point::new(x as f64, y as f64),
            );
            let n = ((10.0 * curve.arclen(1.0)).ln() / 2_f64.ln()).ceil() as usize;
            let mut curves = vec![curve];
            { 0..n }.for_each(|_| {
                curves = curves
                    .iter()
                    .flat_map(|curve| {
                        let curves = curve.subdivide();
                        std::iter::once(curves.0).chain(std::iter::once(curves.1))
                    })
                    .collect();
            });
            curves.drain(..).for_each(|curve| {
                path_position += curve.arclen(1.0) as f32;
                if path_position >= led_distance * f64::from(leds_added as i32) as f32 {
                    let end = curve.end();
                    measurement_points.push(MeasurementPoint {
                        leds: vec![parameter
                            .leds
                            .get(leds_added)
                            .expect("Could not find led")
                            .clone()],
                        x: end.x as f32 / max,
                        y: end.y as f32 / max,
                    });
                    leds_added += 1;
                }
            });
            prev_x = x;
            prev_y = y;
        }
        PathSegment::Close => {}
    });

    if leds_added == leds - 1 {
        measurement_points.push(MeasurementPoint {
            leds: vec![parameter
                .leds
                .get(leds_added)
                .expect("Could not find led")
                .clone()],
            x: prev_x / max,
            y: prev_y / max,
        });
        leds_added += 1;
    }
    assert!((path_length - path_position).abs() < 1.0);
    assert_eq!(leds_added, leds);
}

fn path_length(path: &tiny_skia::Path) -> f64 {
    let mut prev_mx = path.points()[0].x;
    let mut prev_my = path.points()[0].y;
    let mut prev_x = prev_mx;
    let mut prev_y = prev_my;

    fn create_curve_from_line(px: f32, py: f32, x: f32, y: f32) -> kurbo::CubicBez {
        let line = kurbo::Line::new(
            kurbo::Point::new(px as f64, py as f64),
            kurbo::Point::new(x as f64, y as f64),
        );
        let p1 = line.eval(0.33);
        let p2 = line.eval(0.66);
        kurbo::CubicBez::new(line.p0, p1, p2, line.p1)
    }

    let mut length = 0.0;
    for seg in path.segments() {
        let curve = match seg {
            tiny_skia::PathSegment::MoveTo(p) => {
                prev_mx = p.x;
                prev_my = p.y;
                prev_x = p.x;
                prev_y = p.y;
                continue;
            }
            tiny_skia::PathSegment::LineTo(p) => create_curve_from_line(prev_x, prev_y, p.x, p.y),
            tiny_skia::PathSegment::QuadTo(p1, p) => kurbo::QuadBez::new(
                kurbo::Point::new(prev_x as f64, prev_y as f64),
                kurbo::Point::new(p1.x as f64, p1.y as f64),
                kurbo::Point::new(p.x as f64, p.y as f64),
            )
            .raise(),
            tiny_skia::PathSegment::CubicTo(p1, p2, p) => kurbo::CubicBez::new(
                kurbo::Point::new(prev_x as f64, prev_y as f64),
                kurbo::Point::new(p1.x as f64, p1.y as f64),
                kurbo::Point::new(p2.x as f64, p2.y as f64),
                kurbo::Point::new(p.x as f64, p.y as f64),
            ),
            tiny_skia::PathSegment::Close => {
                create_curve_from_line(prev_x, prev_y, prev_mx, prev_my)
            }
        };

        length += curve.arclen(0.5);
        prev_x = curve.p3.x as f32;
        prev_y = curve.p3.y as f32;
    }

    length
}