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
use std::fmt;
use std::hash::{Hash, Hasher};

use bevy_app::prelude::*;
use bevy_ecs::prelude::*;
use bevy_ecs::system::EntityCommands;
use bevy_hierarchy::BuildWorldChildren;
use bevy_reflect::prelude::*;
use bevy_utils::HashMap;

pub mod prelude {
    pub use super::{
        spawn_children, spawn_key, RegisterSpawnable, Spawn, SpawnChildBuilder, SpawnChildren,
        SpawnCommands, SpawnKey, SpawnOnce, SpawnPlugin, SpawnWorld, Spawnables, StaticSpawnKey,
        WithChildren,
    };
}

pub struct SpawnPlugin;

impl Plugin for SpawnPlugin {
    fn build(&self, app: &mut App) {
        app.register_type::<SpawnKey>()
            .insert_resource(Spawnables::default())
            .add_systems(First, invoke_spawn_children.run_if(should_spawn_children));
    }
}

/// Represents a type which spawns an [`Entity`] exactly once.
///
/// # Usage
/// The output of a spawn is a [`Bundle`] which is inserted into the given spawned [`Entity`].
///
/// By default, all bundles implement this trait.
pub trait SpawnOnce {
    type Output: Bundle;

    #[must_use]
    fn spawn_once(self, world: &World, entity: Entity) -> Self::Output;
}

impl<T: Bundle> SpawnOnce for T {
    type Output = Self;

    fn spawn_once(self, _world: &World, _entity: Entity) -> Self::Output {
        self
    }
}

/// Represents a type which spawns an [`Entity`].
///
/// # Usage
/// The output of a spawn is a [`Bundle`] which is inserted into the given spawned [`Entity`].
///
/// By default, anything which implements [`SpawnOnce`] and [`Clone`] also implements this trait.
/// This includes bundles which can be cloned.
pub trait Spawn {
    type Output: Bundle;

    #[must_use]
    fn spawn(&self, world: &World, entity: Entity) -> Self::Output;
}

impl<T: SpawnOnce + Clone> Spawn for T {
    type Output = T::Output;

    fn spawn(&self, world: &World, entity: Entity) -> Self::Output {
        self.clone().spawn_once(world, entity)
    }
}

/// Trait used to register a spawnable with an [`App`].
///
/// # Usage
/// A spawnable is any thing which implements [`Spawn`]. A spawnable is registered by a unique [`SpawnKey`].
/// This spawn key may then be used to spawn a new instance of the spawnable.
pub trait RegisterSpawnable {
    fn register_spawnable<T: Spawn>(self, key: impl Into<SpawnKey>, spawnable: T) -> SpawnKey
    where
        T: 'static + Send + Sync;
}

impl RegisterSpawnable for &mut App {
    fn register_spawnable<T: Spawn>(self, key: impl Into<SpawnKey>, spawnable: T) -> SpawnKey
    where
        T: 'static + Send + Sync,
    {
        self.world
            .resource_mut::<Spawnables>()
            .register(key, spawnable)
    }
}

/// Trait used to spawn spawnables either directly or via a [`SpawnKey`] using [`Commands`].
pub trait SpawnCommands {
    fn spawn_with<T: SpawnOnce>(&mut self, spawnable: T) -> EntityCommands<'_>
    where
        T: 'static + Send + Sync;

    fn spawn_with_key(&mut self, key: impl Into<SpawnKey>) -> EntityCommands<'_>;
}

impl SpawnCommands for Commands<'_, '_> {
    fn spawn_with<T: SpawnOnce>(&mut self, spawnable: T) -> EntityCommands<'_>
    where
        T: 'static + Send + Sync,
    {
        let entity = self.spawn_empty().id();
        self.add(move |world: &mut World| {
            let bundle = spawnable.spawn_once(world, entity);
            world.entity_mut(entity).insert(bundle);
        });
        self.entity(entity)
    }

    fn spawn_with_key(&mut self, key: impl Into<SpawnKey>) -> EntityCommands<'_> {
        let key = key.into();
        let entity = self.spawn_empty().id();
        self.add(move |world: &mut World| {
            if let Some(spawnable) = world.resource_mut::<Spawnables>().take(&key) {
                spawnable.spawn(world, entity);
                world.resource_mut::<Spawnables>().insert(key, spawnable);
            } else {
                panic!("invalid spawn key: {key:?}");
            }
        });
        self.entity(entity)
    }
}

/// Trait used to spawn spawnables either directly or via a [`SpawnKey`] using [`World`].
pub trait SpawnWorld {
    fn spawn_with<T: SpawnOnce>(&mut self, spawnable: T) -> EntityWorldMut
    where
        T: 'static + Send + Sync;

    fn spawn_with_key(&mut self, key: impl Into<SpawnKey>) -> EntityWorldMut;
}

impl SpawnWorld for World {
    fn spawn_with<T: SpawnOnce>(&mut self, spawnable: T) -> EntityWorldMut
    where
        T: 'static + Send + Sync,
    {
        let entity = self.spawn_empty().id();
        let bundle = spawnable.spawn_once(self, entity);
        self.entity_mut(entity).insert(bundle);
        invoke_spawn_children(self);
        self.entity_mut(entity)
    }

    fn spawn_with_key(&mut self, key: impl Into<SpawnKey>) -> EntityWorldMut {
        let key = key.into();
        let entity = self.spawn_empty().id();
        if let Some(spawnable) = self.resource_mut::<Spawnables>().take(&key) {
            spawnable.spawn(self, entity);
            self.resource_mut::<Spawnables>().insert(key, spawnable);
            invoke_spawn_children(self);
        } else {
            panic!("invalid spawn key: {key:?}");
        }
        self.entity_mut(entity)
    }
}

/// A [`Resource`] which contains all registered spawnables.
#[derive(Resource, Default)]
pub struct Spawnables(HashMap<SpawnKey, Box<dyn Spawnable>>);

impl Spawnables {
    /// Registers a spawnable with a unique [`SpawnKey`] and returns it.
    ///
    /// # Warning
    /// This function will panic if the given key is already registered.
    #[must_use]
    pub fn register<T: Spawn>(&mut self, key: impl Into<SpawnKey>, spawnable: T) -> SpawnKey
    where
        T: 'static + Send + Sync,
    {
        let key = key.into();
        let previous = self.0.insert(key.clone(), Box::new(spawnable));
        assert!(previous.is_none(), "spawn key must be unique: {key:?}",);
        key
    }

    /// Returns an iterator over all registered [`SpawnKey`]s.
    pub fn keys(&self) -> impl Iterator<Item = &SpawnKey> {
        self.0.keys()
    }

    #[must_use]
    fn take(&mut self, key: &SpawnKey) -> Option<Box<dyn Spawnable>> {
        self.0.remove(key)
    }

    fn insert(&mut self, key: SpawnKey, spawnable: Box<dyn Spawnable>) {
        self.0.insert(key, spawnable);
    }
}

pub struct StaticSpawnKey(&'static str);

impl From<StaticSpawnKey> for SpawnKey {
    fn from(key: StaticSpawnKey) -> Self {
        key.0.into()
    }
}

/// A unique string-based identifier used to spawn a spawnable registered with [`Spawnables`].
#[derive(Clone, Reflect)]
pub struct SpawnKey(String);

impl SpawnKey {
    pub fn new(name: impl Into<String>) -> Self {
        Self(name.into())
    }

    pub fn name(&self) -> &str {
        &self.0
    }
}

impl PartialEq for SpawnKey {
    fn eq(&self, other: &Self) -> bool {
        self.name() == other.name()
    }
}

impl Eq for SpawnKey {}

impl Hash for SpawnKey {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.name().hash(state)
    }
}

impl fmt::Debug for SpawnKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("SpawnKey").field(&self.name()).finish()
    }
}

impl From<String> for SpawnKey {
    fn from(name: String) -> Self {
        Self(name)
    }
}

impl From<&str> for SpawnKey {
    fn from(name: &str) -> Self {
        Self(name.to_owned())
    }
}

/// A function for defining a new static [`SpawnKey`].
///
/// # Example
/// ```
/// # use moonshine_spawn::prelude::*;
/// const FOO: StaticSpawnKey = spawn_key("FOO");
/// ```
pub const fn spawn_key(name: &'static str) -> StaticSpawnKey {
    StaticSpawnKey(name)
}

/// A convenient macro for defining static [`SpawnKey`]s.
/// # Example
/// ```
/// # use moonshine_spawn::prelude::*;
/// spawn_key!(FOO);
/// spawn_key!(BAR, BAZ);
/// ```
#[macro_export]
macro_rules! spawn_key {
    ($i:ident) => {
        const $i: $crate::StaticSpawnKey = $crate::spawn_key(stringify!($i));
    };
    ($($i:ident),*) => {
        $(spawn_key!($i);)*
    };
}

/// Trait used to attach children to an [`Entity`] using a [`Bundle`].
///
/// # Example
/// ```
/// # use bevy::prelude::*;
/// # use moonshine_spawn::prelude::*;
///
/// #[derive(Component)]
/// struct Foo;
///
/// #[derive(Component)]
/// struct Bar;
///
/// let mut world = World::default();
/// world.spawn(Foo.with_children(|foo| {
///    foo.spawn(Bar);
/// }));
/// ```
pub trait WithChildren: Bundle + Sized {
    fn with_children(self, f: impl FnOnce(&mut SpawnChildBuilder)) -> (Self, SpawnChildren);
}

impl<T: Bundle> WithChildren for T {
    fn with_children(self, f: impl FnOnce(&mut SpawnChildBuilder)) -> (Self, SpawnChildren) {
        let mut children = SpawnChildren::new();
        let mut builder = SpawnChildBuilder(&mut children);
        f(&mut builder);
        (self, children)
    }
}

/// A [`Component`] which stores a list of spawnables to spawn as children of its entity.
#[derive(Component)]
#[component(storage = "SparseSet")]
pub struct SpawnChildren(Vec<Box<dyn SpawnableOnce>>);

impl SpawnChildren {
    #[must_use]
    fn new() -> Self {
        Self(Vec::new())
    }

    fn add_child<T: SpawnOnce>(&mut self, spawnable: T)
    where
        T: 'static + Send + Sync,
    {
        self.0.push(Box::new(spawnable));
    }

    fn add_child_with_key(&mut self, key: SpawnKey) {
        self.0.push(Box::new(SpawnKeySpawnable(key)));
    }

    fn invoke(world: &mut World, entity: Entity, mut child_spawned: impl FnMut(Entity)) {
        if let Some(children) = world.entity_mut(entity).take::<SpawnChildren>() {
            for spawnable in children.0 {
                let child = world.spawn_empty().id();
                spawnable.spawn_once(world, child);
                child_spawned(child);
                world.entity_mut(entity).add_child(child);
            }
        }
    }
}

/// An ergonomic function used to create a [`SpawnChildren`] component.
#[must_use]
pub fn spawn_children(f: impl FnOnce(&mut SpawnChildBuilder)) -> SpawnChildren {
    let mut children = SpawnChildren::new();
    f(&mut SpawnChildBuilder(&mut children));
    children
}

impl Default for SpawnChildren {
    fn default() -> Self {
        Self::new()
    }
}

pub struct SpawnChildBuilder<'a>(&'a mut SpawnChildren);

impl SpawnChildBuilder<'_> {
    pub fn spawn<T: SpawnOnce>(&mut self, spawnable: T) -> &mut Self
    where
        T: 'static + Send + Sync,
    {
        self.0.add_child(spawnable);
        self
    }

    pub fn spawn_with_key(&mut self, key: impl Into<SpawnKey>) -> &mut Self {
        self.0.add_child_with_key(key.into());
        self
    }
}

trait Spawnable: 'static + Send + Sync {
    fn spawn(&self, world: &mut World, entity: Entity);
}

impl<T: Spawn> Spawnable for T
where
    T: 'static + Send + Sync,
{
    fn spawn(&self, world: &mut World, entity: Entity) {
        let bundle = self.spawn(world, entity);
        world.entity_mut(entity).insert(bundle);
    }
}

trait SpawnableOnce: 'static + Send + Sync {
    fn spawn_once(self: Box<Self>, world: &mut World, entity: Entity);
}

impl<T: SpawnOnce> SpawnableOnce for T
where
    T: 'static + Send + Sync,
{
    fn spawn_once(self: Box<Self>, world: &mut World, entity: Entity) {
        let bundle = (*self).spawn_once(world, entity);
        world.entity_mut(entity).insert(bundle);
    }
}

struct SpawnKeySpawnable(SpawnKey);

impl SpawnableOnce for SpawnKeySpawnable {
    fn spawn_once(self: Box<Self>, world: &mut World, entity: Entity) {
        let Self(key) = *self;
        if let Some(spawnable) = world.resource_mut::<Spawnables>().take(&key) {
            spawnable.spawn(world, entity);
            world.resource_mut::<Spawnables>().insert(key, spawnable);
        } else {
            panic!("invalid spawn key: {key:?}");
        }
    }
}

fn should_spawn_children(query: Query<(), With<SpawnChildren>>) -> bool {
    !query.is_empty()
}

fn invoke_spawn_children(world: &mut World) {
    let mut entities = Vec::new();

    for entity in world.iter_entities() {
        if entity.contains::<SpawnChildren>() {
            entities.push(entity.id());
        }
    }

    while !entities.is_empty() {
        let batch = std::mem::take(&mut entities);
        for entity in batch {
            SpawnChildren::invoke(world, entity, |child| entities.push(child));
        }
    }
}

#[cfg(test)]
mod tests {
    use bevy::{ecs::system::RunSystemOnce, prelude::*};

    use super::*;

    fn app() -> App {
        let mut app = App::new();
        app.add_plugins((MinimalPlugins, SpawnPlugin));
        app
    }

    #[derive(Component, Clone)]
    struct Foo;

    #[derive(Component, Clone)]
    struct Bar;

    spawn_key!(FOO, BAR);

    #[test]
    fn spawn_bundle() {
        let mut app = app();
        let world = &mut app.world;
        let entity = world.spawn_with(Foo).id();
        assert!(world.entity(entity).contains::<Foo>());
    }

    #[test]
    fn spawn_bundle_deferred() {
        let mut app = app();
        let entity = {
            let world = &mut app.world;
            world.run_system_once(|mut commands: Commands| commands.spawn_with(Foo).id())
        };
        app.update();
        let world = app.world;
        assert!(world.entity(entity).contains::<Foo>());
    }

    #[test]
    fn spawn_with_key() {
        let mut app = app();
        app.register_spawnable(FOO, Foo);
        let world = &mut app.world;
        let entity = world.spawn_with_key(FOO).id();
        assert!(world.entity(entity).contains::<Foo>());
    }

    #[test]
    fn spawn_with_key_deferred() {
        let mut app = app();
        app.register_spawnable(FOO, Foo);
        let entity = {
            let world = &mut app.world;
            world.run_system_once(|mut commands: Commands| commands.spawn_with_key(FOO).id())
        };
        app.update();
        let world = app.world;
        assert!(world.entity(entity).contains::<Foo>());
    }

    #[test]
    fn spawn_bundle_with_children() {
        let mut app = app();
        let world = &mut app.world;
        let entity = world
            .spawn_with(Foo.with_children(|foo| {
                foo.spawn(Bar);
            }))
            .id();
        let children = world.entity(entity).get::<Children>().unwrap();
        let child = children.iter().copied().next().unwrap();
        assert!(world.entity(child).contains::<Bar>());
    }

    #[test]
    fn spawn_bundle_with_children_deferred() {
        let mut app = app();
        let entity = {
            let world = &mut app.world;
            world.run_system_once(|mut commands: Commands| {
                commands
                    .spawn_with(Foo.with_children(|foo| {
                        foo.spawn(Bar);
                    }))
                    .id()
            })
        };
        app.update();
        let world = app.world;
        let children = world.entity(entity).get::<Children>().unwrap();
        let child = children.iter().copied().next().unwrap();
        assert!(world.entity(child).contains::<Bar>());
    }

    #[test]
    fn spawn_bundle_with_children_with_key() {
        let mut app = app();
        app.register_spawnable(BAR, Bar);
        let world = &mut app.world;
        let entity = world
            .spawn_with(Foo.with_children(|foo| {
                foo.spawn_with_key(BAR);
            }))
            .id();
        let children = world.entity(entity).get::<Children>().unwrap();
        let child = children.iter().copied().next().unwrap();
        assert!(world.entity(child).contains::<Bar>());
    }

    #[test]
    fn spawn_bundle_with_children_with_key_deferred() {
        let mut app = app();
        app.register_spawnable(BAR, Bar);
        let entity = {
            let world = &mut app.world;
            world.run_system_once(|mut commands: Commands| {
                commands
                    .spawn_with(Foo.with_children(|foo| {
                        foo.spawn_with_key(BAR);
                    }))
                    .id()
            })
        };
        app.update();
        let world = app.world;
        let children = world.entity(entity).get::<Children>().unwrap();
        let child = children.iter().copied().next().unwrap();
        assert!(world.entity(child).contains::<Bar>());
    }
}