Skip to main content

azalea_physics/collision/
shape.rs

1use std::{cmp, num::NonZeroU32, sync::LazyLock};
2
3use azalea_core::{
4    direction::{Axis, AxisCycle, Direction},
5    hit_result::BlockHitResult,
6    math::{EPSILON, binary_search},
7    position::{BlockPos, Vec3, Vec3i},
8};
9
10use super::mergers::IndexMerger;
11use crate::collision::{Aabb, BitSetDiscreteVoxelShape, DiscreteVoxelShape};
12
13pub struct Shapes;
14
15pub static BLOCK_SHAPE: LazyLock<VoxelShape> = LazyLock::new(|| {
16    let mut shape = BitSetDiscreteVoxelShape::new(1, 1, 1);
17    shape.fill(0, 0, 0);
18    VoxelShape::Cube(CubeVoxelShape::new(DiscreteVoxelShape::BitSet(shape)))
19});
20
21pub fn box_shape(
22    min_x: f64,
23    min_y: f64,
24    min_z: f64,
25    max_x: f64,
26    max_y: f64,
27    max_z: f64,
28) -> VoxelShape {
29    // we don't check for the numbers being out of bounds because some blocks
30    // are weird and are outside 0-1
31
32    if max_x - min_x < EPSILON && max_y - min_y < EPSILON && max_z - min_z < EPSILON {
33        return EMPTY_SHAPE.clone();
34    }
35
36    let x_bits = find_bits(min_x, max_x);
37    let y_bits = find_bits(min_y, max_y);
38    let z_bits = find_bits(min_z, max_z);
39
40    if x_bits < 0 || y_bits < 0 || z_bits < 0 {
41        return VoxelShape::Array(ArrayVoxelShape::new(
42            BLOCK_SHAPE.shape().to_owned(),
43            [min_x, max_x].into(),
44            [min_y, max_y].into(),
45            [min_z, max_z].into(),
46        ));
47    }
48    if x_bits == 0 && y_bits == 0 && z_bits == 0 {
49        return BLOCK_SHAPE.clone();
50    }
51
52    let x_bits = 1 << x_bits;
53    let y_bits = 1 << y_bits;
54    let z_bits = 1 << z_bits;
55    let shape = BitSetDiscreteVoxelShape::with_filled_bounds(
56        x_bits,
57        y_bits,
58        z_bits,
59        Vec3i {
60            x: (min_x * x_bits as f64).round() as i32,
61            y: (min_y * y_bits as f64).round() as i32,
62            z: (min_z * z_bits as f64).round() as i32,
63        },
64        Vec3i {
65            x: (max_x * x_bits as f64).round() as i32,
66            y: (max_y * y_bits as f64).round() as i32,
67            z: (max_z * z_bits as f64).round() as i32,
68        },
69    );
70    VoxelShape::Cube(CubeVoxelShape::new(DiscreteVoxelShape::BitSet(shape)))
71}
72
73pub static EMPTY_SHAPE: LazyLock<VoxelShape> = LazyLock::new(|| {
74    VoxelShape::Array(ArrayVoxelShape::new(
75        DiscreteVoxelShape::BitSet(BitSetDiscreteVoxelShape::new(0, 0, 0)),
76        [0.].into(),
77        [0.].into(),
78        [0.].into(),
79    ))
80});
81
82fn find_bits(min: f64, max: f64) -> i32 {
83    if min < -EPSILON || max > 1. + EPSILON {
84        return -1;
85    }
86    for bits in 0..=3 {
87        let shifted_bits = 1 << bits;
88        let min = min * shifted_bits as f64;
89        let max = max * shifted_bits as f64;
90        let min_ok = (min - min.round()).abs() < EPSILON * shifted_bits as f64;
91        let max_ok = (max - max.round()).abs() < EPSILON * shifted_bits as f64;
92        if min_ok && max_ok {
93            return bits;
94        }
95    }
96    -1
97}
98
99impl Shapes {
100    pub fn or(a: VoxelShape, b: VoxelShape) -> VoxelShape {
101        Self::join(a, b, |a, b| a || b)
102    }
103
104    pub fn collide(
105        axis: Axis,
106        entity_box: &Aabb,
107        collision_boxes: &[VoxelShape],
108        mut movement: f64,
109    ) -> f64 {
110        for shape in collision_boxes {
111            if movement.abs() < EPSILON {
112                return 0.;
113            }
114            movement = shape.collide(axis, entity_box, movement);
115        }
116        movement
117    }
118
119    pub fn join(a: VoxelShape, b: VoxelShape, op: fn(bool, bool) -> bool) -> VoxelShape {
120        Self::join_unoptimized(a, b, op).optimize()
121    }
122
123    pub fn join_unoptimized(
124        a: VoxelShape,
125        b: VoxelShape,
126        op: fn(bool, bool) -> bool,
127    ) -> VoxelShape {
128        if op(false, false) {
129            panic!("Illegal operation");
130        };
131        // if (a == b) {
132        //     return if op(true, true) { a } else { empty_shape() };
133        // }
134        let op_true_false = op(true, false);
135        let op_false_true = op(false, true);
136        if a.is_empty() {
137            return if op_false_true {
138                b
139            } else {
140                EMPTY_SHAPE.clone()
141            };
142        }
143        if b.is_empty() {
144            return if op_true_false {
145                a
146            } else {
147                EMPTY_SHAPE.clone()
148            };
149        }
150        let var5 = Self::create_index_merger(
151            1,
152            a.get_coords(Axis::X),
153            b.get_coords(Axis::X),
154            op_true_false,
155            op_false_true,
156        );
157        let var6 = Self::create_index_merger(
158            (var5.size() - 1).try_into().unwrap(),
159            a.get_coords(Axis::Y),
160            b.get_coords(Axis::Y),
161            op_true_false,
162            op_false_true,
163        );
164        let var7 = Self::create_index_merger(
165            ((var5.size() - 1) * (var6.size() - 1)).try_into().unwrap(),
166            a.get_coords(Axis::Z),
167            b.get_coords(Axis::Z),
168            op_true_false,
169            op_false_true,
170        );
171        let var8 = BitSetDiscreteVoxelShape::join(a.shape(), b.shape(), &var5, &var6, &var7, op);
172
173        if matches!(var5, IndexMerger::DiscreteCube { .. })
174            && matches!(var6, IndexMerger::DiscreteCube { .. })
175            && matches!(var7, IndexMerger::DiscreteCube { .. })
176        {
177            VoxelShape::Cube(CubeVoxelShape::new(DiscreteVoxelShape::BitSet(var8)))
178        } else {
179            VoxelShape::Array(ArrayVoxelShape::new(
180                DiscreteVoxelShape::BitSet(var8),
181                var5.get_list().into(),
182                var6.get_list().into(),
183                var7.get_list().into(),
184            ))
185        }
186    }
187
188    /// Check if the op is true anywhere when joining the two shapes
189    /// vanilla calls this joinIsNotEmpty (join_is_not_empty).
190    pub fn matches_anywhere(
191        a: &VoxelShape,
192        b: &VoxelShape,
193        op: impl Fn(bool, bool) -> bool,
194    ) -> bool {
195        debug_assert!(!op(false, false));
196        let a_is_empty = a.is_empty();
197        let b_is_empty = b.is_empty();
198        if a_is_empty || b_is_empty {
199            return op(!a_is_empty, !b_is_empty);
200        }
201        if a == b {
202            return op(true, true);
203        }
204
205        let op_true_false = op(true, false);
206        let op_false_true = op(false, true);
207
208        for axis in [Axis::X, Axis::Y, Axis::Z] {
209            if a.max(axis) < b.min(axis) - EPSILON {
210                return op_true_false || op_false_true;
211            }
212            if b.max(axis) < a.min(axis) - EPSILON {
213                return op_true_false || op_false_true;
214            }
215        }
216
217        let x_merger = Self::create_index_merger(
218            1,
219            a.get_coords(Axis::X),
220            b.get_coords(Axis::X),
221            op_true_false,
222            op_false_true,
223        );
224        let y_merger = Self::create_index_merger(
225            (x_merger.size() - 1) as i32,
226            a.get_coords(Axis::Y),
227            b.get_coords(Axis::Y),
228            op_true_false,
229            op_false_true,
230        );
231        let z_merger = Self::create_index_merger(
232            ((x_merger.size() - 1) * (y_merger.size() - 1)) as i32,
233            a.get_coords(Axis::Z),
234            b.get_coords(Axis::Z),
235            op_true_false,
236            op_false_true,
237        );
238
239        Self::matches_anywhere_with_mergers(
240            x_merger,
241            y_merger,
242            z_merger,
243            a.shape().to_owned(),
244            b.shape().to_owned(),
245            op,
246        )
247    }
248
249    pub fn matches_anywhere_with_mergers(
250        merged_x: IndexMerger,
251        merged_y: IndexMerger,
252        merged_z: IndexMerger,
253        shape1: DiscreteVoxelShape,
254        shape2: DiscreteVoxelShape,
255        op: impl Fn(bool, bool) -> bool,
256    ) -> bool {
257        !merged_x.for_merged_indexes(|x, x2, _x3| {
258            merged_y.for_merged_indexes(|y, y2, _y3| {
259                merged_z.for_merged_indexes(|z, z2, _z3| {
260                    !op(
261                        shape1.is_full_wide(Vec3i::new(x, y, z)),
262                        shape2.is_full_wide(Vec3i::new(x2, y2, z2)),
263                    )
264                })
265            })
266        })
267    }
268
269    pub fn create_index_merger(
270        _var0: i32,
271        coords1: &[f64],
272        coords2: &[f64],
273        var3: bool,
274        var4: bool,
275    ) -> IndexMerger {
276        let var5 = coords1.len() - 1;
277        let var6 = coords2.len() - 1;
278        // if (&var1 as &dyn Any).is::<CubePointRange>() && (&var2 as &dyn
279        // Any).is::<CubePointRange>() {
280        // return new DiscreteCubeMerger(var0, var5, var6, var3, var4);
281        // let var7: i64 = lcm(var5 as u32, var6 as u32).try_into().unwrap();
282        // //    if ((long)var0 * var7 <= 256L) {
283        // if var0 as i64 * var7 <= 256 {
284        //     return IndexMerger::new_discrete_cube(var5 as u32, var6 as u32);
285        // }
286        // }
287
288        if coords1[var5] < coords2[0] - EPSILON {
289            IndexMerger::NonOverlapping {
290                lower: coords1.into(),
291                upper: coords2.into(),
292                swap: false,
293            }
294        } else if coords2[var6] < coords1[0] - EPSILON {
295            IndexMerger::NonOverlapping {
296                lower: coords2.into(),
297                upper: coords1.into(),
298                swap: true,
299            }
300        } else if var5 == var6 && coords1 == coords2 {
301            IndexMerger::Identical {
302                coords: coords1.into(),
303            }
304        } else {
305            IndexMerger::new_indirect(coords1, coords2, var3, var4)
306        }
307    }
308}
309
310#[derive(Clone, Debug, PartialEq)]
311pub enum VoxelShape {
312    Array(ArrayVoxelShape),
313    Cube(CubeVoxelShape),
314}
315
316impl VoxelShape {
317    fn min(&self, axis: Axis) -> f64 {
318        let first_full = self.shape().first_full(axis);
319        if first_full >= self.shape().size(axis) as i32 {
320            f64::INFINITY
321        } else {
322            self.get(axis, first_full.try_into().unwrap())
323        }
324    }
325    fn max(&self, axis: Axis) -> f64 {
326        let last_full = self.shape().last_full(axis);
327        if last_full <= 0 {
328            f64::NEG_INFINITY
329        } else {
330            self.get(axis, last_full.try_into().unwrap())
331        }
332    }
333
334    pub fn shape(&self) -> &DiscreteVoxelShape {
335        match self {
336            VoxelShape::Array(s) => s.shape(),
337            VoxelShape::Cube(s) => s.shape(),
338        }
339    }
340
341    #[inline]
342    pub fn get_coords(&self, axis: Axis) -> &[f64] {
343        match self {
344            VoxelShape::Array(s) => s.get_coords(axis),
345            VoxelShape::Cube(s) => s.get_coords(axis),
346        }
347    }
348
349    pub fn is_empty(&self) -> bool {
350        self.shape().is_empty()
351    }
352
353    #[must_use]
354    pub fn move_relative(&self, delta: Vec3) -> VoxelShape {
355        if self.shape().is_empty() {
356            return EMPTY_SHAPE.clone();
357        }
358
359        VoxelShape::Array(ArrayVoxelShape::new(
360            self.shape().to_owned(),
361            self.get_coords(Axis::X)
362                .iter()
363                .map(|c| c + delta.x)
364                .collect(),
365            self.get_coords(Axis::Y)
366                .iter()
367                .map(|c| c + delta.y)
368                .collect(),
369            self.get_coords(Axis::Z)
370                .iter()
371                .map(|c| c + delta.z)
372                .collect(),
373        ))
374    }
375
376    #[inline]
377    pub fn get(&self, axis: Axis, index: usize) -> f64 {
378        // self.get_coords(axis)[index]
379        match self {
380            VoxelShape::Array(s) => s.get_coords(axis)[index],
381            VoxelShape::Cube(s) => s.get_coords(axis)[index],
382            // _ => self.get_coords(axis)[index],
383        }
384    }
385
386    pub fn find_index(&self, axis: Axis, coord: f64) -> i32 {
387        match self {
388            VoxelShape::Cube(s) => s.find_index(axis, coord),
389            _ => {
390                let upper_limit = (self.shape().size(axis) + 1) as i32;
391                binary_search(0, upper_limit, |t| coord < self.get(axis, t as usize)) - 1
392            }
393        }
394    }
395
396    pub fn clip(&self, from: Vec3, to: Vec3, block_pos: BlockPos) -> Option<BlockHitResult> {
397        if self.is_empty() {
398            return None;
399        }
400        let vector = to - from;
401        if vector.length_squared() < EPSILON {
402            return None;
403        }
404        let right_after_start = from + (vector * 0.001);
405
406        if self.shape().is_full_wide(Vec3i::new(
407            self.find_index(Axis::X, right_after_start.x - block_pos.x as f64),
408            self.find_index(Axis::Y, right_after_start.y - block_pos.y as f64),
409            self.find_index(Axis::Z, right_after_start.z - block_pos.z as f64),
410        )) {
411            Some(BlockHitResult {
412                block_pos,
413                direction: Direction::nearest(vector).opposite(),
414                location: right_after_start,
415                inside: true,
416                miss: false,
417                world_border: false,
418            })
419        } else {
420            Aabb::clip_iterable(&self.to_aabbs(), from, to, block_pos)
421        }
422    }
423
424    pub fn collide(&self, axis: Axis, entity_box: &Aabb, movement: f64) -> f64 {
425        self.collide_x(AxisCycle::between(axis, Axis::X), entity_box, movement)
426    }
427    pub fn collide_x(&self, axis_cycle: AxisCycle, entity_box: &Aabb, mut movement: f64) -> f64 {
428        if self.shape().is_empty() {
429            return movement;
430        }
431        if movement.abs() < EPSILON {
432            return 0.;
433        }
434
435        let inverse_axis_cycle = axis_cycle.inverse();
436
437        let x_axis = inverse_axis_cycle.cycle(Axis::X);
438        let y_axis = inverse_axis_cycle.cycle(Axis::Y);
439        let z_axis = inverse_axis_cycle.cycle(Axis::Z);
440
441        let max_x = entity_box.max(&x_axis);
442        let min_x = entity_box.min(&x_axis);
443
444        let x_min_index = self.find_index(x_axis, min_x + EPSILON);
445        let x_max_index = self.find_index(x_axis, max_x - EPSILON);
446
447        let y_min_index = cmp::max(
448            0,
449            self.find_index(y_axis, entity_box.min(&y_axis) + EPSILON),
450        );
451        let y_max_index = cmp::min(
452            self.shape().size(y_axis) as i32,
453            self.find_index(y_axis, entity_box.max(&y_axis) - EPSILON) + 1,
454        );
455
456        let z_min_index = cmp::max(
457            0,
458            self.find_index(z_axis, entity_box.min(&z_axis) + EPSILON),
459        );
460        let z_max_index = cmp::min(
461            self.shape().size(z_axis) as i32,
462            self.find_index(z_axis, entity_box.max(&z_axis) - EPSILON) + 1,
463        );
464
465        if movement > 0. {
466            for x in x_max_index + 1..(self.shape().size(x_axis) as i32) {
467                for y in y_min_index..y_max_index {
468                    for z in z_min_index..z_max_index {
469                        if self
470                            .shape()
471                            .is_full_wide_axis_cycle(inverse_axis_cycle, Vec3i { x, y, z })
472                        {
473                            let var23 = self.get(x_axis, x as usize) - max_x;
474                            if var23 >= -EPSILON {
475                                movement = f64::min(movement, var23);
476                            }
477                            return movement;
478                        }
479                    }
480                }
481            }
482        } else if movement < 0. && x_min_index > 0 {
483            for x in (0..x_min_index).rev() {
484                for y in y_min_index..y_max_index {
485                    for z in z_min_index..z_max_index {
486                        if self
487                            .shape()
488                            .is_full_wide_axis_cycle(inverse_axis_cycle, Vec3i { x, y, z })
489                        {
490                            let var23 = self.get(x_axis, (x + 1) as usize) - min_x;
491                            if var23 <= EPSILON {
492                                movement = f64::max(movement, var23);
493                            }
494                            return movement;
495                        }
496                    }
497                }
498            }
499        }
500
501        movement
502    }
503
504    fn optimize(&self) -> VoxelShape {
505        let mut shape = EMPTY_SHAPE.clone();
506        self.for_all_boxes(|var1x, var3, var5, var7, var9, var11| {
507            shape = Shapes::join_unoptimized(
508                shape.clone(),
509                box_shape(var1x, var3, var5, var7, var9, var11),
510                |a, b| a || b,
511            );
512        });
513        shape
514    }
515
516    pub fn for_all_boxes(&self, mut consumer: impl FnMut(f64, f64, f64, f64, f64, f64))
517    where
518        Self: Sized,
519    {
520        let x_coords = self.get_coords(Axis::X);
521        let y_coords = self.get_coords(Axis::Y);
522        let z_coords = self.get_coords(Axis::Z);
523        self.shape().for_all_boxes(
524            |min_x, min_y, min_z, max_x, max_y, max_z| {
525                consumer(
526                    x_coords[min_x as usize],
527                    y_coords[min_y as usize],
528                    z_coords[min_z as usize],
529                    x_coords[max_x as usize],
530                    y_coords[max_y as usize],
531                    z_coords[max_z as usize],
532                );
533            },
534            true,
535        );
536    }
537
538    pub fn to_aabbs(&self) -> Vec<Aabb> {
539        let mut aabbs = Vec::new();
540        self.for_all_boxes(|min_x, min_y, min_z, max_x, max_y, max_z| {
541            aabbs.push(Aabb {
542                min: Vec3::new(min_x, min_y, min_z),
543                max: Vec3::new(max_x, max_y, max_z),
544            });
545        });
546        aabbs
547    }
548
549    pub fn bounds(&self) -> Aabb {
550        assert!(!self.is_empty(), "Can't get bounds for empty shape");
551        Aabb {
552            min: Vec3::new(self.min(Axis::X), self.min(Axis::Y), self.min(Axis::Z)),
553            max: Vec3::new(self.max(Axis::X), self.max(Axis::Y), self.max(Axis::Z)),
554        }
555    }
556}
557
558impl From<&Aabb> for VoxelShape {
559    fn from(aabb: &Aabb) -> Self {
560        box_shape(
561            aabb.min.x, aabb.min.y, aabb.min.z, aabb.max.x, aabb.max.y, aabb.max.z,
562        )
563    }
564}
565impl From<Aabb> for VoxelShape {
566    fn from(aabb: Aabb) -> Self {
567        VoxelShape::from(&aabb)
568    }
569}
570
571#[derive(Clone, Debug, PartialEq)]
572pub struct ArrayVoxelShape {
573    shape: DiscreteVoxelShape,
574    // TODO: check where faces is used in minecraft
575    #[allow(dead_code)]
576    faces: Option<Box<[VoxelShape]>>,
577
578    xs: CompactArray<f64>,
579    ys: CompactArray<f64>,
580    zs: CompactArray<f64>,
581}
582
583#[derive(Clone, Debug, PartialEq)]
584pub struct CubeVoxelShape {
585    shape: DiscreteVoxelShape,
586    // TODO: check where faces is used in minecraft
587    #[allow(dead_code)]
588    faces: Option<Vec<VoxelShape>>,
589
590    x_coords: CompactArray<f64>,
591    y_coords: CompactArray<f64>,
592    z_coords: CompactArray<f64>,
593}
594
595impl ArrayVoxelShape {
596    pub fn new(
597        shape: DiscreteVoxelShape,
598        xs: CompactArray<f64>,
599        ys: CompactArray<f64>,
600        zs: CompactArray<f64>,
601    ) -> Self {
602        let x_size = shape.size(Axis::X) + 1;
603        let y_size = shape.size(Axis::Y) + 1;
604        let z_size = shape.size(Axis::Z) + 1;
605
606        // Lengths of point arrays must be consistent with the size of the
607        // VoxelShape.
608        debug_assert_eq!(x_size, xs.len() as u32);
609        debug_assert_eq!(y_size, ys.len() as u32);
610        debug_assert_eq!(z_size, zs.len() as u32);
611
612        Self {
613            faces: None,
614            shape,
615            xs,
616            ys,
617            zs,
618        }
619    }
620
621    fn shape(&self) -> &DiscreteVoxelShape {
622        &self.shape
623    }
624
625    #[inline]
626    fn get_coords(&self, axis: Axis) -> &[f64] {
627        axis.choose(&self.xs, &self.ys, &self.zs).as_slice()
628    }
629}
630
631impl CubeVoxelShape {
632    pub fn new(shape: DiscreteVoxelShape) -> Self {
633        let x_coords = Self::calculate_coords(&shape, Axis::X);
634        let y_coords = Self::calculate_coords(&shape, Axis::Y);
635        let z_coords = Self::calculate_coords(&shape, Axis::Z);
636
637        Self {
638            shape,
639            faces: None,
640            x_coords,
641            y_coords,
642            z_coords,
643        }
644    }
645}
646
647impl CubeVoxelShape {
648    fn shape(&self) -> &DiscreteVoxelShape {
649        &self.shape
650    }
651
652    fn calculate_coords(shape: &DiscreteVoxelShape, axis: Axis) -> CompactArray<f64> {
653        let size = shape.size(axis);
654
655        (0..=size).map(|i| i as f64 / size as f64).collect()
656    }
657
658    #[inline]
659    fn get_coords(&self, axis: Axis) -> &[f64] {
660        axis.choose(&self.x_coords, &self.y_coords, &self.z_coords)
661            .as_slice()
662    }
663
664    fn find_index(&self, axis: Axis, coord: f64) -> i32 {
665        let n = self.shape().size(axis);
666        f64::floor(f64::clamp(coord * (n as f64), -1f64, n as f64)) as i32
667    }
668}
669
670#[derive(Debug)]
671pub struct CubePointRange {
672    /// Needs at least 1 part
673    pub parts: NonZeroU32,
674}
675impl CubePointRange {
676    pub fn get_double(&self, index: u32) -> f64 {
677        index as f64 / self.parts.get() as f64
678    }
679
680    pub fn size(&self) -> u32 {
681        self.parts.get() + 1
682    }
683
684    pub fn iter(&self) -> Box<[f64]> {
685        (0..=self.parts.get()).map(|i| self.get_double(i)).collect()
686    }
687}
688
689#[derive(Clone, Debug, PartialEq)]
690pub enum CompactArray<T: Clone + Copy> {
691    Box(Box<[T]>),
692    Inline([T; 1]),
693}
694impl<T: Clone + Copy> CompactArray<T> {
695    fn as_slice(&self) -> &[T] {
696        match self {
697            CompactArray::Box(slice) => slice,
698            CompactArray::Inline(arr) => arr,
699        }
700    }
701    fn len(&self) -> usize {
702        match self {
703            CompactArray::Box(slice) => slice.len(),
704            CompactArray::Inline(arr) => arr.len(),
705        }
706    }
707}
708impl<T: Clone + Copy> From<Box<[T]>> for CompactArray<T> {
709    fn from(value: Box<[T]>) -> Self {
710        if value.len() == 1 {
711            Self::Inline([value[0]])
712        } else {
713            Self::Box(value)
714        }
715    }
716}
717impl<T: Clone + Copy, const N: usize> From<[T; N]> for CompactArray<T> {
718    fn from(value: [T; N]) -> Self {
719        if value.len() == 1 {
720            Self::Inline([value[0]])
721        } else {
722            Self::Box(Box::new(value))
723        }
724    }
725}
726impl<T: Clone + Copy> FromIterator<T> for CompactArray<T> {
727    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
728        Self::from(Box::from_iter(iter))
729    }
730}
731
732#[cfg(test)]
733mod tests {
734    use super::*;
735
736    #[test]
737    fn test_block_shape() {
738        let shape = &*BLOCK_SHAPE;
739        assert_eq!(shape.shape().size(Axis::X), 1);
740        assert_eq!(shape.shape().size(Axis::Y), 1);
741        assert_eq!(shape.shape().size(Axis::Z), 1);
742
743        assert_eq!(shape.get_coords(Axis::X).len(), 2);
744        assert_eq!(shape.get_coords(Axis::Y).len(), 2);
745        assert_eq!(shape.get_coords(Axis::Z).len(), 2);
746    }
747
748    #[test]
749    fn test_box_shape() {
750        let shape = box_shape(0., 0., 0., 1., 1., 1.);
751        assert_eq!(shape.shape().size(Axis::X), 1);
752        assert_eq!(shape.shape().size(Axis::Y), 1);
753        assert_eq!(shape.shape().size(Axis::Z), 1);
754
755        assert_eq!(shape.get_coords(Axis::X).len(), 2);
756        assert_eq!(shape.get_coords(Axis::Y).len(), 2);
757        assert_eq!(shape.get_coords(Axis::Z).len(), 2);
758    }
759
760    #[test]
761    fn test_top_slab_shape() {
762        let shape = box_shape(0., 0.5, 0., 1., 1., 1.);
763        assert_eq!(shape.shape().size(Axis::X), 1);
764        assert_eq!(shape.shape().size(Axis::Y), 2);
765        assert_eq!(shape.shape().size(Axis::Z), 1);
766
767        assert_eq!(shape.get_coords(Axis::X).len(), 2);
768        assert_eq!(shape.get_coords(Axis::Y).len(), 3);
769        assert_eq!(shape.get_coords(Axis::Z).len(), 2);
770    }
771
772    #[test]
773    fn test_join_is_not_empty() {
774        let shape = box_shape(0., 0., 0., 1., 1., 1.);
775        let shape2 = box_shape(0., 0.5, 0., 1., 1., 1.);
776        // detect if the shapes intersect at all
777        let joined = Shapes::matches_anywhere(&shape, &shape2, |a, b| a && b);
778        assert!(joined, "Shapes should intersect");
779    }
780
781    #[test]
782    fn clip_in_front_of_block() {
783        let block_shape = &*BLOCK_SHAPE;
784        let block_hit_result = block_shape
785            .clip(
786                Vec3::new(-0.3, 0.5, 0.),
787                Vec3::new(5.3, 0.5, 0.),
788                BlockPos::new(0, 0, 0),
789            )
790            .unwrap();
791
792        assert_eq!(
793            block_hit_result,
794            BlockHitResult {
795                location: Vec3 {
796                    x: 0.0,
797                    y: 0.5,
798                    z: 0.0
799                },
800                direction: Direction::West,
801                block_pos: BlockPos { x: 0, y: 0, z: 0 },
802                inside: false,
803                world_border: false,
804                miss: false
805            }
806        );
807    }
808}