use super::BufferGeometry;
use crate::math::{Box3, Sphere};
use std::sync::{Arc, RwLock};
#[derive(Default)]
pub struct DerivedCache {
slot: RwLock<Option<Arc<Derived>>>,
}
impl Clone for DerivedCache {
fn clone(&self) -> Self {
Self::default()
}
}
impl std::fmt::Debug for DerivedCache {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let filled = self.slot.read().map(|s| s.is_some()).unwrap_or(false);
f.debug_struct("DerivedCache")
.field("filled", &filled)
.finish()
}
}
impl DerivedCache {
pub fn clear(&mut self) {
*self.slot.get_mut().unwrap_or_else(|e| e.into_inner()) = None;
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Stamp {
version: u32,
position: usize,
index: usize,
polygons: usize,
}
impl Stamp {
fn of(g: &BufferGeometry) -> Self {
let len = |s: Option<&[u32]>| s.map_or(usize::MAX, <[u32]>::len);
Self {
version: g.geometry_version,
position: g
.attributes
.get("position")
.map_or(usize::MAX, |a| a.array.len()),
index: len(g.index.as_deref()),
polygons: len(g.polygons.as_deref()),
}
}
}
#[derive(Debug)]
pub(crate) struct Derived {
stamp: Stamp,
pub bounding_box: Box3,
pub bounding_sphere: Sphere,
polygon_ends: Option<Vec<u32>>,
}
impl Derived {
fn compute(g: &BufferGeometry) -> Self {
let mut bounding_box = Box3::empty();
if let Some(points) = g.positions() {
for p in points {
bounding_box.expand_by_point(p);
}
}
let bounding_sphere = if bounding_box.is_empty() {
Sphere::empty()
} else {
let center = bounding_box.center();
let mut max_r2 = 0.0f32;
if let Some(points) = g.positions() {
for p in points {
max_r2 = max_r2.max((p - center).length_sq());
}
}
Sphere::new(center, max_r2.sqrt())
};
let polygon_ends = g.polygons.as_deref().and_then(|counts| {
let mut ends = Vec::with_capacity(counts.len());
let mut at = 0u64;
for &n in counts {
at += n as u64;
ends.push(u32::try_from(at).ok()?);
}
(at == g.triangle_count() as u64).then_some(ends)
});
Self {
stamp: Stamp::of(g),
bounding_box,
bounding_sphere,
polygon_ends,
}
}
pub fn polygon_of(&self, t: usize) -> Option<usize> {
let ends = self.polygon_ends.as_deref()?;
let p = ends.partition_point(|&end| end as usize <= t);
(p < ends.len()).then_some(p)
}
}
impl BufferGeometry {
pub(crate) fn derived(&self) -> Arc<Derived> {
let stamp = Stamp::of(self);
let lock = &self.derived.slot;
if let Some(d) = lock.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
if d.stamp == stamp {
return d.clone();
}
}
let fresh = Arc::new(Derived::compute(self));
*lock.write().unwrap_or_else(|e| e.into_inner()) = Some(fresh.clone());
fresh
}
pub fn polygon_of_triangle(&self, t: usize) -> Option<usize> {
self.polygons.as_ref()?;
self.derived().polygon_of(t)
}
pub fn bounding_sphere_cached(&self) -> Sphere {
self.bounding_sphere
.unwrap_or_else(|| self.derived().bounding_sphere)
}
pub fn bounding_box_cached(&self) -> Box3 {
self.bounding_box
.unwrap_or_else(|| self.derived().bounding_box)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::BufferAttribute;
fn strip() -> BufferGeometry {
crate::geometries::PlaneGeometry::with_segments(4.0, 1.0, 4, 1)
}
fn linear(g: &BufferGeometry, t: usize) -> Option<usize> {
g.polygons_of_triangles(&[t])[0]
}
#[test]
fn lookup_matches_the_linear_walk() {
let mut g = strip();
g.set_polygons(vec![1, 3, 2, 1, 1]);
for t in 0..g.triangle_count() + 2 {
assert_eq!(g.polygon_of_triangle(t), linear(&g, t), "triangle {t}");
}
assert_eq!(g.polygon_of_triangle(0), Some(0));
assert_eq!(g.polygon_of_triangle(3), Some(1));
assert_eq!(g.polygon_of_triangle(4), Some(2));
assert_eq!(g.polygon_of_triangle(7), Some(4));
assert_eq!(g.polygon_of_triangle(8), None);
}
#[test]
fn set_polygons_refreshes_the_cache() {
let mut g = strip();
assert_eq!(g.polygon_of_triangle(2), Some(1));
g.set_polygons(vec![4, 4]);
assert_eq!(g.polygon_of_triangle(2), Some(0));
assert_eq!(g.polygon_of_triangle(5), Some(1));
}
#[test]
fn set_index_drops_the_grouping() {
let mut g = strip();
assert_eq!(g.polygon_of_triangle(2), Some(1));
let index = g.index.clone().unwrap();
g.set_index(index);
assert_eq!(g.polygon_of_triangle(2), None);
}
#[test]
fn direct_writes_are_seen_after_a_version_bump() {
let mut g = strip();
assert_eq!(g.polygon_of_triangle(6), Some(3));
g.polygons = Some(vec![8, 0, 0, 0]);
g.bump_version();
assert_eq!(g.polygon_of_triangle(6), Some(0));
g.polygons = Some(vec![2, 2]);
assert_eq!(g.polygon_of_triangle(1), None, "length change");
g.polygons = Some(vec![2, 2, 2, 2]);
assert_eq!(g.polygon_of_triangle(5), Some(2), "length change");
let mut index = g.index.clone().unwrap();
index.truncate(12);
g.index = Some(index);
assert_eq!(g.polygon_of_triangle(1), None, "length change");
}
#[test]
fn an_in_place_edit_needs_the_bump() {
let mut g = BufferGeometry::new();
g.set_attribute(
"position",
BufferAttribute::new(vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0], 3),
);
assert_eq!(g.bounding_box_cached().max.x, 1.0);
g.attributes.get_mut("position").unwrap().array[3] = 5.0;
let v = g.geometry_version;
g.bump_version();
assert_ne!(g.geometry_version, v);
assert_eq!(g.bounding_box_cached().max.x, 5.0);
}
#[test]
fn a_same_length_replacement_with_a_bump_always_refreshes() {
let mut g = strip();
for trial in 0..200u32 {
let first = 1 + trial % 7;
let table = vec![first, 8 - first];
g.polygons = Some(table);
g.bump_version();
assert_eq!(g.polygon_of_triangle(0), Some(0));
assert_eq!(
g.polygon_of_triangle(first as usize),
Some(1),
"trial {trial}"
);
}
}
#[test]
fn stored_bounds_are_used_as_is() {
let mut g = BufferGeometry::new();
g.set_attribute(
"position",
BufferAttribute::new(vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0], 3),
);
g.bounding_sphere = Some(Sphere::new(crate::math::Vector3::ZERO, 42.0));
assert_eq!(g.bounding_sphere_cached().radius, 42.0);
g.bounding_sphere = None;
assert!((g.bounding_sphere_cached().radius - 0.5f32.sqrt()).abs() < 1e-6);
}
#[test]
fn bounds_follow_set_attribute() {
let mut g = BufferGeometry::new();
g.set_attribute(
"position",
BufferAttribute::new(vec![0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 2.0, 0.0], 3),
);
let s = g.bounding_sphere_cached();
assert!((s.radius - 2f32.sqrt()).abs() < 1e-6);
g.set_attribute(
"position",
BufferAttribute::new(vec![0.0, 0.0, 0.0, 4.0, 0.0, 0.0, 0.0, 4.0, 0.0], 3),
);
let s = g.bounding_sphere_cached();
assert!((s.radius - 8f32.sqrt()).abs() < 1e-6, "{s:?}");
assert_eq!(g.bounding_box_cached().max.x, 4.0);
g.attributes.insert(
"position".into(),
BufferAttribute::new(vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0], 3),
);
g.bump_version();
assert_eq!(g.bounding_box_cached().max.x, 1.0);
}
}