azalea_world/
container.rs1use 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#[derive(Default, Resource)]
23pub struct Worlds {
24 pub map: FxHashMap<WorldName, Weak<RwLock<World>>>,
37}
38
39impl Worlds {
40 pub fn new() -> Self {
41 Worlds::default()
42 }
43
44 pub fn get(&self, name: &WorldName) -> Option<Arc<RwLock<World>>> {
48 self.map.get(name).and_then(|world| world.upgrade())
49 }
50
51 #[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#[derive(Clone, Component, Debug, Deref, DerefMut, Eq, Hash, PartialEq)]
98#[doc(alias("dimension"))]
99pub struct WorldName(pub Identifier);
100impl WorldName {
101 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}