mod automation;
mod conform;
mod cuboct;
mod field;
mod frame;
#[cfg(all(feature = "render", not(target_arch = "wasm32")))]
mod gpu_solve;
mod homogenize;
mod infill;
mod mesher;
mod metrics;
mod region;
mod scale_rich;
mod stochastic;
mod strut;
mod tpms;
mod voxel;
pub use automation::{CuboctAssemblyPlan, CuboctAssemblyStep};
pub use conform::Conform;
pub use cuboct::{ChiralRule, Cuboct, Hand};
pub use field::Field;
pub use frame::{CuboctFrame, FrameMaterial, FrameResponse};
pub use homogenize::{
homogenize, homogenize_conduction, homogenize_strength, Conductivity, SolidMaterial, Solver,
Stiffness, Strength,
};
pub use infill::Infill;
pub use metrics::LatticeMetrics;
pub use region::Region;
pub use scale_rich::{ScaleRich, ScaleRichAngles, ScaleRichLigament, ScaleRichNet};
pub use stochastic::{SeedLayout, Stochastic};
pub use strut::{Segment, Strut};
pub use tpms::Tpms;
pub use voxel::{CuboctAssembly, CuboctJoint, CuboctJointKind};
use crate::core::BufferGeometry;
use crate::math::{Box3, Vector3};
use mesher::IsoGrid;
use std::f32::consts::TAU;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LatticeKind {
Tpms(Tpms),
Strut(Strut),
Infill(Infill),
Cuboct(Cuboct),
Stochastic(Stochastic),
}
impl LatticeKind {
pub fn all() -> Vec<LatticeKind> {
Tpms::ALL
.into_iter()
.map(LatticeKind::Tpms)
.chain(Strut::ALL.into_iter().map(LatticeKind::Strut))
.chain(Infill::ALL.into_iter().map(LatticeKind::Infill))
.chain(Cuboct::ALL.into_iter().map(LatticeKind::Cuboct))
.chain(Stochastic::ALL.into_iter().map(LatticeKind::Stochastic))
.collect()
}
pub fn name(self) -> &'static str {
match self {
LatticeKind::Tpms(t) => t.name(),
LatticeKind::Strut(s) => s.name(),
LatticeKind::Infill(i) => i.name(),
LatticeKind::Cuboct(c) => c.name(),
LatticeKind::Stochastic(s) => s.name(),
}
}
pub fn from_name(name: &str) -> Option<LatticeKind> {
Tpms::from_name(name)
.map(LatticeKind::Tpms)
.or_else(|| Strut::from_name(name).map(LatticeKind::Strut))
.or_else(|| Infill::from_name(name).map(LatticeKind::Infill))
.or_else(|| Cuboct::from_name(name).map(LatticeKind::Cuboct))
.or_else(|| Stochastic::from_name(name).map(LatticeKind::Stochastic))
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum LatticeStyle {
#[default]
Sheet,
Solid,
}
const PADDING: usize = 6;
const MIN_DIM: usize = PADDING;
#[derive(Clone, Copy, Debug)]
enum Spacing {
Size(Vector3),
Count([usize; 3]),
}
pub struct Lattice<'a> {
kind: LatticeKind,
style: LatticeStyle,
bounds: Box3,
spacing: Spacing,
thickness: f32,
resolution: usize,
max_samples: usize,
skin: f32,
pinned_bounds: bool,
grade: Option<std::sync::Arc<dyn Fn(Vector3) -> f32 + Sync + Send + 'a>>,
trim: Option<std::sync::Arc<dyn Fn(Vector3) -> f32 + Sync + Send + 'a>>,
clip: Option<std::sync::Arc<dyn Fn(Vector3) -> f32 + Sync + Send + 'a>>,
shape: f32,
program: Option<crate::geometries::lattice::voxel::CuboctProgram<'a>>,
chiral_rule: Option<ChiralRule>,
conform: Option<Conform<'a>>,
seed: u32,
jitter: f32,
solver: Solver,
drop_specks: bool,
seed_layout: SeedLayout,
plateau_border: Option<f32>,
seeds_per_cell: usize,
size_ratio: f32,
}
impl<'a> Lattice<'a> {
pub fn new(kind: LatticeKind) -> Self {
Self {
kind,
style: LatticeStyle::default(),
bounds: Box3::from_center_and_size(Vector3::ZERO, Vector3::new(1.0, 1.0, 1.0)),
spacing: Spacing::Count([4, 4, 4]),
thickness: 0.05,
resolution: 16,
max_samples: 8_000_000,
skin: 0.0,
pinned_bounds: false,
grade: None,
trim: None,
clip: None,
shape: 0.15,
program: None,
chiral_rule: None,
drop_specks: false,
seed_layout: SeedLayout::Random,
plateau_border: None,
seeds_per_cell: 8,
size_ratio: 2.0,
conform: None,
seed: 0,
jitter: 1.0,
solver: Solver::default(),
}
}
pub fn bounds(mut self, bounds: Box3) -> Self {
self.bounds = bounds;
self.pinned_bounds = true;
self
}
pub fn size(mut self, size: Vector3) -> Self {
self.bounds = Box3::from_center_and_size(Vector3::ZERO, size);
self.pinned_bounds = true;
self
}
pub fn fill(mut self, region: Region<'a>) -> Self {
let bounds = region.bounds();
if !self.pinned_bounds && !bounds.is_empty() {
self.bounds = bounds;
}
self.trim = Some(region.into_field());
self
}
pub fn skin(mut self, thickness: f32) -> Self {
self.skin = thickness.max(0.0);
self
}
pub fn cell_size(mut self, cell: Vector3) -> Self {
self.spacing = Spacing::Size(cell);
self
}
pub fn cells(mut self, cells: [usize; 3]) -> Self {
self.spacing = Spacing::Count(cells);
self
}
pub fn shape(mut self, shape: f32) -> Self {
self.shape = shape.max(0.0);
self
}
pub fn program(mut self, program: impl Fn(i32, i32, i32) -> Cuboct + Sync + Send + 'a) -> Self {
self.program = Some(Box::new(program));
self
}
pub fn chiral_rule(mut self, rule: ChiralRule) -> Self {
self.chiral_rule = Some(rule);
self
}
pub fn conform(mut self, conform: Conform<'a>) -> Self {
self.conform = Some(conform);
self
}
pub fn solver(mut self, solver: Solver) -> Self {
self.solver = solver;
self
}
pub fn seed(mut self, seed: u32) -> Self {
self.seed = seed;
self
}
pub fn seed_layout(mut self, layout: SeedLayout) -> Self {
self.seed_layout = layout;
self
}
pub fn seeds_per_cell(mut self, count: usize) -> Self {
self.seeds_per_cell = count.clamp(1, 512);
self
}
pub fn size_ratio(mut self, ratio: f32) -> Self {
self.size_ratio = ratio.max(1.0);
self
}
pub fn plateau_border(mut self, radius: f32) -> Self {
self.plateau_border = Some(radius.max(0.0));
self
}
pub fn drop_specks(mut self, drop: bool) -> Self {
self.drop_specks = drop;
self
}
pub fn jitter(mut self, jitter: f32) -> Self {
self.jitter = jitter.clamp(0.0, 1.0);
self
}
pub fn thickness(mut self, thickness: f32) -> Self {
self.thickness = thickness;
self
}
pub fn style(mut self, style: LatticeStyle) -> Self {
self.style = style;
self
}
pub fn resolution(mut self, samples_per_cell: usize) -> Self {
self.resolution = samples_per_cell.max(2);
self
}
pub fn max_samples(mut self, max_samples: usize) -> Self {
self.max_samples = max_samples.max(64);
self
}
pub fn sample_grid(&self) -> [usize; 3] {
self.grid().0 .0
}
pub fn wall_samples(&self) -> f32 {
match self.wall_width() {
Some(width) => {
let step = self.grid().0 .2;
width / step.x.max(step.y).max(step.z)
}
None => f32::INFINITY,
}
}
fn wall_width(&self) -> Option<f32> {
if self.is_level_set() {
None
} else {
Some(self.thickness.abs() * self.grade_floor())
}
}
fn grade_floor(&self) -> f32 {
let Some(grade) = self.grade.as_deref() else {
return 1.0;
};
const SWEEP: usize = 8;
let size = self.bounds.size();
let mut floor = f32::INFINITY;
for k in 0..SWEEP {
for j in 0..SWEEP {
for i in 0..SWEEP {
let at = |index: usize, lo: f32, extent: f32| {
lo + extent * (index as f32 + 0.5) / SWEEP as f32
};
let p = Vector3::new(
at(i, self.bounds.min.x, size.x),
at(j, self.bounds.min.y, size.y),
at(k, self.bounds.min.z, size.z),
);
floor = floor.min(grade(p).max(0.0));
}
}
}
if floor.is_finite() {
floor.clamp(0.05, 1.0)
} else {
1.0
}
}
fn is_level_set(&self) -> bool {
self.style == LatticeStyle::Solid
&& match self.kind {
LatticeKind::Tpms(_) => true,
LatticeKind::Stochastic(s) => s.is_field(),
_ => false,
}
}
pub fn resolve_walls(mut self, samples: f32) -> Self {
let Some(thickness) = self.wall_width() else {
return self;
};
if thickness <= 0.0 || samples <= 0.0 {
return self;
}
let cell = self.resolved_cell();
let widest = cell.x.max(cell.y).max(cell.z);
let needed = (samples * widest / thickness).ceil();
if needed.is_finite() && needed > 0.0 {
self.resolution = self.resolution.max(needed as usize);
}
self
}
pub fn grade(mut self, grade: impl Fn(Vector3) -> f32 + Sync + Send + 'a) -> Self {
self.grade = Some(std::sync::Arc::new(grade));
self
}
pub fn trim(mut self, keep: impl Fn(Vector3) -> f32 + Sync + Send + 'a) -> Self {
self.trim = Some(std::sync::Arc::new(keep));
self
}
pub fn clip(mut self, region: Region<'a>) -> Self {
self.clip = Some(region.into_field());
self
}
pub fn relative_density(&self) -> f32 {
self.occupancy(self.density_resolution())
}
fn density_resolution(&self) -> usize {
self.resolution.min(8)
}
const DENSITY_SAMPLES: usize = 250_000;
const DENSITY_MIN: usize = 32_768;
pub fn fit_relative_density(mut self, target: f32) -> Self {
let target = target.clamp(0.0, 1.0);
let cell = self.resolved_cell();
let span = cell.x.min(cell.y).min(cell.z).max(1e-6);
let signed = self.is_level_set();
let grid = self.density_grid(self.density_resolution());
let mut hi = span;
for _ in 0..16 {
self.thickness = hi;
if self.occupancy_on(&grid) >= target {
break;
}
hi *= 2.0;
}
let mut lo = if signed { -span } else { 0.0 };
if signed {
for _ in 0..16 {
self.thickness = lo;
if self.occupancy_on(&grid) <= target {
break;
}
lo *= 2.0;
}
}
for _ in 0..14 {
let mid = 0.5 * (lo + hi);
self.thickness = mid;
if self.occupancy_on(&grid) < target {
lo = mid;
} else {
hi = mid;
}
}
self.thickness = 0.5 * (lo + hi);
self
}
pub fn current_thickness(&self) -> f32 {
self.thickness
}
pub fn build(&self) -> BufferGeometry {
let (grid, sampler) = self.grid();
let ([nx, ny, nz], origin, step) = grid;
let Some(total) = nx.checked_mul(ny).and_then(|v| v.checked_mul(nz)) else {
return BufferGeometry::new();
};
let mut values = vec![0.0f32; total];
let trig = match self.kind {
LatticeKind::Tpms(_) if self.conform.is_none() => {
let axis = |a: usize, n: usize, o: f32, s: f32| -> Vec<(f32, f32)> {
(0..n)
.map(|i| sampler.tpms_angle(a, o + i as f32 * s).sin_cos())
.collect()
};
Some([
axis(0, nx, origin.x, step.x),
axis(1, ny, origin.y, step.y),
axis(2, nz, origin.z, step.z),
])
}
_ => None,
};
let waves = match (self.kind, &self.conform) {
(LatticeKind::Stochastic(s), None) if s.is_field() => sampler.waves.as_deref(),
_ => None,
};
let columns: Option<Vec<(f64, f64)>> = waves.map(|waves| {
let mut t = Vec::with_capacity(nx * waves.len());
for i in 0..nx {
let dx = (origin.x + i as f32 * step.x - sampler.phase.x) as f64;
for w in waves {
t.push((w.k.x as f64 * dx).sin_cos());
}
}
t
});
crate::utils::parallel::par_fill_chunks(&mut values, nx * ny, |k, slab| {
let z = origin.z + k as f32 * step.z;
let count = waves.map_or(0, <[_]>::len);
let mut row = vec![(0.0f64, 0.0f64); count];
let mut here = vec![(0.0f32, 0.0f32); count];
for j in 0..ny {
let y = origin.y + j as f32 * step.y;
if let Some(waves) = waves {
let (dy, dz) = ((y - sampler.phase.y) as f64, (z - sampler.phase.z) as f64);
for (r, w) in row.iter_mut().zip(waves) {
*r = (w.k.y as f64 * dy + w.k.z as f64 * dz + w.phase as f64).sin_cos();
}
}
for i in 0..nx {
let x = origin.x + i as f32 * step.x;
let pre = if let Some(columns) = &columns {
let column = &columns[i * count..(i + 1) * count];
for ((h, &(sa, ca)), &(sr, cr)) in here.iter_mut().zip(column).zip(&row) {
*h = ((sa * cr + ca * sr) as f32, (ca * cr - sa * sr) as f32);
}
Some(Pre::Waves(&here))
} else {
trig.as_ref()
.map(|[tx, ty, tz]| Pre::Tpms([tx[i], ty[j], tz[k]]))
};
slab[j * nx + i] = sampler.value_trig(Vector3::new(x, y, z), pre);
}
}
});
let geometry = IsoGrid {
dims: [nx, ny, nz],
origin,
step,
values,
}
.triangulate();
if !self.drop_specks {
return geometry;
}
let cell_volume = step.x * step.y * step.z;
crate::utils::mesh_check::remove_loose_pieces(
&geometry,
crate::utils::mesh_check::LoosePieces::Specks {
min_volume: 10.0 * cell_volume,
max_fraction: 0.02,
},
)
.0
}
fn chiral_n(&self) -> i32 {
match self.spacing {
Spacing::Count([nx, ..]) => nx as i32,
Spacing::Size(_) => {
let size = self.bounds.size();
let cell = self.resolved_cell();
(size.x / cell.x).round().max(0.0) as i32
}
}
}
fn resolved_cell(&self) -> Vector3 {
let size = self.bounds.size();
match self.spacing {
Spacing::Size(c) => Vector3::new(
c.x.abs().max(1e-6),
c.y.abs().max(1e-6),
c.z.abs().max(1e-6),
),
Spacing::Count([nx, ny, nz]) => Vector3::new(
size.x / nx.max(1) as f32,
size.y / ny.max(1) as f32,
size.z / nz.max(1) as f32,
),
}
}
fn grid(&self) -> (([usize; 3], Vector3, Vector3), Sampler<'_>) {
let cell = self.resolved_cell();
let size = self.bounds.size();
let resolution = self.resolution.max(2);
let mut step = Vector3::new(
cell.x / resolution as f32,
cell.y / resolution as f32,
cell.z / resolution as f32,
);
let dims_for = |step: Vector3| -> [usize; 3] {
let count = |extent: f32, step: f32| -> usize {
#[allow(clippy::neg_cmp_op_on_partial_ord)]
if !(step > 0.0) {
return MIN_DIM;
}
((extent / step).ceil() as usize)
.saturating_add(PADDING)
.max(MIN_DIM)
};
[
count(size.x, step.x),
count(size.y, step.y),
count(size.z, step.z),
]
};
let mut dims = dims_for(step);
for _ in 0..32 {
let total = dims[0].saturating_mul(dims[1]).saturating_mul(dims[2]);
if total <= self.max_samples || dims == [MIN_DIM; 3] || !step.x.is_finite() {
break;
}
let shrink = (self.max_samples as f64 / total as f64).cbrt();
step = step * (1.0 / shrink.clamp(1e-9, 0.95) as f32);
dims = dims_for(step);
}
let origin = Vector3::new(
self.bounds.min.x - 2.5 * step.x,
self.bounds.min.y - 2.5 * step.y,
self.bounds.min.z - 2.5 * step.z,
);
((dims, origin, step), self.sampler(cell, step, true))
}
fn sampler(&self, cell: Vector3, step: Vector3, clipped: bool) -> Sampler<'_> {
let cuboct_cached = match (self.kind, self.program.is_some(), self.chiral_rule) {
(LatticeKind::Cuboct(c), false, None) => Some(c.segments(self.shape)),
_ => None,
};
let margin = 2.0 * step.x.max(step.y).max(step.z);
let strut_bins = if self.grade.is_none() && self.conform.is_none() {
let cull = (self.thickness * 0.5).max(0.0) + margin;
match self.kind {
LatticeKind::Strut(s) => strut::Bins::new(s.segments(), cell, cull),
LatticeKind::Cuboct(_) => cuboct_cached
.as_deref()
.and_then(|segs| strut::Bins::new(segs, cell, cull)),
_ => None,
}
} else {
None
};
let seed_table = match self.kind {
LatticeKind::Stochastic(s)
if !s.is_field()
&& self.conform.is_none()
&& self.seed_layout == SeedLayout::Random =>
{
let reach = 4.0 * step.x.max(step.y).max(step.z);
let lo = Vector3::new(-reach, -reach, -reach);
let hi = self.bounds.size() + Vector3::new(reach, reach, reach);
let ring = 5;
let cells = |v: Vector3, by: i32| {
[
(v.x / cell.x).floor() as i32 + by,
(v.y / cell.y).floor() as i32 + by,
(v.z / cell.z).floor() as i32 + by,
]
};
let (lo, hi) = (cells(lo, -ring), cells(hi, ring));
stochastic::SeedTable::new(lo, hi, self.jitter, self.seed)
}
_ => None,
};
let (seed_sites, seed_weights) = match self.kind {
LatticeKind::Stochastic(s) if !s.is_field() => {
if self.seed_layout == SeedLayout::Bimodal {
let (sites, weights) = stochastic::bimodal_tile(
self.seeds_per_cell,
self.size_ratio as f64,
cell,
self.seed,
);
(sites, weights)
} else {
let (layout, count) = (self.seed_layout, self.seeds_per_cell);
let sites = stochastic::seed_tile(layout, count, cell, self.seed);
(sites, Vec::new())
}
}
_ => (Vec::new(), Vec::new()),
};
let seed_graph = match self.kind {
LatticeKind::Stochastic(s) if !s.is_field() && self.conform.is_none() => {
let reach = 4.0 * step.x.max(step.y).max(step.z);
let (lo, hi) = (
Vector3::new(-reach, -reach, -reach),
self.bounds.size() + Vector3::new(reach, reach, reach),
);
let cells = |v: Vector3| {
[
(v.x / cell.x).floor() as i32,
(v.y / cell.y).floor() as i32,
(v.z / cell.z).floor() as i32,
]
};
stochastic::shared_graph(
cells(lo),
cells(hi),
[cell.x as f64, cell.y as f64, cell.z as f64],
&seed_sites,
&seed_weights,
self.jitter,
self.seed,
)
}
_ => None,
};
let edge_bins = match (&seed_graph, self.kind) {
(Some(graph), LatticeKind::Stochastic(Stochastic::Voronoi)) if self.grade.is_none() => {
let reach = 4.0 * step.x.max(step.y).max(step.z);
let size = self.bounds.size();
let cull = (self.thickness * 0.5).max(0.0) + margin;
stochastic::EdgeBins::new(
graph,
[-reach as f64; 3],
[
(size.x + reach) as f64,
(size.y + reach) as f64,
(size.z + reach) as f64,
],
cull as f64,
)
}
_ => None,
};
let waves = match self.kind {
LatticeKind::Stochastic(s)
if s.is_field()
&& s != Stochastic::Hyperuniform
&& s != Stochastic::ReactionDiffusion =>
{
Some(stochastic::waves(s, cell, self.seed))
}
_ => None,
};
Sampler {
kind: self.kind,
style: self.style,
phase: if self.conform.is_some() {
Vector3::ZERO
} else {
self.bounds.min
},
cell,
omega: Vector3::new(TAU / cell.x, TAU / cell.y, TAU / cell.z),
half: self.thickness * 0.5,
margin,
skin: self.skin,
bounds: self.bounds,
grade: self.grade.as_deref(),
trim: self.trim.as_deref(),
clip: if clipped { self.clip.as_deref() } else { None },
cuboct_shape: self.shape,
cuboct_rule: self.chiral_rule,
cuboct_n: self.chiral_n(),
cuboct_program: self.program.as_deref(),
cuboct_cached,
strut_bins,
seed_table,
conform: self.conform.as_ref(),
jitter: self.jitter,
seed: self.seed,
turing: match self.kind {
LatticeKind::Stochastic(Stochastic::ReactionDiffusion) => {
Some(stochastic::turing(self.seed))
}
_ => None,
},
seed_sites,
seed_weights,
seed_graph,
edge_bins,
plateau_border: self
.plateau_border
.unwrap_or(0.15 * cell.x.min(cell.y).min(cell.z)),
waves,
}
}
pub fn homogenize(&self, resolution: usize) -> Stiffness {
self.homogenize_with(resolution, SolidMaterial::default())
}
pub fn homogenize_with(&self, resolution: usize, material: SolidMaterial) -> Stiffness {
self.homogenize_window(1, resolution, material)
}
pub fn homogenize_window(
&self,
cells: usize,
resolution: usize,
material: SolidMaterial,
) -> Stiffness {
let (occupancy, origin, window, voxels) = self.periodic_window(cells, resolution);
homogenize(occupancy, origin, window, voxels, material, self.solver)
}
pub fn strength(&self, resolution: usize) -> Strength {
self.strength_with(resolution, SolidMaterial::default())
}
pub fn strength_with(&self, resolution: usize, material: SolidMaterial) -> Strength {
self.strength_window(1, resolution, material)
}
pub fn strength_window(
&self,
cells: usize,
resolution: usize,
material: SolidMaterial,
) -> Strength {
let (occupancy, origin, window, voxels) = self.periodic_window(cells, resolution);
homogenize_strength(occupancy, origin, window, voxels, material, self.solver)
}
pub fn conductivity(&self, resolution: usize) -> Conductivity {
self.conductivity_with(resolution, 1.0)
}
pub fn conductivity_with(&self, resolution: usize, solid: f64) -> Conductivity {
self.conductivity_window(1, resolution, solid)
}
pub fn conductivity_window(&self, cells: usize, resolution: usize, solid: f64) -> Conductivity {
let (occupancy, origin, window, voxels) = self.periodic_window(cells, resolution);
homogenize_conduction(occupancy, origin, window, voxels, solid, self.solver)
}
fn periodic_window(
&self,
cells: usize,
resolution: usize,
) -> (
impl Fn(Vector3) -> bool + Sync + Send + '_,
Vector3,
Vector3,
usize,
) {
let cells = cells.max(1);
let cell = self.resolved_cell();
let sampler = self.sampler(cell, Vector3::ZERO, false);
let half = sampler.half;
let origin = if self.conform.is_some() {
Vector3::ZERO
} else {
self.bounds.min
};
(
move |p| sampler.solid_at(p, half, p.x - origin.x) > 0.0,
origin,
cell * cells as f32,
resolution.max(2).saturating_mul(cells),
)
}
fn occupancy(&self, samples_per_cell: usize) -> f32 {
self.occupancy_on(&self.density_grid(samples_per_cell))
}
fn density_grid(&self, samples_per_cell: usize) -> DensityGrid {
let cell = self.resolved_cell();
let size = self.bounds.size();
let mut res = samples_per_cell.max(2) as f32;
let count =
|extent: f32, cell: f32, res: f32| (((extent / cell) * res).ceil() as usize).max(1);
let mut dims = [
count(size.x, cell.x, res),
count(size.y, cell.y, res),
count(size.z, cell.z, res),
];
let budget = self.max_samples.min(Self::DENSITY_SAMPLES);
let floor = Self::DENSITY_MIN.min(budget);
let resize = |res: f32| {
[
count(size.x, cell.x, res),
count(size.y, cell.y, res),
count(size.z, cell.z, res),
]
};
for _ in 0..32 {
let total = dims[0].saturating_mul(dims[1]).saturating_mul(dims[2]);
let scale = if total > budget {
(budget as f64 / total as f64).cbrt().clamp(1e-9, 0.95)
} else if total < floor {
(floor as f64 / total as f64).cbrt().max(1.05)
} else {
break;
};
res *= scale as f32;
let next = resize(res);
if next == dims {
break;
}
dims = next;
}
let stride = Vector3::new(
size.x / dims[0] as f32,
size.y / dims[1] as f32,
size.z / dims[2] as f32,
);
let mut points = Vec::with_capacity(dims[0] * dims[1] * dims[2]);
for k in 0..dims[2] {
for j in 0..dims[1] {
for i in 0..dims[0] {
let at = jitter(i, j, k);
points.push(Vector3::new(
self.bounds.min.x + (i as f32 + at[0]) * stride.x,
self.bounds.min.y + (j as f32 + at[1]) * stride.y,
self.bounds.min.z + (k as f32 + at[2]) * stride.z,
));
}
}
}
let cuts = match self.trim.as_deref() {
Some(trim) => crate::utils::parallel::par_map(&points, |p| trim(*p)),
None => Vec::new(),
};
DensityGrid { points, cuts, cell }
}
fn occupancy_on(&self, grid: &DensityGrid) -> f32 {
if grid.points.is_empty() {
return 0.0;
}
let sampler = self.sampler(grid.cell, Vector3::ZERO, false);
let chunk = grid.points.len().div_ceil(64).max(1);
let counts =
crate::utils::parallel::par_map_range(grid.points.len().div_ceil(chunk), |c| {
let lo = c * chunk;
let hi = (lo + chunk).min(grid.points.len());
let (mut solid, mut part) = (0usize, 0usize);
for n in lo..hi {
let cut = grid.cuts.get(n).copied();
if cut.is_none_or(|c| c > 0.0) {
part += 1;
if sampler.value_at(grid.points[n], cut) > 0.0 {
solid += 1;
}
}
}
(solid, part)
});
let (solid, part) = counts
.iter()
.fold((0usize, 0usize), |acc, c| (acc.0 + c.0, acc.1 + c.1));
if part == 0 {
return 0.0;
}
solid as f32 / part as f32
}
}
struct DensityGrid {
points: Vec<Vector3>,
cuts: Vec<f32>,
cell: Vector3,
}
fn jitter(i: usize, j: usize, k: usize) -> [f32; 3] {
let mut h = (i as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15)
^ (j as u64).wrapping_mul(0xbf58_476d_1ce4_e5b9)
^ (k as u64).wrapping_mul(0x94d0_49bb_1331_11eb);
let mut out = [0.0f32; 3];
for axis in &mut out {
h ^= h >> 33;
h = h.wrapping_mul(0xff51_afd7_ed55_8ccd);
h ^= h >> 33;
*axis = (h >> 40) as f32 / (1u32 << 24) as f32;
}
out
}
#[derive(Clone, Copy)]
enum Pre<'a> {
Tpms([(f32, f32); 3]),
Waves(&'a [(f32, f32)]),
}
struct Sampler<'a> {
kind: LatticeKind,
style: LatticeStyle,
phase: Vector3,
cell: Vector3,
omega: Vector3,
half: f32,
margin: f32,
skin: f32,
bounds: Box3,
grade: Option<&'a (dyn Fn(Vector3) -> f32 + Sync + Send)>,
trim: Option<&'a (dyn Fn(Vector3) -> f32 + Sync + Send)>,
clip: Option<&'a (dyn Fn(Vector3) -> f32 + Sync + Send)>,
cuboct_shape: f32,
cuboct_rule: Option<ChiralRule>,
cuboct_n: i32,
cuboct_program: Option<&'a (dyn Fn(i32, i32, i32) -> Cuboct + Sync + Send)>,
cuboct_cached: Option<Vec<Segment>>,
strut_bins: Option<strut::Bins>,
seed_table: Option<stochastic::SeedTable>,
conform: Option<&'a Conform<'a>>,
jitter: f32,
seed: u32,
turing: Option<std::sync::Arc<stochastic::Turing>>,
seed_graph: Option<std::sync::Arc<stochastic::SeedGraph>>,
edge_bins: Option<stochastic::EdgeBins>,
seed_weights: Vec<f64>,
seed_sites: Vec<[f64; 3]>,
plateau_border: f32,
waves: Option<Vec<stochastic::Wave>>,
}
impl Sampler<'_> {
#[cfg(test)]
fn value(&self, p: Vector3) -> f32 {
self.value_trig(p, None)
}
fn value_trig(&self, p: Vector3, pre: Option<Pre<'_>>) -> f32 {
self.value_at_trig(p, self.trim.map(|t| t(p)), pre)
}
fn value_at(&self, p: Vector3, cut: Option<f32>) -> f32 {
self.value_at_trig(p, cut, None)
}
fn value_at_trig(&self, p: Vector3, cut: Option<f32>, pre: Option<Pre<'_>>) -> f32 {
let half = match self.grade {
Some(g) => self.half * g(p).max(0.0),
None => self.half,
};
let mut boundary = self.box_distance(p);
let mut depth = self.plan_distance(p);
if let Some(cut) = cut {
boundary = boundary.min(cut);
depth = depth.min(cut);
}
let filled = self.solid_at_trig(p, half, depth, pre).min(boundary);
let clip = |v: f32| match self.clip {
Some(c) => v.min(c(p)),
None => v,
};
if self.skin <= 0.0 {
return clip(filled);
}
clip(filled.max(boundary.min(self.skin - boundary)))
}
fn solid_at(&self, p: Vector3, half: f32, depth: f32) -> f32 {
self.solid_at_trig(p, half, depth, None)
}
fn solid_at_trig(&self, p: Vector3, half: f32, depth: f32, pre: Option<Pre<'_>>) -> f32 {
let (p, stretch) = match self.conform {
Some(c) => (c.point(p), c.stretch_at(p)),
None => (p, 1.0),
};
let half = half * stretch;
let margin = self.margin * stretch;
let solid = match self.kind {
LatticeKind::Strut(s) => {
let cull = half.max(0.0) + margin;
let d = match &self.strut_bins {
Some(bins) => {
strut::distance_binned(p, self.phase, self.cell, s.segments(), bins, cull)
}
None => strut::distance(p, self.phase, self.cell, s.segments(), cull),
};
half - d
}
LatticeKind::Cuboct(c) => {
let cull = half.max(0.0) + margin;
let d = if let Some(ref segs) = self.cuboct_cached {
match &self.strut_bins {
Some(bins) => {
strut::distance_binned(p, self.phase, self.cell, segs, bins, cull)
}
None => strut::distance(p, self.phase, self.cell, segs, cull),
}
} else {
cuboct::distance(
p,
self.phase,
self.cell,
cull,
|i, j, k| match self.cuboct_program {
Some(f) => f(i, j, k),
None => c,
},
self.cuboct_shape,
self.cuboct_rule,
self.cuboct_n,
)
};
half - d
}
LatticeKind::Infill(i) => half - infill::distance(i, p, self.phase, self.cell, depth),
LatticeKind::Tpms(t) => {
let trig = match pre {
Some(Pre::Tpms(trig)) if self.conform.is_none() => trig,
_ => self.tpms_trig(p),
};
let sd = self.tpms_distance_trig(t, trig);
let solid = match self.style {
LatticeStyle::Sheet => half - sd.abs(),
LatticeStyle::Solid => sd + half,
};
match t.clip_radius() {
Some(limit) => {
let per = self.omega.x.max(self.omega.y);
solid.min((limit - tpms::axis_radius(trig)) / per)
}
None => solid,
}
}
LatticeKind::Stochastic(Stochastic::ReactionDiffusion) => {
let u = [
((p.x - self.phase.x) / self.cell.x) as f64,
((p.y - self.phase.y) / self.cell.y) as f64,
((p.z - self.phase.z) / self.cell.z) as f64,
];
let (value, g) = match &self.turing {
Some(t) => t.sample(u),
None => (0.0, [0.0; 3]),
};
let gradient =
Vector3::new(g[0] / self.cell.x, g[1] / self.cell.y, g[2] / self.cell.z);
let sd = value / gradient.length().max(1e-6);
match self.style {
LatticeStyle::Sheet => half - sd.abs(),
LatticeStyle::Solid => sd + half,
}
}
LatticeKind::Stochastic(Stochastic::Hyperuniform) => {
let (value, gradient) =
stochastic::hyperuniform(p, self.phase, self.cell, self.seed);
let sd = value / gradient.length().max(1e-6);
match self.style {
LatticeStyle::Sheet => half - sd.abs(),
LatticeStyle::Solid => sd + half,
}
}
LatticeKind::Stochastic(s) if s.is_field() => {
let sd = match pre {
Some(Pre::Waves(sc)) if self.conform.is_none() => {
let waves = self.waves.as_deref().unwrap_or(&[]);
let (value, gradient) = stochastic::value_and_gradient_sc(waves, sc);
value / gradient.length().max(1e-6)
}
_ => self.spinodal_distance(p),
};
match self.style {
LatticeStyle::Sheet => half - sd.abs(),
LatticeStyle::Solid => sd + half,
}
}
LatticeKind::Stochastic(Stochastic::VoronoiWet) => {
let skeleton = stochastic::Skeleton::Wet {
border: self.plateau_border * stretch,
};
let cap = half.max(0.0) + margin;
let graph = if self.seed_weights.is_empty() {
None
} else {
self.graph_distance(p, skeleton, cap, f32::NEG_INFINITY)
};
let w = graph.unwrap_or_else(|| {
stochastic::voronoi_distance(
p,
self.phase,
self.cell,
skeleton,
self.jitter,
self.seed,
&self.seed_sites,
cap,
f32::NEG_INFINITY,
self.seed_table.as_ref(),
)
});
w + half
}
LatticeKind::Stochastic(s) if !self.seed_weights.is_empty() => {
let wall = s == Stochastic::VoronoiWall;
let skeleton = if wall {
stochastic::Skeleton::Walls
} else {
stochastic::Skeleton::Edges
};
let cap = half.max(0.0) + margin;
let d = self
.edge_bin_distance(p, skeleton, cap)
.or_else(|| self.graph_distance(p, skeleton, cap, f32::NEG_INFINITY))
.unwrap_or_else(|| {
stochastic::power_distance(
p,
self.phase,
self.cell,
wall,
&self.seed_sites,
&self.seed_weights,
cap,
)
});
half - d
}
LatticeKind::Stochastic(s) => {
let skeleton = if s == Stochastic::VoronoiWall {
stochastic::Skeleton::Walls
} else {
stochastic::Skeleton::Edges
};
let (cap, floor) = (half.max(0.0) + margin, half - margin);
let graph = if skeleton == stochastic::Skeleton::Walls {
self.graph_distance(p, skeleton, cap, floor)
} else {
self.edge_bin_distance(p, skeleton, cap)
};
let d = graph.unwrap_or_else(|| {
stochastic::voronoi_distance(
p,
self.phase,
self.cell,
skeleton,
self.jitter,
self.seed,
&self.seed_sites,
cap,
floor,
self.seed_table.as_ref(),
)
});
half - d
}
};
solid / stretch
}
fn edge_bin_distance(
&self,
p: Vector3,
skeleton: stochastic::Skeleton,
cap: f32,
) -> Option<f32> {
if skeleton != stochastic::Skeleton::Edges || self.conform.is_some() {
return None;
}
let rel = [
(p.x - self.phase.x) as f64,
(p.y - self.phase.y) as f64,
(p.z - self.phase.z) as f64,
];
self.edge_bins.as_ref()?.distance(rel, cap as f64)
}
fn graph_distance(
&self,
p: Vector3,
skeleton: stochastic::Skeleton,
cap: f32,
floor: f32,
) -> Option<f32> {
if self.conform.is_some() {
return None;
}
let graph = self.seed_graph.as_ref()?;
let rel = [
(p.x - self.phase.x) as f64,
(p.y - self.phase.y) as f64,
(p.z - self.phase.z) as f64,
];
graph.distance(rel, skeleton, cap as f64, floor as f64)
}
fn spinodal_distance(&self, p: Vector3) -> f32 {
let waves = self.waves.as_deref().unwrap_or(&[]);
let (value, gradient) = stochastic::value_and_gradient(waves, p - self.phase);
value / gradient.length().max(1e-6)
}
fn tpms_angle(&self, axis: usize, coordinate: f32) -> f32 {
match axis {
0 => (coordinate - self.phase.x) * self.omega.x,
1 => (coordinate - self.phase.y) * self.omega.y,
_ => (coordinate - self.phase.z) * self.omega.z,
}
}
fn tpms_trig(&self, p: Vector3) -> [(f32, f32); 3] {
[
self.tpms_angle(0, p.x).sin_cos(),
self.tpms_angle(1, p.y).sin_cos(),
self.tpms_angle(2, p.z).sin_cos(),
]
}
fn tpms_distance_trig(&self, t: Tpms, trig: [(f32, f32); 3]) -> f32 {
let (value, g) = t.value_and_gradient_trig(trig);
let gradient = Vector3::new(
g[0] * self.omega.x,
g[1] * self.omega.y,
g[2] * self.omega.z,
);
value / gradient.length().max(1e-6)
}
fn plan_distance(&self, p: Vector3) -> f32 {
let lo = self.bounds.min;
let hi = self.bounds.max;
(p.x - lo.x).min(hi.x - p.x).min(p.y - lo.y).min(hi.y - p.y)
}
fn box_distance(&self, p: Vector3) -> f32 {
let lo = self.bounds.min;
let hi = self.bounds.max;
(p.x - lo.x)
.min(hi.x - p.x)
.min(p.y - lo.y)
.min(hi.y - p.y)
.min(p.z - lo.z)
.min(hi.z - p.z)
}
}
pub struct LatticeGeometry;
impl LatticeGeometry {
pub fn new(
kind: LatticeKind,
size: Vector3,
cells: [usize; 3],
thickness: f32,
) -> BufferGeometry {
Lattice::new(kind)
.size(size)
.cells(cells)
.thickness(thickness)
.build()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
fn geom_of(kind: LatticeKind) -> BufferGeometry {
Lattice::new(kind)
.size(Vector3::new(2.0, 2.0, 2.0))
.cells([2, 2, 2])
.thickness(0.14)
.resolution(12)
.build()
}
fn assert_watertight(geom: &BufferGeometry, what: &str) {
let index = geom
.index
.as_ref()
.unwrap_or_else(|| panic!("{what}: no index"));
assert!(!index.is_empty(), "{what}: no triangles");
let mut edges: HashMap<(u32, u32), i32> = HashMap::new();
for t in index.as_chunks::<3>().0 {
for e in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
let (key, dir) = if e.0 < e.1 {
((e.0, e.1), 1)
} else {
((e.1, e.0), -1)
};
*edges.entry(key).or_insert(0) += dir;
}
}
let open = edges.values().filter(|&&v| v != 0).count();
assert_eq!(open, 0, "{what}: {open} unpaired edges");
}
fn build_per_point(lattice: &Lattice) -> BufferGeometry {
let (([nx, ny, nz], origin, step), sampler) = lattice.grid();
let mut values = Vec::with_capacity(nx * ny * nz);
for k in 0..nz {
for j in 0..ny {
for i in 0..nx {
values.push(sampler.value(Vector3::new(
origin.x + i as f32 * step.x,
origin.y + j as f32 * step.y,
origin.z + k as f32 * step.z,
)));
}
}
}
mesher::IsoGrid {
dims: [nx, ny, nz],
origin,
step,
values,
}
.triangulate()
}
#[test]
fn grid_tables_reproduce_per_point_sampling() {
let lattice = |kind| {
Lattice::new(kind)
.size(Vector3::new(6.0, 5.0, 4.0))
.cells([3, 2, 2])
.thickness(0.4)
.resolution(10)
};
let exact = Tpms::ALL
.into_iter()
.map(LatticeKind::Tpms)
.chain(Strut::ALL.into_iter().map(LatticeKind::Strut))
.chain(Cuboct::ALL.into_iter().map(LatticeKind::Cuboct));
for kind in exact {
let l = lattice(kind);
let (fast, slow) = (l.build(), build_per_point(&l));
assert_eq!(fast.index, slow.index, "{kind:?}");
assert_eq!(
fast.get_attribute("position").unwrap().array,
slow.get_attribute("position").unwrap().array,
"{kind:?}"
);
}
for s in Stochastic::ALL.into_iter().filter(|s| s.is_field()) {
let l = lattice(LatticeKind::Stochastic(s));
let (fast, slow) = (l.build(), build_per_point(&l));
assert_eq!(fast.index, slow.index, "{}", s.name());
let step = l.grid().0 .2.x;
let moved = fast
.get_attribute("position")
.unwrap()
.array
.iter()
.zip(&slow.get_attribute("position").unwrap().array)
.map(|(a, b)| (a - b).abs())
.fold(0.0f32, f32::max);
assert!(moved < 1e-3 * step, "{}: moved {moved}", s.name());
}
}
#[test]
fn drop_specks_takes_debris_and_nothing_else() {
let lattice = |drop| {
Lattice::new(LatticeKind::Stochastic(Stochastic::Spinodal))
.size(Vector3::new(20.0, 20.0, 20.0))
.cells([4, 4, 4])
.seed(3)
.thickness(1.2)
.resolution(12)
.drop_specks(drop)
};
let (all, clean) = (lattice(false).build(), lattice(true).build());
let (before, after) = (
crate::utils::mesh_check::split_pieces(&all),
crate::utils::mesh_check::split_pieces(&clean),
);
assert!(
after.len() < before.len(),
"{} -> {}",
before.len(),
after.len()
);
assert!(crate::utils::mesh_check::edge_report(&clean).is_closed());
assert!((before[0].volume - after[0].volume).abs() < 1e-3 * before[0].volume);
let gyroid = |drop| {
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.resolution(8)
.drop_specks(drop)
.build()
};
assert_eq!(gyroid(true).index, gyroid(false).index);
}
#[test]
fn every_seed_layout_builds_watertight_foams() {
for layout in SeedLayout::ALL {
for kind in [Stochastic::Voronoi, Stochastic::VoronoiWall] {
let lattice = Lattice::new(LatticeKind::Stochastic(kind))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.seed_layout(layout)
.resolution(14)
.fit_relative_density(0.25);
let what = format!("{} {}", layout.name(), kind.name());
let density = lattice.relative_density();
assert!((density - 0.25).abs() < 0.02, "{what}: {density}");
assert_watertight(&lattice.build(), &what);
}
}
}
#[test]
fn grain_fields_build_watertight_at_a_fitted_density() {
let grains = [
Stochastic::GaussianField,
Stochastic::Hyperuniform,
Stochastic::ReactionDiffusion,
];
for kind in grains {
for style in [LatticeStyle::Solid, LatticeStyle::Sheet] {
let lattice = Lattice::new(LatticeKind::Stochastic(kind))
.size(Vector3::new(6.0, 6.0, 6.0))
.cells([3, 3, 3])
.style(style)
.seed(2)
.resolution(14)
.fit_relative_density(0.3);
let what = format!("{} {style:?}", kind.name());
let density = lattice.relative_density();
assert!((density - 0.3).abs() < 0.02, "{what}: {density}");
assert_watertight(&lattice.build(), &what);
}
}
}
#[test]
fn a_wetter_foam_holds_more_liquid() {
let liquid = |border: f32| {
Lattice::new(LatticeKind::Stochastic(Stochastic::VoronoiWet))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.thickness(0.04)
.plateau_border(border)
.resolution(20)
.relative_density()
};
let (dry, wet, wetter) = (liquid(0.1), liquid(0.25), liquid(0.45));
assert!(dry < wet && wet < wetter, "{dry} {wet} {wetter}");
for layout in [SeedLayout::Random, SeedLayout::Kelvin] {
let lattice = Lattice::new(LatticeKind::Stochastic(Stochastic::VoronoiWet))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.seed_layout(layout)
.plateau_border(0.3)
.resolution(16)
.fit_relative_density(0.15);
let what = format!("wet {}", layout.name());
let density = lattice.relative_density();
assert!((density - 0.15).abs() < 0.02, "{what}: {density}");
assert_watertight(&lattice.build(), &what);
}
}
#[test]
fn the_seed_graph_builds_the_same_foam_as_the_search() {
let layouts = [
SeedLayout::Random,
SeedLayout::Kelvin,
SeedLayout::Relaxed,
SeedLayout::Bimodal,
];
for layout in layouts {
for kind in [
Stochastic::Voronoi,
Stochastic::VoronoiWall,
Stochastic::VoronoiWet,
] {
if kind == Stochastic::VoronoiWet && layout == SeedLayout::Bimodal {
continue;
}
let thickness = if kind == Stochastic::VoronoiWet {
0.3
} else {
0.2
};
let l = Lattice::new(LatticeKind::Stochastic(kind))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.seed_layout(layout)
.plateau_border(0.25)
.thickness(thickness)
.resolution(12);
let graph = build_per_point(&l);
let (([nx, ny, nz], origin, step), mut sampler) = l.grid();
sampler.seed_graph = None;
sampler.edge_bins = None;
let mut values = Vec::with_capacity(nx * ny * nz);
for k in 0..nz {
for j in 0..ny {
for i in 0..nx {
values.push(sampler.value(Vector3::new(
origin.x + i as f32 * step.x,
origin.y + j as f32 * step.y,
origin.z + k as f32 * step.z,
)));
}
}
}
let grid = mesher::IsoGrid {
dims: [nx, ny, nz],
origin,
step,
values,
};
let search = grid.triangulate();
let what = format!("{} {}", layout.name(), kind.name());
assert_eq!(graph.index, search.index, "{what}");
let moved = graph
.get_attribute("position")
.unwrap()
.array
.iter()
.zip(&search.get_attribute("position").unwrap().array)
.map(|(a, b)| (a - b).abs())
.fold(0.0f32, f32::max);
assert!(moved < 1e-5 * step.x, "{what}: moved {moved}");
}
}
}
#[test]
fn every_tpms_builds_watertight() {
for t in Tpms::ALL {
let kind = LatticeKind::Tpms(t);
assert_watertight(&geom_of(kind), t.name());
}
}
#[test]
fn every_strut_builds_watertight() {
for s in Strut::ALL {
let kind = LatticeKind::Strut(s);
assert_watertight(&geom_of(kind), s.name());
}
}
#[test]
fn every_infill_builds_watertight() {
for i in Infill::ALL {
let kind = LatticeKind::Infill(i);
assert_watertight(&geom_of(kind), i.name());
}
}
#[test]
fn every_cuboct_builds_watertight() {
for c in Cuboct::ALL {
let kind = LatticeKind::Cuboct(c);
assert_watertight(&geom_of(kind), c.name());
}
}
#[test]
fn a_programmed_chiral_column_builds_watertight() {
let m = 4i32;
let geom = Lattice::new(LatticeKind::Cuboct(Cuboct::ChiralCcw))
.size(Vector3::new(2.0, 2.0, 4.0))
.cells([2, 2, 4])
.thickness(0.14)
.resolution(12)
.chiral_rule(ChiralRule::R2)
.program(move |_, _, k| Cuboct::column_half(k, m))
.build();
assert_watertight(&geom, "chiral column");
}
#[test]
fn a_ring_of_cells_closes_on_itself() {
let radius = 12.0f32;
let count = 16usize;
let axis = Vector3::new(0.0, 0.0, 1.0);
let worst_of = |pitch: f32| {
let lattice = Lattice::new(LatticeKind::Strut(Strut::Cubic))
.size(Vector3::new(30.0, 30.0, 10.0))
.conform(Conform::cylindrical(Vector3::ZERO, axis, radius))
.cell_size(Vector3::new(pitch, 3.0, 2.0))
.thickness(0.6);
let cell = lattice.resolved_cell();
let sampler = lattice.sampler(cell, Vector3::new(0.05, 0.05, 0.05), false);
let half = sampler.half;
let angle = TAU / count as f32;
let (sin, cos) = angle.sin_cos();
let mut worst = 0.0f32;
for i in 0..40 {
let t = i as f32 / 40.0;
let r = radius - 2.0 + 4.0 * t;
let a = t * 2.3;
let p = Vector3::new(r * a.cos(), r * a.sin(), t * 6.0 - 3.0);
let turned = Vector3::new(p.x * cos - p.y * sin, p.x * sin + p.y * cos, p.z);
let here = sampler.solid_at(p, half, f32::INFINITY);
let there = sampler.solid_at(turned, half, f32::INFINITY);
worst = worst.max((here - there).abs());
}
worst
};
assert!(
worst_of(Conform::ring_pitch(radius, count)) < 1e-4,
"a turn of one cell moved the lattice: {}",
worst_of(Conform::ring_pitch(radius, count))
);
assert!(
worst_of(Conform::ring_pitch(radius, count) * 1.3) > 1e-3,
"an ill-fitting pitch closed anyway"
);
}
#[test]
fn a_depth_map_stacks_whole_layers_through_a_curved_wall() {
let outer = 10.0f32;
let cell_z = 2.0f32;
let build = |conform: bool| {
let mut lattice = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(20.0, 20.0, 20.0))
.cell_size(Vector3::new(4.0, 4.0, cell_z))
.thickness(0.5);
if conform {
lattice = lattice.conform(Conform::depth(Region::sphere(Vector3::ZERO, outer)));
}
let cell = lattice.resolved_cell();
let sampler = lattice.sampler(cell, Vector3::new(0.05, 0.05, 0.05), false);
let half = sampler.half;
let (a, b) = (1.0f32, 1.0f32);
let at = |r: f32| {
let z = (r * r - a * a - b * b).sqrt();
sampler.solid_at(Vector3::new(a, b, z), half, f32::INFINITY)
};
(at(8.0), at(8.0 - cell_z))
};
let (near, deep) = build(true);
assert!(
(near - deep).abs() < 1e-3,
"the layers did not line up: {near} vs {deep}"
);
let (near, deep) = build(false);
assert!(
(near - deep).abs() > 1e-3,
"world-space cells lined up by accident: {near} vs {deep}"
);
}
#[test]
fn every_foam_fits_a_density_target() {
for cell in Stochastic::ALL {
let lattice = Lattice::new(LatticeKind::Stochastic(cell))
.size(Vector3::new(12.0, 12.0, 12.0))
.cells([4, 4, 4])
.seed(7)
.fit_relative_density(0.25);
assert!(
(lattice.relative_density() - 0.25).abs() < 0.02,
"{}: {}",
cell.name(),
lattice.relative_density()
);
assert_watertight(&lattice.resolution(12).build(), cell.name());
}
}
#[test]
fn two_seeds_are_two_foams_of_the_same_density() {
let build = |seed: u32| {
Lattice::new(LatticeKind::Stochastic(Stochastic::Voronoi))
.size(Vector3::new(10.0, 10.0, 10.0))
.cells([3, 3, 3])
.seed(seed)
.fit_relative_density(0.2)
};
let a = build(1);
let b = build(2);
assert!((a.relative_density() - b.relative_density()).abs() < 0.02);
let cell = a.resolved_cell();
let step = Vector3::new(0.05, 0.05, 0.05);
let (sa, sb) = (a.sampler(cell, step, false), b.sampler(cell, step, false));
let differs = (0..50).any(|i| {
let t = i as f32 * 0.17;
let p = Vector3::new(t.sin() * 4.0, t.cos() * 4.0, t * 0.1);
(sa.value(p) - sb.value(p)).abs() > 1e-3
});
assert!(differs, "two seeds made the same foam");
}
#[test]
fn jitter_zero_is_a_periodic_foam() {
let build = |jitter: f32| {
Lattice::new(LatticeKind::Stochastic(Stochastic::VoronoiWall))
.size(Vector3::new(9.0, 9.0, 9.0))
.cells([3, 3, 3])
.jitter(jitter)
.seed(4)
.thickness(0.4)
};
let cell = Vector3::new(3.0, 3.0, 3.0);
let step = Vector3::new(0.05, 0.05, 0.05);
let p = Vector3::new(0.7, -1.1, 0.4);
let shifted = p + cell;
for (jitter, want_same) in [(0.0f32, true), (1.0, false)] {
let lattice = build(jitter);
let sampler = lattice.sampler(cell, step, false);
let half = sampler.half;
let a = sampler.solid_at(p, half, f32::INFINITY);
let b = sampler.solid_at(shifted, half, f32::INFINITY);
assert_eq!(
(a - b).abs() < 1e-4,
want_same,
"jitter {jitter}: {a} vs {b}"
);
}
}
#[test]
fn a_stretch_dominated_cell_beats_a_bending_dominated_one() {
let modulus = |strut: Strut| {
Lattice::new(LatticeKind::Strut(strut))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([1, 1, 1])
.fit_relative_density(0.25)
.homogenize(12)
.youngs_moduli()[2]
};
let octet = modulus(Strut::Octet);
let bcc = modulus(Strut::Bcc);
assert!(octet > 1.5 * bcc, "octet {octet} vs bcc {bcc}");
assert!(octet < 0.5, "{octet}");
}
#[test]
fn density_buys_stiffness() {
let modulus = |density: f32| {
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([1, 1, 1])
.fit_relative_density(density)
.homogenize(12)
.youngs_moduli()[0]
};
let light = modulus(0.15);
let heavy = modulus(0.45);
assert!(heavy > 2.0 * light, "{light} then {heavy}");
}
#[test]
fn a_lamellar_spinodal_is_anisotropic_and_an_isotropic_one_is_not() {
let measure = |cell: Stochastic| {
Lattice::new(LatticeKind::Stochastic(cell))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([1, 1, 1])
.seed(11)
.fit_relative_density(0.3)
.homogenize(12)
};
let lamellar = measure(Stochastic::SpinodalLamellar);
let e = lamellar.youngs_moduli();
assert!(e[0] > 2.0 * e[2], "in plane {} across {}", e[0], e[2]);
let isotropic = measure(Stochastic::Spinodal);
assert!(
isotropic.anisotropy() < lamellar.anisotropy(),
"isotropic {} vs lamellar {}",
isotropic.anisotropy(),
lamellar.anisotropy()
);
}
#[test]
fn a_field_grades_a_lattice_thicker_where_it_says() {
let size = Vector3::new(20.0, 20.0, 20.0);
let bounds = Box3::from_center_and_size(Vector3::ZERO, size);
let field = Field::scattered(
bounds,
[8, 8, 8],
&[
(Vector3::new(-10.0, 0.0, 0.0), 100.0),
(Vector3::new(10.0, 0.0, 0.0), 0.0),
],
);
let lattice = Lattice::new(LatticeKind::Strut(Strut::Octet))
.bounds(bounds)
.cells([4, 4, 4])
.thickness(0.8)
.grade(field.into_grade(2.0, 0.5));
let cell = lattice.resolved_cell();
let sampler = lattice.sampler(cell, Vector3::new(0.05, 0.05, 0.05), false);
let offset = Vector3::new(0.4, 0.4, 0.4);
let hot = sampler.value(Vector3::new(-7.5, 0.0, 0.0) + offset);
let cold = sampler.value(Vector3::new(7.5, 0.0, 0.0) + offset);
assert!(hot > cold, "hot {hot} cold {cold}");
assert!(lattice.build().index.is_some());
}
#[test]
fn a_continuous_surface_conducts_better_per_gram_than_bars() {
let measure = |kind| {
Lattice::new(kind)
.size(Vector3::new(10.0, 10.0, 10.0))
.cells([1, 1, 1])
.fit_relative_density(0.3)
.conductivity(12)
};
let gyroid = measure(LatticeKind::Tpms(Tpms::Gyroid));
let cubic = measure(LatticeKind::Strut(Strut::Cubic));
assert!(
gyroid.tortuosity_factor(1.0) > cubic.tortuosity_factor(1.0),
"gyroid {} vs cubic {}",
gyroid.tortuosity_factor(1.0),
cubic.tortuosity_factor(1.0)
);
for k in [gyroid, cubic] {
assert!((k.anisotropy() - 1.0).abs() < 0.05, "{}", k.anisotropy());
assert!(k.axes()[0] < k.relative_density, "{:?}", k.axes());
assert!(k.tortuosity_factor(1.0) < 1.0);
}
}
#[test]
fn plates_conduct_along_themselves_and_not_across() {
let k = Lattice::new(LatticeKind::Stochastic(Stochastic::SpinodalLamellar))
.size(Vector3::new(10.0, 10.0, 10.0))
.cells([1, 1, 1])
.seed(7)
.fit_relative_density(0.3)
.conductivity(12);
let along = k.axes();
assert!(along[0] > 0.1, "in plane {}", along[0]);
assert!(along[2] < 0.01, "across {}", along[2]);
assert!(k.anisotropy() > 50.0, "{}", k.anisotropy());
assert!(
k.tortuosity_factor(1.0) > 0.9,
"{}",
k.tortuosity_factor(1.0)
);
let principal = k.principal();
let best_axis = along[0].max(along[1]);
assert!(
principal[0] >= best_axis - 1e-9,
"{principal:?} vs {along:?}"
);
assert!(principal[0] < best_axis * 1.1, "{principal:?} vs {along:?}");
}
#[test]
fn every_generator_homogenizes_to_a_real_material() {
for kind in LatticeKind::all() {
let lattice = Lattice::new(kind)
.size(Vector3::new(8.0, 8.0, 8.0))
.cells([4, 4, 4])
.seed(3)
.fit_relative_density(0.3);
let c = lattice.homogenize(8);
let name = kind.name();
assert!(
(c.relative_density - 0.3).abs() < 0.1,
"{name}: voxelised to {}",
c.relative_density
);
let e = c.youngs_moduli();
assert!(e.iter().all(|v| v.is_finite()), "{name}: {e:?}");
assert!(
e.iter().any(|&v| v > 0.01),
"{name}: soft in every direction, {e:?}"
);
}
}
#[test]
fn a_grade_is_counted_in_the_wall_it_leaves() {
let build = |graded: bool| {
let lattice = Lattice::new(LatticeKind::Strut(Strut::Octet))
.size(Vector3::new(20.0, 20.0, 20.0))
.cells([4, 4, 4])
.thickness(1.0)
.resolution(10);
if graded {
lattice.grade(|p| if p.x < 0.0 { 0.4 } else { 1.0 })
} else {
lattice
}
};
let plain = build(false).wall_samples();
let graded = build(true).wall_samples();
assert!(
(graded - 0.4 * plain).abs() < 0.05 * plain,
"plain {plain} graded {graded}"
);
let resolved = build(true).resolve_walls(3.0);
assert!(
resolved.wall_samples() >= 3.0,
"{}",
resolved.wall_samples()
);
let nominal = build(false).resolve_walls(3.0);
assert!(
resolved.sample_grid()[0] > nominal.sample_grid()[0],
"{:?} vs {:?}",
resolved.sample_grid(),
nominal.sample_grid()
);
}
#[test]
fn a_region_can_be_used_twice() {
let shell =
Region::sphere(Vector3::ZERO, 8.0).difference(Region::sphere(Vector3::ZERO, 5.0));
let geom = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.conform(Conform::depth(shell.clone()))
.fill(shell)
.cell_size(Vector3::new(3.0, 3.0, 1.5))
.thickness(0.4)
.resolution(10)
.build();
assert_watertight(&geom, "shell used twice");
}
#[test]
fn a_stretching_cell_uses_more_of_itself_than_a_bending_one() {
let measure = |strut| {
Lattice::new(LatticeKind::Strut(strut))
.size(Vector3::new(10.0, 10.0, 10.0))
.cells([1, 1, 1])
.fit_relative_density(0.3)
.strength(16)
};
let octet = measure(Strut::Octet);
let bcc = measure(Strut::Bcc);
assert!(
octet.resolved(),
"octet unresolved: {:?}",
octet.efficiency()
);
assert!(bcc.resolved(), "bcc unresolved: {:?}", bcc.efficiency());
assert!(
octet.efficiency()[2] > bcc.efficiency()[2],
"octet {:?} bcc {:?}",
octet.efficiency(),
bcc.efficiency()
);
let at_500 = octet.uniaxial(500.0)[2];
let at_1000 = octet.uniaxial(1000.0)[2];
assert!((at_1000 - 2.0 * at_500).abs() < 1e-6);
assert!(at_500 > 0.0 && at_500 < 500.0 * 0.3, "{at_500}");
assert!(octet.stiffness.youngs_moduli()[2] > 0.0);
assert_eq!(octet.stiffness.voxels, 16);
}
#[test]
fn every_generator_is_named_once() {
let all = LatticeKind::all();
assert_eq!(
all.len(),
Tpms::ALL.len()
+ Strut::ALL.len()
+ Infill::ALL.len()
+ Cuboct::ALL.len()
+ Stochastic::ALL.len()
);
let mut names: Vec<&str> = all.iter().map(|k| k.name()).collect();
names.sort_unstable();
let before = names.len();
names.dedup();
assert_eq!(before, names.len(), "duplicate generator name");
for kind in all {
assert_eq!(LatticeKind::from_name(kind.name()), Some(kind));
}
assert_eq!(LatticeKind::from_name("gyroidal"), None);
}
#[test]
fn building_twice_gives_the_same_mesh() {
let build = || {
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(3.0, 3.0, 3.0))
.cells([3, 3, 3])
.thickness(0.2)
.resolution(14)
.trim(|p| 1.4 - p.length())
.build()
};
let (a, b) = (build(), build());
assert_eq!(a.index, b.index);
for name in ["position", "normal", "uv"] {
assert_eq!(
a.get_attribute(name).unwrap().array,
b.get_attribute(name).unwrap().array,
"{name} differs between builds"
);
}
}
#[test]
fn resolve_walls_puts_samples_across_the_wall() {
let thin = Lattice::new(LatticeKind::Tpms(Tpms::Lidinoid))
.size(Vector3::new(20.0, 20.0, 20.0))
.cells([3, 3, 3])
.thickness(0.25);
assert!(thin.wall_samples() < 1.0, "{}", thin.wall_samples());
let resolved = Lattice::new(LatticeKind::Tpms(Tpms::Lidinoid))
.size(Vector3::new(20.0, 20.0, 20.0))
.cells([3, 3, 3])
.thickness(0.25)
.max_samples(64_000_000)
.resolve_walls(4.0);
assert!(
resolved.wall_samples() >= 4.0,
"only {} samples",
resolved.wall_samples()
);
assert!(resolved.sample_grid()[0] > thin.sample_grid()[0]);
}
#[test]
fn the_sample_budget_still_wins_over_resolve_walls() {
let lattice = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(20.0, 20.0, 20.0))
.cells([3, 3, 3])
.thickness(0.05)
.max_samples(150_000)
.resolve_walls(8.0);
let dims = lattice.sample_grid();
assert!(dims[0] * dims[1] * dims[2] <= 150_000, "{dims:?}");
assert!(lattice.wall_samples() < 8.0);
}
#[test]
fn solid_style_builds_watertight() {
for t in [Tpms::Gyroid, Tpms::SchwarzP, Tpms::IWP] {
let geom = Lattice::new(LatticeKind::Tpms(t))
.size(Vector3::new(2.0, 2.0, 2.0))
.cells([2, 2, 2])
.style(LatticeStyle::Solid)
.thickness(0.0)
.resolution(12)
.build();
assert_watertight(&geom, t.name());
}
}
#[test]
fn geometry_stays_inside_the_bounds() {
let geom = geom_of(LatticeKind::Tpms(Tpms::Gyroid));
let pos = geom.get_attribute("position").unwrap();
for v in pos.array.as_chunks::<3>().0 {
for a in v {
assert!(a.abs() <= 1.0 + 1e-3, "{a} escapes the box");
}
}
}
#[test]
fn attributes_are_complete() {
let geom = geom_of(LatticeKind::Strut(Strut::Octet));
let count = geom.get_attribute("position").unwrap().count();
assert_eq!(geom.get_attribute("normal").unwrap().count(), count);
assert_eq!(geom.get_attribute("uv").unwrap().count(), count);
for i in geom.index.as_ref().unwrap() {
assert!((*i as usize) < count);
}
}
#[test]
fn thicker_walls_mean_more_material() {
let base = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2]);
let thin = base.thickness(0.2).relative_density();
let thick = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.thickness(0.6)
.relative_density();
assert!(thin < thick, "{thin} !< {thick}");
assert!(thin > 0.0 && thick < 1.0);
}
#[test]
fn density_fit_lands_on_target() {
for kind in [
LatticeKind::Tpms(Tpms::Gyroid),
LatticeKind::Tpms(Tpms::Diamond),
LatticeKind::Strut(Strut::Octet),
LatticeKind::Strut(Strut::Bcc),
LatticeKind::Cuboct(Cuboct::Rigid),
LatticeKind::Infill(Infill::Grid),
LatticeKind::Infill(Infill::Honeycomb),
] {
for target in [0.2f32, 0.45] {
let lattice = Lattice::new(kind)
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.fit_relative_density(target);
let got = lattice.relative_density();
assert!(
(got - target).abs() < 0.01,
"{} wanted {target}, got {got} at thickness {}",
kind.name(),
lattice.current_thickness()
);
assert!(lattice.current_thickness() > 0.0);
}
}
}
#[test]
fn every_tpms_builds_solid_as_well_as_sheet() {
for t in Tpms::ALL {
let geom = Lattice::new(LatticeKind::Tpms(t))
.size(Vector3::new(2.0, 2.0, 2.0))
.cells([2, 2, 2])
.style(LatticeStyle::Solid)
.thickness(0.0)
.resolution(12)
.build();
assert_watertight(&geom, t.name());
}
}
#[test]
fn solid_density_climbs_with_the_offset() {
for t in [Tpms::Gyroid, Tpms::Diamond, Tpms::IWP] {
let density = |offset: f32| {
Lattice::new(LatticeKind::Tpms(t))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.style(LatticeStyle::Solid)
.thickness(offset)
.relative_density()
};
let steps: Vec<f32> = [-1.5f32, -0.75, 0.0, 0.75, 1.5]
.into_iter()
.map(density)
.collect();
for pair in steps.windows(2) {
assert!(
pair[1] > pair[0],
"{}: density went {:?} as the offset grew",
t.name(),
steps
);
}
assert!(steps[0] < 0.2 && *steps.last().unwrap() > 0.8, "{steps:?}");
}
}
#[test]
fn solid_style_fits_a_density_target() {
for t in [Tpms::Gyroid, Tpms::SchwarzP, Tpms::Diamond] {
for target in [0.2f32, 0.5, 0.8] {
let lattice = Lattice::new(LatticeKind::Tpms(t))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.style(LatticeStyle::Solid)
.fit_relative_density(target);
let got = lattice.relative_density();
assert!(
(got - target).abs() < 0.02,
"{} solid wanted {target}, got {got} at offset {}",
t.name(),
lattice.current_thickness()
);
}
}
}
#[test]
fn a_solid_lattice_fills_a_region_and_takes_a_skin() {
let geom = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.fill(Region::sphere(Vector3::ZERO, 3.0))
.cells([2, 2, 2])
.style(LatticeStyle::Solid)
.thickness(0.0)
.resolution(14)
.skin(0.3)
.build();
assert_watertight(&geom, "solid in a sphere with a skin");
let pos = geom.get_attribute("position").unwrap();
for v in pos.array.as_chunks::<3>().0 {
let r = Vector3::new(v[0], v[1], v[2]).length();
assert!(r <= 3.05, "{r} escaped the sphere");
}
}
#[test]
fn the_wall_guard_knows_a_solid_lattice_has_no_wall() {
let solid = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.style(LatticeStyle::Solid)
.thickness(0.05);
assert!(
solid.wall_samples().is_infinite(),
"a solid lattice has no wall to resolve, got {}",
solid.wall_samples()
);
let asked = solid.resolution;
assert_eq!(
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.style(LatticeStyle::Solid)
.thickness(0.05)
.resolve_walls(2.5)
.resolution,
asked,
"resolve_walls should leave a solid lattice alone"
);
let sheet = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.thickness(0.05);
assert!(sheet.wall_samples().is_finite() && sheet.wall_samples() < 1.0);
}
#[test]
fn the_density_fit_reaches_targets_outside_one_cell_of_thickness() {
for (style, targets) in [
(LatticeStyle::Sheet, [0.02f32, 0.97]),
(LatticeStyle::Solid, [0.02, 0.97]),
] {
for target in targets {
let lattice = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.style(style)
.fit_relative_density(target);
let got = lattice.relative_density();
assert!(
(got - target).abs() < 0.02,
"{style:?} wanted {target}, got {got} at {}",
lattice.current_thickness()
);
}
}
}
#[test]
fn grading_a_solid_lattice_needs_an_offset_to_scale() {
let halves = |offset: f32| {
let side = |lo: f32, hi: f32| {
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.bounds(Box3::new(
Vector3::new(lo, -1.0, -1.0),
Vector3::new(hi, 1.0, 1.0),
))
.cell_size(Vector3::new(1.0, 1.0, 1.0))
.style(LatticeStyle::Solid)
.thickness(offset)
.grade(|p| (p.x + 2.0) * 0.5)
.relative_density()
};
(side(-2.0, 0.0), side(0.0, 2.0))
};
let (left, right) = halves(0.0);
assert!((left - right).abs() < 1e-6, "{left} vs {right}");
let (left, right) = halves(0.3);
assert!(right > left + 0.1, "{left} vs {right}");
}
#[test]
fn every_combination_comes_out_closed() {
for kind in LatticeKind::all() {
for style in [LatticeStyle::Sheet, LatticeStyle::Solid] {
let solid_tpms = style == LatticeStyle::Solid
&& match kind {
LatticeKind::Tpms(_) => true,
LatticeKind::Stochastic(s) => s.is_field(),
_ => false,
};
for skin in [0.0f32, 0.25] {
for filled in [false, true] {
let lattice = Lattice::new(kind)
.size(Vector3::new(3.0, 3.0, 3.0))
.cells([2, 2, 2])
.style(style)
.thickness(if solid_tpms { 0.0 } else { 0.35 })
.resolution(10)
.skin(skin);
let lattice = if filled {
lattice.fill(Region::sphere(Vector3::ZERO, 1.5))
} else {
lattice
};
let geom = lattice.build();
let what = format!("{} {style:?} skin={skin} fill={filled}", kind.name());
assert_watertight(&geom, &what);
for name in ["position", "normal", "uv"] {
let attr = geom.get_attribute(name).unwrap();
assert!(
attr.array.iter().all(|v| v.is_finite()),
"{what}: non-finite {name}"
);
}
}
}
}
}
}
#[test]
fn degenerate_settings_produce_a_mesh_or_nothing_but_never_a_panic() {
let cases: Vec<(&str, Lattice<'_>)> = vec![
(
"no cells",
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(2.0, 2.0, 2.0))
.cells([0, 0, 0])
.thickness(0.2),
),
(
"no size",
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::ZERO)
.cells([2, 2, 2])
.thickness(0.2),
),
(
"inside-out bounds",
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(-2.0, -2.0, -2.0))
.cells([2, 2, 2])
.thickness(0.2),
),
(
"thickness past the cell",
Lattice::new(LatticeKind::Strut(Strut::Bcc))
.size(Vector3::new(2.0, 2.0, 2.0))
.cells([2, 2, 2])
.thickness(500.0)
.resolution(8),
),
];
for (what, lattice) in cases {
let geom = lattice.build();
if let Some(pos) = geom.get_attribute("position") {
assert!(
pos.array.iter().all(|v| v.is_finite()),
"{what}: non-finite position"
);
}
assert!(lattice.relative_density().is_finite(), "{what}: density");
}
}
#[test]
fn solid_style_at_zero_thickness_is_half_dense() {
let density = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.style(LatticeStyle::Solid)
.thickness(0.0)
.relative_density();
assert!((density - 0.5).abs() < 0.05, "{density}");
}
#[test]
fn grading_moves_material_across_the_part() {
let half = |lo: f32, hi: f32| {
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.bounds(Box3::new(
Vector3::new(lo, -1.0, -1.0),
Vector3::new(hi, 1.0, 1.0),
))
.cell_size(Vector3::new(1.0, 1.0, 1.0))
.thickness(0.2)
.grade(|p| (p.x + 2.0) * 0.5)
.relative_density()
};
let (left, right) = (half(-2.0, 0.0), half(0.0, 2.0));
assert!(
right > left * 2.0,
"grading did not bias the wall: {left} / {right}"
);
let geom = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 2.0, 2.0))
.cell_size(Vector3::new(1.0, 1.0, 1.0))
.thickness(0.2)
.resolution(12)
.grade(|p| (p.x + 2.0) * 0.5)
.build();
assert_watertight(&geom, "graded");
}
#[test]
fn filling_a_region_takes_its_bounds_and_its_shape() {
let radius = 3.0f32;
let lattice = Lattice::new(LatticeKind::Strut(Strut::Octet))
.fill(Region::sphere(Vector3::new(1.0, 0.0, -0.5), radius))
.cells([3, 3, 3])
.thickness(0.4)
.resolution(14);
let bounds = Box3::from_center_and_size(
Vector3::new(1.0, 0.0, -0.5),
Vector3::new(1.0, 1.0, 1.0) * (radius * 2.0),
);
assert_eq!(lattice.bounds, bounds);
let geom = lattice.build();
assert_watertight(&geom, "sphere fill");
let pos = geom.get_attribute("position").unwrap();
for v in pos.array.as_chunks::<3>().0 {
let r = (Vector3::new(v[0], v[1], v[2]) - Vector3::new(1.0, 0.0, -0.5)).length();
assert!(r <= radius + 1e-2, "{r} escaped the sphere");
}
}
#[test]
fn an_explicit_box_beats_the_region_either_way_round() {
let want = Box3::new(Vector3::new(-1.0, -1.0, -1.0), Vector3::new(1.0, 1.0, 1.0));
let region = || Region::sphere(Vector3::ZERO, 8.0);
let after = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.fill(region())
.bounds(want);
let before = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.bounds(want)
.fill(region());
assert_eq!(after.bounds, want);
assert_eq!(before.bounds, want);
}
#[test]
fn a_lattice_fills_a_swept_curve() {
use crate::curves::{CatmullRomCurve3, Curve3};
let curve = CatmullRomCurve3::new(vec![
Vector3::new(-3.0, 0.0, 0.0),
Vector3::new(-1.0, 1.5, 0.5),
Vector3::new(1.0, -1.5, -0.5),
Vector3::new(3.0, 0.0, 0.0),
]);
let geom = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.fill(Region::tube(&curve, 1.0, 48))
.cell_size(Vector3::new(0.9, 0.9, 0.9))
.thickness(0.14)
.resolution(12)
.build();
assert_watertight(&geom, "tube fill");
let samples: Vec<Vector3> = (0..=64).map(|i| curve.get_point(i as f32 / 64.0)).collect();
let pos = geom.get_attribute("position").unwrap();
for v in pos.array.as_chunks::<3>().0 {
let p = Vector3::new(v[0], v[1], v[2]);
let near = samples
.iter()
.map(|s| (p - *s).length())
.fold(f32::MAX, f32::min);
assert!(near <= 1.05, "{near} outside the tube");
}
}
#[test]
fn density_is_measured_against_the_part_not_its_box() {
let solid_sphere = Lattice::new(LatticeKind::Strut(Strut::Cubic))
.fill(Region::sphere(Vector3::ZERO, 3.0))
.cells([2, 2, 2])
.thickness(20.0)
.relative_density();
assert!(solid_sphere > 0.99, "{solid_sphere} — the part is full");
let fitted = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.fill(Region::sphere(Vector3::ZERO, 3.0))
.cells([2, 2, 2])
.fit_relative_density(0.7);
assert!((fitted.relative_density() - 0.7).abs() < 0.02);
let boxed = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.fit_relative_density(0.3);
assert!((boxed.relative_density() - 0.3).abs() < 0.02);
}
#[test]
fn a_skin_wraps_the_fill_and_bonds_to_it() {
let plain = Lattice::new(LatticeKind::Strut(Strut::Bcc))
.fill(Region::sphere(Vector3::ZERO, 3.0))
.cells([3, 3, 3])
.thickness(0.3)
.resolution(14);
let bare = plain.relative_density();
let skinned = Lattice::new(LatticeKind::Strut(Strut::Bcc))
.fill(Region::sphere(Vector3::ZERO, 3.0))
.cells([3, 3, 3])
.thickness(0.3)
.resolution(14)
.skin(0.4);
assert!(
skinned.relative_density() > bare,
"a skin adds material: {bare} to {}",
skinned.relative_density()
);
let geom = skinned.build();
assert_watertight(&geom, "skinned");
for dir in [
Vector3::new(1.0, 0.0, 0.0),
Vector3::new(0.0, -1.0, 0.0),
Vector3::new(0.0, 0.0, 1.0),
Vector3::new(0.577, 0.577, 0.577),
] {
let just_inside = dir.normalize() * 2.9;
let just_outside = dir.normalize() * 3.2;
let sampler = skinned.grid().1;
assert!(
sampler.value(just_inside) > 0.0,
"skin has a gap at {dir:?}"
);
assert!(sampler.value(just_outside) < 0.0, "skin bulges at {dir:?}");
}
}
#[test]
fn a_region_with_nothing_in_it_builds_nothing() {
let empty = Region::sphere(Vector3::new(-9.0, 0.0, 0.0), 1.0)
.intersection(Region::sphere(Vector3::new(9.0, 0.0, 0.0), 1.0));
assert!(empty.bounds().is_empty());
let geom = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.fill(empty)
.cells([2, 2, 2])
.thickness(0.1)
.build();
assert!(geom.get_attribute("position").is_none());
}
#[test]
fn a_clip_cuts_after_the_skin_rather_than_before() {
let keep_negative_x = || {
Region::cuboid(Box3::new(
Vector3::new(0.0, -9.0, -9.0),
Vector3::new(9.0, 9.0, 9.0),
))
.invert()
};
let sectioned = Lattice::new(LatticeKind::Strut(Strut::Bcc))
.fill(Region::sphere(Vector3::ZERO, 3.0))
.cells([3, 3, 3])
.thickness(0.5)
.resolution(16)
.skin(0.4)
.clip(keep_negative_x());
let sampler = sectioned.grid().1;
assert!(sampler.value(Vector3::new(-2.9, 0.0, 0.0)) > 0.0);
assert!(sampler.value(Vector3::new(2.9, 0.0, 0.0)) < 0.0);
let void = (0..40)
.map(|i| Vector3::new(-0.05, -2.6 + i as f32 * 0.13, 0.0))
.any(|p| sampler.value(p) < 0.0);
assert!(void, "the cut face was skinned over");
assert_watertight(§ioned.build(), "sectioned");
let whole = Lattice::new(LatticeKind::Strut(Strut::Bcc))
.fill(Region::sphere(Vector3::ZERO, 3.0))
.cells([3, 3, 3])
.thickness(0.5)
.resolution(16)
.skin(0.4);
assert!((sectioned.relative_density() - whole.relative_density()).abs() < 1e-6);
}
#[cfg(feature = "mesh-bvh")]
#[test]
fn a_lattice_fills_a_mesh() {
use crate::geometries::SphereGeometry;
let sphere = SphereGeometry::new(2.0, 32, 24);
let region = Region::mesh(&sphere).expect("a bvh over a sphere");
assert!(region.contains(Vector3::ZERO));
assert!(!region.contains(Vector3::new(3.0, 0.0, 0.0)));
assert!((region.distance(Vector3::ZERO) - 2.0).abs() < 0.05);
let geom = Lattice::new(LatticeKind::Strut(Strut::Octet))
.fill(region)
.cells([2, 2, 2])
.thickness(0.3)
.resolution(12)
.build();
assert_watertight(&geom, "mesh fill");
let pos = geom.get_attribute("position").unwrap();
for v in pos.array.as_chunks::<3>().0 {
let r = Vector3::new(v[0], v[1], v[2]).length();
assert!(r <= 2.05, "{r} escaped the mesh");
}
}
#[cfg(feature = "openscad")]
#[test]
fn a_lattice_fills_a_scad_model() {
let region = Region::scad("difference(){ cube(20, center=true); sphere(12, $fn=32); }")
.expect("valid scad");
assert!(!region.contains(Vector3::ZERO));
assert!(region.contains(Vector3::new(9.0, 9.0, 9.0)));
let geom = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.fill(region)
.cells([3, 3, 3])
.thickness(0.7)
.resolution(10)
.build();
assert_watertight(&geom, "scad fill");
}
#[test]
fn trimming_clips_to_the_field() {
let radius = 0.8f32;
let geom = Lattice::new(LatticeKind::Strut(Strut::Bcc))
.size(Vector3::new(2.0, 2.0, 2.0))
.cells([2, 2, 2])
.thickness(0.16)
.resolution(16)
.trim(move |p| radius - p.length())
.build();
assert_watertight(&geom, "trimmed");
let pos = geom.get_attribute("position").unwrap();
for v in pos.array.as_chunks::<3>().0 {
let r = Vector3::new(v[0], v[1], v[2]).length();
assert!(r <= radius + 1e-2, "{r} outside the trim sphere");
}
}
#[test]
fn anisotropic_cells_stretch_the_pattern() {
let crossings = |geom: &BufferGeometry, axis: usize| {
let pos = geom.get_attribute("position").unwrap();
let mut lo = 0;
for v in pos.array.as_chunks::<3>().0 {
if v[axis] < 0.0 {
lo += 1;
}
}
lo
};
let geom = Lattice::new(LatticeKind::Tpms(Tpms::SchwarzP))
.size(Vector3::new(4.0, 4.0, 4.0))
.cell_size(Vector3::new(4.0, 4.0, 1.0))
.thickness(0.2)
.resolution(10)
.build();
assert_watertight(&geom, "anisotropic");
assert!(crossings(&geom, 0) > 0 && crossings(&geom, 2) > 0);
}
#[test]
fn zero_thickness_makes_nothing() {
let geom = Lattice::new(LatticeKind::Strut(Strut::Cubic))
.size(Vector3::new(2.0, 2.0, 2.0))
.cells([2, 2, 2])
.thickness(0.0)
.build();
assert!(geom.get_attribute("position").is_none());
}
#[test]
fn the_sample_budget_is_respected() {
let lattice = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(100.0, 100.0, 100.0))
.cell_size(Vector3::new(10.0, 10.0, 10.0))
.thickness(2.0)
.resolution(64)
.max_samples(200_000);
let dims = lattice.sample_grid();
let total = dims[0] * dims[1] * dims[2];
assert!(total <= 200_000, "{dims:?} over budget");
assert!(total > 100_000, "{dims:?} gave up too much");
assert!(!lattice.build().index.as_ref().unwrap().is_empty());
}
#[test]
fn the_budget_wins_over_the_sampling_rate() {
let lattice = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(100.0, 100.0, 100.0))
.cell_size(Vector3::new(1.0, 1.0, 1.0))
.max_samples(1_000);
let dims = lattice.sample_grid();
let total = dims[0] * dims[1] * dims[2];
assert!(total <= 1_000, "{dims:?} is {total}, over a budget of 1000");
assert!(lattice.thickness(0.2).wall_samples() < 1.0);
}
#[test]
fn an_unpayable_grid_comes_back_as_a_mesh_rather_than_a_panic() {
for lattice in [
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(2.0, 2.0, 2.0))
.cell_size(Vector3::ZERO)
.thickness(0.2),
Lattice::new(LatticeKind::Strut(Strut::Octet))
.size(Vector3::new(1000.0, 1000.0, 1000.0))
.cell_size(Vector3::new(0.001, 0.001, 0.001))
.thickness(0.0005),
] {
let lattice = lattice.max_samples(200_000);
let dims = lattice.sample_grid();
let total = dims[0] * dims[1] * dims[2];
assert!(total <= 200_000, "{dims:?} is {total}");
let geom = lattice.build();
if let Some(pos) = geom.get_attribute("position") {
assert!(pos.array.iter().all(|v| v.is_finite()));
}
assert!(lattice.relative_density().is_finite());
}
}
#[test]
fn the_one_shot_constructor_matches_the_builder() {
let kind = LatticeKind::Tpms(Tpms::Gyroid);
let size = Vector3::new(2.0, 2.0, 2.0);
let direct = LatticeGeometry::new(kind, size, [2, 2, 2], 0.14);
let built = Lattice::new(kind)
.size(size)
.cells([2, 2, 2])
.thickness(0.14)
.build();
assert_eq!(
direct.get_attribute("position").unwrap().count(),
built.get_attribute("position").unwrap().count()
);
}
}