gled 2.14.0

gled is an application for creating animations and effects on artnet or dmx 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
pub mod scene_instance_path;

use super::{
    AssetTrait, animation::Animation, output_device::routing::OutputRoutings,
    scene::instance::SceneInstance,
};
use crate::{
    app::{svg::Svg, timing::Timing},
    input::{
        artnet::ArtnetConfig,
        event::{GamepadEvent, InputEvent},
    },
    pipeline::{
        extract_output::ExtractOutput,
        group::{Group, Groups},
        output_clear::OutputClear,
        preview::Preview,
        preview_indices::PreviewIndices,
        renderer_callback::RendererCallback,
        transition::{Transition, TransitionGoal},
    },
    storage::{
        asset::{
            Asset, palette::Palette, project::scene_instance_path::SceneInstancePathIndex,
            scene::Scene,
        },
        asset_id::AssetId,
    },
    ui::windows::channel_overwrites::ChannelOverwrites,
    wgpu_render_state,
};
use rand::seq::IndexedMutRandom;
use scene_instance_path::SceneInstancePathId;
use serde::{Deserialize, Serialize};
use std::{
    collections::{BTreeMap, BTreeSet, HashSet},
    time::{Duration, Instant},
};
use uuid::Uuid;
use wgpu::CommandEncoderDescriptor;

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(default)]
pub struct Project {
    pub palette: Option<AssetId<Palette>>,
    pub auto_mode_active: bool,
    pub auto_mode_seconds: u64,
    pub auto_mode_max_scenes: usize,
    #[serde(deserialize_with = "deserialize_groups")]
    pub groups: Groups,
    pub scenes_instances_grid: Vec<SceneInstance>,
    pub scenes_instances_quick: Vec<SceneInstance>,

    #[serde(skip)]
    pub auto_mode_last_change: Option<Instant>,
    pub svg: Option<Svg>,
    pub channel_overwrites: ChannelOverwrites,
    pub output_routings: OutputRoutings,
    pub artnet_config: ArtnetConfig,
    pub tap_input_events: BTreeSet<InputEvent>,
    pub blackout_input_events: BTreeSet<InputEvent>,
    pub blackout_hold_input_events: BTreeSet<InputEvent>,
    pub half_input_events: BTreeSet<InputEvent>,
    pub double_input_events: BTreeSet<InputEvent>,
    pub main_dimmer: f32,
}

impl Default for Project {
    fn default() -> Self {
        Self {
            palette: None,
            auto_mode_active: false,
            auto_mode_seconds: 10,
            auto_mode_max_scenes: 2,
            groups: Groups::default(),
            scenes_instances_grid: Vec::new(),
            scenes_instances_quick: Vec::new(),
            auto_mode_last_change: None,
            svg: Default::default(),
            channel_overwrites: Default::default(),
            output_routings: Default::default(),
            artnet_config: Default::default(),
            tap_input_events: std::iter::once(InputEvent::Key(egui::Key::T))
                .chain(std::iter::once(InputEvent::Gamepad(GamepadEvent::Mode(0))))
                .collect(),
            blackout_input_events: std::iter::once(InputEvent::Key(egui::Key::B)).collect(),
            blackout_hold_input_events: std::iter::once(InputEvent::Key(egui::Key::N))
                .chain(std::iter::once(InputEvent::Gamepad(GamepadEvent::Start(0))))
                .collect(),
            half_input_events: std::iter::once(InputEvent::Key(egui::Key::Minus)).collect(),
            double_input_events: std::iter::once(InputEvent::Key(egui::Key::Plus)).collect(),
            main_dimmer: 1.0,
        }
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DeckPath {
    #[default]
    Grid,
    Quick,
}

impl Project {
    #[inline(always)]
    pub fn all_scene_instances(&mut self) -> impl Iterator<Item = &mut SceneInstance> {
        self.scenes_instances_grid
            .iter_mut()
            .chain(self.scenes_instances_quick.iter_mut())
    }

    pub fn all_scene_instances_id(
        &mut self,
    ) -> impl Iterator<Item = (SceneInstancePathId, &mut SceneInstance)> {
        self.scenes_instances_grid
            .iter_mut()
            .map(|scene_instance| {
                (
                    SceneInstancePathId {
                        deck_path: DeckPath::Grid,
                        id: scene_instance.id,
                    },
                    scene_instance,
                )
            })
            .chain(
                self.scenes_instances_quick
                    .iter_mut()
                    .map(|scene_instance| {
                        (
                            SceneInstancePathId {
                                deck_path: DeckPath::Quick,
                                id: scene_instance.id,
                            },
                            scene_instance,
                        )
                    }),
            )
    }

    pub fn all_scene_instances_index(
        &mut self,
    ) -> impl Iterator<Item = (SceneInstancePathIndex, &mut SceneInstance)> {
        self.scenes_instances_grid
            .iter_mut()
            .enumerate()
            .map(|(index, scene_instance)| {
                (
                    SceneInstancePathIndex {
                        deck_path: DeckPath::Grid,
                        index,
                    },
                    scene_instance,
                )
            })
            .chain(self.scenes_instances_quick.iter_mut().enumerate().map(
                |(index, scene_instance)| {
                    (
                        SceneInstancePathIndex {
                            deck_path: DeckPath::Quick,
                            index,
                        },
                        scene_instance,
                    )
                },
            ))
    }

    pub fn reload_shader_code(&mut self, animation: AssetId<Animation>) {
        self.all_scene_instances().for_each(|scene_instance| {
            scene_instance.reload_shader_code(animation);
        });
    }

    pub fn send_positions(&mut self) {
        self.all_scene_instances().for_each(|scene_instance| {
            scene_instance.send_positions();
        });
    }

    pub fn init_gpu(&mut self) {
        self.all_scene_instances().for_each(|scene_instance| {
            scene_instance.init_states();
        });
        self.set_buffers();
    }

    pub fn set_buffers(&mut self) {
        self.all_scene_instances().for_each(|scene_instance| {
            scene_instance.set_output_mix_buffers();
        });
        Preview::set_buffers();
    }

    #[inline(always)]
    pub fn scene_instance(&mut self, path: SceneInstancePathId) -> Option<&mut SceneInstance> {
        match path.deck_path {
            DeckPath::Grid => self
                .scenes_instances_grid
                .iter_mut()
                .find(|scene_instance| scene_instance.id == path.id),
            DeckPath::Quick => self
                .scenes_instances_quick
                .iter_mut()
                .find(|scene_instance| scene_instance.id == path.id),
        }
    }

    pub fn scene_instance_by_index(
        &mut self,
        path: SceneInstancePathIndex,
    ) -> Option<&mut SceneInstance> {
        match path.deck_path {
            DeckPath::Grid => self.scenes_instances_grid.get_mut(path.index),
            DeckPath::Quick => self.scenes_instances_quick.get_mut(path.index),
        }
    }

    #[inline(always)]
    pub fn scene_instances(&mut self, deck_path: DeckPath) -> &mut Vec<SceneInstance> {
        match deck_path {
            DeckPath::Grid => &mut self.scenes_instances_grid,
            DeckPath::Quick => &mut self.scenes_instances_quick,
        }
    }

    /// Remove scene instance at path and update path to the next scene instance
    pub fn remove_scene_instance(
        &mut self,
        path: &mut SceneInstancePathId,
    ) -> Option<SceneInstance> {
        let scene_instances = match path.deck_path {
            DeckPath::Grid => &mut self.scenes_instances_grid,
            DeckPath::Quick => &mut self.scenes_instances_quick,
        };

        let pos = scene_instances.iter().position(|s| s.id == path.id)?;
        let scene_instance = scene_instances.remove(pos);
        path.id = scene_instances
            .get(pos.saturating_sub(1))
            .map_or_else(Uuid::nil, |s| s.id);
        Some(scene_instance)
    }

    #[allow(clippy::too_many_arguments)]
    pub fn render(
        &mut self,
        timing: &Timing,
        blackout: bool,
        always_render: bool,
        fade_duration: Duration,
    ) {
        let wgpu_render_state = wgpu_render_state();
        let device = wgpu_render_state.device;
        let queue = &wgpu_render_state.queue;

        if self.auto_mode_active {
            if self
                .auto_mode_last_change
                .get_or_insert_with(Instant::now)
                .elapsed()
                .as_secs()
                > self.auto_mode_seconds
            {
                let auto_mode_max_scenes = self.auto_mode_max_scenes;
                let mut prev = HashSet::new();
                {
                    let mut indices = self
                        .scenes_instances_grid
                        .iter()
                        .enumerate()
                        .filter(|(_index, scene)| scene.active)
                        .map(|(index, _scene)| index)
                        .collect::<Vec<_>>();

                    let mut disable_count =
                        (indices.len() + 1).saturating_sub(auto_mode_max_scenes);
                    while disable_count > 0 {
                        if let Some(index) = indices.choose_mut(&mut rand::rng()).copied() {
                            if prev.insert(index) {
                                disable_count -= 1;
                                if let Some(scene) = self.scenes_instances_grid.get_mut(index) {
                                    scene.set_transition(Transition::new(
                                        TransitionGoal::TurnOff,
                                        fade_duration,
                                    ));
                                }
                            }
                        }
                    }
                }

                let mut scenes = self
                    .scenes_instances_grid
                    .iter_mut()
                    .enumerate()
                    .filter(|(index, _scene)| !prev.contains(index))
                    .collect::<Vec<_>>();
                if let Some((_index, scene)) = scenes.choose_mut(&mut rand::rng()) {
                    scene.set_transition(Transition::new(TransitionGoal::TurnOn, fade_duration));
                }

                self.auto_mode_last_change.take();
            }
        } else {
            self.auto_mode_last_change.take();
        }

        let palette = self.palette.and_then(Asset::get);
        let deck_groups = self.groups.clone();
        let main_dimmer = self.main_dimmer;
        for scene_instance in self.all_scene_instances() {
            scene_instance.prepare(
                queue,
                always_render,
                palette.clone(),
                &deck_groups,
                timing,
                main_dimmer,
            );
        }

        PreviewIndices::get().prepare(queue);

        let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor {
            label: Some("Render animations"),
        });

        OutputClear::get().run(&mut encoder);

        for scene_instance in self.all_scene_instances() {
            scene_instance.render(&mut encoder, blackout, always_render);
        }

        ExtractOutput::get().run(&mut encoder);
        PreviewIndices::get().run(&mut encoder);
        Preview::run(&mut encoder);

        RendererCallback::add(encoder.finish());
    }

    pub fn tap_input_is_new(&self) -> bool {
        self.tap_input_events.iter().any(|event| event.is_new())
    }

    pub fn blackout_input_is_new(&self) -> bool {
        self.blackout_input_events
            .iter()
            .any(|event| event.is_new())
    }

    pub fn blackout_hold_input_is_live(&self) -> bool {
        self.blackout_hold_input_events
            .iter()
            .any(|event| event.is_live())
    }

    pub fn half_input_is_new(&self) -> bool {
        self.half_input_events.iter().any(|event| event.is_new())
    }

    pub fn double_input_is_new(&self) -> bool {
        self.double_input_events.iter().any(|event| event.is_new())
    }

    pub fn add_scene(&mut self, deck_path: DeckPath, scene: AssetId<Scene>) -> SceneInstancePathId {
        let mut scene_instance: SceneInstance = scene.into();
        scene_instance.init_states();
        self.add_scene_instance(deck_path, scene_instance)
    }

    pub fn add_scene_instance(
        &mut self,
        deck_path: DeckPath,
        scene_instance: SceneInstance,
    ) -> SceneInstancePathId {
        let scene_instances = match deck_path {
            DeckPath::Grid => &mut self.scenes_instances_grid,
            DeckPath::Quick => &mut self.scenes_instances_quick,
        };
        let path = SceneInstancePathId {
            deck_path,
            id: scene_instance.id,
        };
        scene_instances.push(scene_instance);
        path
    }

    pub fn remove_nonexistant_groups(&mut self) {
        self.groups.remove_nonexistant_groups();
        for scene_instance in self.all_scene_instances() {
            scene_instance.remove_nonexistant_groups();
        }
    }
}

impl AssetTrait for Project {
    const DIR_NAME: &'static str = "projects";
    const NAME: &'static str = "Project";
    const SHOW_NAME_IF_SELECTED: bool = true;
}

fn deserialize_groups<'de, D>(deserializer: D) -> Result<Groups, D::Error>
where
    D: serde::Deserializer<'de>,
{
    BTreeMap::<String, Group>::deserialize(deserializer).map(|map| {
        Groups::new(
            map.into_iter()
                .filter_map(|(index, group)| index.parse().ok().map(|index| (index, group)))
                .collect(),
        )
    })
}