Skip to main content

azalea_world/
find_blocks.rs

1use azalea_block::{BlockState, BlockStates};
2use azalea_core::position::{BlockPos, ChunkPos};
3
4use crate::{
5    Chunk, World, chunk::storage::ChunkStorage, iterators::ChunkIterator, palette::Palette,
6};
7
8impl World {
9    /// Find the coordinates of a block in the world.
10    ///
11    /// Note that this is sorted by `x+y+z` and not `x^2+y^2+z^2` for
12    /// performance purposes.
13    ///
14    /// Also see [`Self::find_blocks`].
15    ///
16    /// ```
17    /// # use azalea_registry::builtin::BlockKind;
18    /// # fn example(position: azalea_core::position::Vec3, world: &azalea_world::World) {
19    /// let pos = world.find_block(position, &BlockKind::Chest.into());
20    /// # }
21    /// ```
22    pub fn find_block(
23        &self,
24        nearest_to: impl Into<BlockPos>,
25        block_states: &BlockStates,
26    ) -> Option<BlockPos> {
27        self.find_blocks(nearest_to, block_states).next()
28    }
29
30    /// Find all the coordinates of a block in the world.
31    ///
32    /// This returns an iterator that yields the [`BlockPos`]s of blocks that
33    /// are in the given block states.
34    ///
35    /// Note that this is sorted by `x+y+z` and not `x^2+y^2+z^2` for
36    /// performance purposes. Blocks that are at an equal distance are not
37    /// guaranteed to be returned in any specific order.
38    pub fn find_blocks<'a>(
39        &'a self,
40        nearest_to: impl Into<BlockPos>,
41        block_states: &'a BlockStates,
42    ) -> FindBlocks<'a> {
43        FindBlocks::new(nearest_to.into(), &self.chunks, block_states)
44    }
45}
46
47pub struct FindBlocks<'a> {
48    nearest_to: BlockPos,
49    start_chunk: ChunkPos,
50    chunk_iterator: ChunkIterator,
51    chunks: &'a ChunkStorage,
52    block_states: &'a BlockStates,
53
54    queued: Vec<BlockPos>,
55}
56
57impl<'a> FindBlocks<'a> {
58    pub fn new(
59        nearest_to: BlockPos,
60        chunks: &'a ChunkStorage,
61        block_states: &'a BlockStates,
62    ) -> Self {
63        let start_chunk: ChunkPos = (&nearest_to).into();
64        Self {
65            nearest_to,
66            start_chunk,
67            chunk_iterator: ChunkIterator::new(start_chunk, 32),
68            chunks,
69            block_states,
70
71            queued: Vec::new(),
72        }
73    }
74}
75
76impl Iterator for FindBlocks<'_> {
77    type Item = BlockPos;
78
79    fn next(&mut self) -> Option<Self::Item> {
80        if let Some(queued) = self.queued.pop() {
81            return Some(queued);
82        }
83
84        let mut found = Vec::new();
85
86        let mut nearest_found_pos: Option<BlockPos> = None;
87        let mut nearest_found_distance = 0;
88
89        while let Some(chunk_pos) = self.chunk_iterator.next() {
90            let Some(chunk) = self.chunks.get(&chunk_pos) else {
91                // if the chunk isn't loaded then we skip it. we don't just
92                // return since it *could* cause issues if there's a random
93                // unloaded chunk and then more that are loaded. unlikely but
94                // still something to consider, and it's not like this slows it
95                // down much anyways.
96                continue;
97            };
98
99            find_blocks_in_chunk(
100                self.block_states,
101                chunk_pos,
102                &chunk.read(),
103                self.chunks.min_y(),
104                |this_block_pos| {
105                    let this_block_distance = (self.nearest_to - this_block_pos).length_manhattan();
106
107                    found.push((this_block_pos, this_block_distance));
108
109                    if nearest_found_pos.is_none() || this_block_distance < nearest_found_distance {
110                        nearest_found_pos = Some(this_block_pos);
111                        nearest_found_distance = this_block_distance;
112                    }
113                },
114            );
115
116            if let Some(nearest_found_pos) = nearest_found_pos {
117                // this is required because find_block searches chunk-by-chunk,
118                // which can cause us to find blocks first that aren't actually
119                // the closest
120                let required_chunk_distance = u32::max(
121                    u32::max(
122                        (chunk_pos.x - self.start_chunk.x).unsigned_abs(),
123                        (chunk_pos.z - self.start_chunk.z).unsigned_abs(),
124                    ),
125                    (self.nearest_to.y - nearest_found_pos.y)
126                        .unsigned_abs()
127                        .div_ceil(16),
128                ) + 1;
129                let nearest_chunk_distance = self.chunk_iterator.layer;
130
131                // if we found a valid position and there's no chance that
132                // there's something closer, return it
133                if nearest_chunk_distance > required_chunk_distance {
134                    break;
135                }
136            }
137        }
138
139        // sort so nearest is at the end
140        found.sort_unstable_by_key(|(_, distance)| u32::MAX - distance);
141
142        self.queued = found.into_iter().map(|(pos, _)| pos).collect();
143        self.queued.pop()
144    }
145}
146
147/// An optimized function for finding the block positions in a chunk that match
148/// the given block states.
149///
150/// This is used internally by [`World::find_block`] and
151/// [`World::find_blocks`].
152pub fn find_blocks_in_chunk(
153    block_states: &BlockStates,
154    chunk_pos: ChunkPos,
155    chunk: &Chunk,
156    min_y: i32,
157    mut cb: impl FnMut(BlockPos),
158) {
159    for (section_index, section) in chunk.sections.iter().enumerate() {
160        let maybe_has_block = palette_maybe_has_block(&section.states.palette, block_states);
161        if !maybe_has_block {
162            continue;
163        }
164
165        for i in 0..4096 {
166            let block_state = section.states.get_at_index(i);
167
168            if block_states.contains(&block_state) {
169                let section_pos = section.states.pos_from_index(i);
170                let (x, y, z) = (
171                    chunk_pos.x * 16 + (section_pos.x as i32),
172                    min_y + (section_index * 16) as i32 + section_pos.y as i32,
173                    chunk_pos.z * 16 + (section_pos.z as i32),
174                );
175                let this_block_pos = BlockPos { x, y, z };
176
177                cb(this_block_pos);
178            }
179        }
180    }
181}
182
183fn palette_maybe_has_block(palette: &Palette<BlockState>, block_states: &BlockStates) -> bool {
184    match &palette {
185        Palette::SingleValue(id) => block_states.contains(id),
186        Palette::Linear(ids) => ids.iter().any(|id| block_states.contains(id)),
187        Palette::Hashmap(ids) => ids.iter().any(|id| block_states.contains(id)),
188        Palette::Global => true,
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use azalea_registry::builtin::BlockKind;
195
196    use super::*;
197    use crate::{Chunk, chunk::partial::PartialChunkStorage};
198
199    #[test]
200    fn find_block() {
201        let mut world = World::default();
202
203        let chunk_storage = &mut world.chunks;
204        let mut partial_chunk_storage = PartialChunkStorage::default();
205
206        // block at (17, 0, 0) and (0, 18, 0)
207
208        partial_chunk_storage.set(
209            &ChunkPos { x: 0, z: 0 },
210            Some(Chunk::default()),
211            chunk_storage,
212        );
213        partial_chunk_storage.set(
214            &ChunkPos { x: 1, z: 0 },
215            Some(Chunk::default()),
216            chunk_storage,
217        );
218
219        chunk_storage.set_block_state(BlockPos { x: 17, y: 0, z: 0 }, BlockKind::Stone.into());
220        chunk_storage.set_block_state(BlockPos { x: 0, y: 18, z: 0 }, BlockKind::Stone.into());
221
222        let pos = world.find_block(BlockPos { x: 0, y: 0, z: 0 }, &BlockKind::Stone.into());
223        assert_eq!(pos, Some(BlockPos { x: 17, y: 0, z: 0 }));
224    }
225
226    #[test]
227    fn find_blocks() {
228        let mut world = World::default();
229
230        let chunk_storage = &mut world.chunks;
231        let mut partial_chunk_storage = PartialChunkStorage::default();
232
233        // must be ordered by distance already
234        let mut positions = Vec::new();
235        for x in 0..50 {
236            positions.push(BlockPos::new(x, 0, 0));
237        }
238
239        for &pos in &positions {
240            let chunk_pos = ChunkPos::from(pos);
241            if !partial_chunk_storage.has(&chunk_pos) {
242                partial_chunk_storage.set(&chunk_pos, Some(Chunk::default()), chunk_storage);
243            }
244            chunk_storage.set_block_state(pos, BlockKind::Stone.into());
245        }
246
247        let result = world
248            .find_blocks(BlockPos { x: 0, y: 0, z: 0 }, &BlockKind::Stone.into())
249            .collect::<Box<[_]>>();
250        let positions = positions.into();
251        assert_eq!(result, positions);
252    }
253
254    #[test]
255    fn find_block_next_to_chunk_border() {
256        let mut world = World::default();
257
258        let chunk_storage = &mut world.chunks;
259        let mut partial_chunk_storage = PartialChunkStorage::default();
260
261        // block at (-1, 0, 0) and (15, 0, 0)
262
263        partial_chunk_storage.set(
264            &ChunkPos { x: -1, z: 0 },
265            Some(Chunk::default()),
266            chunk_storage,
267        );
268        partial_chunk_storage.set(
269            &ChunkPos { x: 0, z: 0 },
270            Some(Chunk::default()),
271            chunk_storage,
272        );
273
274        chunk_storage.set_block_state(BlockPos { x: -1, y: 0, z: 0 }, BlockKind::Stone.into());
275        chunk_storage.set_block_state(BlockPos { x: 15, y: 0, z: 0 }, BlockKind::Stone.into());
276
277        let pos = world.find_block(BlockPos { x: 0, y: 0, z: 0 }, &BlockKind::Stone.into());
278        assert_eq!(pos, Some(BlockPos { x: -1, y: 0, z: 0 }));
279    }
280}