-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathworld.rs
More file actions
283 lines (243 loc) · 8.59 KB
/
world.rs
File metadata and controls
283 lines (243 loc) · 8.59 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
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
use std::{path::PathBuf, sync::Arc};
use ahash::{AHashMap, AHashSet};
use parking_lot::{RwLockReadGuard, RwLockWriteGuard};
use uuid::Uuid;
use base::anvil::player::PlayerData;
use base::{
BlockPosition, Chunk, ChunkHandle, ChunkLock, ChunkPosition, ValidBlockPosition, CHUNK_HEIGHT,
};
use blocks::BlockId;
use ecs::{Ecs, SysResult};
use worldgen::{ComposableGenerator, WorldGenerator};
use crate::{
chunk::cache::ChunkCache,
chunk::worker::{ChunkWorker, LoadRequest, SaveRequest},
events::ChunkLoadEvent,
};
/// 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,
pub cache: ChunkCache,
chunk_worker: ChunkWorker,
loading_chunks: AHashSet<ChunkPosition>,
canceled_chunk_loads: AHashSet<ChunkPosition>,
world_dir: PathBuf,
}
impl Default for World {
fn default() -> Self {
Self {
chunk_map: ChunkMap::new(),
chunk_worker: ChunkWorker::new(
"world",
Arc::new(ComposableGenerator::default_with_seed(0)),
),
cache: ChunkCache::new(),
loading_chunks: AHashSet::new(),
canceled_chunk_loads: AHashSet::new(),
world_dir: "world".into(),
}
}
}
impl World {
pub fn new() -> Self {
Self::default()
}
pub fn with_gen_and_path(
generator: Arc<dyn WorldGenerator>,
world_dir: impl Into<PathBuf> + Clone,
) -> Self {
Self {
world_dir: world_dir.clone().into(),
chunk_worker: ChunkWorker::new(world_dir, generator),
..Default::default()
}
}
/// Queues the given chunk to be loaded. If the chunk was cached, it is loaded immediately.
pub fn queue_chunk_load(&mut self, req: LoadRequest) {
let pos = req.pos;
if self.cache.contains(&pos) {
// Move the chunk from the cache to the map
self.chunk_map
.0
.insert(pos, self.cache.remove(pos).unwrap());
self.chunk_map.chunk_handle_at(pos).unwrap().set_loaded();
} else {
self.loading_chunks.insert(req.pos);
self.chunk_worker.queue_load(req);
}
}
/// Loads any chunks that have been loaded asynchronously
/// after a call to [`World::queue_chunk_load`].
pub fn load_chunks(&mut self, ecs: &mut Ecs) -> SysResult {
while let Some(loaded) = self.chunk_worker.poll_loaded_chunk()? {
self.loading_chunks.remove(&loaded.pos);
if self.canceled_chunk_loads.remove(&loaded.pos) {
continue;
}
let chunk = loaded.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);
}
Ok(())
}
/// Unloads the given chunk.
pub fn unload_chunk(&mut self, pos: ChunkPosition) -> anyhow::Result<()> {
if let Some((pos, handle)) = self.chunk_map.0.remove_entry(&pos) {
handle.set_unloaded()?;
self.chunk_worker.queue_chunk_save(SaveRequest {
pos,
chunk: handle.clone(),
entities: vec![],
block_entities: vec![],
});
self.cache.insert(pos, handle);
}
self.chunk_map.remove_chunk(pos);
if self.is_chunk_loading(pos) {
self.canceled_chunk_loads.insert(pos);
}
log::trace!("Unloaded chunk {:?}", pos);
Ok(())
}
/// 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: ValidBlockPosition, 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: ValidBlockPosition) -> 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 fn load_player_data(&self, uuid: Uuid) -> anyhow::Result<PlayerData> {
Ok(base::anvil::player::load_player_data(
&self.world_dir,
uuid,
)?)
}
pub fn save_player_data(&self, uuid: Uuid, data: &PlayerData) -> anyhow::Result<()> {
base::anvil::player::save_player_data(&self.world_dir, uuid, data)
}
}
pub type ChunkMapInner = AHashMap<ChunkPosition, ChunkHandle>;
/// 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).and_then(|lock| lock.write())
}
/// Returns an `Arc<RwLock<Chunk>>` at the given position.
pub fn chunk_handle_at(&self, pos: ChunkPosition) -> Option<ChunkHandle> {
self.0.get(&pos).map(Arc::clone)
}
pub fn block_at(&self, pos: ValidBlockPosition) -> Option<BlockId> {
check_coords(pos)?;
let (x, y, z) = chunk_relative_pos(pos.into());
self.chunk_at(pos.chunk())
.and_then(|chunk| chunk.block_at(x, y, z))
}
pub fn set_block_at(&self, pos: ValidBlockPosition, block: BlockId) -> bool {
if check_coords(pos).is_none() {
return false;
}
let (x, y, z) = chunk_relative_pos(pos.into());
self.chunk_at_mut(pos.chunk())
.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 = &ChunkHandle> {
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(ChunkLock::new(chunk, true)));
}
/// 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: ValidBlockPosition) -> 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 std::convert::TryInto;
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).try_into().unwrap())
.is_none());
assert!(world
.block_at(BlockPosition::new(0, 0, 0).try_into().unwrap())
.is_some());
}
}