forked from feather-rs/feather
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworld.rs
More file actions
239 lines (206 loc) · 7.34 KB
/
Copy pathworld.rs
File metadata and controls
239 lines (206 loc) · 7.34 KB
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
use ahash::{AHashMap, AHashSet};
use base::{BlockPosition, Chunk, ChunkPosition, CHUNK_HEIGHT};
use blocks::BlockId;
use ecs::Ecs;
use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::sync::Arc;
use crate::{
events::ChunkLoadEvent,
world_source::{null::NullWorldSource, ChunkLoadResult, WorldSource},
};
/// Stores all blocks and chunks in a world,
/// along with global world data like weather, time,
/// and the [`WorldSource`](crate::world_source::WorldSource).
///
/// NB: _not_ what most Rust ECSs call "world."
/// This does not store entities; it only contains blocks.
pub struct World {
chunk_map: ChunkMap,
world_source: Box<dyn WorldSource>,
loading_chunks: AHashSet<ChunkPosition>,
canceled_chunk_loads: AHashSet<ChunkPosition>,
}
impl Default for World {
fn default() -> Self {
Self {
chunk_map: ChunkMap::new(),
world_source: Box::new(NullWorldSource::default()),
loading_chunks: AHashSet::new(),
canceled_chunk_loads: AHashSet::new(),
}
}
}
impl World {
pub fn new() -> Self {
Self::default()
}
/// Creates a `World` from a `WorldSource` for loading chunks.
pub fn with_source(world_source: impl WorldSource + 'static) -> Self {
Self {
world_source: Box::new(world_source),
..Default::default()
}
}
/// Queues the given chunk to be loaded.
pub fn queue_chunk_load(&mut self, pos: ChunkPosition) {
self.loading_chunks.insert(pos);
self.world_source.queue_load(pos);
}
/// Loads any chunks that have been loaded asynchronously
/// after a call to [`queue_chunk_load`].
pub fn load_chunks(&mut self, ecs: &mut Ecs) {
while let Some(loaded) = self.world_source.poll_loaded_chunk() {
self.loading_chunks.remove(&loaded.pos);
if self.canceled_chunk_loads.remove(&loaded.pos) {
continue;
}
let chunk = match loaded.result {
ChunkLoadResult::Missing => {
log::debug!(
"Chunk {:?} is missing; using default empty chunk",
loaded.pos
);
Chunk::new(loaded.pos)
}
ChunkLoadResult::Error(e) => {
log::error!("Failed to load chunk {:?}: {:?}", loaded.pos, e);
continue;
}
ChunkLoadResult::Loaded { chunk } => chunk,
};
self.chunk_map.insert_chunk(chunk);
ecs.insert_event(ChunkLoadEvent {
chunk: Arc::clone(&self.chunk_map.0[&loaded.pos]),
position: loaded.pos,
});
log::trace!("Loaded chunk {:?}", loaded.pos);
}
}
/// Unloads the given chunk.
pub fn unload_chunk(&mut self, pos: ChunkPosition) {
self.chunk_map.remove_chunk(pos);
if self.is_chunk_loading(pos) {
self.canceled_chunk_loads.insert(pos);
}
log::trace!("Unloaded chunk {:?}", pos);
}
/// Returns whether the given chunk is loaded.
pub fn is_chunk_loaded(&self, pos: ChunkPosition) -> bool {
self.chunk_map.0.contains_key(&pos)
}
/// Returns whether the given chunk is queued to be loaded.
pub fn is_chunk_loading(&self, pos: ChunkPosition) -> bool {
self.loading_chunks.contains(&pos)
}
/// Sets the block at the given position.
///
/// Returns `true` if the block was set, or `false`
/// if its chunk was not loaded or the coordinates
/// are out of bounds and thus no operation
/// was performed.
pub fn set_block_at(&self, pos: BlockPosition, block: BlockId) -> bool {
self.chunk_map.set_block_at(pos, block)
}
/// Retrieves the block at the specified
/// location. If the chunk in which the block
/// exists is not loaded or the coordinates
/// are out of bounds, `None` is returned.
pub fn block_at(&self, pos: BlockPosition) -> Option<BlockId> {
self.chunk_map.block_at(pos)
}
/// Returns the chunk map.
pub fn chunk_map(&self) -> &ChunkMap {
&self.chunk_map
}
/// Mutably gets the chunk map.
pub fn chunk_map_mut(&mut self) -> &mut ChunkMap {
&mut self.chunk_map
}
}
pub type ChunkMapInner = AHashMap<ChunkPosition, Arc<RwLock<Chunk>>>;
/// This struct stores all the chunks on the server,
/// so it allows access to blocks and lighting data.
///
/// Chunks are internally wrapped in `Arc<RwLock>`,
/// allowing multiple systems to access different parts
/// of the world in parallel. Mutable access to this
/// type is only required for inserting and removing
/// chunks.
#[derive(Default)]
pub struct ChunkMap(ChunkMapInner);
impl ChunkMap {
/// Creates a new, empty world.
pub fn new() -> Self {
Self::default()
}
/// Retrieves a handle to the chunk at the given
/// position, or `None` if it is not loaded.
pub fn chunk_at(&self, pos: ChunkPosition) -> Option<RwLockReadGuard<Chunk>> {
self.0.get(&pos).map(|lock| lock.read())
}
/// Retrieves a handle to the chunk at the given
/// position, or `None` if it is not loaded.
pub fn chunk_at_mut(&self, pos: ChunkPosition) -> Option<RwLockWriteGuard<Chunk>> {
self.0.get(&pos).map(|lock| lock.write())
}
/// Returns an `Arc<RwLock<Chunk>>` at the given position.
pub fn chunk_handle_at(&self, pos: ChunkPosition) -> Option<Arc<RwLock<Chunk>>> {
self.0.get(&pos).map(Arc::clone)
}
pub fn block_at(&self, pos: BlockPosition) -> Option<BlockId> {
check_coords(pos)?;
let (x, y, z) = chunk_relative_pos(pos);
self.chunk_at(pos.into())
.map(|chunk| chunk.block_at(x, y, z))
.flatten()
}
pub fn set_block_at(&self, pos: BlockPosition, block: BlockId) -> bool {
if check_coords(pos).is_none() {
return false;
}
let (x, y, z) = chunk_relative_pos(pos);
self.chunk_at_mut(pos.into())
.map(|mut chunk| chunk.set_block_at(x, y, z, block))
.is_some()
}
/// Returns an iterator over chunks.
pub fn iter_chunks(&self) -> impl IntoIterator<Item = &Arc<RwLock<Chunk>>> {
self.0.values()
}
/// Inserts a new chunk into the chunk map.
pub fn insert_chunk(&mut self, chunk: Chunk) {
self.0
.insert(chunk.position(), Arc::new(RwLock::new(chunk)));
}
/// Removes the chunk at the given position, returning `true` if it existed.
pub fn remove_chunk(&mut self, pos: ChunkPosition) -> bool {
self.0.remove(&pos).is_some()
}
}
fn check_coords(pos: BlockPosition) -> Option<()> {
if pos.y >= 0 && pos.y < CHUNK_HEIGHT as i32 {
Some(())
} else {
None
}
}
fn chunk_relative_pos(block_pos: BlockPosition) -> (usize, usize, usize) {
(
block_pos.x as usize & 0xf,
block_pos.y as usize,
block_pos.z as usize & 0xf,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn world_out_of_bounds() {
let mut world = World::new();
world
.chunk_map_mut()
.insert_chunk(Chunk::new(ChunkPosition::new(0, 0)));
assert!(world.block_at(BlockPosition::new(0, -1, 0)).is_none());
assert!(world.block_at(BlockPosition::new(0, 0, 0)).is_some());
}
}