ssplayer_wgpu/events.rs
1//! Timeline events, decoded into owned Rust values.
2//!
3//! **Everything here is owned, not borrowed**, so a host's reaction to an event
4//! may outlive the tick that raised it.
5//!
6//! The runtime reports which frames of the timeline the last update crossed; the
7//! payloads live in the `.ssab`, addressed by the same index. [`decode_events`]
8//! joins the two.
9//!
10//! Events are collected during the update, which is what makes them complete: a
11//! slow tick under frame skipping crosses several frames at once and a loop can
12//! wrap mid-tick, and every frame stepped through raises its events. Reading
13//! only the frame that was landed on loses the rest.
14
15use ssab::ssab::ss::format::{AnimationData, SignalCommandParamValue, SsAnimeBinary};
16
17/// One value carried by a signal parameter.
18#[derive(Clone, Debug, PartialEq)]
19pub enum SignalValue {
20 Bool(bool),
21 /// A choice from a list, as its index.
22 Index(i32),
23 Integer(i32),
24 Floating(f32),
25 Text(String),
26 /// The parameter exists but was left unset.
27 None,
28}
29
30/// One `param_id` → value pair on a signal.
31#[derive(Clone, Debug, PartialEq)]
32pub struct SignalParam {
33 pub id: String,
34 pub value: SignalValue,
35}
36
37/// A "User Data" marker: up to four optional values, in whatever combination
38/// the animator filled in. A field is `None` when it was left unset — which is
39/// not the same as zero, and is why these are options rather than defaults.
40#[derive(Clone, Debug, Default, PartialEq)]
41pub struct UserDataEvent {
42 pub part_index: u32,
43 /// The part's name as authored, or empty when the pack has none for it.
44 pub part_name: String,
45 /// The frame the key is **authored** on, which is not necessarily the frame
46 /// it was noticed on: one update can step across several and reports every
47 /// key in between.
48 pub frame_no: u32,
49 /// The source that fired it — see [`SsEvent::source`].
50 pub source: u32,
51 pub integer: Option<i32>,
52 /// `[left, top, right, bottom]` as authored — four edges, not origin+size.
53 pub rect: Option<[f32; 4]>,
54 pub point: Option<[f32; 2]>,
55 pub text: Option<String>,
56}
57
58/// A "Signal": a named command plus its parameters.
59#[derive(Clone, Debug, PartialEq)]
60pub struct SignalEvent {
61 pub part_index: u32,
62 /// The part's name as authored, or empty when the pack has none for it.
63 pub part_name: String,
64 /// The frame the key is **authored** on, which is not necessarily the frame
65 /// it was noticed on: one update can step across several and reports every
66 /// key in between.
67 pub frame_no: u32,
68 /// The source that fired it — see [`SsEvent::source`].
69 pub source: u32,
70 pub command_id: String,
71 pub params: Vec<SignalParam>,
72}
73
74/// An audio trigger. **The player never produces sound**: this says what to
75/// play and how many times, and the host feeds its own audio stack.
76#[derive(Clone, Debug, PartialEq)]
77pub struct AudioEvent {
78 pub part_index: u32,
79 /// The part's name as authored, or empty when the pack has none for it.
80 pub part_name: String,
81 /// The frame the key is **authored** on, which is not necessarily the frame
82 /// it was noticed on: one update can step across several and reports every
83 /// key in between.
84 pub frame_no: u32,
85 /// The source that fired it — see [`SsEvent::source`].
86 pub source: u32,
87 /// The alias as authored, kept for diagnostics and for hosts that key their
88 /// own audio by name.
89 pub sound_name: String,
90 /// Addresses the `SoundList`, and the `SoundFile` within it — the pair a
91 /// host resolves against the pack when it wants the file rather than the
92 /// name.
93 pub sound_list_name_hash: u32,
94 pub sound_name_hash: u32,
95 /// How many times to play it. SpriteStudio has no infinite audio loop, so
96 /// this is a count rather than a flag.
97 pub loop_num: i32,
98}
99
100/// Something that happened on a frame the last update crossed.
101#[derive(Clone, Debug, PartialEq)]
102pub enum SsEvent {
103 UserData(UserDataEvent),
104 Signal(SignalEvent),
105 Audio(AudioEvent),
106}
107
108impl SsEvent {
109 /// Which part raised it.
110 pub fn part_index(&self) -> u32 {
111 match self {
112 Self::UserData(e) => e.part_index,
113 Self::Signal(e) => e.part_index,
114 Self::Audio(e) => e.part_index,
115 }
116 }
117
118 /// The frame the key is **authored** on — not necessarily the frame it was
119 /// noticed on, since one update can step across several.
120 pub fn frame_no(&self) -> u32 {
121 match self {
122 Self::UserData(e) => e.frame_no,
123 Self::Signal(e) => e.frame_no,
124 Self::Audio(e) => e.frame_no,
125 }
126 }
127
128 /// The raising part's name as authored, or empty when the pack has none.
129 pub fn part_name(&self) -> &str {
130 match self {
131 Self::UserData(e) => &e.part_name,
132 Self::Signal(e) => &e.part_name,
133 Self::Audio(e) => &e.part_name,
134 }
135 }
136
137 /// The source on the character's track stack that fired it, as the handle
138 /// [`SSPlayer::track_main_source`] and [`SSPlayer::add_track_source`] use.
139 /// By default only track 0's main source fires, so this is that one; it
140 /// tells events apart once another source has opted in with
141 /// [`SSPlayer::set_source_event_threshold`].
142 ///
143 /// [`SSPlayer::track_main_source`]: crate::SSPlayer::track_main_source
144 /// [`SSPlayer::add_track_source`]: crate::SSPlayer::add_track_source
145 /// [`SSPlayer::set_source_event_threshold`]: crate::SSPlayer::set_source_event_threshold
146 pub fn source(&self) -> u32 {
147 match self {
148 Self::UserData(e) => e.source,
149 Self::Signal(e) => e.source,
150 Self::Audio(e) => e.source,
151 }
152 }
153}
154
155/// Append every event on the frames `indices` names to `out`, stamped with the
156/// `source` that fired them.
157///
158/// `anim` is **the firing source's** animation, whose `EventsPerFrame` vector
159/// `indices` addresses — not necessarily the one `set_animation` chose, since a
160/// crossfade on track 0 hands the track to another. **Indices are
161/// bounds-checked**: they are only meaningful against that animation, and a
162/// stale one — or the runtime's not-found `-1` — would otherwise read past the
163/// FlatBuffer.
164///
165/// Signals that are switched off are skipped, matching the sibling Players:
166/// an inactive signal is authoring state, not something that happened.
167pub(crate) fn decode_events(ab: &SsAnimeBinary<'_>, anim: &AnimationData<'_>, source: u32, indices: &[i32], out: &mut Vec<SsEvent>) {
168 let Some(events) = anim.events() else { return };
169 let len = events.len();
170 // The pack's part list is shared across its animations, so one lookup per
171 // event resolves the name a host would otherwise carry the pack around for.
172 let parts = ab.parts();
173 let part_name = |index: u32| -> String { parts.get(index as usize).name().to_owned() };
174 for &index in indices {
175 if index < 0 || index as usize >= len {
176 continue;
177 }
178 let per_frame = events.get(index as usize);
179 let frame_no = per_frame.frame_index() as u32;
180
181 if let Some(users) = per_frame.users() {
182 for user in users {
183 let value = user.value();
184 out.push(SsEvent::UserData(UserDataEvent {
185 part_index: user.part_index() as u32,
186 part_name: part_name(user.part_index() as u32),
187 frame_no,
188 source,
189 integer: value.integer().map(|v| v.value()),
190 rect: value.rect().map(|r| [r.left(), r.top(), r.right(), r.bottom()]),
191 point: value.point().map(|p| [p.v1(), p.v2()]),
192 text: value.str().map(str::to_owned),
193 }));
194 }
195 }
196
197 if let Some(signals) = per_frame.signals() {
198 for signal in signals {
199 let value = signal.value();
200 if !value.active() {
201 continue;
202 }
203 let params = value.params().iter().map(|param| SignalParam { id: param.param_id().to_owned(), value: decode_signal_value(¶m) }).collect();
204 out.push(SsEvent::Signal(SignalEvent { part_index: signal.part_index() as u32, part_name: part_name(signal.part_index() as u32), frame_no, source, command_id: value.command_id().to_owned(), params }));
205 }
206 }
207
208 if let Some(audios) = per_frame.audios() {
209 for audio in audios {
210 let value = audio.value();
211 out.push(SsEvent::Audio(AudioEvent {
212 part_index: audio.part_index() as u32,
213 part_name: part_name(audio.part_index() as u32),
214 frame_no,
215 source,
216 sound_name: value.sound_name().to_owned(),
217 sound_list_name_hash: value.sound_list_name_hash(),
218 sound_name_hash: value.sound_name_hash(),
219 loop_num: value.loop_num(),
220 }));
221 }
222 }
223 }
224}
225
226/// Unwrap one parameter's union. An unset or unrecognised union reads as
227/// [`SignalValue::None`] rather than being dropped, so a host iterating params
228/// still sees that the parameter is there.
229fn decode_signal_value(param: &ssab::ssab::ss::format::SignalCommandParam<'_>) -> SignalValue {
230 match param.value_type() {
231 SignalCommandParamValue::Bool => param.value_as_bool().map(|v| SignalValue::Bool(v.value())),
232 SignalCommandParamValue::Index => param.value_as_index().map(|v| SignalValue::Index(v.value())),
233 SignalCommandParamValue::Integer => param.value_as_integer().map(|v| SignalValue::Integer(v.value())),
234 SignalCommandParamValue::Floating => param.value_as_floating().map(|v| SignalValue::Floating(v.value())),
235 SignalCommandParamValue::Text => param.value_as_text().map(|v| SignalValue::Text(v.value().to_owned())),
236 _ => None,
237 }
238 .unwrap_or(SignalValue::None)
239}