Skip to main content

ssruntime/
effect_slot.rs

1//! [`EffectContext`] and [`EffectSlot`]: an effect part's particles, and the plan for drawing them.
2
3use crate::error;
4use crate::resource::AnimationResource;
5
6pub struct EffectContext<'a> {
7    pub eval: crate::eval::effect::instance::EffectEvaluationContext<'a>,
8    pub instance: crate::eval::effect::instance::EffectInstanceState,
9    seed: u32,
10}
11
12impl<'a> EffectContext<'a> {
13    pub fn new(resource: &'a AnimationResource<'a>, effect_name_hash: u32, seed: u32) -> Result<Self, error::SSRuntimeError> {
14        let ssab = unsafe { ssab::ssab::ss::format::root_as_ss_anime_binary_unchecked(resource.data) };
15        let Some(effects) = ssab.effects() else {
16            return Err(error::SSRuntimeError::AnimationNotFound);
17        };
18        let Some(effect) = crate::eval::ssab_lookup::find_effect(&effects, effect_name_hash) else {
19            return Err(error::SSRuntimeError::AnimationNotFound);
20        };
21        // The effect was located by name_hash, but its data is malformed
22        // (e.g. missing required `effect_node` table).
23        let Some((eval, instance)) = crate::eval::effect::instance::EffectEvaluationContext::from_ssab(&effect, seed) else {
24            return Err(error::SSRuntimeError::MalformedEffect);
25        };
26        Ok(Self { eval, instance, seed })
27    }
28
29    pub fn get_seed(&self) -> u32 {
30        self.seed
31    }
32
33    pub fn reset(&mut self) {
34        self.instance.reset();
35    }
36
37    pub fn set_loop(&mut self, loop_flag: bool) {
38        self.instance.set_loop(loop_flag);
39    }
40
41    pub fn get_lifetime(&self) -> i32 {
42        self.eval.effect_time_length
43    }
44
45    pub fn is_infinite(&self) -> bool {
46        self.eval.is_infinite
47    }
48
49    pub fn update(&mut self, frame: f32) {
50        self.instance.update(&self.eval, frame);
51    }
52
53    pub fn get_draw_commands(&mut self) -> (&[crate::eval::effect::instance::EmitterDrawCommand], &[crate::eval::effect::types::ParticleDrawState]) {
54        self.instance.get_draw_commands(&self.eval)
55    }
56}
57
58/// Resolved emitter render resources, cached on first encounter and reused
59/// across frames. Identified by (cellmap_hash, cell_hash, blend_in) — the
60/// effect simulator may reorder emitters when siblings go silent, so the
61/// cache is keyed by content not slot index.
62struct EmitterResourceEntry {
63    cellmap_hash: u32,
64    cell_hash: u32,
65    blend_in: i32,
66    resolved_ok: bool,
67    blend_byte: u8,
68    quad_left: f32,
69    quad_top: f32,
70    sw: f32,
71    sh: f32,
72    u0: f32,
73    v0: f32,
74    u1: f32,
75    v1: f32,
76}
77
78// Lifted out of `build_draw_plan` so the row buffer can be a cached field.
79#[derive(Default, Clone, Copy)]
80struct ResolvedEmitter {
81    ok: bool,
82    blend_byte: u8,
83    quad_left: f32,
84    quad_top: f32,
85    sw: f32,
86    sh: f32,
87    u0: f32,
88    v0: f32,
89    u1: f32,
90    v1: f32,
91    cellmap_hash: u32,
92}
93
94/// A particle quad's corners as `(xs, ys)`, in the plan's UV order: left-top,
95/// right-top, left-bottom, right-bottom. `left` and `top` are in the cell's Y-up
96/// space; `y_sign` mirrors the quad for a Y-down target, as it does the particle's
97/// position and rotation, so the texture's top stays on top for either target.
98pub(crate) fn particle_quad(left: f32, top: f32, width: f32, height: f32, y_sign: f32) -> ([f32; 4], [f32; 4]) {
99    let (t, b) = (y_sign * top, y_sign * (top - height));
100    ([left, left + width, left, left + width], [t, t, b, b])
101}
102
103/// High-level effect slot: wraps `EffectContext` with the per-slot lifecycle
104/// state. Callers resolve the active effect event externally (via `Context::get_active_effect_event`)
105/// and feed it to `step()` along with frame timing — `step` owns transition
106/// detection, accumulator, dead-effect skip, simulator update, and draw-plan
107/// build in one call.
108///
109/// The cross-language contract is identical in Rust / C / Web: 1) construct
110/// once per effect part, 2) call `step()` per frame with the resolved event
111/// and timing, 3) read `draw_plan_buf` only when `visible == true` and only
112/// before the next `step()`.
113pub struct EffectSlot<'a> {
114    ctx: EffectContext<'a>,
115    // SSAB root, kept for cellmap lookup during draw-plan build. Borrows from
116    // the same resource as `ctx`; lifetime tied to the surrounding `'a`.
117    ssab: ssab::ssab::ss::format::SsAnimeBinary<'a>,
118    // FlatBufferBuilder owned by the slot for `EffectDrawPlan` output.
119    // Reset each `step`; buffer pointer stays valid until the next call.
120    fb: flatbuffers::FlatBufferBuilder<'a>,
121    emitter_resource_cache: alloc::vec::Vec<EmitterResourceEntry>,
122    // Per-frame scratch for `build_draw_plan`: clear()+reserve()'d each tick
123    // so capacities stabilise at the peak and steady-state allocation is zero.
124    scratch_cmd_keys: alloc::vec::Vec<(u32, u32, i32, usize, usize)>,
125    scratch_entries: alloc::vec::Vec<(usize, usize, usize)>,
126    scratch_verts: alloc::vec::Vec<f32>,
127    scratch_uvs: alloc::vec::Vec<f32>,
128    scratch_colors: alloc::vec::Vec<f32>,
129    scratch_indices: alloc::vec::Vec<i32>,
130    scratch_resolved: alloc::vec::Vec<ResolvedEmitter>,
131    scratch_command_meta: alloc::vec::Vec<(u32, u8, u32, u32)>,
132    scratch_cmds: alloc::vec::Vec<crate::runtime::effect_draw_plan::ss::runtime::EffectDrawCommand>,
133    // Cached at create time — never changes for a given effect resource.
134    lifetime: i32,
135    is_infinite: bool,
136    // Transition detection: any change in (event_frame, is_synthetic, independent)
137    // triggers reset/set_loop and re-seeds `accumulated_time`.
138    last_event_frame: i32,
139    last_is_synthetic: bool,
140    last_independent: bool,
141    // Speed of the last real EventEffect — reused while the implicit frame-0
142    // key is being ignored (independent playback across a parent loop).
143    last_speed: f32,
144    // Independent-mode time accumulator (frame units, includes start_time bias).
145    accumulated_time: f32,
146}
147
148impl<'a> EffectSlot<'a> {
149    pub fn new(resource: &'a AnimationResource<'a>, effect_name_hash: u32, seed: u32) -> Result<Self, error::SSRuntimeError> {
150        let ctx = EffectContext::new(resource, effect_name_hash, seed)?;
151        let ssab = unsafe { ssab::ssab::ss::format::root_as_ss_anime_binary_unchecked(resource.data) };
152        let lifetime = ctx.get_lifetime();
153        let is_infinite = ctx.is_infinite();
154        Ok(Self {
155            ctx,
156            ssab,
157            fb: flatbuffers::FlatBufferBuilder::new(),
158            emitter_resource_cache: alloc::vec::Vec::new(),
159            scratch_cmd_keys: alloc::vec::Vec::new(),
160            scratch_entries: alloc::vec::Vec::new(),
161            scratch_verts: alloc::vec::Vec::new(),
162            scratch_uvs: alloc::vec::Vec::new(),
163            scratch_colors: alloc::vec::Vec::new(),
164            scratch_indices: alloc::vec::Vec::new(),
165            scratch_resolved: alloc::vec::Vec::new(),
166            scratch_command_meta: alloc::vec::Vec::new(),
167            scratch_cmds: alloc::vec::Vec::new(),
168            lifetime,
169            is_infinite,
170            last_event_frame: -1,
171            last_is_synthetic: false,
172            last_independent: false,
173            last_speed: 1.0,
174            accumulated_time: 0.0,
175        })
176    }
177
178    pub fn get_seed(&self) -> u32 {
179        self.ctx.get_seed()
180    }
181
182    /// Whether the slot is currently running independently of the parent's
183    /// frame. Reflects the most recently seen `EventEffect.independent`;
184    /// used by callers to decide whether to schedule continuous tick updates.
185    pub fn is_independent(&self) -> bool {
186        self.last_independent
187    }
188
189    /// Reset the slot's playback / "last started key" memory to its
190    /// just-created state. The host calls this on an explicit head-out
191    /// (`play` / replay) so a re-played animation re-fires the effect from
192    /// scratch instead of debouncing the first key as the same one it last
193    /// started. The resource binding, emitter caches and simulator
194    /// are left intact — forcing `last_event_frame = -1` makes the next `step`
195    /// transition, which re-seeds the simulator via the existing `ctx.reset()`
196    /// path.
197    pub fn reset(&mut self) {
198        self.last_event_frame = -1;
199        self.last_is_synthetic = false;
200        self.last_independent = false;
201        self.last_speed = 1.0;
202        self.accumulated_time = 0.0;
203    }
204
205    /// Resolve `(cellmap_hash, cell_hash, blend_in)` to render geometry/UV,
206    /// caching the result in `emitter_resource_cache`. Linear search — typical
207    /// effects have 1-3 unique tuples and the cache survives across frames.
208    /// Free-standing form so callers can split-borrow `cache` and `ssab`
209    /// independently of other `self` fields (the simulator output borrow lives
210    /// on `self.ctx.instance` simultaneously inside `build_draw_plan`).
211    fn ensure_emitter_resource_in(cache: &mut alloc::vec::Vec<EmitterResourceEntry>, ssab: &ssab::ssab::ss::format::SsAnimeBinary<'a>, cellmap_hash: u32, cell_hash: u32, blend_in: i32) -> usize {
212        if let Some(idx) = cache.iter().position(|c| c.cellmap_hash == cellmap_hash && c.cell_hash == cell_hash && c.blend_in == blend_in) {
213            return idx;
214        }
215        let mut entry = EmitterResourceEntry { cellmap_hash, cell_hash, blend_in, resolved_ok: false, blend_byte: 0, quad_left: 0.0, quad_top: 0.0, sw: 0.0, sh: 0.0, u0: 0.0, v0: 0.0, u1: 0.0, v1: 0.0 };
216
217        if cellmap_hash != 0
218            && let Some(cellmaps) = ssab.cellmaps()
219            && let Some(cellmap) = crate::eval::ssab_lookup::find_cellmap(&cellmaps, cellmap_hash)
220            && let Some(cells) = cellmap.cells()
221            && let Some(cell) = crate::eval::ssab_lookup::find_cell(&cells, cell_hash)
222        {
223            // SS6-style blend mapping: 0=Mix, 1=Add. Anything else falls back to Mix.
224            entry.blend_byte = if blend_in == 1 { 1 } else { 0 };
225
226            let region = cell.region();
227            let (src_x, src_y, sw, sh) = (region.x(), region.y(), region.w(), region.h());
228            // The box a Normal part draws this cell in, in the cell's Y-up space.
229            let p = cell.pivot();
230            let (vx, vy) = crate::eval::geometry::compute_local_vertices((sw, sh), (p.v1(), p.v2()), (0.0, 0.0), (false, false), None);
231            entry.sw = sw;
232            entry.sh = sh;
233            entry.quad_left = vx[0];
234            entry.quad_top = vy[0];
235
236            // UV uses cellmap.size_original — the texture dimensions at SSAB build time.
237            // Atlas / scaled-texture pipelines must remap UVs engine-side.
238            let s = cellmap.size_original();
239            let (tex_w, tex_h) = (s.v1(), s.v2());
240            let tex_w = if tex_w > 0.0 { tex_w } else { 1.0 };
241            let tex_h = if tex_h > 0.0 { tex_h } else { 1.0 };
242            entry.u0 = src_x / tex_w;
243            entry.v0 = src_y / tex_h;
244            entry.u1 = (src_x + sw) / tex_w;
245            entry.v1 = (src_y + sh) / tex_h;
246            entry.resolved_ok = true;
247        }
248
249        let idx = cache.len();
250        cache.push(entry);
251        idx
252    }
253
254    /// Advance the slot one frame and, when `draw` is set, build its draw plan.
255    ///
256    /// `draw` is whether the Player draws the part this frame, that is whether the
257    /// part is in the frame's `draw_order`. A hidden part is not, and its slot
258    /// still has to step every frame so an independently playing effect keeps
259    /// time; with `draw == false` the step moves only that (the clock and the
260    /// transition state) and returns not visible. The particles are a function of
261    /// the effect's time alone, so the next drawn step builds exactly the plan it
262    /// would have built had every step drawn.
263    pub fn step(&mut self, ev: crate::types::ss_effect_event_info, parent_frame: f32, delta_seconds: f32, fps: f32, parent_looped: bool, y_flip: bool, vert_stride: u8, draw: bool) -> crate::types::ss_effect_step_result {
264        // While the slot is playing independently, the SpriteStudio implicit frame-0
265        // playback key (synthetic default) is ignored — the independent effect
266        // keeps running across the parent's loop instead of being reset to it.
267        // Only a real authored EventEffect re-transitions the slot.
268        let ignore_implicit = self.last_independent && ev.is_synthetic_default;
269
270        // Parent loop edge re-arms transition detection so a *synced* effect
271        // re-fires its authored EventEffect on the next playthrough (without this
272        // reset the equality check below would treat the loop edge as a no-op,
273        // freezing the effect at the end of the previous cycle).
274        //
275        // Independent playback follows the opposite rule: the slot
276        // remembers "the last key that started playback" and a re-crossing of the
277        // *same* key must NOT restart it — finite single-key effects play once and
278        // stay dead across loops ("fire-once"), only a *different* key re-fires.
279        // So when the last started key was independent, keep the memory intact:
280        // don't re-arm. `ignore_implicit` already skips the synthetic-key case;
281        // `!self.last_independent` additionally protects the real-key case (e.g.
282        // a partial-section loop whose first active key is the play key).
283        if parent_looped && !ignore_implicit && !self.last_independent {
284            self.last_event_frame = -1;
285            self.last_is_synthetic = false;
286        }
287
288        // When ignoring the implicit key, keep stepping with the last real
289        // event's identity / mode / speed rather than the synthetic default's.
290        let event_frame = if ignore_implicit { self.last_event_frame } else { ev.event_frame };
291        let start_time = ev.start_time;
292        let speed = if ignore_implicit { self.last_speed } else { ev.speed };
293        let independent = if ignore_implicit { true } else { ev.independent };
294        let is_synthetic = ev.is_synthetic_default;
295
296        let transitioned = !ignore_implicit && (self.last_event_frame != event_frame || self.last_is_synthetic != is_synthetic || self.last_independent != independent);
297
298        if transitioned {
299            self.ctx.reset();
300            // `independent` controls the *clock* (own delta-time vs parent-synced
301            // frame), not whether the effect loops. Looping is a property of the
302            // effect resource itself: only genuinely infinite effects loop; finite
303            // ones play once and are culled by the dead-effect early-return below,
304            // whatever `independent` says.
305            self.ctx.set_loop(self.is_infinite);
306            self.last_event_frame = event_frame;
307            self.last_is_synthetic = is_synthetic;
308            self.last_independent = independent;
309            self.last_speed = speed;
310            self.accumulated_time = start_time as f32;
311        }
312
313        let relative_frame: f32 = if independent {
314            // Skip the first tick after transition — `play()` snaps to start_time
315            // and stepping on the same tick would visibly overshoot frame 1.
316            if !transitioned && delta_seconds > 0.0 {
317                let delta_frames = delta_seconds * fps;
318                self.accumulated_time += delta_frames * speed;
319            }
320            self.accumulated_time
321        } else {
322            let elapsed = parent_frame - event_frame as f32;
323            if elapsed < 0.0 {
324                return crate::types::ss_effect_step_result::not_visible();
325            }
326            elapsed * speed + start_time as f32
327        };
328
329        if relative_frame < 0.0 {
330            return crate::types::ss_effect_step_result::not_visible();
331        }
332
333        // Dead-effect skip: a finite effect past its last particle's death is
334        // gone — independent or not. Independent only changes how `relative_frame`
335        // is advanced (own accumulator vs parent-synced); both clocks must still
336        // honour the effect's finite lifetime.
337        if !self.is_infinite && self.lifetime > 0 && relative_frame > self.lifetime as f32 {
338            return crate::types::ss_effect_step_result::not_visible();
339        }
340
341        if !draw {
342            return crate::types::ss_effect_step_result::not_visible();
343        }
344
345        self.ctx.update(relative_frame);
346        let buf = self.build_draw_plan(y_flip, vert_stride);
347        if buf.is_empty() { crate::types::ss_effect_step_result::not_visible() } else { crate::types::ss_effect_step_result { visible: true, draw_plan_buf: buf.as_ptr(), draw_plan_len: buf.len() } }
348    }
349
350    /// Build the `EffectDrawPlan` FlatBuffer from the simulator's current
351    /// draw_commands + draw_particles. Resolves per-emitter resources via
352    /// `ensure_emitter_resource_in` (cached) and writes verts/uvs/colors/indices
353    /// concatenated for all emitters in one pass. Returns the FlatBuffer slice;
354    /// valid until the next call on this slot.
355    fn build_draw_plan(&mut self, y_flip: bool, vert_stride: u8) -> &[u8] {
356        // π/180.
357        const DEG_TO_RAD: f32 = 0.017_453_292;
358        let stride = if vert_stride == 3 { 3usize } else { 2usize };
359        let y_sign: f32 = if y_flip { -1.0 } else { 1.0 };
360
361        // Narrow the borrow on `self.ctx.get_draw_commands` so other self
362        // fields stay touchable afterwards.
363        self.scratch_cmd_keys.clear();
364        {
365            let (commands, _particles) = self.ctx.get_draw_commands();
366            self.scratch_cmd_keys.reserve(commands.len());
367            for c in commands.iter() {
368                self.scratch_cmd_keys.push((c.cell_map_name_hash, c.cell_name_hash, c.blend_type, c.particle_start, c.particle_end));
369            }
370        }
371
372        // Resolve each command's resources, split-borrowing disjoint self fields.
373        self.scratch_entries.clear();
374        self.scratch_entries.reserve(self.scratch_cmd_keys.len());
375        {
376            let cache = &mut self.emitter_resource_cache;
377            let ssab = &self.ssab;
378            for &(cmh, ch, bi, ps, pe) in self.scratch_cmd_keys.iter() {
379                self.scratch_entries.push((Self::ensure_emitter_resource_in(cache, ssab, cmh, ch, bi), ps, pe));
380            }
381        }
382
383        let total_quads: usize = self.scratch_entries.iter().map(|(_, s, e)| e - s).sum();
384        if total_quads == 0 {
385            return &[];
386        }
387
388        self.scratch_verts.clear();
389        self.scratch_uvs.clear();
390        self.scratch_colors.clear();
391        self.scratch_indices.clear();
392        self.scratch_verts.reserve(total_quads * 4 * stride);
393        self.scratch_uvs.reserve(total_quads * 4 * 2);
394        self.scratch_colors.reserve(total_quads * 4 * 4);
395        self.scratch_indices.reserve(total_quads * 6);
396
397        // Snapshot resolved entries so self.emitter_resource_cache is free
398        // to be re-borrowed when we later write into self.fb.
399        self.scratch_resolved.clear();
400        self.scratch_resolved.reserve(self.scratch_entries.len());
401        for (i, _, _) in self.scratch_entries.iter() {
402            let e = &self.emitter_resource_cache[*i];
403            self.scratch_resolved.push(ResolvedEmitter { ok: e.resolved_ok, blend_byte: e.blend_byte, quad_left: e.quad_left, quad_top: e.quad_top, sw: e.sw, sh: e.sh, u0: e.u0, v0: e.v0, u1: e.u1, v1: e.v1, cellmap_hash: e.cellmap_hash });
404        }
405
406        self.scratch_command_meta.clear();
407        self.scratch_command_meta.reserve(self.scratch_entries.len());
408
409        let particles = &self.ctx.instance.draw_particles;
410
411        for (cmd_idx, (_, p_start, p_end)) in self.scratch_entries.iter().enumerate() {
412            let r = &self.scratch_resolved[cmd_idx];
413            let particle_offset = (self.scratch_verts.len() / (4 * stride)) as u32;
414            let particle_count = (p_end - p_start) as u32;
415
416            if !r.ok {
417                self.scratch_command_meta.push((r.cellmap_hash, r.blend_byte, 0, particle_offset));
418                continue;
419            }
420
421            let (lx, ly) = particle_quad(r.quad_left, r.quad_top, r.sw, r.sh, y_sign);
422            let uvs_corner = [r.u0, r.v0, r.u1, r.v0, r.u0, r.v1, r.u1, r.v1];
423
424            for (i, p) in particles[*p_start..*p_end].iter().enumerate() {
425                let angle = y_sign * (p.rotation * DEG_TO_RAD + p.direction);
426                let c = libm::cosf(angle);
427                let s = libm::sinf(angle);
428                let py = y_sign * p.y;
429
430                for v in 0..4 {
431                    let xx = lx[v] * p.scale_x;
432                    let yy = ly[v] * p.scale_y;
433                    let wx = c * xx - s * yy + p.x;
434                    let wy = s * xx + c * yy + py;
435                    self.scratch_verts.push(wx);
436                    self.scratch_verts.push(wy);
437                    if stride == 3 {
438                        self.scratch_verts.push(0.0);
439                    }
440                }
441                self.scratch_uvs.extend_from_slice(&uvs_corner);
442                let r_f = p.color.r as f32 / 255.0;
443                let g_f = p.color.g as f32 / 255.0;
444                let b_f = p.color.b as f32 / 255.0;
445                let a_f = p.color.a as f32 / 255.0;
446                for _ in 0..4 {
447                    self.scratch_colors.extend_from_slice(&[r_f, g_f, b_f, a_f]);
448                }
449                // Quad-local indices: command consumers slice [off*6 .. (off+qc)*6]
450                // and pair it with the verts slice [off*4*stride .. (off+qc)*4*stride],
451                // so values must be 0..qc*4 within the command, not global.
452                let v = (i * 4) as i32;
453                self.scratch_indices.extend_from_slice(&[v, v + 1, v + 2, v + 2, v + 1, v + 3]);
454            }
455
456            self.scratch_command_meta.push((r.cellmap_hash, r.blend_byte, particle_count, particle_offset));
457        }
458
459        // Commands are inlined fixed-size structs; collect as POD then create
460        // the vector in one shot (no per-element vtable/offset overhead).
461        self.fb.reset();
462        self.scratch_cmds.clear();
463        self.scratch_cmds.reserve(self.scratch_command_meta.len());
464        for &(hash, blend, qc, off) in self.scratch_command_meta.iter() {
465            self.scratch_cmds.push(crate::runtime::effect_draw_plan::ss::runtime::EffectDrawCommand::new(hash, qc, off, blend));
466        }
467        let commands_off = self.fb.create_vector(&self.scratch_cmds);
468        let verts_off = self.fb.create_vector(&self.scratch_verts);
469        let uvs_off = self.fb.create_vector(&self.scratch_uvs);
470        let colors_off = self.fb.create_vector(&self.scratch_colors);
471        let indices_off = self.fb.create_vector(&self.scratch_indices);
472
473        let mut plan_b = crate::runtime::effect_draw_plan::ss::runtime::EffectDrawPlanBuilder::new(&mut self.fb);
474        plan_b.add_commands(commands_off);
475        plan_b.add_vert_stride(stride as u8);
476        plan_b.add_verts(verts_off);
477        plan_b.add_uvs(uvs_off);
478        plan_b.add_colors(colors_off);
479        plan_b.add_indices(indices_off);
480        let root = plan_b.finish();
481        self.fb.finish_minimal(root);
482        self.fb.finished_data()
483    }
484}