Skip to main content

ssruntime/context/
events.rs

1//! The events a frame passes, and the event / effect keys active on a part.
2
3use super::Context;
4
5impl<'a> Context<'a> {
6    pub(super) fn collect_events(&mut self) {
7        self.instance.collected_event_indices.clear();
8        self.instance.collected_event_source_handles.clear();
9        let Some(resource) = self.eval.resource else {
10            return;
11        };
12        let primary_idx = self.instance.primary_idx();
13        let num_sources = self.instance.sources.len();
14
15        for i in 0..num_sources {
16            let source = &self.instance.sources[i];
17            if !source.has_real_animation() {
18                continue;
19            }
20            let is_primary = i == primary_idx;
21            if !is_primary && !self.instance.source_fires_events(i) {
22                continue;
23            }
24            let metadata = &resource.animations[source.animation_idx as usize];
25            let Some(events_vec) = metadata.events else { continue };
26            let source_handle = i as u32;
27
28            for &frame_no in source.controller.get_passed_frames() {
29                if frame_no < 0 || frame_no > u16::MAX as i32 {
30                    continue;
31                }
32                let target_frame = frame_no as u16;
33                let mut low = 0;
34                let mut high = events_vec.len();
35                while low < high {
36                    let mid = low + (high - low) / 2;
37                    match events_vec.get(mid).frame_index().cmp(&target_frame) {
38                        ::core::cmp::Ordering::Equal => {
39                            self.instance.collected_event_indices.push(mid as i32);
40                            self.instance.collected_event_source_handles.push(source_handle);
41                            break;
42                        }
43                        ::core::cmp::Ordering::Less => low = mid + 1,
44                        ::core::cmp::Ordering::Greater => high = mid,
45                    }
46                }
47            }
48        }
49    }
50
51    /// The events the last [`Self::update`] passed. They stay until the next one,
52    /// [`Self::setup_animation`], [`Self::bind_resource`] or [`Self::reset`].
53    pub fn get_passed_event_indices(&self) -> &[i32] {
54        &self.instance.collected_event_indices
55    }
56
57    /// Parallel to [`Self::get_passed_event_indices`]: source handle that fired
58    /// each collected event. With every source and every track's outgoing side
59    /// at the default event threshold (`+∞`), entries are uniformly
60    /// [`Self::get_track_main_source`] of track 0. Diverges once secondaries opt
61    /// in to event firing via [`Self::set_source_event_threshold`], or a
62    /// crossfade's outgoing side via [`Self::set_track_outgoing_event_threshold`].
63    pub fn get_passed_event_source_handles(&self) -> &[u32] {
64        &self.instance.collected_event_source_handles
65    }
66
67    /// Resolve the most-recent `EventInstance` whose `frame_index <= current frame`
68    /// for `slot_index` on the *currently selected animation*. Returns
69    /// `synthetic_default()` when no event has fired yet (SS6 default semantics).
70    /// Designed to live behind the `ss_runtime_get_active_event_instance` FFI.
71    pub fn get_active_event_instance(&self, slot_index: u32) -> crate::types::ss_event_instance_info {
72        let mut info = crate::types::ss_event_instance_info::synthetic_default();
73        let Some(resource) = self.eval.resource else { return info };
74        if self.instance.primary_source().animation_idx < 0 {
75            return info;
76        }
77        let metadata = &resource.animations[self.instance.primary_source().animation_idx as usize];
78        let Some(events) = metadata.events else { return info };
79
80        let frame_no = self.instance.primary_source().controller.get_frame_no();
81        let frame_int = if frame_no < 0.0 {
82            -1
83        } else if frame_no >= u16::MAX as f32 {
84            u16::MAX as i32
85        } else {
86            frame_no as i32
87        };
88
89        // Forward scan: events are sorted by frame_index. Later matches override
90        // earlier ones, so the loop naturally lands on the most-recent
91        // EventInstance for `slot_index`.
92        for i in 0..events.len() {
93            let epf = events.get(i);
94            if (epf.frame_index() as i32) > frame_int {
95                break;
96            }
97            let Some(instances) = epf.instances() else { continue };
98            for j in 0..instances.len() {
99                let ev = instances.get(j);
100                if ev.part_index() as u32 != slot_index {
101                    continue;
102                }
103                let attr = ev.value();
104                info = crate::types::ss_event_instance_info {
105                    event_frame: epf.frame_index() as i32,
106                    start_label_hash: attr.start_label_hash(),
107                    start_offset: attr.start_offset(),
108                    end_label_hash: attr.end_label_hash(),
109                    end_offset: attr.end_offset(),
110                    loop_num: attr.loop_num(),
111                    speed: attr.speed(),
112                    independent: attr.independent(),
113                    reverse: attr.reverse(),
114                    pingpong: attr.pingpong(),
115                    is_synthetic_default: false,
116                };
117            }
118        }
119        info
120    }
121
122    /// Resolve the most-recent `EventEffect` whose `frame_index <= current frame`
123    /// for `slot_index` on the *currently selected animation*. When no event has
124    /// fired yet, falls back to `InitialEvents.effect` for that slot (still flagged
125    /// `is_synthetic_default = true`); if neither exists returns full SS6 defaults.
126    /// Designed to live behind the `ss_runtime_get_active_effect_event` FFI.
127    pub fn get_active_effect_event(&self, slot_index: u32) -> crate::types::ss_effect_event_info {
128        let mut info = crate::types::ss_effect_event_info::synthetic_default();
129        let Some(resource) = self.eval.resource else { return info };
130        if self.instance.primary_source().animation_idx < 0 {
131            return info;
132        }
133        let metadata = &resource.animations[self.instance.primary_source().animation_idx as usize];
134
135        // Fallback first: InitialEvents.effect for this slot. Real EventEffect
136        // matches override below; the synthetic-default flag stays `true` for
137        // initial-only state so callers don't treat it as an event edge.
138        if let Some(inits) = metadata.initial_events
139            && (slot_index as usize) < inits.len()
140        {
141            let entry = inits.get(slot_index as usize);
142            if let Some(eff) = entry.effect() {
143                info.event_frame = 0;
144                info.start_time = eff.start_time();
145                let s = eff.speed();
146                info.speed = if s == 0.0 { 1.0 } else { s };
147                // The implicit frame-0 (Setup) key is never an independent-playback
148                // start point: only a real authored EventEffect may begin independent
149                // playback. Forced to false so this mirrors the Instance synthetic
150                // default (`ss_event_instance_info::synthetic_default`, independent =
151                // false) and the two part types stay symmetric.
152                info.independent = false;
153                info.is_synthetic_default = true;
154            }
155        }
156
157        let Some(events) = metadata.events else { return info };
158
159        let frame_no = self.instance.primary_source().controller.get_frame_no();
160        let frame_int = if frame_no < 0.0 {
161            -1
162        } else if frame_no >= u16::MAX as f32 {
163            u16::MAX as i32
164        } else {
165            frame_no as i32
166        };
167
168        for i in 0..events.len() {
169            let epf = events.get(i);
170            if (epf.frame_index() as i32) > frame_int {
171                break;
172            }
173            let Some(effects) = epf.effects() else { continue };
174            for j in 0..effects.len() {
175                let ev = effects.get(j);
176                if ev.part_index() as u32 != slot_index {
177                    continue;
178                }
179                let attr = ev.value();
180                let s = attr.speed();
181                info = crate::types::ss_effect_event_info { event_frame: epf.frame_index() as i32, start_time: attr.start_time(), speed: if s == 0.0 { 1.0 } else { s }, independent: attr.independent(), is_synthetic_default: false };
182            }
183        }
184        info
185    }
186
187    /// Look up `label_hash` in the currently selected animation's `labels`
188    /// table and return its `time`. Returns `fallback` when `label_hash == 0`
189    /// (caller convention for "unset"), no animation is bound, or the hash
190    /// is not found. Linear scan — labels per animation are typically <50.
191    pub fn resolve_label_time(&self, label_hash: u32, fallback: i32) -> i32 {
192        if label_hash == 0 {
193            return fallback;
194        }
195        let Some(resource) = self.eval.resource else { return fallback };
196        if self.instance.primary_source().animation_idx < 0 {
197            return fallback;
198        }
199        let metadata = &resource.animations[self.instance.primary_source().animation_idx as usize];
200        let Some(labels) = metadata.labels else { return fallback };
201        for i in 0..labels.len() {
202            let label = labels.get(i);
203            if label.name_hash() == label_hash {
204                return label.time();
205            }
206        }
207        fallback
208    }
209}