Skip to main content

gled_protocol/
state.rs

1//! What the engine publishes to its user interfaces, and what they send it
2//! besides actions. In-process the desktop app gets these over channels;
3//! remote interfaces get them as `message`s.
4
5use std::{
6    collections::{BTreeMap, BTreeSet},
7    sync::Arc,
8};
9
10use gled_model::{
11    asset::{
12        animation::Animation,
13        output_device::routing::{OutputRouting, OutputRoutings},
14        project::{Project, io::ArtnetConfig},
15        scene::grid::GridLocation,
16    },
17    asset_id::AssetId,
18    input::key_code::KeyCode,
19    patching::color_orders::ColorOrders,
20    sound::{AudioDeviceId, trigger_params::FREQ_BINS, trigger_ref::SoundLevels},
21    timing::BeatState,
22};
23use serde::{Deserialize, Serialize};
24use uuid::Uuid;
25
26use crate::{
27    action::UiAction,
28    assets::{AnyAsset, AnyAssetId},
29    bytes::SharedBytes,
30    midi::TestCommand,
31};
32
33/// Which universes are rendered, where they are routed and in which channel
34/// order their lamps take red, green and blue.
35#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
36pub struct OutputConfig {
37    pub universes: Arc<BTreeSet<u16>>,
38    pub routings: Arc<OutputRoutings>,
39    /// Lamps that are not RGB, derived from the patch with the universes.
40    #[serde(default)]
41    pub color_orders: Arc<ColorOrders>,
42}
43
44/// How the render thread keeps up, over the last second.
45#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
46pub struct RenderStats {
47    pub fps: f32,
48    /// The longest time between two frames.
49    pub max_frame_ms: f32,
50}
51
52/// What the machine running the engine is doing besides the show.
53#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
54#[serde(default)]
55pub struct ServerStatus {
56    /// What the asset repository is busy with, `None` while idle.
57    pub storage_task: Option<String>,
58    /// How far the task is, 0 to 1, when it can tell.
59    pub storage_progress: Option<f32>,
60    pub storage_error: Option<String>,
61    /// The repository is being read, written or synchronized.
62    pub storage_working: bool,
63    /// Changed files not yet committed.
64    pub staged_files: usize,
65    pub branches: Vec<String>,
66    pub current_branch: Option<String>,
67    /// Where the asset repository is on the engine's machine.
68    pub storage_dir: String,
69    /// Art-Net and DMX traffic in Mbit/s.
70    pub network_in: f32,
71    pub network_out: f32,
72    /// The hottest temperature sensor of the engine's machine in °C, `None`
73    /// on a machine without one.
74    pub temperature: Option<f32>,
75    /// The engine machine's host name, which tells its readings apart from
76    /// those of the machine showing the interface.
77    pub host_name: String,
78    /// Other Ableton Link peers.
79    pub link_peers: u64,
80    pub settings: ServerSettings,
81    /// The running Art-Net input: the project's settings and, per universe
82    /// seen, how much data arrived.
83    pub artnet: ArtnetConfig,
84    /// The devices of the engine's machine, while an interface watches them.
85    pub devices: Devices,
86}
87
88/// The devices the engine's machine has, for choosing among them.
89#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
90#[serde(default)]
91pub struct Devices {
92    /// Audio inputs sound triggers can listen to, with a label to show.
93    pub audio_inputs: Vec<(AudioDeviceId, String)>,
94    pub midi_outputs: Vec<String>,
95    /// Serial numbers of the connected Enttec DMX USB Pro interfaces.
96    pub enttec: Vec<String>,
97}
98
99/// Highest selectable output frame rate. Choosing it means unlimited.
100pub const FPS_LIMIT_MAX: f32 = 333.0;
101
102/// Settings of the machine running the engine, which any interface may change.
103#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
104#[serde(default)]
105pub struct ServerSettings {
106    /// The render and output frame rate limit; `FPS_LIMIT_MAX` and above
107    /// mean unlimited.
108    pub fps_limit: f32,
109    /// Follow the Ableton Link tempo without changing it.
110    pub ableton_link_read_only: bool,
111    /// The asset repository's remote.
112    pub git_url: String,
113    /// The SSH key for the repository, a path on the engine's machine.
114    pub git_private_key: Option<String>,
115    pub git_use_passphrase: bool,
116}
117
118/// Work on the asset repository an interface asks for.
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
120pub enum StorageCommand {
121    Commit {
122        message: String,
123    },
124    Pull,
125    Push,
126    SwitchBranch(String),
127    /// Deletes the local repository and clones it again from the git URL.
128    Reclone,
129    /// The passphrase of the SSH key, kept in the engine machine's keyring.
130    SetGitPassphrase(String),
131}
132
133/// The engine's state as user interfaces see it, published every tick.
134#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
135pub struct EngineState {
136    /// The engine's project, shared: the engine publishes a new `Arc` only
137    /// when the project changed, so an unchanged one is the same `Arc` and
138    /// compares in O(1). It goes over the wire as a plain project.
139    pub project: Option<Arc<Project>>,
140    pub project_id: Option<AssetId<Project>>,
141    pub selected_scene_instance: GridLocation,
142    pub blackout: bool,
143    pub blackout_hold: bool,
144    pub midi_output_active: bool,
145    pub output_config: OutputConfig,
146    pub beat: BeatState,
147    /// Taps counted for the tap button's indicator.
148    pub tap_count: usize,
149    /// Changes whenever the lamp positions changed: the patch or one of the
150    /// fixture definitions it uses.
151    pub layout_generation: u64,
152    pub render: RenderStats,
153    pub status: ServerStatus,
154}
155
156impl EngineState {
157    /// A copy without the project, which goes as a patch.
158    pub fn without_project(&self) -> Self {
159        let Self {
160            project: _,
161            project_id,
162            selected_scene_instance,
163            blackout,
164            blackout_hold,
165            midi_output_active,
166            output_config,
167            beat,
168            tap_count,
169            layout_generation,
170            render,
171            status,
172        } = self;
173        Self {
174            project: None,
175            project_id: *project_id,
176            selected_scene_instance: *selected_scene_instance,
177            blackout: *blackout,
178            blackout_hold: *blackout_hold,
179            midi_output_active: *midi_output_active,
180            output_config: output_config.clone(),
181            beat: *beat,
182            tap_count: *tap_count,
183            layout_generation: *layout_generation,
184            render: *render,
185            status: status.clone(),
186        }
187    }
188
189    /// Whether both differ only in their timing: the beat, which changes
190    /// every tick and which remote interfaces extrapolate between updates, and
191    /// the render stats.
192    pub fn same_but_timing(&self, other: &Self) -> bool {
193        self.same_but_timing_and_project(other)
194            && match (self.project.as_deref(), other.project.as_deref()) {
195                // The engine's unchanged project is the same value.
196                (Some(a), Some(b)) => std::ptr::eq(a, b) || a == b,
197                (a, b) => a.is_none() && b.is_none(),
198            }
199    }
200
201    /// Whether both differ at most in their timing and their project, which
202    /// an update carries on its own (`ProjectUpdate`).
203    pub fn same_but_timing_and_project(&self, other: &Self) -> bool {
204        let Self {
205            project: _,
206            project_id,
207            selected_scene_instance,
208            blackout,
209            blackout_hold,
210            midi_output_active,
211            output_config,
212            beat: _,
213            tap_count,
214            layout_generation,
215            render: _,
216            status,
217        } = self;
218        *project_id == other.project_id
219            && *selected_scene_instance == other.selected_scene_instance
220            && *blackout == other.blackout
221            && *blackout_hold == other.blackout_hold
222            && *midi_output_active == other.midi_output_active
223            && *tap_count == other.tap_count
224            && *layout_generation == other.layout_generation
225            && *output_config == other.output_config
226            && *status == other.status
227    }
228}
229
230/// What a user interface sends the engine besides actions.
231#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
232pub enum ClientInput {
233    /// An action from the interface, numbered in the order it was sent.
234    Action {
235        sequence: u64,
236        action: UiAction,
237    },
238    /// The keys held in the interface, for key inputs.
239    Keys(BTreeSet<KeyCode>),
240    /// The tempo set with the BPM slider.
241    SetBeatsPerMinute(f32),
242    /// Stores an asset in the collections and the repository.
243    SaveAsset(AnyAsset),
244    /// Removes an asset from the collections and the repository.
245    DeleteAsset(AnyAssetId),
246    Storage(StorageCommand),
247    SetServerSettings(ServerSettings),
248    /// The output routing the pointer is over, whose universe then blinks so
249    /// the installation shows which lamps it drives. `None` when it left.
250    HoverOutputRouting(Option<OutputRouting>),
251    /// Whether this interface shows a device list, so the engine scans for
252    /// devices.
253    WatchDevices(bool),
254    /// Whether this interface shows the MIDI monitor, so the engine streams
255    /// the traffic.
256    WatchMidi(bool),
257    /// Whether this interface waits for MIDI learn input.
258    MidiLearning(bool),
259    MidiTest(TestCommand),
260    /// The sound triggers this interface edits, whose spectra it needs.
261    WatchSoundTriggers(BTreeSet<Uuid>),
262}
263
264/// Something the user interfaces have to react to once.
265#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
266pub enum EngineEvent {
267    /// The code of this animation (all for `None`) changed: rebuild previews.
268    ShaderReloaded(Option<AssetId<Animation>>),
269    /// An error to show the user.
270    Error(String),
271}
272
273/// The sound triggers' levels and the input spectrum, as interfaces need them
274/// to draw effects that follow the music.
275#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
276#[serde(default)]
277pub struct SoundSnapshot {
278    pub levels: BTreeMap<Uuid, f32>,
279    /// The envelope input of every trigger, 0 to 1.
280    pub impulses: BTreeMap<Uuid, f32>,
281    /// `FREQ_BINS` little-endian `f32`s, as effects read them.
282    pub spectrum: SharedBytes,
283    /// The averaged spectrum of the triggers an interface edits, as
284    /// little-endian `f32`s.
285    pub trigger_spectra: BTreeMap<Uuid, SharedBytes>,
286}
287
288impl SoundSnapshot {
289    /// What the trigger editor shows of a running trigger: impulse, level
290    /// and its averaged spectrum (empty unless the trigger is watched).
291    pub fn reading(&self, id: &Uuid) -> Option<(f32, f32, Vec<f32>)> {
292        let level = *self.levels.get(id)?;
293        let impulse = self.impulses.get(id).copied().unwrap_or_default();
294        let spectrum = self
295            .trigger_spectra
296            .get(id)
297            .map(|bytes| {
298                bytes
299                    .0
300                    .as_chunks::<4>()
301                    .0
302                    .iter()
303                    .map(|chunk| f32::from_le_bytes(*chunk))
304                    .collect()
305            })
306            .unwrap_or_default();
307        Some((impulse, level, spectrum))
308    }
309}
310
311impl SoundLevels for SoundSnapshot {
312    fn level(&self, id: &Uuid) -> f32 {
313        self.levels.get(id).copied().unwrap_or(0.0)
314    }
315
316    fn spectrum_bytes(&self) -> [u8; FREQ_BINS * 4] {
317        let mut bytes = [0; FREQ_BINS * 4];
318        let len = self.spectrum.0.len().min(bytes.len());
319        bytes[..len].copy_from_slice(&self.spectrum.0[..len]);
320        bytes
321    }
322}
323
324/// Where a thread's client inputs go.
325type InputRoute = Box<dyn Fn(ClientInput)>;
326
327thread_local! {
328    /// Where client inputs enqueued on this thread go: the interface's
329    /// connection to the engine.
330    static INPUT_ROUTE: std::cell::RefCell<Option<InputRoute>> =
331        const { std::cell::RefCell::new(None) };
332}
333
334/// Sends every client input enqueued on the calling thread to `route`.
335pub fn route_inputs_on_this_thread(route: impl Fn(ClientInput) + 'static) {
336    INPUT_ROUTE.with(|cell| *cell.borrow_mut() = Some(Box::new(route)));
337}
338
339impl ClientInput {
340    /// Sends this input to the engine through the calling thread's route.
341    pub fn enqueue(self) {
342        INPUT_ROUTE.with(|cell| match cell.borrow().as_ref() {
343            Some(route) => route(self),
344            None => tracing::warn!("Dropped {self:?}: this thread has no connection to the engine"),
345        });
346    }
347}