Skip to main content

repame_shell/
lib.rs

1//! App wiring: Repose platform runners, host helpers, and the portal.
2//!
3//! Games provide the root view; the `run_*` runners mount only, and stepping
4//! stays game-side via [`Sim::step`]. [`RetainedRoot`] keeps the mounted view
5//! alive across frames, and [`GamepadPoller`] drains hardware events from the
6//! shared platform backend into the UI nav and the game's own pad state.
7//!
8//! Around that sit the helpers a host game needs once: [`Staging`] as the one
9//! per-frame input snapshot (held keys, edges, clicks, aim, touches, pads),
10//! [`on_first_user_gesture`] for the browser's autoplay rule, [`RumbleBridge`]
11//! for haptics, [`PadBank`] and [`PadMotion`] for pads and their motion,
12//! [`apply_scheduler_levels`] for scheduler priority, [`Quit`] for the
13//! platform-specific exit, and the shared shortcut edges.
14//!
15//! [`portal`] is the part a hosted game cannot do without: ads with deadlines,
16//! cloud-save push and pull, host pause, lifecycle mute, and the [`Suspend`]
17//! gate that decides whether the clock runs this frame. It is a module of its
18//! own because those rules are worth reading in one place.
19use std::collections::HashSet;
20use web_time::Duration;
21
22use anyhow::Result;
23pub use repame_sim::{Sim, SimTime};
24pub use repame_view2d::{Camera2d, PickEvent, SpriteInstance};
25use repose_core::View;
26pub use repose_core::input::{GamepadEvent, GamepadId};
27use repose_platform::gamepad::{GamepadBackend, create_backend};
28
29mod gesture;
30mod haptics;
31mod levels;
32mod motion;
33mod pads;
34pub mod portal;
35mod quit;
36mod shortcuts;
37mod staging;
38pub use gesture::{on_first_user_gesture, user_gesture_seen};
39pub use haptics::{RUMBLE_REFRESH, RUMBLE_UPLOAD_MS, RumbleBridge};
40pub use levels::apply_scheduler_levels;
41pub use motion::{MotionPoller, PadMotion};
42pub use pads::{PadBank, PadBridge, TRIGGER_HELD};
43pub mod pipeline_cache;
44pub use portal::{AdKind, AdOutcome, GameState, PortalHost, PortalReport, Suspend};
45pub use quit::Quit;
46pub use shortcuts::{
47    SharedEdges, ShortcutEdges, game_shortcut_map, install_game_shortcuts, install_handler_into,
48    install_map, shared_edges, shortcut_handler, take as take_shortcut_edges,
49};
50pub use staging::Staging;
51
52/// Per-frame hooks the game implements.
53pub trait ShellHooks {
54    /// Variable-rate hook (tweens, audio, autosave timers).
55    fn on_frame(&mut self, _sim: &mut Sim, _dt: Duration) {}
56}
57
58pub struct RetainedRoot {
59    key: String,
60    generation: u64,
61}
62
63impl RetainedRoot {
64    pub fn new() -> Self {
65        Self {
66            key: format!(
67                "repame.retained_root.{}",
68                repose_core::unique_component_id()
69            ),
70            generation: 0,
71        }
72    }
73
74    pub fn call<F>(&mut self, sched: &mut repose_core::runtime::Scheduler, build: F) -> View
75    where
76        F: FnOnce(&mut repose_core::runtime::Scheduler) -> View,
77    {
78        let key = &self.key;
79        let epoch = repose_core::timer::frame_count();
80        let generation = self.generation;
81        repose_core::scope!(key, sched, [epoch, generation], { build(sched) })
82    }
83
84    pub fn clear(&mut self) {
85        self.generation = self.generation.wrapping_add(1);
86    }
87}
88
89impl Default for RetainedRoot {
90    fn default() -> Self {
91        Self::new()
92    }
93}
94
95/// Desktop entry point. Mounts `root` with title and size.
96/// The root closure owns stepping and requests frames for continuity.
97/// The closure receives the live [`repose_core::runtime::Scheduler`] each frame, whose
98/// `held_keys` / `window_focused` / `mouse_*` fields are the single
99/// polled hardware snapshot (GML `keyboard_check` /
100/// `mouse_check_button` parity).
101#[cfg(all(not(target_os = "android"), not(target_arch = "wasm32")))]
102pub fn run_desktop(
103    title: &str,
104    size: (u32, u32),
105    mut root: impl FnMut(
106        &mut repose_core::runtime::Scheduler,
107        &repose_core::RenderContext,
108    ) -> repose_core::View
109    + 'static,
110) -> Result<()> {
111    let config = repose_app::AppConfig {
112        window_title: title.to_string(),
113        window_size: size,
114        ..Default::default()
115    };
116    let mut retained = RetainedRoot::new();
117    repose_platform::run_desktop_app_with_config(
118        move |sched, ctx| retained.call(sched, |sched| root(sched, ctx)),
119        config,
120    )?;
121    Ok(())
122}
123
124/// Web entry point. Mounts `root` with default options.
125#[cfg(target_arch = "wasm32")]
126pub fn run_web(
127    mut root: impl FnMut(
128        &mut repose_core::runtime::Scheduler,
129        &repose_core::RenderContext,
130    ) -> repose_core::View
131    + 'static,
132) -> Result<(), wasm_bindgen::JsValue> {
133    let mut options = repose_platform::web::WebOptions::new(None);
134    options.set_prevent_default(true);
135    let mut retained = RetainedRoot::new();
136    repose_platform::web::run_web_app(
137        move |sched, ctx| retained.call(sched, |sched| root(sched, ctx)),
138        options,
139    )
140}
141
142/// Android entry point. Mounts `root` with default options.
143#[cfg(target_os = "android")]
144pub fn run_android(
145    app: winit::platform::android::activity::AndroidApp,
146    mut root: impl FnMut(
147        &mut repose_core::runtime::Scheduler,
148        &repose_core::RenderContext,
149    ) -> repose_core::View
150    + 'static,
151) -> Result<()> {
152    let mut retained = RetainedRoot::new();
153    repose_platform::android::run_android_app_with_options(
154        app,
155        move |sched, ctx| retained.call(sched, |sched| root(sched, ctx)),
156        repose_app::AndroidOptions::default(),
157    )
158}
159
160/// Gamepad polling on the shared platform backend. Events feed
161/// `ReposeRuntime::handle_gamepad` (UI nav) and `rt.gamepads` (gameplay).
162pub struct GamepadPoller {
163    backend: Option<Box<dyn GamepadBackend>>,
164    connected: HashSet<u32>,
165}
166
167impl GamepadPoller {
168    pub fn new() -> Self {
169        Self {
170            backend: create_backend().map(|b| Box::new(b) as Box<dyn GamepadBackend>),
171            // Boot-plugged pads report on first poll; no press needed.
172            connected: HashSet::new(),
173        }
174    }
175
176    /// Drain hardware events since the last call. Tracks connection state
177    /// so `connected_ids` stays live.
178    pub fn poll(&mut self) -> Vec<GamepadEvent> {
179        let Some(backend) = &mut self.backend else {
180            return Vec::new();
181        };
182        let events = backend.poll();
183        for ev in &events {
184            match ev {
185                GamepadEvent::Connected { id, .. } => {
186                    self.connected.insert(id.0);
187                }
188                GamepadEvent::Disconnected { id } => {
189                    self.connected.remove(&id.0);
190                }
191                GamepadEvent::Button { id, .. } | GamepadEvent::Axis { id, .. } => {
192                    self.connected.insert(id.0);
193                }
194            }
195        }
196        events
197    }
198
199    pub fn connected_ids(&self) -> Vec<GamepadId> {
200        let mut ids: Vec<GamepadId> = self.connected.iter().copied().map(GamepadId).collect();
201        ids.sort_by_key(|id| id.0);
202        ids
203    }
204
205    pub fn connected_count(&self) -> usize {
206        self.connected.len()
207    }
208}
209
210impl Default for GamepadPoller {
211    fn default() -> Self {
212        Self::new()
213    }
214}