svenstaro / bvh

A fast BVH using SAH in rust
https://docs.rs/bvh
MIT License
225 stars 37 forks source link

`Bvh::traverse{_iterator}` panics on an empty BVH #105

Closed finnbear closed 1 week ago

finnbear commented 4 weeks ago

Thanks for making this crate! I noticed a panic when iterating an empty BVH. Here is a reproducible example:

[package]
name = "bvh_test"
version = "0.1.0"
edition = "2021"

[dependencies]
bvh = "0.9.0"
nalgebra = "0.32.5"
use bvh::{aabb::{Aabb, Bounded}, bounding_hierarchy::BHShape, bvh::Bvh, ray::Ray};
use nalgebra::{OPoint, Vector};

fn main() {
    struct Shape;
    const DIM : usize = 3;
    impl Bounded<f32, DIM> for Shape {
        fn aabb(&self) -> Aabb<f32, DIM> {
            unreachable!();
        }
    }
    impl BHShape<f32, DIM> for Shape {
        fn bh_node_index(&self) -> usize {
            unreachable!();
        }
        fn set_bh_node_index(&mut self, _: usize) {
            unreachable!();
        }
    }
    let mut shapes = [];
    let bvh = Bvh::<f32, 3>::build::<Shape>(&mut shapes);
    bvh.traverse_iterator(&Ray::new(OPoint::origin(), Vector::x()), &shapes).next();
}
thread 'main' panicked at /home/finnb/.cargo/registry/src/index.crates.io-6f17d22bba15001f/bvh-0.9.0/src/bvh/iter.rs:68:29:
index out of bounds: the len is 0 but the index is 0
stack backtrace:
   0: rust_begin_unwind
             at /rustc/f067fd6084d750f3797f54b71771c5dbc149726f/library/std/src/panicking.rs:647:5
   1: core::panicking::panic_fmt
             at /rustc/f067fd6084d750f3797f54b71771c5dbc149726f/library/core/src/panicking.rs:72:14
   2: core::panicking::panic_bounds_check
             at /rustc/f067fd6084d750f3797f54b71771c5dbc149726f/library/core/src/panicking.rs:208:5
   3: <usize as core::slice::index::SliceIndex<[T]>>::index
             at /rustc/f067fd6084d750f3797f54b71771c5dbc149726f/library/core/src/slice/index.rs:255:10
   4: core::slice::index::<impl core::ops::index::Index<I> for [T]>::index
             at /rustc/f067fd6084d750f3797f54b71771c5dbc149726f/library/core/src/slice/index.rs:18:9
   5: <alloc::vec::Vec<T,A> as core::ops::index::Index<I>>::index
             at /rustc/f067fd6084d750f3797f54b71771c5dbc149726f/library/alloc/src/vec/mod.rs:2771:9
   6: bvh::bvh::iter::BvhTraverseIterator<T,_,Shape>::move_left
             at /home/finnb/.cargo/registry/src/index.crates.io-6f17d22bba15001f/bvh-0.9.0/src/bvh/iter.rs:68:29
   7: <bvh::bvh::iter::BvhTraverseIterator<T,_,Shape> as core::iter::traits::iterator::Iterator>::next
             at /home/finnb/.cargo/registry/src/index.crates.io-6f17d22bba15001f/bvh-0.9.0/src/bvh/iter.rs:124:17
   8: bvh_test::main
             at ./src/main.rs:22:5
   9: core::ops::function::FnOnce::call_once
             at /rustc/f067fd6084d750f3797f54b71771c5dbc149726f/library/core/src/ops/function.rs:250:5
svenstaro commented 4 weeks ago

Hm I think this might have been reported before. Would you like to try fixing it?

finnbear commented 4 weeks ago

Sure!