2019-04-29 20:37:19 +00:00
|
|
|
use crate::vol::{ReadVol, Vox};
|
2019-04-23 22:48:31 +00:00
|
|
|
use vek::*;
|
|
|
|
|
|
|
|
pub trait RayUntil<V: Vox> = FnMut(&V) -> bool;
|
|
|
|
|
|
|
|
pub struct Ray<'a, V: ReadVol, F: RayUntil<V::Vox>> {
|
|
|
|
vol: &'a V,
|
|
|
|
from: Vec3<f32>,
|
|
|
|
to: Vec3<f32>,
|
|
|
|
until: F,
|
|
|
|
max_iter: usize,
|
2019-05-12 05:37:10 +00:00
|
|
|
ignore_error: bool,
|
2019-04-23 22:48:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, V: ReadVol, F: RayUntil<V::Vox>> Ray<'a, V, F> {
|
|
|
|
pub fn new(vol: &'a V, from: Vec3<f32>, to: Vec3<f32>, until: F) -> Self {
|
|
|
|
Self {
|
|
|
|
vol,
|
|
|
|
from,
|
|
|
|
to,
|
|
|
|
until,
|
|
|
|
max_iter: 100,
|
2019-05-12 05:37:10 +00:00
|
|
|
ignore_error: false,
|
2019-04-23 22:48:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-24 16:47:11 +00:00
|
|
|
pub fn until(self, f: F) -> Ray<'a, V, F> {
|
2019-04-29 20:37:19 +00:00
|
|
|
Ray { until: f, ..self }
|
2019-04-23 22:48:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn max_iter(mut self, max_iter: usize) -> Self {
|
|
|
|
self.max_iter = max_iter;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-05-12 05:37:10 +00:00
|
|
|
pub fn ignore_error(mut self) -> Self {
|
|
|
|
self.ignore_error = true;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-04-24 17:33:04 +00:00
|
|
|
pub fn cast(mut self) -> (f32, Result<Option<&'a V::Vox>, V::Err>) {
|
2019-04-23 22:48:31 +00:00
|
|
|
// TODO: Fully test this!
|
|
|
|
|
|
|
|
const PLANCK: f32 = 0.001;
|
|
|
|
|
|
|
|
let mut dist = 0.0;
|
|
|
|
let dir = (self.to - self.from).normalized();
|
2019-05-05 15:17:57 +00:00
|
|
|
let max = (self.to - self.from).magnitude();
|
2019-04-23 22:48:31 +00:00
|
|
|
|
|
|
|
let mut pos = self.from;
|
2019-05-05 15:17:57 +00:00
|
|
|
let mut ipos = pos.map(|e| e.floor() as i32);
|
2019-04-23 22:48:31 +00:00
|
|
|
|
|
|
|
for _ in 0..self.max_iter {
|
2019-04-24 16:47:11 +00:00
|
|
|
pos = self.from + dir * dist;
|
2019-05-05 15:17:57 +00:00
|
|
|
ipos = pos.map(|e| e.floor() as i32);
|
2019-04-23 22:48:31 +00:00
|
|
|
|
2019-04-29 20:37:19 +00:00
|
|
|
match self.vol.get(ipos).map(|vox| (vox, (self.until)(vox))) {
|
2019-04-24 17:33:04 +00:00
|
|
|
Ok((vox, true)) => return (dist, Ok(Some(vox))),
|
2019-05-12 05:37:10 +00:00
|
|
|
Err(err) if !self.ignore_error => return (dist, Err(err)),
|
|
|
|
_ => {}
|
2019-04-23 22:48:31 +00:00
|
|
|
}
|
|
|
|
|
2019-05-05 15:17:57 +00:00
|
|
|
// Allow one iteration above max
|
|
|
|
if dist > max {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2019-04-29 20:37:19 +00:00
|
|
|
let deltas =
|
2019-05-05 15:17:57 +00:00
|
|
|
(dir.map(|e| if e < 0.0 { 0.0 } else { 1.0 }) - pos.map(|e| e.abs().fract())) / dir;
|
2019-04-23 22:48:31 +00:00
|
|
|
|
|
|
|
dist += deltas.reduce(f32::min).max(PLANCK);
|
|
|
|
}
|
|
|
|
|
2019-04-24 17:33:04 +00:00
|
|
|
(dist, Ok(None))
|
2019-04-23 22:48:31 +00:00
|
|
|
}
|
|
|
|
}
|