bevy_scene 0.19.0

Provides scene functionality for Bevy Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
use crate::{CachedSceneError, ResolvedScene, SceneList, ScenePatch};
use bevy_asset::{Asset, AssetPath, AssetServer, Assets};
use bevy_ecs::{
    bundle::Bundle,
    component::Component,
    error::Result,
    event::EntityEvent,
    name::Name,
    relationship::Relationship,
    system::IntoObserverSystem,
    template::{FnTemplate, FromTemplate, SceneEntityReference, Template, TemplateContext},
};
use core::{any::TypeId, marker::PhantomData};
use thiserror::Error;
use variadics_please::all_tuples;

/// Conceptually, a [`Scene`] describes what a spawned [`Entity`] should look like. This often describes what [`Component`]s the entity should have.
///
/// [`Scene`] is _always_ a single top level [`Entity`] / root entity.  For "lists of scenes" / multiple "root" entities, see [`SceneList`]. These are
/// separate traits for logical reasons: [`World::spawn`] is a "single entity" action. Additionally, "scene caching" only makes sense when both scenes
/// are "single root entities". A good way to think of this is [`Entity`] vs [`Vec<Entity>`]: these are different types with different APIs and semantics.
///
/// ## Resolving Scenes
///
/// Functionally, a [`Scene`] is something that can contribute to a [`ResolvedScene`] by calling [`Scene::resolve`]. [`Scene`] is inherently composable.
/// A collection of [`Scene`]s is essentially a description of what a final [`ResolvedScene`] should look like. This is typically done with
/// tuples of [`Scene`]s (which also implement [`Scene`]).
///
/// A [`Scene`] generally does one or more of the following to a [`ResolvedScene`]:
/// - Adding a new [`Template`]
/// - Editing an existing [`Template`] (ex: "patching" [`Template`] fields)
/// - Adding one or more "related" [`ResolvedScene`]s, which will be spawned alongside the root [`ResolvedScene`] and "related" back to it with a [`Relationship`].
/// - Editing an existing "related" [`ResolvedScene`].
/// - Setting a [`ScenePatch`] containing a cached [`ResolvedScene`] to apply first.
///
/// See [`ResolvedScene`] for more information on how it can be composed.
///
/// A [`Scene`] can have dependencies (defined in [`Scene::register_dependencies`]), which _must_ be loaded before calling [`Scene::resolve`], or it
/// might return a [`ResolveSceneError`].
///
/// You generally don't need to resolve [`Scene`]s yourself. Instead use APIs like [`World::spawn_scene`] or [`World::queue_spawn_scene`]
///
/// [`World::spawn`]: crate::World::spawn
/// [`World::spawn_scene`]: crate::WorldSceneExt::spawn_scene
/// [`World::queue_spawn_scene`]: crate::WorldSceneExt::queue_spawn_scene
/// [`Entity`]: bevy_ecs::entity::Entity
/// [`Component`]: bevy_ecs::component::Component
pub trait Scene: SceneBox {
    /// This will apply the changes described in this [`Scene`] to the given [`ResolvedScene`]. This should not be called until all of the dependencies
    /// in [`Scene::register_dependencies`] have been loaded. The scene system will generally call this method on behalf of developers.
    ///
    /// [`Scene`]s are free to modify [`ResolvedScene`] in arbitrary ways. In the context of related entities, in general they should just be pushing new
    /// entities to the back of the list.
    fn resolve(
        self,
        context: &mut ResolveContext,
        scene: &mut ResolvedScene,
    ) -> Result<(), ResolveSceneError>;

    /// [`Scene`] can have [`Asset`] dependencies, which _must_ be loaded before calling [`Scene::resolve`] / [`SceneList::resolve_list`] or it might return a [`ResolveSceneError`]!
    ///
    /// In most cases, the scene system will ensure [`Scene::resolve`] / [`SceneList::resolve_list`] is called _after_ these dependencies have been loaded.
    ///
    /// [`Asset`]: bevy_asset::Asset
    fn register_dependencies(&self, _dependencies: &mut SceneDependencies) {}
}

/// Boxed version of [`Scene`], which enables implementing [`Scene`] for [`Box<dyn Scene>`]. Most
/// developers do not need to think about or use this trait.
///
/// Related: [`SceneListBox`].
///
/// ## Why does this exist?
///
/// [`Scene::resolve`] consumes `self`, which by default is not something that [`Box<dyn Scene>`]
/// can do in Rust, as `dyn Scene` is "unsized". The "way out" is to have every [`Scene`] type
/// _also_ know how to resolve itself for `self: Box<Self>`. [`SceneBox`] has a blanket impl
/// for `Scene + Sized` (which can just rely on the [`Scene`] impl). Then [`Box<dyn Scene>`] has a
/// manual [`SceneBox`] impl that relies on the _stored_ [`SceneBox::resolve_box`] impl.
///
/// [`SceneListBox`]: crate::SceneListBox
pub trait SceneBox: Send + Sync + 'static {
    /// See [`Scene::resolve`].
    fn resolve_box(
        self: Box<Self>,
        context: &mut ResolveContext,
        scene: &mut ResolvedScene,
    ) -> Result<(), ResolveSceneError>;

    /// See [`Scene::register_dependencies`].
    fn register_dependencies_box(&self, _dependencies: &mut SceneDependencies);
}

impl<S: Scene + Sized> SceneBox for S {
    #[inline]
    fn resolve_box(
        self: Box<Self>,
        context: &mut ResolveContext,
        scene: &mut ResolvedScene,
    ) -> Result<(), ResolveSceneError> {
        (*self).resolve(context, scene)
    }

    #[inline]
    fn register_dependencies_box(&self, dependencies: &mut SceneDependencies) {
        self.register_dependencies(dependencies);
    }
}

impl<T: ?Sized + SceneBox> Scene for Box<T> {
    fn resolve(
        self,
        context: &mut ResolveContext,
        scene: &mut ResolvedScene,
    ) -> Result<(), ResolveSceneError> {
        self.resolve_box(context, scene)
    }

    fn register_dependencies(&self, dependencies: &mut SceneDependencies) {
        (**self).register_dependencies_box(dependencies);
    }
}

/// A collection of asset dependencies required by a [`Scene`].
#[derive(Default)]
pub struct SceneDependencies(Vec<SceneDependency>);

impl SceneDependencies {
    /// Registers a new asset dependency with the given `type_id` and `path`. The `type_id` should match
    /// the type of the asset being loaded.
    pub fn register_erased(&mut self, type_id: TypeId, path: AssetPath<'static>) {
        self.0.push(SceneDependency { path, type_id });
    }

    /// Registers a new asset dependency with the given `A` type and `path`. `A` should match
    /// the type of the asset being loaded.
    pub fn register<A: Asset>(&mut self, path: AssetPath<'static>) {
        self.register_erased(TypeId::of::<A>(), path);
    }

    /// Iterates the current dependencies.
    pub fn iter(&self) -> impl Iterator<Item = &SceneDependency> {
        self.0.iter()
    }
}

/// An asset dependency of a [`Scene`].
pub struct SceneDependency {
    /// The path of the asset.
    pub path: AssetPath<'static>,
    /// The type of the asset.
    pub type_id: TypeId,
}

/// An [`Error`] that occurs during [`Scene::resolve`].
#[derive(Error, Debug)]
pub enum ResolveSceneError {
    /// Caused when a dependency listed in [`Scene::register_dependencies`] is not available when calling [`Scene::resolve`]
    #[error("Cannot resolve scene because the asset dependency {0} is not present. This could be because it isn't loaded yet, or because the asset does not exist. Consider using `queue_spawn_scene()` if you would like to wait for scene dependencies before spawning.")]
    MissingSceneDependency(AssetPath<'static>),
    /// Caused when including a cached scene during [`Scene::resolve`] fails.
    #[error(transparent)]
    CachedSceneError(#[from] CachedSceneError),
    /// Caused when a [`Scene`]/[`SceneList`] is not present on the scene asset.
    #[error("The Scene/SceneList is not present on the scene asset. This is likely because the scene has already been resolved, which consumed the source scene")]
    MissingScene,
}

/// Context used by [`Scene`] implementations during [`Scene::resolve`].
pub struct ResolveContext<'a> {
    /// The current asset server
    pub assets: &'a AssetServer,
    /// The current [`ScenePatch`] asset collection
    pub patches: &'a Assets<ScenePatch>,
    /// The currently cached [`ScenePatch`], if there is one.
    pub cached: Option<&'a ScenePatch>,
}

macro_rules! scene_impl {
    ($($patch: ident),*) => {
        impl<$($patch: Scene),*> Scene for ($($patch,)*) {
            fn resolve(self, _context: &mut ResolveContext, _scene: &mut ResolvedScene) -> Result<(), ResolveSceneError> {
                #[expect(
                    clippy::allow_attributes,
                    reason = "This is inside a macro, and as such, may not trigger in all cases."
                )]
                #[allow(
                    non_snake_case,
                    reason = "The names of these variables are provided by the caller, not by us."
                )]
                let ($($patch,)*) = self;
                $($patch.resolve(_context, _scene)?;)*
                Ok(())
            }

            fn register_dependencies(&self, _dependencies: &mut SceneDependencies) {
                #[expect(
                    clippy::allow_attributes,
                    reason = "This is inside a macro, and as such, may not trigger in all cases."
                )]
                #[allow(
                    non_snake_case,
                    reason = "The names of these variables are provided by the caller, not by us."
                )]
                let ($($patch,)*) = self;
                $($patch.register_dependencies(_dependencies);)*
            }
       }
    }
}

all_tuples!(scene_impl, 0, 12, P);

impl<S> Scene for Option<S>
where
    S: Scene,
{
    #[inline]
    fn resolve(
        self,
        context: &mut ResolveContext,
        scene: &mut ResolvedScene,
    ) -> Result<(), ResolveSceneError> {
        self.map(|value| value.resolve(context, scene))
            .unwrap_or(Ok(()))
    }

    #[inline]
    fn register_dependencies(&self, dependencies: &mut SceneDependencies) {
        if let Some(value) = &self {
            value.register_dependencies(dependencies);
        }
    }
}

impl<L: SceneList> SceneList for Option<L>
where
    L: SceneList,
{
    #[inline]
    fn resolve_list(
        self,
        context: &mut ResolveContext,
        scenes: &mut Vec<ResolvedScene>,
    ) -> std::prelude::v1::Result<(), ResolveSceneError> {
        self.map(|scene_list| scene_list.resolve_list(context, scenes))
            .unwrap_or(Ok(()))
    }

    #[inline]
    fn register_dependencies(&self, dependencies: &mut SceneDependencies) {
        if let Some(scene_list) = &self {
            scene_list.register_dependencies(dependencies);
        }
    }
}

/// A [`Scene`] that patches a [`Template`] of type `T` with a given function `F`.
///
/// Functionally, a [`TemplatePatch`] scene will initialize a [`Default`] value of the patched
/// template if it does not already exist in the [`ResolvedScene`], then it will apply the patch on top
/// of the current [`Template`] in the [`ResolvedScene`].
///
/// This is usually created by the [`PatchTemplate`] or [`PatchFromTemplate`] traits.
///
/// This enables defining things like "field" patches, which set specific fields without overriding
/// any other fields:
/// ```
/// # use bevy_ecs::prelude::*;
/// # use bevy_scene::PatchFromTemplate;
/// #[derive(FromTemplate)]
/// struct Position {
///     x: usize,
///     y: usize,
/// }
///
/// let patch = Position::patch(|position_template, context| {
///     position_template.x = 10;
/// });
///
/// let position = Position { x: 0, y: 0};
/// // applying patch to position would result in { x: 10, y: 0 }
/// ```
pub struct TemplatePatch<F: FnOnce(&mut T, &mut ResolveContext), T>(pub F, pub PhantomData<T>);

/// Returns a [`Scene`] that completely overwrites the current value of a [`Template`] `T` with the given `value`.
/// The `value` is cloned each time the [`Template`] is built.
pub fn template_value<T: Template>(
    value: T,
) -> TemplatePatch<impl FnOnce(&mut T, &mut ResolveContext), T> {
    TemplatePatch(
        move |input: &mut T, _context: &mut ResolveContext| {
            *input = value;
        },
        PhantomData,
    )
}

/// A helper function that returns a [`TemplatePatch`] [`Scene`] for something that implements [`FromTemplate`].
/// It will use [`FromTemplate::Template`] as the "patched template".
pub trait PatchFromTemplate {
    /// The [`Template`] that will be patched.
    type Template;

    /// Takes a "patch function" `func`, and turns it into a [`TemplatePatch`].
    fn patch<F: FnOnce(&mut Self::Template, &mut ResolveContext)>(
        func: F,
    ) -> TemplatePatch<F, Self::Template>;
}

impl<G: FromTemplate> PatchFromTemplate for G {
    type Template = G::Template;
    fn patch<F: FnOnce(&mut Self::Template, &mut ResolveContext)>(
        func: F,
    ) -> TemplatePatch<F, Self::Template> {
        TemplatePatch(func, PhantomData)
    }
}

/// A helper function that returns a [`TemplatePatch`] [`Scene`] for something that implements [`Template`].
pub trait PatchTemplate: Sized {
    /// Takes a "patch function" `func` that patches this [`Template`], and turns it into a [`TemplatePatch`].
    fn patch_template<F: FnOnce(&mut Self, &mut ResolveContext)>(func: F)
        -> TemplatePatch<F, Self>;
}

impl<T: Template> PatchTemplate for T {
    fn patch_template<F: FnOnce(&mut Self, &mut ResolveContext)>(
        func: F,
    ) -> TemplatePatch<F, Self> {
        TemplatePatch(func, PhantomData)
    }
}

impl<
        F: FnOnce(&mut T, &mut ResolveContext) + Send + Sync + 'static,
        T: Template<Output: Component> + Send + Sync + Default + 'static,
    > Scene for TemplatePatch<F, T>
{
    fn resolve(
        self,
        context: &mut ResolveContext,
        scene: &mut ResolvedScene,
    ) -> Result<(), ResolveSceneError> {
        let template = scene.get_or_insert_template::<T>(context);
        (self.0)(template, context);
        Ok(())
    }
}

/// A [`Scene`] that adds an `L` [`SceneList`] as "related scenes", using the `R` [`Relationship`]
pub struct RelatedScenes<R: Relationship, L: SceneList> {
    /// The related [`SceneList`]. Each entity described in the list will be spawned with the given [`Relationship`] to the
    /// entity described in the current [`Scene`].
    pub related_template_list: L,

    /// Marker holding the `R` type.
    pub marker: PhantomData<R>,
}

impl<R: Relationship, L: SceneList> RelatedScenes<R, L> {
    /// Creates a new [`RelatedScenes`] with the given `list`.
    pub fn new(list: L) -> Self {
        Self {
            related_template_list: list,
            marker: PhantomData,
        }
    }
}

impl<R: Relationship, L: SceneList> Scene for RelatedScenes<R, L> {
    fn resolve(
        self,
        context: &mut ResolveContext,
        scene: &mut ResolvedScene,
    ) -> Result<(), ResolveSceneError> {
        let related = scene.get_or_insert_related_resolved_scenes::<R>();
        self.related_template_list
            .resolve_list(context, &mut related.scenes)
    }

    fn register_dependencies(&self, dependencies: &mut SceneDependencies) {
        self.related_template_list
            .register_dependencies(dependencies);
    }
}

/// A [`Scene`] that will include the cached [`ScenePatch`] stored at the given [`AssetPath`].
/// This will _not_ resolve the cached scene directly on top of this [`ResolvedScene`]. Instead
/// it will set [`ResolvedScene::include_cached`], which (when spawning the [`ResolvedScene`]) will apply the cached [`ResolvedScene`]
/// first. _Then_ the top-level [`ResolvedScene`] will be applied.
///
/// This also enables copy-on-write semantics for all future [`Template`] accesses. See [`ResolvedScene`] for more info on caching.
#[derive(Clone)]
pub struct CachedSceneAsset(
    /// The [`AssetPath`] of the [`ScenePatch`] to include.
    pub AssetPath<'static>,
);

impl<I: Into<AssetPath<'static>>> From<I> for CachedSceneAsset {
    fn from(value: I) -> Self {
        CachedSceneAsset(value.into())
    }
}

impl Scene for CachedSceneAsset {
    fn resolve(
        self,
        context: &mut ResolveContext,
        scene: &mut ResolvedScene,
    ) -> Result<(), ResolveSceneError> {
        if let Some(handle) = context.assets.get_handle::<ScenePatch>(&self.0)
            && let Some(scene_patch) = context.patches.get(&handle)
        {
            scene.include_cached(handle)?;
            context.cached = Some(scene_patch);
            Ok(())
        } else {
            Err(ResolveSceneError::MissingSceneDependency(self.0))
        }
    }

    fn register_dependencies(&self, dependencies: &mut SceneDependencies) {
        dependencies.register::<ScenePatch>(self.0.clone());
    }
}

impl<F: (Fn(&mut TemplateContext) -> Result<O>) + Clone + Send + Sync + 'static, O: Component> Scene
    for FnTemplate<F, O>
{
    fn resolve(
        self,
        _context: &mut ResolveContext,
        scene: &mut ResolvedScene,
    ) -> Result<(), ResolveSceneError> {
        scene.push_template(FnTemplate(self.0));
        Ok(())
    }
}

/// Sets up a given name as an "entity reference" for the current entity. This pairs the [`Self::name`] field
/// to a given [`Self::reference`] field.
///
/// Usually the reference is not set manually by a user. Instead this is generally done by a macro (such as the [`bsn!`] macro) or an asset loader
/// (such as the BSN asset loader).
///
/// [`bsn!`]: crate::bsn
pub struct NameEntityReference {
    /// The name to give this entity.
    pub name: Name,
    /// A unique entity reference.
    pub reference: SceneEntityReference,
}

impl NameEntityReference {
    /// Resolves this reference "inline" without going through a [`Scene`] impl.
    pub fn resolve_inline(self, context: &mut ResolveContext, scene: &mut ResolvedScene) {
        scene.entity_references.push(self.reference);
        let name = scene.get_or_insert_template::<Name>(context);
        *name = self.name;
    }
}

impl Scene for NameEntityReference {
    fn resolve(
        self,
        context: &mut ResolveContext,
        scene: &mut ResolvedScene,
    ) -> Result<(), ResolveSceneError> {
        self.resolve_inline(context, scene);
        Ok(())
    }
}

/// A [`Scene`] that will create a new "entity scope" and fully resolve the given scene `S` on top of the current [`ResolvedScene`] (using that scope).
/// It is not cached.
#[must_use]
pub struct SceneScope<S: Scene>(pub S);

impl<S: Scene> Scene for SceneScope<S> {
    fn resolve(
        self,
        context: &mut ResolveContext,
        scene: &mut ResolvedScene,
    ) -> Result<(), ResolveSceneError> {
        self.0.resolve(context, scene)
    }

    fn register_dependencies(&self, dependencies: &mut SceneDependencies) {
        self.0.register_dependencies(dependencies);
    }
}

/// A [`SceneList`] that will create a new "entity scope" and fully resolve the given scene list `L` on top of the current [`Vec<ResolvedScene>`]
/// (using that scope). It is not cached.
#[must_use]
pub struct SceneListScope<L: SceneList>(pub L);

impl<L: SceneList> SceneList for SceneListScope<L> {
    fn resolve_list(
        self,
        context: &mut ResolveContext,
        scenes: &mut Vec<ResolvedScene>,
    ) -> Result<(), ResolveSceneError> {
        self.0.resolve_list(context, scenes)
    }

    fn register_dependencies(&self, dependencies: &mut SceneDependencies) {
        self.0.register_dependencies(dependencies);
    }
}

/// A [`Template`] / [`Scene`] that will create an [`Observer`] of a given [`EntityEvent`] on the current [`Scene`] entity.
/// This is typically initialized using the [`on()`] function, which returns an [`OnTemplate`].
///
/// [`Observer`]: bevy_ecs::observer::Observer
pub struct OnTemplate<I, E, B, M>(pub I, pub PhantomData<fn() -> (E, B, M)>);

impl<I: IntoObserverSystem<E, B, M> + Clone, E: EntityEvent, B: Bundle, M: 'static> Template
    for OnTemplate<I, E, B, M>
{
    type Output = ();

    fn build_template(&self, context: &mut TemplateContext) -> Result<Self::Output> {
        context.entity.observe(self.0.clone());
        Ok(())
    }

    fn clone_template(&self) -> Self {
        Self(self.0.clone(), PhantomData)
    }
}

impl<
        I: IntoObserverSystem<E, B, M> + Clone + Send + Sync,
        E: EntityEvent,
        B: Bundle,
        M: 'static,
    > Scene for OnTemplate<I, E, B, M>
{
    fn resolve(
        self,
        _context: &mut ResolveContext,
        scene: &mut ResolvedScene,
    ) -> Result<(), ResolveSceneError> {
        scene.push_bundle_template(OnTemplate(self.0, PhantomData));
        Ok(())
    }
}

/// Returns an [`OnTemplate`] that will create an [`Observer`] of a given [`EntityEvent`] on the current [`Scene`] entity.
///
/// [`Observer`]: bevy_ecs::observer::Observer
pub fn on<I: IntoObserverSystem<E, B, M>, E: EntityEvent, B: Bundle, M: 'static>(
    observer: I,
) -> OnTemplate<I, E, B, M> {
    OnTemplate(observer, PhantomData)
}

impl<S: Scene> From<SceneScope<S>> for Box<dyn Scene> {
    fn from(value: SceneScope<S>) -> Self {
        Box::new(value)
    }
}

impl<S: Scene> From<SceneScope<S>> for Option<Box<dyn Scene>> {
    fn from(value: SceneScope<S>) -> Self {
        Some(Box::new(value))
    }
}

impl<S: SceneList> From<SceneListScope<S>> for Box<dyn SceneList> {
    fn from(value: SceneListScope<S>) -> Self {
        Box::new(value)
    }
}

impl<S: Scene> From<SceneScope<S>> for Box<dyn SceneList> {
    fn from(value: SceneScope<S>) -> Self {
        Box::new(value)
    }
}

impl<S: Scene> From<SceneScope<S>> for Option<Box<dyn SceneList>> {
    fn from(value: SceneScope<S>) -> Self {
        Some(Box::new(value))
    }
}

impl<S: SceneList> From<SceneListScope<S>> for Option<Box<dyn SceneList>> {
    fn from(value: SceneListScope<S>) -> Self {
        Some(Box::new(value))
    }
}

/// A [`Scene`] that initializes a template if it doesn't yet exist.
#[derive(Default)]
pub struct InitTemplate<T>(PhantomData<T>);

impl<T: Template<Output: Component> + Default + Send + Sync + 'static> Scene for InitTemplate<T> {
    fn resolve(
        self,
        context: &mut ResolveContext,
        scene: &mut ResolvedScene,
    ) -> Result<(), ResolveSceneError> {
        let _ = scene.get_or_insert_template::<T>(context);
        Ok(())
    }
}

/// A [`Scene`] that uses a function `F` to perform arbitrary [`Scene`] logic.
pub struct SceneFunction<F: FnOnce(&mut ResolveContext, &mut ResolvedScene)>(pub F);

impl<F: FnOnce(&mut ResolveContext, &mut ResolvedScene) + Send + Sync + 'static> Scene
    for SceneFunction<F>
{
    fn resolve(
        self,
        context: &mut ResolveContext,
        scene: &mut ResolvedScene,
    ) -> Result<(), ResolveSceneError> {
        (self.0)(context, scene);
        Ok(())
    }
}