moonshine-save 0.6.1

Save/Load framework for Bevy
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
use std::any::TypeId;
use std::io::{self, Write};
use std::marker::PhantomData;
use std::path::PathBuf;

use bevy_ecs::entity::EntityHashSet;
use bevy_ecs::prelude::*;
use bevy_ecs::query::QueryFilter;
use bevy_log::prelude::*;
use bevy_scene::{DynamicScene, DynamicSceneBuilder, SceneFilter};

use moonshine_util::event::{OnSingle, SingleEvent, TriggerSingle};
use moonshine_util::Static;
use thiserror::Error;

use crate::{MapComponent, SceneMapper};

/// A [`Component`] which marks its [`Entity`] to be saved.
#[derive(Component, Default, Debug, Clone)]
pub struct Save;

/// A trait used to trigger a [`SaveEvent`] via [`Commands`] or [`World`].
pub trait TriggerSave {
    /// Triggers the given [`SaveEvent`].
    #[doc(alias = "trigger_single")]
    fn trigger_save(self, event: impl SaveEvent);
}

impl TriggerSave for &mut Commands<'_, '_> {
    fn trigger_save(self, event: impl SaveEvent) {
        self.trigger_single(event);
    }
}

impl TriggerSave for &mut World {
    fn trigger_save(self, event: impl SaveEvent) {
        self.trigger_single(event);
    }
}

/// A [`SingleEvent`] which starts the save process with the given parameters.
///
/// See also:
/// - [`trigger_save`](TriggerSave::trigger_save)
/// - [`trigger_single`](TriggerSingle::trigger_single)
/// - [`SaveWorld`]
pub trait SaveEvent: SingleEvent {
    /// A [`QueryFilter`] used as the initial filter for selecting saved entities.
    type SaveFilter: QueryFilter;

    /// Return `true` if the given [`Entity`] should be saved.
    fn filter_entity(&self, _entity: EntityRef) -> bool {
        true
    }

    /// Called once before the save process starts.
    ///
    /// This is useful if you want to modify the world just before saving.
    fn before_save(&mut self, _world: &mut World) {}

    /// Called once before serialization.
    ///
    /// This is useful to undo any modifications done before saving.
    fn before_serialize(&mut self, _world: &mut World, _entities: &[Entity]) {}

    /// Returns a [`SceneFilter`] for selecting which components should be saved.
    fn component_filter(&mut self) -> SceneFilter {
        SceneFilter::allow_all()
    }

    /// Returns a [`SceneFilter`] for selecting which resources should be saved.
    fn resource_filter(&mut self) -> SceneFilter {
        SceneFilter::deny_all()
    }

    /// Called once after serialization.
    ///
    /// This is useful if you would like to do any post-processing of the [`Saved`] data *before* [`OnSave`] is triggered.
    fn after_save(&mut self, _world: &mut World, _result: &SaveResult) {}

    /// Returns the [`SaveOutput`] of the save process.
    fn output(&mut self) -> SaveOutput;
}

/// A generic [`SaveEvent`] which can be used to save the [`World`].
pub struct SaveWorld<F: QueryFilter = DefaultSaveFilter> {
    /// A filter for selecting which entities should be saved.
    ///
    /// By default, all entities are selected.
    pub entities: EntityFilter,
    /// A filter for selecting which resources should be saved.
    ///
    /// By default, no resources are selected. Most Bevy resources are not safely serializable.
    pub resources: SceneFilter,
    /// A filter for selecting which components should be saved.
    ///
    /// By default, all serializable components are selected.
    pub components: SceneFilter,
    /// A mapper for transforming components during the save process.
    ///
    /// See [`MapComponent`] for more information.
    pub mapper: SceneMapper,
    /// Output of the saved world.
    pub output: SaveOutput,
    #[doc(hidden)]
    pub filter: PhantomData<F>,
}

impl<F: QueryFilter> SaveWorld<F> {
    /// Creates a new [`SaveWorld`] event with the given [`SaveOutput`].
    pub fn new(output: SaveOutput) -> Self {
        Self {
            entities: EntityFilter::allow_all(),
            resources: SceneFilter::deny_all(),
            components: SceneFilter::allow_all(),
            mapper: SceneMapper::default(),
            output,
            filter: PhantomData,
        }
    }

    /// Creates a new [`SaveWorld`] event which saves entities matching the
    /// given [`QueryFilter`] into a file at the given path.
    pub fn into_file(path: impl Into<PathBuf>) -> Self {
        Self {
            entities: EntityFilter::allow_all(),
            resources: SceneFilter::deny_all(),
            components: SceneFilter::allow_all(),
            mapper: SceneMapper::default(),
            output: SaveOutput::file(path),
            filter: PhantomData,
        }
    }

    /// Creates a new [`SaveWorld`] event which saves entities matching the
    /// given [`QueryFilter`] into a [`Write`] stream.
    pub fn into_stream(stream: impl SaveStream) -> Self {
        Self {
            entities: EntityFilter::allow_all(),
            resources: SceneFilter::deny_all(),
            components: SceneFilter::allow_all(),
            mapper: SceneMapper::default(),
            output: SaveOutput::stream(stream),
            filter: PhantomData,
        }
    }

    /// Includes the given [`Resource`] in the save data.
    pub fn include_resource<R: Resource>(mut self) -> Self {
        self.resources = self.resources.allow::<R>();
        self
    }

    /// Includes the given [`Resource`] by its [`TypeId`] in the save data.
    pub fn include_resource_by_id(mut self, type_id: TypeId) -> Self {
        self.resources = self.resources.allow_by_id(type_id);
        self
    }

    /// Excludes the given [`Component`] from the save data.
    pub fn exclude_component<T: Component>(mut self) -> Self {
        self.components = self.components.deny::<T>();
        self
    }

    /// Excludes the given [`Component`] by its [`TypeId`] from the save data.
    pub fn exclude_component_by_id(mut self, type_id: TypeId) -> Self {
        self.components = self.components.deny_by_id(type_id);
        self
    }

    /// Maps the given [`Component`] into another using a [component mapper](MapComponent) before saving.
    pub fn map_component<T: Component>(mut self, m: impl MapComponent<T>) -> Self {
        self.mapper = self.mapper.map(m);
        self
    }
}

impl SaveWorld {
    /// Creates a new [`SaveWorld`] event which saves default entities (with [`Save`])
    /// into a file at the given path.
    pub fn default_into_file(path: impl Into<PathBuf>) -> Self {
        Self::into_file(path)
    }

    /// Creates a new [`SaveWorld`] event which saves default entities (with [`Save`])
    /// into a [`Write`] stream.
    pub fn default_into_stream(stream: impl SaveStream) -> Self {
        Self::into_stream(stream)
    }
}

impl SaveWorld<()> {
    /// Creates a new [`SaveWorld`] event which saves all entities into a file at the given path.
    pub fn all_into_file(path: impl Into<PathBuf>) -> Self {
        Self::into_file(path)
    }

    /// Creates a new [`SaveWorld`] event which saves all entities into a [`Write`] stream.
    pub fn all_into_stream(stream: impl SaveStream) -> Self {
        Self::into_stream(stream)
    }
}

impl<F: QueryFilter> SingleEvent for SaveWorld<F> where F: Static {}

impl<F: QueryFilter> SaveEvent for SaveWorld<F>
where
    F: Static,
{
    type SaveFilter = F;

    fn filter_entity(&self, entity: EntityRef) -> bool {
        match &self.entities {
            EntityFilter::Allow(allow) => allow.contains(&entity.id()),
            EntityFilter::Block(block) => !block.contains(&entity.id()),
        }
    }

    fn before_serialize(&mut self, world: &mut World, entities: &[Entity]) {
        for entity in entities {
            self.mapper.apply(world.entity_mut(*entity));
        }
    }

    fn after_save(&mut self, world: &mut World, result: &SaveResult) {
        let Ok(saved) = result else {
            return;
        };

        for entity in saved.entities() {
            self.mapper.undo(world.entity_mut(entity));
        }
    }

    fn component_filter(&mut self) -> SceneFilter {
        std::mem::replace(&mut self.components, SceneFilter::Unset)
    }

    fn resource_filter(&mut self) -> SceneFilter {
        std::mem::replace(&mut self.resources, SceneFilter::Unset)
    }

    fn output(&mut self) -> SaveOutput {
        self.output.consume().unwrap()
    }
}

/// Filter used for the default [`SaveWorld`] event.
/// This includes all entities with the [`Save`] component.
pub type DefaultSaveFilter = With<Save>;

/// Output of the save process.
pub enum SaveOutput {
    /// Save into a file at the given path.
    File(PathBuf),
    /// Save into a [`Write`] stream.
    Stream(Box<dyn SaveStream>),
    /// Drops the save data.
    ///
    /// This is useful if you would like to process the [`Saved`] data manually.
    /// You can observe the [`OnSave`] event for post-processing logic.
    Drop,
    #[doc(hidden)]
    Invalid,
}

impl SaveOutput {
    /// Creates a new [`SaveOutput`] which saves into a file at the given path.
    pub fn file(path: impl Into<PathBuf>) -> Self {
        Self::File(path.into())
    }

    /// Creates a new [`SaveOutput`] which saves into a [`Write`] stream.
    pub fn stream<S: SaveStream + 'static>(stream: S) -> Self {
        Self::Stream(Box::new(stream))
    }

    /// Invalidates this [`SaveOutput`] and returns it if it was valid.
    pub fn consume(&mut self) -> Option<SaveOutput> {
        let output = std::mem::replace(self, SaveOutput::Invalid);
        if let SaveOutput::Invalid = output {
            return None;
        }
        Some(output)
    }
}

/// A filter for selecting which [`Entity`]s within a [`World`].
#[derive(Clone, Debug)]
pub enum EntityFilter {
    /// Select only the specified entities.
    Allow(EntityHashSet),
    /// Select all entities except the specified ones.
    Block(EntityHashSet),
}

impl EntityFilter {
    /// Creates a new [`EntityFilter`] which allows all entities.
    pub fn allow_all() -> Self {
        Self::Block(EntityHashSet::new())
    }

    /// Creates a new [`EntityFilter`] which allows only the specified entities.
    pub fn allow(entities: impl IntoIterator<Item = Entity>) -> Self {
        Self::Allow(entities.into_iter().collect())
    }

    /// Creates a new [`EntityFilter`] which blocks the specified entities.
    pub fn block(entities: impl IntoIterator<Item = Entity>) -> Self {
        Self::Block(entities.into_iter().collect())
    }
}

impl Default for EntityFilter {
    fn default() -> Self {
        Self::allow_all()
    }
}

/// Alias for a `'static` [`Write`] stream.
pub trait SaveStream: Write
where
    Self: Static,
{
}

impl<S: Write> SaveStream for S where S: Static {}

/// An [`Event`] triggered at the end of the save process.
///
/// This event contains the saved [`World`] data as a [`DynamicScene`].
#[derive(Event)]
pub struct Saved {
    /// The saved [`DynamicScene`] to be serialized.
    pub scene: DynamicScene,
}

impl Saved {
    /// Iterates over all the saved entities.
    pub fn entities(&self) -> impl Iterator<Item = Entity> + '_ {
        self.scene.entities.iter().map(|de| de.entity)
    }
}

#[doc(hidden)]
#[deprecated(since = "0.5.2", note = "use `Saved` instead")]
pub type OnSave = Saved;

/// An error that may occur during the save process.
#[derive(Error, Debug)]
pub enum SaveError {
    /// An error occurred while serializing the scene.
    #[error("Failed to serialize world: {0}")]
    Ron(ron::Error),
    /// An error occurred while writing into [`SaveOutput`].
    #[error("Failed to write world: {0}")]
    Io(io::Error),
}

impl From<ron::Error> for SaveError {
    fn from(e: ron::Error) -> Self {
        Self::Ron(e)
    }
}

impl From<io::Error> for SaveError {
    fn from(e: io::Error) -> Self {
        Self::Io(e)
    }
}

/// [`Result`] of a [`SaveEvent`].
pub type SaveResult = Result<Saved, SaveError>;

/// An [`Observer`] which saved the world when a [`SaveWorld`] event is triggered.
pub fn save_on_default_event(event: OnSingle<SaveWorld>, commands: Commands) {
    save_on(event, commands);
}

/// An [`Observer`] which saved the world when the given [`SaveEvent`] is triggered.
pub fn save_on<E: SaveEvent>(event: OnSingle<E>, mut commands: Commands) {
    commands.queue_handled(SaveCommand(event.consume().unwrap()), |err, ctx| {
        error!("save failed: {err:?} ({ctx})");
    });
}

fn save_world<E: SaveEvent>(mut event: E, world: &mut World) -> SaveResult {
    // Notify
    event.before_save(world);

    // Filter
    let entities: Vec<_> = world
        .query_filtered::<Entity, E::SaveFilter>()
        .iter(world)
        .filter(|entity| event.filter_entity(world.entity(*entity)))
        .collect();

    // Serialize
    event.before_serialize(world, &entities);
    let scene = DynamicSceneBuilder::from_world(world)
        .with_component_filter(event.component_filter())
        .with_resource_filter(event.resource_filter())
        .extract_resources()
        .extract_entities(entities.iter().copied())
        .build();

    // Write
    let saved = match event.output() {
        SaveOutput::File(path) => {
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)?;
            }

            let type_registry = world.resource::<AppTypeRegistry>().read();
            let data = scene.serialize(&type_registry)?;
            std::fs::write(&path, data.as_bytes())?;
            debug!("saved into file: {path:?}");
            Saved { scene }
        }
        SaveOutput::Stream(mut stream) => {
            let type_registry = world.resource::<AppTypeRegistry>().read();
            let data = scene.serialize(&type_registry)?;
            stream.write_all(data.as_bytes())?;
            debug!("saved into stream");
            Saved { scene }
        }
        SaveOutput::Drop => {
            debug!("saved data dropped");
            Saved { scene }
        }
        SaveOutput::Invalid => {
            panic!("SaveOutput is invalid");
        }
    };

    let result = Ok(saved);
    event.after_save(world, &result);
    result
}

struct SaveCommand<E>(E);

impl<E: SaveEvent> Command<Result<(), SaveError>> for SaveCommand<E> {
    fn apply(self, world: &mut World) -> Result<(), SaveError> {
        let saved = save_world(self.0, world)?;
        world.trigger(saved);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::fs::*;

    use bevy::prelude::*;
    use bevy_ecs::system::RunSystemOnce;

    use super::*;

    #[derive(Component, Default, Reflect)]
    #[reflect(Component)]
    #[require(Save)]
    struct Foo;

    fn app() -> App {
        let mut app = App::new();
        app.add_plugins(MinimalPlugins).register_type::<Foo>();
        app
    }

    #[test]
    fn test_save_into_file() {
        #[derive(Resource)]
        struct EventTriggered;

        pub const PATH: &str = "test_save_into_file.ron";
        let mut app = app();
        app.add_observer(save_on_default_event);

        app.add_observer(|_: On<Saved>, mut commands: Commands| {
            commands.insert_resource(EventTriggered);
        });

        let _ = app.world_mut().run_system_once(|mut commands: Commands| {
            commands.spawn((Foo, Save));
            commands.trigger_save(SaveWorld::default_into_file(PATH));
        });

        let data = read_to_string(PATH).unwrap();
        let world = app.world();
        assert!(data.contains("Foo"));
        assert!(world.contains_resource::<EventTriggered>());

        remove_file(PATH).unwrap();
    }

    #[test]
    fn test_save_into_stream() {
        pub const PATH: &str = "test_save_to_stream.ron";

        let mut app = app();
        app.add_observer(save_on_default_event);

        let _ = app.world_mut().run_system_once(|mut commands: Commands| {
            commands.spawn((Foo, Save));
            commands.trigger_save(SaveWorld::default_into_stream(File::create(PATH).unwrap()));
        });

        let data = read_to_string(PATH).unwrap();
        assert!(data.contains("Foo"));

        remove_file(PATH).unwrap();
    }

    #[test]
    fn test_save_resource() {
        pub const PATH: &str = "test_save_resource.ron";

        #[derive(Resource, Default, Reflect)]
        #[reflect(Resource)]
        struct Bar;

        let mut app = app();
        app.register_type::<Bar>()
            .add_observer(save_on_default_event);

        let _ = app.world_mut().run_system_once(|mut commands: Commands| {
            commands.insert_resource(Bar);
            commands.trigger_save(
                SaveWorld::default_into_stream(File::create(PATH).unwrap())
                    .include_resource::<Bar>(),
            );
        });

        app.update();

        let data = read_to_string(PATH).unwrap();
        assert!(data.contains("Bar"));

        remove_file(PATH).unwrap();
    }

    #[test]
    fn test_save_without_component() {
        pub const PATH: &str = "test_save_without_component.ron";

        #[derive(Component, Default, Reflect)]
        #[reflect(Component)]
        #[require(Save)]
        struct Baz;

        let mut app = app();
        app.add_observer(save_on_default_event);

        let _ = app.world_mut().run_system_once(|mut commands: Commands| {
            commands.spawn((Foo, Baz, Save));
            commands.trigger_save(SaveWorld::default_into_file(PATH).exclude_component::<Baz>());
        });

        let data = read_to_string(PATH).unwrap();
        assert!(data.contains("Foo"));
        assert!(!data.contains("Baz"));

        remove_file(PATH).unwrap();
    }

    #[test]
    fn test_map_component() {
        pub const PATH: &str = "test_map_component.ron";

        #[derive(Component, Default)]
        struct Bar(#[allow(dead_code)] u32); // Not serializable

        #[derive(Component, Default, Reflect)]
        #[reflect(Component)]
        struct Baz(u32); // Serializable

        let mut app = app();
        app.register_type::<Baz>()
            .add_observer(save_on_default_event);

        let entity = app
            .world_mut()
            .run_system_once(|mut commands: Commands| {
                let entity = commands.spawn((Bar(12), Save)).id();
                commands.trigger_save(
                    SaveWorld::default_into_file(PATH).map_component::<Bar>(|Bar(i): &Bar| Baz(*i)),
                );
                entity
            })
            .unwrap();

        let data = read_to_string(PATH).unwrap();
        assert!(data.contains("Baz"));
        assert!(data.contains("(12)"));
        assert!(!data.contains("Bar"));
        assert!(app.world().entity(entity).contains::<Bar>());
        assert!(!app.world().entity(entity).contains::<Baz>());

        remove_file(PATH).unwrap();
    }
}