Skip to main content

euv_engine/scene/
impl.rs

1use super::*;
2
3/// Implements static scene creation for `SceneManager`.
4impl SceneManager {
5    /// Creates a new `SceneRc` wrapping the given scene in a reference-counted cell.
6    ///
7    /// # Arguments
8    ///
9    /// - `T` - The concrete scene type implementing `Scene`.
10    ///
11    /// # Returns
12    ///
13    /// - `SceneRc` - The wrapped scene.
14    pub fn create_scene<T>(scene: T) -> SceneRc
15    where
16        T: Scene + 'static,
17    {
18        // `EngineCell<T: ?Sized>` accepts `dyn Scene` directly,
19        // so we do not need an intermediate `Box`.
20        Rc::new(EngineCell::new(scene))
21    }
22}
23
24/// Implements scene registration and lifecycle management for `SceneManager`.
25impl SceneManager {
26    /// Registers a scene under the given name.
27    ///
28    /// # Arguments
29    ///
30    /// - `String` - The name to register the scene under.
31    /// - `SceneRc` - The scene to register.
32    pub fn register(&mut self, name: String, scene: SceneRc) {
33        self.get_mut_scenes().insert(name, scene);
34    }
35
36    /// Unregisters and removes the scene with the given name.
37    ///
38    /// # Arguments
39    ///
40    /// - `N: AsRef<str>` - The name of the scene to remove.
41    pub fn unregister<N>(&mut self, name: N)
42    where
43        N: AsRef<str>,
44    {
45        self.get_mut_scenes().remove(name.as_ref());
46    }
47
48    /// Transitions to the scene with the given name.
49    ///
50    /// Calls `on_exit` on the current scene and `on_enter` on the new scene.
51    /// Returns `false` if no scene with the given name is registered.
52    ///
53    /// # Arguments
54    ///
55    /// - `N: AsRef<str>` - The name of the scene to switch to.
56    ///
57    /// # Returns
58    ///
59    /// - `bool` - True if the transition was successful.
60    pub fn switch_to<N>(&mut self, name: N) -> bool
61    where
62        N: AsRef<str>,
63    {
64        let name_ref: &str = name.as_ref();
65        if !self.get_scenes().contains_key(name_ref) {
66            return false;
67        }
68        let current_name: Option<String> = self.get_mut_current_scene_name().clone();
69        if let Some(name) = current_name.as_ref()
70            && let Some(current_scene) = self.get_scenes().get(name)
71        {
72            current_scene.get_mut().on_exit();
73        }
74        self.set_current_scene_name(Some(name_ref.to_string()));
75        if let Some(new_scene) = self.get_scenes().get(name_ref) {
76            new_scene.get_mut().on_enter();
77        }
78        true
79    }
80
81    /// Requests a deferred scene transition to be applied on the next update.
82    ///
83    /// # Arguments
84    ///
85    /// - `String` - The name of the scene to switch to.
86    pub fn request_transition(&mut self, name: String) {
87        self.set_pending_scene_name(Some(name));
88    }
89
90    /// Processes a pending scene transition if one was requested.
91    pub fn process_pending_transition(&mut self) {
92        let Some(name) = self.get_mut_pending_scene_name().take() else {
93            return;
94        };
95        self.switch_to(&name);
96    }
97
98    /// Calls `on_update` on the current scene.
99    ///
100    /// # Arguments
101    ///
102    /// - `f64` - The delta time in seconds.
103    pub fn update(&mut self, delta_time: f64) {
104        self.process_pending_transition();
105        let current_name: Option<String> = self.get_mut_current_scene_name().clone();
106        let Some(current_name) = current_name.as_ref() else {
107            return;
108        };
109        let Some(scene) = self.get_scenes().get(current_name) else {
110            return;
111        };
112        scene.get_mut().on_update(delta_time);
113    }
114
115    /// Calls `on_render` on the current scene, recording into the shared draw list.
116    ///
117    /// The manager's reusable `DrawList` is cleared, filled by the scene, and
118    /// left populated for the caller to replay (e.g. via
119    /// `CanvasRenderer::replay`). Reusing the list avoids per-frame allocation.
120    ///
121    /// # Arguments
122    ///
123    /// - `&CanvasRenderingContext2d` - The canvas rendering context used to replay
124    ///   the recorded commands.
125    pub fn render(&mut self, context: &CanvasRenderingContext2d) {
126        let Some(current_name) = self.try_get_current_scene_name().as_ref() else {
127            return;
128        };
129        // Clone the `Rc` so the immutable borrow of the scenes map ends before
130        // we mutably borrow the draw list.
131        let Some(scene) = self.get_scenes().get(current_name).cloned() else {
132            return;
133        };
134        self.get_mut_draw_list().clear();
135        {
136            let draw_list: &mut DrawList = self.get_mut_draw_list();
137            scene.get().on_render(draw_list);
138        }
139        CanvasRenderer::replay_context(context, self.get_draw_list());
140    }
141
142    /// Returns whether a scene with the given name is registered.
143    ///
144    /// # Arguments
145    ///
146    /// - `N: AsRef<str>` - The scene name to check.
147    ///
148    /// # Returns
149    ///
150    /// - `bool` - True if the scene is registered.
151    pub fn has_scene<N>(&self, name: N) -> bool
152    where
153        N: AsRef<str>,
154    {
155        self.get_scenes().contains_key(name.as_ref())
156    }
157
158    /// Returns the name of the currently active scene.
159    ///
160    /// # Returns
161    ///
162    /// - `Option<&str>` - The current scene name, or `None`.
163    pub fn current_name(&self) -> Option<&str> {
164        self.try_get_current_scene_name().as_deref()
165    }
166}
167
168/// Forwards `SceneManager::update` through the [`Updatable`] trait so that
169/// scene managers can be driven alongside entities, animators, and physics
170/// worlds in a single homogeneous update loop.
171///
172/// The inherent [`SceneManager::update`] method is the canonical implementation;
173/// this impl exists purely for trait dispatch. The inherent call resolves
174/// first when both are in scope, so there is no recursion.
175impl Updatable for SceneManager {
176    fn update(&mut self, delta_time: f64) {
177        SceneManager::update(self, delta_time);
178    }
179}
180
181/// Implements `Default` for `SceneManager` as a new empty manager.
182impl Default for SceneManager {
183    fn default() -> SceneManager {
184        SceneManager::new()
185    }
186}