Skip to main content

azalea_world/chunk/
partial.rs

1use std::{
2    fmt::{self, Debug},
3    io::Cursor,
4    sync::Arc,
5};
6
7use azalea_block::BlockState;
8use azalea_buf::BufReadError;
9use azalea_core::{
10    heightmap_kind::HeightmapKind,
11    position::{BlockPos, ChunkBlockPos, ChunkPos},
12};
13use parking_lot::RwLock;
14use tracing::{debug, trace, warn};
15
16use crate::{Chunk, chunk::storage::ChunkStorage};
17
18/// An efficient storage of chunks for a client that has a limited render
19/// distance.
20///
21/// This has support for using a shared [`ChunkStorage`].
22pub struct PartialChunkStorage {
23    /// The center of the view, i.e. the chunk the player is currently in.
24    view_center: ChunkPos,
25    pub(crate) chunk_radius: u32,
26    view_range: u32,
27    // chunks is a list of size chunk_radius * chunk_radius
28    chunks: Box<[Option<Arc<RwLock<Chunk>>>]>,
29}
30
31impl PartialChunkStorage {
32    pub fn new(chunk_radius: u32) -> Self {
33        let view_range = chunk_radius * 2 + 1;
34        PartialChunkStorage {
35            view_center: ChunkPos::new(0, 0),
36            chunk_radius,
37            view_range,
38            chunks: vec![None; (view_range * view_range) as usize].into(),
39        }
40    }
41
42    /// Update the chunk to center the view on.
43    ///
44    /// This should be called when the client receives a `SetChunkCacheCenter`
45    /// packet.
46    pub fn update_view_center(&mut self, view_center: ChunkPos) {
47        // this code block makes it force unload the chunks that are out of
48        // range after updating the view center. it's usually fine without it
49        // but the commented code is there in case you want to temporarily
50        // uncomment to test something
51
52        // ```
53        // for index in 0..self.chunks.len() {
54        //     let chunk_pos = self.chunk_pos_from_index(index);
55        //     if !in_range_for_view_center_and_radius(&chunk_pos, view_center, self.chunk_radius) {
56        //         self.chunks[index] = None;
57        //     }
58        // }
59        // ```
60
61        self.view_center = view_center;
62    }
63
64    /// Get the center of the view. This is usually the chunk that the player is
65    /// in.
66    pub fn view_center(&self) -> ChunkPos {
67        self.view_center
68    }
69
70    pub fn view_range(&self) -> u32 {
71        self.view_range
72    }
73
74    pub fn index_from_chunk_pos(&self, chunk_pos: &ChunkPos) -> usize {
75        let view_range = self.view_range as i32;
76
77        let x = i32::rem_euclid(chunk_pos.x, view_range) * view_range;
78        let z = i32::rem_euclid(chunk_pos.z, view_range);
79        (x + z) as usize
80    }
81
82    pub fn chunk_pos_from_index(&self, index: usize) -> ChunkPos {
83        let view_range = self.view_range as i32;
84
85        // find the base from the view center
86        let base_x = self.view_center.x.div_euclid(view_range) * view_range;
87        let base_z = self.view_center.z.div_euclid(view_range) * view_range;
88
89        // add the offset from the base
90        let offset_x = index as i32 / view_range;
91        let offset_z = index as i32 % view_range;
92
93        ChunkPos::new(base_x + offset_x, base_z + offset_z)
94    }
95
96    pub fn in_range(&self, chunk_pos: &ChunkPos) -> bool {
97        in_range_for_view_center_and_radius(chunk_pos, self.view_center, self.chunk_radius)
98    }
99
100    pub fn set_block_state(
101        &self,
102        pos: BlockPos,
103        state: BlockState,
104        chunk_storage: &ChunkStorage,
105    ) -> Option<BlockState> {
106        if pos.y < chunk_storage.min_y()
107            || pos.y >= (chunk_storage.min_y() + chunk_storage.height() as i32)
108        {
109            return None;
110        }
111        let chunk_pos = ChunkPos::from(pos);
112        let chunk_lock = chunk_storage.get(&chunk_pos)?;
113        let mut chunk = chunk_lock.write();
114        Some(chunk.get_and_set_block_state(&ChunkBlockPos::from(pos), state, chunk_storage.min_y()))
115    }
116
117    pub fn replace_with_packet_data(
118        &mut self,
119        pos: &ChunkPos,
120        data: &mut Cursor<&[u8]>,
121        heightmaps: &[(HeightmapKind, Box<[u64]>)],
122        chunk_storage: &mut ChunkStorage,
123    ) -> Result<(), BufReadError> {
124        debug!("Replacing chunk at {:?}", pos);
125        if !self.in_range(pos) {
126            warn!("Ignoring chunk since it's not in the view range: {pos:?}");
127            return Ok(());
128        }
129
130        let chunk = Chunk::read_with_dimension_height(
131            azalea_buf::Ctx::default(),
132            data,
133            chunk_storage.height(),
134            chunk_storage.min_y(),
135            heightmaps,
136        )?;
137
138        self.set(pos, Some(chunk), chunk_storage);
139        trace!("Loaded chunk {pos:?}");
140
141        Ok(())
142    }
143
144    /// Returns whether the given chunk is currently loaded (which also requires
145    /// to be in range).
146    pub fn has(&self, pos: &ChunkPos) -> bool {
147        self.limited_get(pos).is_some()
148    }
149
150    /// Get a [`Chunk`] within render distance, or `None` if it's not loaded.
151    /// Use [`ChunkStorageTrait::get`] to get a chunk from the shared storage.
152    ///
153    /// [`ChunkStorageTrait::get`]: crate::chunk::storage::ChunkStorageTrait::get
154    pub fn limited_get(&self, pos: &ChunkPos) -> Option<&Arc<RwLock<Chunk>>> {
155        if !self.in_range(pos) {
156            warn!(
157                "Chunk at {:?} is not in the render distance (center: {:?}, {} chunks)",
158                pos, self.view_center, self.chunk_radius,
159            );
160            return None;
161        }
162
163        let index = self.index_from_chunk_pos(pos);
164        self.chunks[index].as_ref()
165    }
166    /// Get a mutable reference to a [`Chunk`] within render distance, or
167    /// `None` if it's not loaded.
168    ///
169    /// Use [`ChunkStorageTrait::get`] to get a chunk from the shared storage.
170    ///
171    /// [`ChunkStorageTrait::get`]: crate::chunk::storage::ChunkStorageTrait::get
172    pub fn limited_get_mut(&mut self, pos: &ChunkPos) -> Option<&mut Option<Arc<RwLock<Chunk>>>> {
173        if !self.in_range(pos) {
174            return None;
175        }
176
177        let index = self.index_from_chunk_pos(pos);
178
179        Some(&mut self.chunks[index])
180    }
181
182    /// Set a chunk in the shared storage and reference it from the limited
183    /// storage.
184    ///
185    /// Use [`Self::limited_set`] if you already have an `Arc<RwLock<Chunk>>`.
186    ///
187    /// # Panics
188    /// If the chunk is not in the render distance.
189    pub fn set(&mut self, pos: &ChunkPos, chunk: Option<Chunk>, chunk_storage: &mut ChunkStorage) {
190        let new_chunk = chunk.map(|c| chunk_storage.upsert(*pos, c));
191        self.limited_set(pos, new_chunk);
192    }
193
194    /// Set a chunk in our limited storage, useful if your chunk is already
195    /// referenced somewhere else and you want to make it also be referenced by
196    /// this storage.
197    ///
198    /// Use [`Self::set`] if you don't already have an `Arc<RwLock<Chunk>>`.
199    ///
200    /// # Panics
201    /// If the chunk is not in the render distance.
202    pub fn limited_set(&mut self, pos: &ChunkPos, chunk: Option<Arc<RwLock<Chunk>>>) {
203        if let Some(chunk_mut) = self.limited_get_mut(pos) {
204            *chunk_mut = chunk;
205        }
206    }
207
208    /// Get an iterator over all the chunks in the storage.
209    pub fn chunks(&self) -> impl Iterator<Item = &Option<Arc<RwLock<Chunk>>>> {
210        self.chunks.iter()
211    }
212}
213
214impl Debug for PartialChunkStorage {
215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216        f.debug_struct("PartialChunkStorage")
217            .field("view_center", &self.view_center)
218            .field("chunk_radius", &self.chunk_radius)
219            .field("view_range", &self.view_range)
220            // .field("chunks", &self.chunks)
221            .field("chunks", &format_args!("{} items", self.chunks.len()))
222            .finish()
223    }
224}
225
226impl Default for PartialChunkStorage {
227    fn default() -> Self {
228        Self::new(8)
229    }
230}
231
232pub fn in_range_for_view_center_and_radius(
233    chunk_pos: &ChunkPos,
234    view_center: ChunkPos,
235    chunk_radius: u32,
236) -> bool {
237    (chunk_pos.x - view_center.x).unsigned_abs() <= chunk_radius
238        && (chunk_pos.z - view_center.z).unsigned_abs() <= chunk_radius
239}
240
241#[cfg(test)]
242mod tests {
243    use azalea_core::position::ChunkPos;
244
245    use crate::chunk::partial::PartialChunkStorage;
246
247    #[test]
248    fn test_chunk_pos_from_index() {
249        let mut partial_chunk_storage = PartialChunkStorage::new(5);
250        partial_chunk_storage.update_view_center(ChunkPos::new(0, -1));
251        assert_eq!(
252            partial_chunk_storage.chunk_pos_from_index(
253                partial_chunk_storage.index_from_chunk_pos(&ChunkPos::new(2, -1))
254            ),
255            ChunkPos::new(2, -1),
256        );
257    }
258}