use crate::aggregate::Aggregate;
use crate::atoms::NodeId;
use crate::containers::mesh::{Mesh, SubMesh};
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use std::collections::HashSet;
pub fn points_in_sphere(
mesh: &Mesh,
center: &[f64],
radius: f64,
tol: Option<f64>,
) -> Result<Mesh> {
let ctx = Context::new(mesh, tol, "points_in_sphere")?;
ctx.check_point(center, "center")?;
ctx.check_radius(radius, "radius")?;
let tol = ctx.tol;
ctx.select(mesh, |x| distance(x, center) <= radius + tol)
}
pub fn points_on_sphere(
mesh: &Mesh,
center: &[f64],
radius: f64,
tol: Option<f64>,
) -> Result<Mesh> {
let ctx = Context::new(mesh, tol, "points_on_sphere")?;
ctx.check_point(center, "center")?;
ctx.check_radius(radius, "radius")?;
let tol = ctx.tol;
ctx.select(mesh, |x| (distance(x, center) - radius).abs() <= tol)
}
pub fn points_on_plane(
mesh: &Mesh,
origin: &[f64],
normal: &[f64],
tol: Option<f64>,
) -> Result<Mesh> {
let ctx = Context::new(mesh, tol, "points_on_plane")?;
ctx.check_point(origin, "origin")?;
let n = ctx.unit_vector(normal, "normal")?;
let tol = ctx.tol;
ctx.select(mesh, |x| signed_gap(x, origin, &n).abs() <= tol)
}
pub fn points_below_plane(
mesh: &Mesh,
origin: &[f64],
normal: &[f64],
tol: Option<f64>,
) -> Result<Mesh> {
let ctx = Context::new(mesh, tol, "points_below_plane")?;
ctx.check_point(origin, "origin")?;
let n = ctx.unit_vector(normal, "normal")?;
let tol = ctx.tol;
ctx.select(mesh, |x| signed_gap(x, origin, &n) <= tol)
}
pub fn points_on_line(mesh: &Mesh, a: &[f64], b: &[f64], tol: Option<f64>) -> Result<Mesh> {
let ctx = Context::new(mesh, tol, "points_on_line")?;
ctx.check_point(a, "a")?;
ctx.check_point(b, "b")?;
let axis = ctx.axis(a, b, "a", "b")?;
let tol = ctx.tol;
ctx.select(mesh, |x| axis.radius_at(x).1 <= tol)
}
pub fn points_in_cylinder(
mesh: &Mesh,
base: &[f64],
top: &[f64],
radius: f64,
tol: Option<f64>,
) -> Result<Mesh> {
let ctx = Context::new(mesh, tol, "points_in_cylinder")?;
ctx.check_point(base, "base")?;
ctx.check_point(top, "top")?;
ctx.check_radius(radius, "radius")?;
let axis = ctx.axis(base, top, "base", "top")?;
let tol = ctx.tol;
ctx.select(mesh, |x| {
let (t, rho) = axis.radius_at(x);
axis.spans(t, tol) && rho <= radius + tol
})
}
pub fn points_on_cylinder(
mesh: &Mesh,
base: &[f64],
top: &[f64],
radius: f64,
tol: Option<f64>,
) -> Result<Mesh> {
let ctx = Context::new(mesh, tol, "points_on_cylinder")?;
ctx.check_point(base, "base")?;
ctx.check_point(top, "top")?;
ctx.check_radius(radius, "radius")?;
let axis = ctx.axis(base, top, "base", "top")?;
let tol = ctx.tol;
ctx.select(mesh, |x| {
let (t, rho) = axis.radius_at(x);
axis.spans(t, tol) && (rho - radius).abs() <= tol
})
}
pub fn points_in_cone(
mesh: &Mesh,
base: &[f64],
top: &[f64],
base_radius: f64,
top_radius: f64,
tol: Option<f64>,
) -> Result<Mesh> {
let ctx = Context::new(mesh, tol, "points_in_cone")?;
ctx.check_point(base, "base")?;
ctx.check_point(top, "top")?;
ctx.check_radius(base_radius, "base_radius")?;
ctx.check_radius(top_radius, "top_radius")?;
let axis = ctx.axis(base, top, "base", "top")?;
let tol = ctx.tol;
ctx.select(mesh, |x| {
let (t, rho) = axis.radius_at(x);
axis.spans(t, tol) && rho <= axis.taper(t, base_radius, top_radius) + tol
})
}
pub fn points_on_cone(
mesh: &Mesh,
base: &[f64],
top: &[f64],
base_radius: f64,
top_radius: f64,
tol: Option<f64>,
) -> Result<Mesh> {
let ctx = Context::new(mesh, tol, "points_on_cone")?;
ctx.check_point(base, "base")?;
ctx.check_point(top, "top")?;
ctx.check_radius(base_radius, "base_radius")?;
ctx.check_radius(top_radius, "top_radius")?;
let axis = ctx.axis(base, top, "base", "top")?;
let tol = ctx.tol;
let k = (top_radius - base_radius) / axis.length;
let band = tol * (1.0 + k * k).sqrt();
ctx.select(mesh, |x| {
let (t, rho) = axis.radius_at(x);
axis.spans(t, tol) && (rho - axis.taper(t, base_radius, top_radius)).abs() <= band
})
}
pub fn points_in_torus(
mesh: &Mesh,
center: &[f64],
axis: &[f64],
major_radius: f64,
minor_radius: f64,
tol: Option<f64>,
) -> Result<Mesh> {
let ctx = Context::new(mesh, tol, "points_in_torus")?;
let torus = ctx.torus(center, axis, major_radius, minor_radius)?;
let tol = ctx.tol;
ctx.select(mesh, |x| torus.gap(x) <= minor_radius + tol)
}
pub fn points_on_torus(
mesh: &Mesh,
center: &[f64],
axis: &[f64],
major_radius: f64,
minor_radius: f64,
tol: Option<f64>,
) -> Result<Mesh> {
let ctx = Context::new(mesh, tol, "points_on_torus")?;
let torus = ctx.torus(center, axis, major_radius, minor_radius)?;
let tol = ctx.tol;
ctx.select(mesh, |x| (torus.gap(x) - minor_radius).abs() <= tol)
}
struct Context {
dim: usize,
tol: f64,
op: &'static str,
}
impl Context {
fn new(mesh: &Mesh, tol: Option<f64>, op: &'static str) -> Result<Self> {
if let Some(t) = tol {
if t < 0.0 || t.is_nan() {
return Err(PyrucastError::Message(format!(
"{op}: tol must be ≥ 0, got {t}"
)));
}
}
if mesh.is_empty() {
return Ok(Self {
dim: 0,
tol: tol.unwrap_or(0.0),
op,
});
}
let dim = mesh.coords()?.read().dim() as usize;
let tol = match tol {
Some(t) => t,
None => default_tol(mesh)?,
};
Ok(Self { dim, tol, op })
}
fn check_point(&self, p: &[f64], name: &str) -> Result<()> {
if self.dim != 0 && p.len() != self.dim {
return Err(PyrucastError::Message(format!(
"{}: {name} has {} coordinates, mesh is {}-D",
self.op,
p.len(),
self.dim
)));
}
Ok(())
}
fn check_radius(&self, r: f64, name: &str) -> Result<()> {
if r < 0.0 || r.is_nan() {
return Err(PyrucastError::Message(format!(
"{}: {name} must be ≥ 0, got {r}",
self.op
)));
}
Ok(())
}
fn unit_vector(&self, v: &[f64], name: &str) -> Result<Vec<f64>> {
self.check_point(v, name)?;
let n = v.iter().map(|c| c * c).sum::<f64>().sqrt();
if n == 0.0 {
return Err(PyrucastError::Message(format!(
"{}: {name} must not be the zero vector",
self.op
)));
}
Ok(v.iter().map(|c| c / n).collect())
}
fn axis(&self, a: &[f64], b: &[f64], a_name: &str, b_name: &str) -> Result<Axis> {
let delta: Vec<f64> = b.iter().zip(a).map(|(bi, ai)| bi - ai).collect();
let length = delta.iter().map(|c| c * c).sum::<f64>().sqrt();
if length == 0.0 {
return Err(PyrucastError::Message(format!(
"{}: {a_name} and {b_name} must not coincide (zero-length axis)",
self.op
)));
}
Ok(Axis {
origin: a.to_vec(),
direction: delta.iter().map(|c| c / length).collect(),
length,
})
}
fn torus(&self, center: &[f64], axis: &[f64], major: f64, minor: f64) -> Result<Torus> {
if self.dim != 0 && self.dim != 3 {
return Err(PyrucastError::Message(format!(
"{}: a torus needs a 3-D mesh, this one is {}-D",
self.op, self.dim
)));
}
self.check_point(center, "center")?;
self.check_radius(major, "major_radius")?;
self.check_radius(minor, "minor_radius")?;
Ok(Torus {
center: center.to_vec(),
axis: self.unit_vector(axis, "axis")?,
major,
})
}
fn select(&self, mesh: &Mesh, keep: impl Fn(&[f64]) -> bool) -> Result<Mesh> {
let mut out = Mesh::empty();
for sm in mesh {
let (coords, nodes) = {
let s = sm.read();
let conn = s.connectivity();
let mut known: HashSet<NodeId> = HashSet::with_capacity(conn.len());
let unique: Vec<NodeId> = conn
.iter()
.copied()
.filter(|&nid| known.insert(nid))
.collect();
(s.coords(), unique)
};
let kept: Vec<NodeId> = {
let c = coords.read();
let mut kept = Vec::new();
for nid in nodes {
if keep(c.position(nid)?) {
kept.push(nid);
}
}
kept
};
out.add_sub(Handle::new(SubMesh::poi1_from_node_ids(coords, &kept)?))?;
}
Ok(out)
}
}
struct Axis {
origin: Vec<f64>,
direction: Vec<f64>,
length: f64,
}
impl Axis {
fn radius_at(&self, x: &[f64]) -> (f64, f64) {
let t: f64 = x
.iter()
.zip(&self.origin)
.zip(&self.direction)
.map(|((xi, oi), di)| (xi - oi) * di)
.sum();
let rho2: f64 = x
.iter()
.zip(&self.origin)
.zip(&self.direction)
.map(|((xi, oi), di)| {
let perp = (xi - oi) - t * di;
perp * perp
})
.sum();
(t, rho2.sqrt())
}
fn spans(&self, t: f64, tol: f64) -> bool {
t >= -tol && t <= self.length + tol
}
fn taper(&self, t: f64, base_radius: f64, top_radius: f64) -> f64 {
let s = (t / self.length).clamp(0.0, 1.0);
base_radius + (top_radius - base_radius) * s
}
}
struct Torus {
center: Vec<f64>,
axis: Vec<f64>,
major: f64,
}
impl Torus {
fn gap(&self, x: &[f64]) -> f64 {
let z: f64 = x
.iter()
.zip(&self.center)
.zip(&self.axis)
.map(|((xi, ci), ai)| (xi - ci) * ai)
.sum();
let rho2: f64 = x
.iter()
.zip(&self.center)
.zip(&self.axis)
.map(|((xi, ci), ai)| {
let radial = (xi - ci) - z * ai;
radial * radial
})
.sum();
let in_plane = rho2.sqrt() - self.major;
(in_plane * in_plane + z * z).sqrt()
}
}
fn distance(x: &[f64], p: &[f64]) -> f64 {
x.iter()
.zip(p)
.map(|(a, b)| (a - b) * (a - b))
.sum::<f64>()
.sqrt()
}
fn signed_gap(x: &[f64], origin: &[f64], normal: &[f64]) -> f64 {
x.iter()
.zip(origin)
.zip(normal)
.map(|((xi, oi), ni)| (xi - oi) * ni)
.sum()
}
fn default_tol(mesh: &Mesh) -> Result<f64> {
let coords = mesh.coords()?;
let c = coords.read();
let dim = c.dim() as usize;
let mut lo = vec![f64::INFINITY; dim];
let mut hi = vec![f64::NEG_INFINITY; dim];
for sm in mesh {
let s = sm.read();
for &nid in s.connectivity() {
for (k, &v) in c.position(nid)?.iter().enumerate() {
lo[k] = lo[k].min(v);
hi[k] = hi[k].max(v);
}
}
}
let diagonal = lo
.iter()
.zip(&hi)
.map(|(l, h)| {
let d = h - l;
if d.is_finite() {
d * d
} else {
0.0 }
})
.sum::<f64>()
.sqrt();
Ok(1e-6 * diagonal)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::atoms::{ElementType, Node};
use crate::coords::Coords;
use crate::handle::Handle;
fn grid2d() -> (Mesh, Vec<NodeId>) {
let coords = Handle::new(Coords::new(2).unwrap());
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
let mut ids = Vec::new();
for j in 0..3 {
for i in 0..3 {
let n = Node::create_in(coords.clone(), &[i as f64, j as f64]).unwrap();
mesh.add_cell(&[n.id()]).unwrap();
ids.push(n.id());
}
}
(mesh, ids)
}
fn selected(mesh: &Mesh) -> Vec<NodeId> {
let s = mesh.items()[0].read();
s.connectivity().to_vec()
}
#[test]
fn sphere_selects_disc_then_circle() {
let (mesh, n) = grid2d();
let inside = points_in_sphere(&mesh, &[1.0, 1.0], 1.0, None).unwrap();
assert_eq!(selected(&inside), vec![n[1], n[3], n[4], n[5], n[7]]);
let on = points_on_sphere(&mesh, &[1.0, 1.0], 1.0, None).unwrap();
assert_eq!(selected(&on), vec![n[1], n[3], n[5], n[7]]);
let corners = points_on_sphere(&mesh, &[1.0, 1.0], 2f64.sqrt(), None).unwrap();
assert_eq!(selected(&corners), vec![n[0], n[2], n[6], n[8]]);
}
#[test]
fn plane_cuts_a_row_and_a_half_space() {
let (mesh, n) = grid2d();
let on = points_on_plane(&mesh, &[0.0, 1.0], &[0.0, 1.0], None).unwrap();
assert_eq!(selected(&on), vec![n[3], n[4], n[5]]);
let below = points_below_plane(&mesh, &[0.0, 1.0], &[0.0, 7.0], None).unwrap();
assert_eq!(selected(&below), vec![n[0], n[1], n[2], n[3], n[4], n[5]]);
let above = points_below_plane(&mesh, &[0.0, 1.0], &[0.0, -1.0], None).unwrap();
assert_eq!(selected(&above), vec![n[3], n[4], n[5], n[6], n[7], n[8]]);
}
#[test]
fn line_is_unbounded_where_the_cylinder_is_capped() {
let (mesh, n) = grid2d();
let on = points_on_line(&mesh, &[0.0, 0.0], &[1.0, 1.0], None).unwrap();
assert_eq!(selected(&on), vec![n[0], n[4], n[8]]);
let capped = points_in_cylinder(&mesh, &[0.0, 0.0], &[1.0, 1.0], 1e-9, None).unwrap();
assert_eq!(selected(&capped), vec![n[0], n[4]]);
}
#[test]
fn cylinder_lateral_surface_excludes_the_caps() {
let coords = Handle::new(Coords::new(3).unwrap());
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
let pts = [
[1.0, 0.0, 1.0],
[0.0, 0.0, 1.0],
[0.5, 0.0, 0.0],
[1.0, 0.0, 3.0],
];
let ids: Vec<NodeId> = pts
.iter()
.map(|p| {
let n = Node::create_in(coords.clone(), p).unwrap();
mesh.add_cell(&[n.id()]).unwrap();
n.id()
})
.collect();
let base = [0.0, 0.0, 0.0];
let top = [0.0, 0.0, 2.0];
let on = points_on_cylinder(&mesh, &base, &top, 1.0, None).unwrap();
assert_eq!(selected(&on), vec![ids[0]]);
let inside = points_in_cylinder(&mesh, &base, &top, 1.0, None).unwrap();
assert_eq!(selected(&inside), vec![ids[0], ids[1], ids[2]]);
}
#[test]
fn cone_tapers_between_its_end_radii() {
let coords = Handle::new(Coords::new(3).unwrap());
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
let pts = [
[1.0, 0.0, 1.0], [0.4, 0.0, 1.0], [1.6, 0.0, 1.0], ];
let ids: Vec<NodeId> = pts
.iter()
.map(|p| {
let n = Node::create_in(coords.clone(), p).unwrap();
mesh.add_cell(&[n.id()]).unwrap();
n.id()
})
.collect();
let base = [0.0, 0.0, 0.0];
let apex = [0.0, 0.0, 2.0];
let on = points_on_cone(&mesh, &base, &apex, 2.0, 0.0, None).unwrap();
assert_eq!(selected(&on), vec![ids[0]]);
let inside = points_in_cone(&mesh, &base, &apex, 2.0, 0.0, None).unwrap();
assert_eq!(selected(&inside), vec![ids[0], ids[1]]);
let cyl = points_in_cone(&mesh, &base, &apex, 2.0, 2.0, None).unwrap();
assert_eq!(selected(&cyl), vec![ids[0], ids[1], ids[2]]);
}
#[test]
fn torus_is_a_tube_around_its_directrix() {
let coords = Handle::new(Coords::new(3).unwrap());
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
let pts = [
[2.5, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 2.0, 0.5], ];
let ids: Vec<NodeId> = pts
.iter()
.map(|p| {
let n = Node::create_in(coords.clone(), p).unwrap();
mesh.add_cell(&[n.id()]).unwrap();
n.id()
})
.collect();
let center = [0.0, 0.0, 0.0];
let axis = [0.0, 0.0, 1.0];
let on = points_on_torus(&mesh, ¢er, &axis, 2.0, 0.5, None).unwrap();
assert_eq!(selected(&on), vec![ids[0], ids[3]]);
let inside = points_in_torus(&mesh, ¢er, &axis, 2.0, 0.5, None).unwrap();
assert_eq!(selected(&inside), vec![ids[0], ids[1], ids[3]]);
}
#[test]
fn result_mirrors_the_submeshes_including_the_empty_ones() {
let coords = Handle::new(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
let c = Node::create_in(coords.clone(), &[0.5, 5.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
mesh.add_cell(&[a.id(), b.id()]).unwrap();
let far = {
let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
sm.add_cell(&[c.id()]).unwrap();
Handle::new(sm)
};
mesh.add_sub(far).unwrap();
let sel = points_on_plane(&mesh, &[0.0, 0.0], &[0.0, 1.0], None).unwrap();
assert_eq!(sel.len(), 2, "one POI1 submesh per input submesh");
assert_eq!(
sel.element_types().unwrap(),
vec![ElementType::POI1, ElementType::POI1]
);
assert_eq!(sel.cell_counts().unwrap(), vec![2, 0]);
}
#[test]
fn nodes_are_de_duplicated_in_order_of_first_appearance() {
let coords = Handle::new(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
let c = Node::create_in(coords.clone(), &[2.0, 0.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
mesh.add_cell(&[a.id(), b.id()]).unwrap();
mesh.add_cell(&[b.id(), c.id()]).unwrap();
let sel = points_on_plane(&mesh, &[0.0, 0.0], &[0.0, 1.0], None).unwrap();
assert_eq!(selected(&sel), vec![a.id(), b.id(), c.id()]);
}
#[test]
fn explicit_tolerance_widens_the_band() {
let coords = Handle::new(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0, 0.01]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
mesh.add_cell(&[a.id()]).unwrap();
mesh.add_cell(&[b.id()]).unwrap();
let tight = points_on_plane(&mesh, &[0.0, 0.0], &[0.0, 1.0], None).unwrap();
assert_eq!(selected(&tight), vec![a.id()]);
let loose = points_on_plane(&mesh, &[0.0, 0.0], &[0.0, 1.0], Some(0.02)).unwrap();
assert_eq!(selected(&loose), vec![a.id(), b.id()]);
}
#[test]
fn invalid_arguments_are_rejected() {
let (mesh, _) = grid2d();
assert!(points_in_sphere(&mesh, &[0.0, 0.0, 0.0], 1.0, None).is_err());
assert!(points_in_sphere(&mesh, &[0.0, 0.0], -1.0, None).is_err());
assert!(points_in_sphere(&mesh, &[0.0, 0.0], 1.0, Some(-1e-9)).is_err());
assert!(points_on_plane(&mesh, &[0.0, 0.0], &[0.0, 0.0], None).is_err());
assert!(points_on_line(&mesh, &[1.0, 1.0], &[1.0, 1.0], None).is_err());
assert!(points_in_torus(&mesh, &[0.0, 0.0], &[0.0, 1.0], 1.0, 0.1, None).is_err());
}
#[test]
fn empty_mesh_selects_nothing() {
let sel = points_in_sphere(&Mesh::empty(), &[0.0, 0.0], 1.0, None).unwrap();
assert_eq!(sel.len(), 0);
}
}