Skip to main content

azalea_world/
container.rs

1use std::{
2    collections::HashMap,
3    fmt::{self, Display},
4    sync::{Arc, Weak},
5};
6
7use azalea_core::identifier::Identifier;
8use azalea_registry::registry_holder::RegistryHolder;
9use bevy_ecs::{component::Component, resource::Resource};
10use derive_more::{Deref, DerefMut};
11use nohash_hasher::IntMap;
12use parking_lot::RwLock;
13use rustc_hash::FxHashMap;
14use tracing::{debug, error};
15
16use crate::{ChunkStorage, World};
17
18/// A container of [`World`] instances.
19///
20/// Worlds are stored as a `Weak` pointer here, so if no clients are using a
21/// world then it will be forgotten.
22#[derive(Default, Resource)]
23pub struct Worlds {
24    // We just refer to the chunks here and don't include entities because
25    // there's not that many cases where we'd want to get every entity in the
26    // world (just getting the entities in chunks should work fine).
27
28    // Entities are garbage collected (by manual reference counting in
29    // EntityUuidIndex) so we don't need to worry about them here.
30
31    // If it looks like we're relying on the server giving us unique world
32    // names, that's because we are. An evil server could give us two worlds
33    // with the same name and then we'd have no way of telling them apart. We
34    // hope most servers are nice and don't do that. Perhaps this should be
35    // changed in the future to be configurable.
36    pub map: FxHashMap<WorldName, Weak<RwLock<World>>>,
37}
38
39impl Worlds {
40    pub fn new() -> Self {
41        Worlds::default()
42    }
43
44    /// Get a world instance from the container.
45    ///
46    /// Returns `None` if none of the clients are in the requested world.
47    pub fn get(&self, name: &WorldName) -> Option<Arc<RwLock<World>>> {
48        self.map.get(name).and_then(|world| world.upgrade())
49    }
50
51    /// Add an empty world to the container (unless it already exists) and
52    /// returns a strong reference to the world.
53    #[must_use = "the world will be immediately forgotten if unused"]
54    pub fn get_or_insert(
55        &mut self,
56        name: WorldName,
57        height: u32,
58        min_y: i32,
59        default_registries: &RegistryHolder,
60    ) -> Arc<RwLock<World>> {
61        match self.map.get(&name).and_then(|world| world.upgrade()) {
62            Some(existing_lock) => {
63                let existing = existing_lock.read();
64                if existing.chunks.height() != height {
65                    error!(
66                        "Shared world height mismatch: {} != {height}",
67                        existing.chunks.height()
68                    );
69                }
70                if existing.chunks.min_y() != min_y {
71                    error!(
72                        "Shared world min_y mismatch: {} != {min_y}",
73                        existing.chunks.min_y()
74                    );
75                }
76                existing_lock.clone()
77            }
78            _ => {
79                let world = Arc::new(RwLock::new(World {
80                    chunks: ChunkStorage::new(height, min_y),
81                    entities_by_chunk: HashMap::new(),
82                    entity_by_id: IntMap::default(),
83                    registries: default_registries.clone(),
84                }));
85                debug!("Added new world {name:?}");
86                self.map.insert(name, Arc::downgrade(&world));
87                world
88            }
89        }
90    }
91}
92
93/// The name of the [`World`] (aka dimension) that an entity is in.
94///
95/// If two entities share the same world name, then Azalea assumes that they're
96/// in the same world.
97#[derive(Clone, Component, Debug, Deref, DerefMut, Eq, Hash, PartialEq)]
98#[doc(alias("dimension"))]
99pub struct WorldName(pub Identifier);
100impl WorldName {
101    /// Create a new `WorldName` with the given name.
102    pub fn new(name: &str) -> Self {
103        Self(Identifier::new(name))
104    }
105}
106impl Display for WorldName {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        self.0.fmt(f)
109    }
110}
111impl From<Identifier> for WorldName {
112    fn from(ident: Identifier) -> Self {
113        Self(ident)
114    }
115}