use crate::{Dijkstra3dError, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VolumeShape {
pub(crate) sx: u64,
pub(crate) sy: u64,
pub(crate) sz: u64,
}
impl VolumeShape {
pub fn try_new(sx: u64, sy: u64, sz: u64) -> Result<Self> {
if sx == 0 || sy == 0 || sz == 0 {
return Err(Dijkstra3dError::InvalidInput(format!(
"volume dimensions must be positive; got ({sx}, {sy}, {sz})"
)));
}
sx.checked_mul(sy)
.and_then(|xy| xy.checked_mul(sz))
.ok_or_else(|| {
Dijkstra3dError::InvalidInput(format!(
"volume dimensions ({sx}, {sy}, {sz}) overflow the voxel count"
))
})?;
Ok(Self { sx, sy, sz })
}
#[track_caller]
pub fn new(sx: u64, sy: u64, sz: u64) -> Self {
match Self::try_new(sx, sy, sz) {
Ok(shape) => shape,
Err(error) => panic!("{error}"),
}
}
#[inline]
pub fn sx(&self) -> u64 {
self.sx
}
#[inline]
pub fn sy(&self) -> u64 {
self.sy
}
#[inline]
pub fn sz(&self) -> u64 {
self.sz
}
#[inline]
pub fn total(&self) -> u64 {
self.sx * self.sy * self.sz
}
#[inline]
pub fn stride_y(&self) -> u64 {
self.sx
}
#[inline]
pub fn stride_z(&self) -> u64 {
self.sx * self.sy
}
#[inline]
pub fn coords(&self, idx: u64) -> (u64, u64, u64) {
let z = idx / self.stride_z();
let rem = idx % self.stride_z();
let y = rem / self.stride_y();
let x = rem % self.stride_y();
(x, y, z)
}
#[inline]
pub fn linear(&self, x: u64, y: u64, z: u64) -> u64 {
x + y * self.stride_y() + z * self.stride_z()
}
#[inline]
pub fn min_cross_section(&self) -> u64 {
let mut dims = [self.sx, self.sy, self.sz];
dims.sort_unstable();
dims[0].saturating_mul(dims[1])
}
#[inline]
pub fn parallel_field_worthwhile(&self, threads: usize, min_voxels: u64) -> bool {
threads > 1 && self.total() >= min_voxels && self.min_cross_section() >= PARALLEL_MIN_CROSS
}
}
pub const PARALLEL_DISTANCE_MIN_VOXELS: u64 = 7_077_888;
pub const PARALLEL_PARENTAL_MIN_VOXELS: u64 = 16_777_216;
pub const PARALLEL_MIN_CROSS: u64 = 16_384;
pub const PARALLEL_PARENTAL_MAX_WEIGHT: u64 = 8;
pub trait ToF32Fast: Copy {
fn to_f32_fast(self) -> f32;
}
macro_rules! impl_to_f32_fast {
($($t:ty),*) => {
$(
impl ToF32Fast for $t {
#[inline(always)]
fn to_f32_fast(self) -> f32 {
self as f32
}
}
)*
};
}
impl_to_f32_fast!(u8, u16, u32, u64, i8, i16, i32, i64, f32, f64);
pub trait ToU64Fast: Copy {
fn to_u64_fast(self) -> u64;
}
macro_rules! impl_to_u64_fast {
($($t:ty),*) => {
$(
impl ToU64Fast for $t {
#[inline(always)]
fn to_u64_fast(self) -> u64 {
self as u64
}
}
)*
};
}
impl_to_u64_fast!(u8, u16, u32, u64);
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Anisotropy {
pub wx: f32,
pub wy: f32,
pub wz: f32,
}
impl Default for Anisotropy {
fn default() -> Self {
Self {
wx: 1.0,
wy: 1.0,
wz: 1.0,
}
}
}
impl Anisotropy {
pub fn new(wx: f32, wy: f32, wz: f32) -> Self {
Self { wx, wy, wz }
}
}
pub trait VoxelSource {
type Item: Copy;
fn shape(&self) -> VolumeShape;
fn get(&self, idx: u64) -> Result<Self::Item>;
}
pub struct ArrayView3Source<'a, T> {
view: ndarray::ArrayView3<'a, T>,
shape: VolumeShape,
}
impl<'a, T: Copy> ArrayView3Source<'a, T> {
pub fn try_new(view: ndarray::ArrayView3<'a, T>) -> Result<Self> {
let shape_dims = view.shape();
let shape = VolumeShape::try_new(
shape_dims[0] as u64,
shape_dims[1] as u64,
shape_dims[2] as u64,
)?;
Ok(Self { view, shape })
}
#[track_caller]
pub fn new(view: ndarray::ArrayView3<'a, T>) -> Self {
match Self::try_new(view) {
Ok(source) => source,
Err(error) => panic!("{error}"),
}
}
}
impl<'a, T: Copy> VoxelSource for ArrayView3Source<'a, T> {
type Item = T;
fn shape(&self) -> VolumeShape {
self.shape
}
fn get(&self, idx: u64) -> Result<Self::Item> {
let (x, y, z) = self.shape.coords(idx);
if let Some(&value) = self.view.get([x as usize, y as usize, z as usize]) {
Ok(value)
} else {
Err(crate::Dijkstra3dError::OutOfBounds {
idx,
volume_size: self.shape.total(),
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_volume_shape_coords_linear_roundtrip() {
let shape = VolumeShape::new(3, 4, 5);
for z in 0..5 {
for y in 0..4 {
for x in 0..3 {
let idx = shape.linear(x, y, z);
let (rx, ry, rz) = shape.coords(idx);
assert_eq!(
(rx, ry, rz),
(x, y, z),
"Round-trip failed for ({}, {}, {})",
x,
y,
z
);
}
}
}
}
#[test]
fn volume_shape_try_new_rejects_zero_dimension() {
let result = VolumeShape::try_new(0, 2, 2);
assert!(matches!(result, Err(Dijkstra3dError::InvalidInput(_))));
}
#[test]
fn volume_shape_try_new_rejects_total_overflow() {
let result = VolumeShape::try_new(u64::MAX, 2, 1);
assert!(matches!(result, Err(Dijkstra3dError::InvalidInput(_))));
}
#[test]
fn array_view_source_try_new_rejects_empty_view() {
let array = ndarray::Array3::<u8>::zeros((0, 2, 2));
let result = ArrayView3Source::try_new(array.view());
assert!(matches!(result, Err(Dijkstra3dError::InvalidInput(_))));
}
#[test]
fn test_volume_shape_fortran_order() {
let shape = VolumeShape::new(3, 4, 5);
assert_eq!(shape.linear(0, 0, 0), 0);
assert_eq!(shape.linear(1, 0, 0), 1);
assert_eq!(shape.linear(2, 0, 0), 2);
assert_eq!(shape.linear(0, 1, 0), 3);
assert_eq!(shape.linear(0, 2, 0), 6);
assert_eq!(shape.linear(0, 0, 1), 12);
}
#[test]
fn test_parallel_crossover_heuristic() {
let d = PARALLEL_DISTANCE_MIN_VOXELS;
let p = PARALLEL_PARENTAL_MIN_VOXELS;
assert!(!VolumeShape::new(256, 256, 256).parallel_field_worthwhile(1, d));
assert!(!VolumeShape::new(64, 64, 64).parallel_field_worthwhile(32, d));
assert!(!VolumeShape::new(128, 128, 128).parallel_field_worthwhile(32, d));
assert!(!VolumeShape::new(128, 128, 128).parallel_field_worthwhile(32, p));
assert!(VolumeShape::new(192, 192, 192).parallel_field_worthwhile(32, d));
assert!(!VolumeShape::new(192, 192, 192).parallel_field_worthwhile(32, p));
assert!(VolumeShape::new(256, 256, 256).parallel_field_worthwhile(32, d));
assert!(VolumeShape::new(256, 256, 256).parallel_field_worthwhile(32, p));
let channel = VolumeShape::new(4, 4, 4_000_000);
assert!(channel.total() >= d);
assert_eq!(channel.min_cross_section(), 16); assert!(!channel.parallel_field_worthwhile(32, d));
let slab = VolumeShape::new(8, 2048, 2048);
assert!(slab.total() >= d);
assert_eq!(slab.min_cross_section(), 8 * 2048); assert!(slab.parallel_field_worthwhile(32, d));
}
#[test]
fn test_min_cross_section() {
assert_eq!(VolumeShape::new(3, 4, 5).min_cross_section(), 12); assert_eq!(VolumeShape::new(10, 2, 3).min_cross_section(), 6); assert_eq!(VolumeShape::new(7, 7, 7).min_cross_section(), 49);
}
#[test]
fn test_arrayview3source_basic() {
use ndarray::Array3;
let mut arr = Array3::<u32>::zeros((2, 2, 2));
arr[[0, 0, 0]] = 1;
arr[[1, 0, 0]] = 2;
arr[[0, 1, 0]] = 3;
arr[[0, 0, 1]] = 4;
let source = ArrayView3Source::new(arr.view());
let shape = source.shape();
assert_eq!(shape.sx, 2);
assert_eq!(shape.sy, 2);
assert_eq!(shape.sz, 2);
assert_eq!(source.get(0).unwrap(), 1); assert_eq!(source.get(1).unwrap(), 2); assert_eq!(source.get(2).unwrap(), 3); assert_eq!(source.get(4).unwrap(), 4); }
}