use crate::{Error, Result};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GridParams {
samples: [u32; 3],
origin: [f32; 3],
cell_size: f32,
}
impl GridParams {
pub const UNIFORM_SIZE: u64 = 32;
pub fn new(samples: [u32; 3], origin: [f32; 3], cell_size: f32) -> Result<Self> {
if samples.iter().any(|&s| s < 2) {
return Err(Error::DegenerateGrid { samples });
}
if !cell_size.is_finite() || cell_size <= 0.0 {
return Err(Error::InvalidCellSize);
}
if origin.iter().any(|c| !c.is_finite()) {
return Err(Error::InvalidOrigin);
}
let count = u64::from(samples[0])
.checked_mul(u64::from(samples[1]))
.and_then(|n| n.checked_mul(u64::from(samples[2])))
.and_then(|n| n.checked_mul(4));
if count.is_none() {
return Err(Error::GridTooLarge { samples });
}
Ok(Self {
samples,
origin,
cell_size,
})
}
#[must_use]
pub const fn samples(&self) -> [u32; 3] {
self.samples
}
#[must_use]
pub const fn origin(&self) -> [f32; 3] {
self.origin
}
#[must_use]
pub const fn cell_size(&self) -> f32 {
self.cell_size
}
#[must_use]
pub fn sample_count(&self) -> u64 {
u64::from(self.samples[0]) * u64::from(self.samples[1]) * u64::from(self.samples[2])
}
#[must_use]
pub fn cell_count(&self) -> u64 {
u64::from(self.samples[0] - 1)
* u64::from(self.samples[1] - 1)
* u64::from(self.samples[2] - 1)
}
#[must_use]
pub fn field_buffer_size(&self) -> u64 {
self.sample_count() * 4
}
#[must_use]
pub fn sample_position(&self, index: [u32; 3]) -> [f32; 3] {
[
self.origin[0] + self.cell_size * index[0] as f32,
self.origin[1] + self.cell_size * index[1] as f32,
self.origin[2] + self.cell_size * index[2] as f32,
]
}
#[must_use]
pub fn to_std140(&self) -> [u8; Self::UNIFORM_SIZE as usize] {
let mut out = [0u8; Self::UNIFORM_SIZE as usize];
let words = [
self.samples[0].to_le_bytes(),
self.samples[1].to_le_bytes(),
self.samples[2].to_le_bytes(),
0u32.to_le_bytes(),
self.origin[0].to_le_bytes(),
self.origin[1].to_le_bytes(),
self.origin[2].to_le_bytes(),
self.cell_size.to_le_bytes(),
];
for (slot, word) in out.chunks_exact_mut(4).zip(words) {
slot.copy_from_slice(&word);
}
out
}
}
#[cfg(test)]
mod tests;