Skip to main content

ssplayer_bevy/
lib.rs

1//! Bevy adapter for [`ssplayer_wgpu`] — SpriteStudio characters inside a Bevy
2//! app, drawn on the device Bevy already owns.
3//!
4//! # Shape
5//!
6//! Bevy renders in two worlds, and this crate is split along that seam:
7//!
8//! * **Main world** — [`SsPlayer`], [`SsTransform`] and [`SsPlayback`]. Spawn
9//!   them, change them, and that is the whole authoring surface. The `.ssab` a
10//!   character plays is an [`SsPack`] asset, loaded through the `AssetServer`.
11//! * **Render world** — the playback trees, one device-scoped `SSRenderer` and
12//!   one target-scoped `SSScene`. Nothing here is reachable from gameplay code.
13//!
14//! Authoring state crosses to the render world through `ExtractSchedule`;
15//! playback state crosses back through a shared buffer — the timeline events
16//! ([`SsEventMessage`]), the start, loop and completion edges ([`SsStarted`],
17//! [`SsLooped`], [`SsFinished`]), and the frame landed on ([`SsPlaybackState`]). The
18//! return trip is one frame late, because playback runs in the render world.
19//!
20//! The player never owns Bevy's `Device` / `Queue` / render target; the draw
21//! system lends them for the frame, which is the same contract the winit viewer
22//! and the C++ hosts honour.
23//!
24//! # Supported Bevy
25//!
26//! Bevy **0.20.x**, and no other line. Bevy and this player must resolve to one
27//! `wgpu` — 0.20 wants `^30` and the player is pinned to 30 — because two
28//! majors of `wgpu` are two unrelated sets of types, and no amount of glue
29//! bridges them. npm would express this as a peer dependency; cargo has no such
30//! thing, so it is stated here and enforced by the workspace resolving one
31//! `wgpu`.
32//!
33//! # Masks
34//!
35//! Bevy's 2d depth texture is `Depth32Float` and carries no stencil, so this
36//! adapter selects the player's coverage-bitmap mask backend
37//! (`MaskBackend::Coverage`) rather than its stencil one. Nothing is asked of
38//! Bevy's attachments; the player rasterises its own bitmap into the encoder the
39//! draw pass is opened on, which is what makes the clip this frame's rather than
40//! the last one's. It costs one extra render pass per masking character.
41//!
42//! # Fades and crowds
43//!
44//! [`SsSceneSettings::group_alpha`] fades a character as one layer rather than
45//! part by part, drawn ahead of the pass into the same encoder, as the masks
46//! are. [`SsCrowd`] draws one character's playhead at many placements for the
47//! cost of one.
48//!
49//! # Limits of this version
50//!
51//! * **One view.** The adapter holds one `SSScene` with every character in it,
52//!   and `SSScene::update` fuses the timeline advance with the geometry build,
53//!   so a second view would advance every animation twice per frame. Later views
54//!   are skipped, with a warning.
55//! * **MSAA must be off.** The player's pipelines are single-sampled.
56
57mod asset;
58mod components;
59mod extract;
60mod feedback;
61mod render;
62
63pub use asset::{SsPack, SsPackLoadError, SsPackLoader};
64pub use components::{SsCellmapTextures, SsCrowd, SsPlay, SsPlayback, SsPlaybackState, SsPlayer, SsSceneSettings, SsSeek, SsSourceInfo, SsStop, SsTrackCommand, SsTrackInfo, SsTrackState, SsTransform, TrackCommand};
65pub use feedback::{SsEventMessage, SsFinished, SsLooped, SsStarted};
66// The event payloads a host matches on, re-exported so it need not also depend
67// on `ssplayer-wgpu` just to name them.
68pub use ssplayer_wgpu::{AudioEvent, CrowdMember, PlaybackDirection, PlaybackStyle, SignalEvent, SignalParam, SignalValue, SsEvent, TrackBlend, TrackSync, UserDataEvent};
69
70use bevy::app::{App, Plugin, PreUpdate};
71use bevy::asset::AssetApp;
72use bevy::core_pipeline::core_2d::main_transparent_pass_2d;
73use bevy::core_pipeline::{Core2d, Core2dSystems};
74use bevy::log::error;
75use bevy::prelude::IntoScheduleConfigs;
76use bevy::render::render_asset::RenderAssetPlugin;
77use bevy::render::{ExtractSchedule, Render, RenderApp, RenderStartup, RenderSystems};
78
79/// Adds SpriteStudio playback and drawing to a Bevy app.
80///
81/// Add it after `DefaultPlugins`; it needs the render app to exist.
82pub struct SsPlayerPlugin;
83
84impl Plugin for SsPlayerPlugin {
85    fn build(&self, app: &mut App) {
86        // The buffer playback feedback crosses on. Both worlds hold a clone of
87        // the one `Arc`, so what the render world writes the main world reads.
88        let channel = feedback::FeedbackChannel::default();
89
90        app.init_asset::<SsPack>()
91            .init_asset_loader::<SsPackLoader>()
92            // Moves each loaded pack into the render world, and again on a reload.
93            .add_plugins(RenderAssetPlugin::<asset::RenderSsPack>::default())
94            .add_message::<SsEventMessage>()
95            .add_message::<SsStarted>()
96            .add_message::<SsFinished>()
97            .add_message::<SsLooped>()
98            .add_message::<SsSeek>()
99            .add_message::<SsPlay>()
100            .add_message::<SsStop>()
101            .add_message::<SsTrackCommand>()
102            .init_resource::<SsSceneSettings>()
103            .insert_resource(channel.clone())
104            // In `PreUpdate` so a gameplay system reading these in `Update` sees
105            // the same frame's batch.
106            .add_systems(PreUpdate, feedback::dispatch_feedback);
107
108        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
109            error!("ssplayer-bevy: no render app — add this plugin after DefaultPlugins");
110            return;
111        };
112
113        render_app
114            .init_resource::<extract::ExtractedPlayers>()
115            .insert_resource(channel)
116            .add_systems(RenderStartup, render::init_state)
117            .add_systems(ExtractSchedule, extract::extract_players)
118            .add_systems(Render, render::sync_players.in_set(RenderSystems::Prepare))
119            .add_systems(Core2d, render::draw_players.in_set(Core2dSystems::MainPass).after(main_transparent_pass_2d));
120    }
121}