Skip to main content

yog_api/
storage.rs

1//! Where the mod keeps its data — typed values in stores scoped the way web
2//! storage is (`yog-storage`), opened for this mod in the right folder:
3//!
4//! ```ignore
5//! use yog_api::storage;
6//!
7//! storage::game().set("theme", &theme);              // the install, whatever world
8//! if let Some(world) = storage::world() {            // this world, saved with it
9//!     world.update("visits", |n: &mut u32| *n += 1);
10//! }
11//! storage::session().set("last_screen", &screen);    // while the game runs
12//! ```
13//!
14//! Or a value kept for the mod, loaded when first used and saved with the
15//! world ([`WorldData`], [`PlayerData`], [`GameData`]):
16//!
17//! ```ignore
18//! static LABELS: WorldData<Vec<Label>> = WorldData::new("labels");
19//! LABELS.with_mut(|labels| labels.push(label));
20//! ```
21//!
22//! What's kept with the world is written as the world is saved
23//! (`server::life::Saving`: an autosave, `/save-all`, the server stopping),
24//! so it's saved with the world it belongs to.
25
26mod kept;
27
28use std::path::PathBuf;
29
30use yog_sync::Mutex;
31use yog_sync::atomic::{AtomicBool, Ordering};
32
33pub use kept::{GameData, PlayerData, WorldData};
34pub use yog_storage::{Scope, Store, close_under, flush_all};
35
36use crate::Registry;
37use crate::event::server::life::{Saving, Started, Stopping};
38
39/// The open world's folder (none on a client of another's server, or at the title screen).
40static WORLD: Mutex<Option<PathBuf>> = Mutex::new(None);
41/// The server is stopping: the next save is the world's last.
42static CLOSING: AtomicBool = AtomicBool::new(false);
43
44/// This mod's session store: kept while the game runs, never written.
45pub fn session() -> Store {
46    Store::session(crate::mod_id())
47}
48
49/// This mod's store for the install, whatever world.
50pub fn game() -> Store {
51    Store::open(&game_dir(), crate::mod_id(), Scope::Game)
52}
53
54/// This mod's store for the open world.
55pub fn world() -> Option<Store> {
56    in_world(Scope::World)
57}
58
59/// This mod's store for dimension `dim` of the open world.
60pub fn dimension(dim: &str) -> Option<Store> {
61    in_world(Scope::Dimension(dim))
62}
63
64/// This mod's store for player `uuid` in the open world.
65pub fn player(uuid: &str) -> Option<Store> {
66    in_world(Scope::Player(uuid))
67}
68
69/// This mod's store for entity `uuid` in the open world.
70pub fn entity(uuid: &str) -> Option<Store> {
71    in_world(Scope::Entity(uuid))
72}
73
74/// This mod's store for chunk `cx`, `cz` of dimension `dim` in the open world.
75pub fn chunk(dim: &str, cx: i32, cz: i32) -> Option<Store> {
76    in_world(Scope::Chunk(dim, cx, cz))
77}
78
79fn in_world(scope: Scope<'_>) -> Option<Store> {
80    let root = WORLD.lock().clone()?;
81    Some(Store::open(&root, crate::mod_id(), scope))
82}
83
84/// The game's folder (the working folder when the host can't say).
85fn game_dir() -> PathBuf {
86    crate::game::dir().map(PathBuf::from).unwrap_or_default()
87}
88
89/// The world's folder known as it starts — registered by `export_mod!`
90/// before the mod's own handlers, so theirs find its stores.
91#[doc(hidden)]
92pub fn __know_world(registry: &mut Registry) {
93    registry.on::<Started, _>(|e, _| {
94        *WORLD.lock() = Some(PathBuf::from(&e.world_dir));
95    });
96}
97
98/// What's kept saved with the world — registered by `export_mod!` after
99/// the mod's own handlers, so what theirs put in the stores is written.
100#[doc(hidden)]
101pub fn __save_with_world(registry: &mut Registry) {
102    registry.on::<Stopping, _>(|_, _| CLOSING.store(true, Ordering::Release));
103    registry.on::<Saving, _>(|_, _| saving());
104}
105
106/// The world being saved: what's kept written; the world's last save closes it.
107fn saving() {
108    kept::keep_all();
109    if let Err(e) = flush_all() {
110        crate::error!("[{}] couldn't save its data: {e}", crate::mod_id());
111    }
112    if !CLOSING.swap(false, Ordering::AcqRel) {
113        return;
114    }
115    kept::forget_world();
116    if let Some(root) = WORLD.lock().take()
117        && let Err(e) = close_under(&root)
118    {
119        crate::error!("[{}] couldn't save its data: {e}", crate::mod_id());
120    }
121}
122
123#[cfg(test)]
124mod tests;