Skip to main content

ssplayer_bevy/
components.rs

1//! What a Bevy application spawns to put a character on screen.
2//!
3//! These live in the **main world**. They are the whole authoring surface: the
4//! playback tree itself never appears here, because it is owned by the render
5//! world and reached only through these components.
6
7use bevy::platform::collections::HashMap;
8use bevy::prelude::*;
9
10use ssplayer_wgpu::{CrowdMember, PlaybackDirection, PlaybackStyle, TrackBlend, TrackSync};
11
12use crate::asset::SsPack;
13
14/// A SpriteStudio character.
15///
16/// Changing `pack` or `animation` rebuilds the playback tree on the next frame,
17/// and so does the pack's file changing under a hot-reloading app; everything
18/// else is allocation-free transport, which is why placement and playback sit in
19/// their own components. The one exception is a change of `animation` with a
20/// `transition_ms` above zero: that crossfades instead, on the tree in place.
21#[derive(Component, Clone, Debug, Default)]
22#[require(SsTransform, SsPlayback, SsPlaybackState, SsTrackState)]
23pub struct SsPlayer {
24    /// The `.ssab` this character plays from: `asset_server.load("Ringo/Ringo.ssab")`.
25    /// The character appears once the pack and its atlases have loaded.
26    pub pack: Handle<SsPack>,
27    /// Animation to select. Empty means "do not select one yet".
28    ///
29    /// This is the one way to change track 0's animation: [`TrackCommand`]s
30    /// that would lay one on track 0 are refused, so what this names and what
31    /// track 0 plays never part. Only a change of value acts, so a system may
32    /// write it every frame.
33    pub animation: String,
34    /// How a change of `animation` is made: `0` (the default) switches at once,
35    /// rebuilding the tree; above zero crossfades to the new animation over that
36    /// many milliseconds, as [`TrackCommand::Crossfade`] does on other tracks.
37    /// The first animation a character selects, and the first after a change of
38    /// `pack`, is always switched to at once: there is nothing to fade from.
39    pub transition_ms: f32,
40}
41
42/// Where the character sits, in the same terms
43/// [`ssplayer_wgpu::SSPlayer::set_transform`] takes but in Bevy's world units —
44/// logical pixels under the default 2D projection — from the view's centre, with
45/// `y` downward. The camera's own `Transform` and zoom do not apply.
46///
47/// Deliberately not Bevy's [`Transform`]: that is a 3D affine whose decomposition
48/// into the player's five scalars is lossy, and a host that wants the two linked
49/// can write the one system that copies across.
50#[derive(Component, Clone, Copy, Debug)]
51pub struct SsTransform {
52    /// Horizontal position from the view's centre.
53    pub x: f32,
54    /// Vertical position from the view's centre, measured downward.
55    pub y: f32,
56    /// Horizontal scale; negative mirrors.
57    pub scale_x: f32,
58    /// Vertical scale; negative mirrors.
59    pub scale_y: f32,
60    /// Radians.
61    pub rotation: f32,
62}
63
64impl Default for SsTransform {
65    fn default() -> Self {
66        Self { x: 0.0, y: 0.0, scale_x: 1.0, scale_y: 1.0, rotation: 0.0 }
67    }
68}
69
70/// Transport and compositing state — everything that costs nothing to change.
71#[derive(Component, Clone, Copy, Debug)]
72pub struct SsPlayback {
73    /// Whether the timeline advances. Toggling it pauses and resumes in place; it
74    /// never rewinds, so it cannot replay a finished animation, nor start one an
75    /// [`SsStop`] ended — that is [`SsPlayback::restart`]'s job, or an
76    /// [`SsPlay`]'s.
77    pub playing: bool,
78    /// A multiple of the authored rate. `0` and negatives stop the playhead.
79    pub speed_scale: f32,
80    /// Draw order within the render target; lower draws first. Ties keep the
81    /// order the entities were extracted in.
82    pub order: i32,
83    /// Player-level fade, folded into every vertex — part by part, so
84    /// overlapping parts read more opaque than this, unless
85    /// [`SsSceneSettings::group_alpha`] fades each character as one layer.
86    pub alpha: f32,
87    /// Player-level tint, `0xRRGGBB`, multiplied into every part after its
88    /// PartsColor; white (the default) leaves colours as authored. Like `alpha`,
89    /// it leaves mask coverage alone.
90    pub tint: u32,
91    /// False draws nothing while the timeline keeps running, so hiding a
92    /// character for a moment does not slow it down.
93    pub visible: bool,
94    /// True skips the timeline advance as well as the draw — for a character
95    /// that cannot be seen at all. The time spent culled is dropped.
96    pub culled: bool,
97    /// Bump this (any change in value) to replay the animation from its head,
98    /// re-arming the loop count. A generation counter rather than a flag so a host
99    /// can re-trigger a one-shot at will without having to clear anything, and so
100    /// two restarts in a row are two restarts.
101    pub restart: u32,
102    /// Which way the playhead walks, as
103    /// [`ssplayer_wgpu::SSPlayer::set_playback_direction`] takes it. The way it
104    /// is actually travelling is [`SsPlaybackState::playing_forward`]: a
105    /// ping-pong's return leg runs backward under `Forward`.
106    pub direction: PlaybackDirection,
107    /// What the playhead does at the far end: `Normal` wraps, `PingPong` turns
108    /// back.
109    pub style: PlaybackStyle,
110    /// Cycles to play before stopping; `-1` (or `0`) loops for ever, which is
111    /// also what an animation does unless told otherwise. A change re-arms the
112    /// count, as a restart does.
113    pub loop_count: i32,
114    /// Replaces the authored frame rate; `0` keeps it. Prefer `speed_scale`,
115    /// which scales the authored timing rather than replacing it.
116    pub frame_rate: i32,
117    /// On (the default) keeps playback on the wall clock by dropping frames
118    /// under load; off advances exactly one frame per tick.
119    pub frame_skip_enabled: bool,
120    /// On (the default) draws between authored frames; off floors the frame
121    /// that is drawn, pinning playback to whole ones.
122    pub sub_frame_enabled: bool,
123    /// Restrict the playhead to `start..=end` of the current animation, so
124    /// looping and ping-pong turn around inside it; `None` is the whole
125    /// animation. Setting or changing it puts the playhead at its start, and it
126    /// applies to whichever animation is set up, so change it with `animation`.
127    /// Both ends are included, and an end outside the animation is its edge on
128    /// that side. An end before the start, both inside the animation, is
129    /// refused as [`ssplayer_wgpu::SSPlayer::set_animation_section`] refuses
130    /// it: the adapter warns once, and the section stays as it was.
131    pub animation_section: Option<(i32, i32)>,
132}
133
134impl Default for SsPlayback {
135    fn default() -> Self {
136        Self {
137            playing: true,
138            speed_scale: 1.0,
139            order: 0,
140            alpha: 1.0,
141            tint: 0xFF_FFFF,
142            visible: true,
143            culled: false,
144            restart: 0,
145            direction: PlaybackDirection::Forward,
146            style: PlaybackStyle::Normal,
147            loop_count: -1,
148            frame_rate: 0,
149            frame_skip_enabled: true,
150            sub_frame_enabled: true,
151            animation_section: None,
152        }
153    }
154}
155
156/// Move a character's playhead to `frame`, as
157/// [`ssplayer_wgpu::SSPlayer::seek`] does: a fractional frame is honoured, and
158/// the playhead stays inside the section.
159///
160/// A message rather than a field of [`SsPlayback`], because a seek happens once
161/// rather than being a state the character is in: write it with a
162/// `MessageWriter<SsSeek>`. One sent before the character's pack has loaded is
163/// kept and applied once its animation is set up; of several in one frame, the
164/// last wins.
165#[derive(Message, Clone, Copy, Debug)]
166pub struct SsSeek {
167    /// The character to seek.
168    pub entity: Entity,
169    /// The frame to move the playhead to.
170    pub frame: f32,
171}
172
173/// Start a character's animation from the head of its section, or from
174/// `start_frame`, as [`ssplayer_wgpu::SSPlayer::play`] and
175/// [`ssplayer_wgpu::SSPlayer::play_from`] do: it rewinds, re-arms the loop count
176/// and starts even a finished or stopped animation. `start_frame: None` is what
177/// bumping [`SsPlayback::restart`] does.
178///
179/// [`SsPlayback::playing`] still governs afterwards, as it does after a
180/// restart: a character held with `playing: false` starts and holds on its
181/// first frame. One sent before the pack has loaded is applied once the
182/// animation is set up; of several in one frame, the last wins.
183#[derive(Message, Clone, Copy, Debug)]
184pub struct SsPlay {
185    /// The character to start.
186    pub entity: Entity,
187    /// The frame to start from; `None` starts from the head of the section.
188    pub start_frame: Option<f32>,
189}
190
191/// End a character's playback where it stands, as
192/// [`ssplayer_wgpu::SSPlayer::stop`] does. The playhead stays, so the frame it
193/// stopped on is still drawn, and it does not count as finished.
194///
195/// A stop is not a pause: turning [`SsPlayback::playing`] off and on again
196/// does not start a stopped animation, because resuming only carries on what
197/// is running. Start it again with [`SsPlay`] or [`SsPlayback::restart`]. One
198/// sent before the pack has loaded is applied once the animation is set up.
199#[derive(Message, Clone, Copy, Debug)]
200pub struct SsStop {
201    /// The character to stop.
202    pub entity: Entity,
203}
204
205/// One operation on a character's track stack — motion blending, as
206/// [`ssplayer_wgpu::SSPlayer`]'s track API performs it.
207///
208/// Tracks fold onto the setup pose in ascending order; track 0 is what
209/// [`SsPlayer::animation`] sets up, and only it: `SetAnimation` and `Crossfade`
210/// on track 0 are refused with a warning.
211/// Crossfade track 0 by changing `animation` with [`SsPlayer::transition_ms`]
212/// set. A message rather than a component because
213/// these are operations, a crossfade above all, rather than a state: write
214/// them with a `MessageWriter<SsTrackCommand>`. Several in one frame apply in
215/// the order they were written. Ones sent before the character's pack has
216/// loaded are kept and applied once its animation is set up.
217///
218/// **A new `animation` resets the stack** to track 0 alone, as
219/// [`ssplayer_wgpu::SSPlayer::set_animation`] does: send the overlays and the
220/// track settings again after changing it. What the stack holds comes back in
221/// [`SsTrackState`], a frame late.
222#[derive(Message, Clone, Debug)]
223pub struct SsTrackCommand {
224    /// The character whose track stack to change.
225    pub entity: Entity,
226    /// The operation.
227    pub command: TrackCommand,
228}
229
230/// What an [`SsTrackCommand`] does. Each variant is the
231/// [`ssplayer_wgpu::SSPlayer`] call of the same name.
232///
233/// A track's playback settings (`SetSpeed` to `SetPlaybackDirection`) are the
234/// track's: they reach every animation on it, and every one laid on it later.
235/// Track 0's come from [`SsPlayback`], as its loop count does, so these
236/// commands are refused on track 0.
237#[derive(Clone, Debug, PartialEq)]
238pub enum TrackCommand {
239    /// Lay `animation` on `track`, replacing what it played. Not on track 0,
240    /// which [`SsPlayer::animation`] sets.
241    SetAnimation { track: u32, animation: String },
242    /// Fade `track` over to `animation` in `duration_ms`. Not on track 0: change
243    /// [`SsPlayer::animation`] with [`SsPlayer::transition_ms`] set.
244    Crossfade { track: u32, animation: String, duration_ms: f32 },
245    /// Drive `track`'s alpha to `target` in `duration_ms`.
246    FadeTrack { track: u32, target: f32, duration_ms: f32 },
247    /// Stop the fade on `track` where it stands.
248    CancelFade { track: u32 },
249    /// Silence `track`. Track 0 is refused.
250    Clear { track: u32 },
251    /// `track`'s strength.
252    SetAlpha { track: u32, alpha: f32 },
253    /// How `track` layers onto what is below.
254    SetBlend { track: u32, blend: TrackBlend },
255    /// Where the animations laid on `track` from now on start. Send it before
256    /// the animation it is for.
257    SetSync { track: u32, sync: TrackSync },
258    /// Seek `track` — how a continuous-control axis is driven.
259    SetFrame { track: u32, frame: f32 },
260    /// `track`'s own speed; `0` parks it.
261    SetSpeed { track: u32, speed: f32 },
262    /// The frame rate `track` plays at instead of the authored one; `0` clears it.
263    SetFrameRate { track: u32, fps: i32 },
264    /// Whether `track` drops frames to keep to the wall clock.
265    SetFrameSkipEnabled { track: u32, enabled: bool },
266    /// Which way `track` plays, and what it does at the far end.
267    SetPlaybackDirection { track: u32, direction: PlaybackDirection, style: PlaybackStyle },
268    /// How many times `track`'s animation plays before it holds its last
269    /// frame; `-1` (or `0`) loops forever. It belongs to the animation: send it
270    /// after the one it is for, since each is laid looping forever. Not on
271    /// track 0, whose count is [`SsPlayback::loop_count`].
272    SetLoopCount { track: u32, count: i32 },
273    /// How far into a crossfade on `track` the outgoing animation keeps firing
274    /// events: while its share of the track, `1 - progress`, is at least this.
275    /// `f32::INFINITY` (the default) silences it from the start of the fade.
276    SetOutgoingEventThreshold { track: u32, threshold: f32 },
277    /// Lay `animation` on `track` beside what it carries, mixed by `weight`. Its
278    /// handle comes back in [`SsTrackState::sources`].
279    AddSource { track: u32, animation: String, weight: f32 },
280    /// A source's share within its track.
281    SetSourceWeight { source: u32, weight: f32 },
282    /// Seek one source.
283    SetSourceFrame { source: u32, frame: f32 },
284    /// The weight at or above which a source fires its events; only track 0's
285    /// main source fires by default.
286    SetSourceEventThreshold { source: u32, threshold: f32 },
287}
288
289/// A character's track stack as the render world last left it — the readable
290/// half of [`SsTrackCommand`]. **One frame behind**, like [`SsPlaybackState`].
291/// Required by [`SsPlayer`], so it is always present; empty until the
292/// character's animation is set up.
293#[derive(Component, Clone, Debug, Default)]
294pub struct SsTrackState {
295    /// One entry per track, track 0 first.
296    pub tracks: Vec<SsTrackInfo>,
297    /// The sources laid with [`TrackCommand::AddSource`] that are still
298    /// playing, with their handles. A source leaves the list when it is
299    /// released: a crossfade on its track completing, `Clear`, or a new
300    /// animation.
301    pub sources: Vec<SsSourceInfo>,
302}
303
304/// One track of [`SsTrackState`].
305#[derive(Clone, Debug, PartialEq)]
306pub struct SsTrackInfo {
307    /// The source carrying the track's animation; `None` on an empty track.
308    pub main_source: Option<u32>,
309    /// The track's alpha.
310    pub alpha: f32,
311    /// How the track composes onto the tracks below it.
312    pub blend: TrackBlend,
313    /// Where the animations laid on the track start.
314    pub sync: TrackSync,
315    /// The track's playhead; `None` on an empty track.
316    pub frame: Option<f32>,
317    /// How far a fade on the track has got, `0..=1`; `None` when not fading.
318    pub fade_progress: Option<f32>,
319    /// The track's speed, frame rate (the override or the authored rate),
320    /// frame skip and heading — what [`TrackCommand::SetSpeed`] and the
321    /// commands after it set.
322    pub speed: f32,
323    /// The track's frame rate: the override, or the authored rate.
324    pub frame_rate: i32,
325    /// Whether the track skips frames to keep time.
326    pub frame_skip_enabled: bool,
327    /// Which way the track's playhead walks.
328    pub direction: PlaybackDirection,
329    /// How the track behaves at the end of its section.
330    pub style: PlaybackStyle,
331    /// `-1` for a track that loops forever; `None` on an empty track.
332    pub loop_count: Option<i32>,
333    /// The track's animation has played its loop count out and holds its last
334    /// frame.
335    pub finished: bool,
336    /// The last advance wrapped the track's animation back to its start.
337    pub just_looped: bool,
338    /// The threshold the outgoing side of a crossfade on the track fires its
339    /// events at.
340    pub outgoing_event_threshold: f32,
341}
342
343/// A source added with [`TrackCommand::AddSource`], as it stands.
344#[derive(Clone, Debug, PartialEq)]
345pub struct SsSourceInfo {
346    /// The handle the `Source*` commands take.
347    pub source: u32,
348    /// The track it was laid on.
349    pub track: u32,
350    /// The animation it was laid with.
351    pub animation: String,
352    /// Its weight within the track.
353    pub weight: f32,
354    /// Its playhead.
355    pub frame: f32,
356}
357
358/// Runtime texture replacement: swap the texture a cellmap binds for a Bevy
359/// image, live, from gameplay code
360/// (costume changes, dynamic expressions).
361///
362/// Keyed by cellmap name, or by a TextureChange target's file name — whatever the
363/// character's pack lists. Insert an entry to override, remove it to restore the
364/// original atlas; the render world reconciles the map against what it has applied
365/// each frame. An image that is not yet loaded is applied the frame it becomes
366/// ready, so binding a freshly-spawned `Handle<Image>` is fine.
367///
368/// The replacement should match the original atlas's size and cell layout — the
369/// runtime's UVs stay in the original cellmap's pixel space — and be loaded with
370/// `is_srgb: false` in its `ImageLoaderSettings`: the player takes atlas bytes as
371/// authored, and an sRGB image draws too dark. The override is this
372/// character's alone: another entity playing the same pack is unaffected, and an
373/// instance child (its own pack) does not inherit it.
374///
375/// Optional — only characters that swap textures need spawn it.
376#[derive(Component, Clone, Debug, Default)]
377pub struct SsCellmapTextures {
378    /// Cellmap (or TextureChange-target) name -> the image to bind for it.
379    pub overrides: HashMap<String, Handle<Image>>,
380}
381
382/// Draw this character's one playhead once at each member's placement: a crowd
383/// that costs one character's evaluation and draw calls, however large, as
384/// [`ssplayer_wgpu::SSPlayer::set_crowd`] does.
385///
386/// Each member is placed in [`SsTransform`]'s terms, composed under the
387/// character's own `SsTransform`, and faded and tinted on top of its
388/// [`SsPlayback`]. Everything else is shared — the frame, the events (reported
389/// once), the masks and the effects. Members interleave draw by draw where they
390/// overlap. An empty list, or no component, draws the character once; members
391/// past [`ssplayer_wgpu::MAX_CROWD_MEMBERS`] are left out.
392///
393/// Optional — only characters drawn as crowds need spawn it. Copied into the
394/// render world every frame, into room it keeps, so moving the members
395/// allocates nothing.
396#[derive(Component, Clone, Debug, Default)]
397pub struct SsCrowd {
398    /// The copies to draw, each at its own placement.
399    pub members: Vec<CrowdMember>,
400}
401
402/// How this crate's scene draws. A resource, present from the moment the plugin
403/// is added; change it whenever.
404#[derive(Resource, Clone, Copy, Debug, Default)]
405pub struct SsSceneSettings {
406    /// Fade each character whose [`SsPlayback::alpha`] is below 1 as one layer,
407    /// composited at its alpha, rather than part by part — so overlapping parts
408    /// of a half-faded character read half, not three quarters. Off by default.
409    ///
410    /// Each character faded at once costs a render pass per frame and a layer
411    /// the size of the view (about 8 MiB at 1920x1080). Inside a layer the parts
412    /// blend against transparency rather than the scene behind: Add, Mul and
413    /// Screen parts composite with the character's own parts alone.
414    pub group_alpha: bool,
415}
416
417/// Playback state read back from the render world, refreshed every frame.
418///
419/// This is the pollable half of the round-trip; the reactive half is the
420/// messages ([`SsStarted`](crate::SsStarted), [`SsLooped`](crate::SsLooped),
421/// [`SsFinished`](crate::SsFinished), [`SsEventMessage`](crate::SsEventMessage)).
422/// Both are **one frame behind** — what you read this frame is what playback
423/// produced last frame — because playback runs in the render world. Required by
424/// [`SsPlayer`], so it is always present.
425#[derive(Component, Clone, Copy, Debug)]
426pub struct SsPlaybackState {
427    /// The frame the timeline last landed on.
428    pub frame_no: f32,
429    /// Whether the animation has reached its end.
430    pub finished: bool,
431    /// Which way the playhead is actually travelling: false on a ping-pong's
432    /// return leg as well as under a backward direction. Gate an
433    /// [`SsEvent::Audio`](ssplayer_wgpu::SsEvent::Audio) on it — SpriteStudio
434    /// has no reverse audio, so a key crossed going backward is not meant to
435    /// sound.
436    pub playing_forward: bool,
437}
438
439impl Default for SsPlaybackState {
440    /// Forward at rest, as the player reports it before anything has played.
441    fn default() -> Self {
442        Self { frame_no: 0.0, finished: false, playing_forward: true }
443    }
444}