use crate::aggregate::Aggregate;
use crate::atoms::{Cell, CellIter, ElementType, Node, NodeId, RgbColor};
use crate::coords::Coords;
use crate::error::{PyrucastError, Result};
use crate::store::{insert, read, write, Handle};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::sync::OnceLock;
#[derive(Serialize, Deserialize)]
pub struct SubMesh {
element_type: ElementType,
coords: Handle<Coords>,
connectivity: Vec<NodeId>,
#[serde(default)]
face_color: RgbColor,
#[serde(default)]
sealed: bool,
#[serde(skip)]
node_index: OnceLock<HashMap<NodeId, usize>>,
#[serde(skip)]
poi1_companion: OnceLock<Handle<SubMesh>>,
}
impl SubMesh {
pub fn new(coords: Handle<Coords>, element_type: ElementType) -> Self {
Self {
element_type,
coords,
connectivity: Vec::new(),
face_color: RgbColor::default(),
sealed: false,
node_index: OnceLock::new(),
poi1_companion: OnceLock::new(),
}
}
pub fn is_sealed(&self) -> bool {
self.sealed
}
pub fn node_index(&self) -> &HashMap<NodeId, usize> {
self.node_index.get_or_init(|| {
let mut map = HashMap::with_capacity(self.connectivity.len());
for &nid in &self.connectivity {
let next = map.len();
map.entry(nid).or_insert(next);
}
map
})
}
pub fn seal(&mut self) {
self.sealed = true;
}
pub fn face_color(&self) -> RgbColor {
self.face_color
}
pub fn set_face_color(&mut self, color: RgbColor) {
self.face_color = color;
}
pub fn add_cell(&mut self, nodes: &[NodeId]) -> Result<usize> {
if self.sealed {
return Err(PyrucastError::MeshSealed);
}
let npc = self.element_type.nodes_per_cell();
if nodes.len() != npc {
return Err(PyrucastError::Message(format!(
"add_cell({}): expected {} nodes, got {}",
self.element_type,
npc,
nodes.len()
)));
}
{
let mut c = write(&self.coords)?;
for (acquired, &n) in nodes.iter().enumerate() {
if let Err(e) = c.incref(n) {
for &m in &nodes[..acquired] {
let _ = c.decref(m);
}
return Err(e);
}
}
}
let idx = self.connectivity.len() / npc;
self.connectivity.extend_from_slice(nodes);
Ok(idx)
}
pub fn add_cell_taking(&mut self, nodes: &[NodeId]) -> Result<usize> {
if self.sealed {
return Err(PyrucastError::MeshSealed);
}
let npc = self.element_type.nodes_per_cell();
if nodes.len() != npc {
return Err(PyrucastError::Message(format!(
"add_cell_taking({}): expected {} nodes, got {}",
self.element_type,
npc,
nodes.len()
)));
}
{
let c = read(&self.coords)?;
for &n in nodes {
if !c.is_alive(n) {
return Err(PyrucastError::Message(format!(
"add_cell_taking: node {} is not alive",
n
)));
}
}
}
let idx = self.connectivity.len() / npc;
self.connectivity.extend_from_slice(nodes);
Ok(idx)
}
pub fn duplicate(&self) -> Result<SubMesh> {
let mut copy = SubMesh::new(self.coords.clone(), self.element_type);
copy.face_color = self.face_color;
let npc = self.element_type.nodes_per_cell();
if npc > 0 {
for chunk in self.connectivity.chunks(npc) {
copy.add_cell(chunk)?;
}
}
Ok(copy)
}
pub fn element_type(&self) -> ElementType {
self.element_type
}
pub fn cell_count(&self) -> usize {
self.connectivity.len() / self.element_type.nodes_per_cell()
}
pub(crate) fn connectivity(&self) -> &[NodeId] {
&self.connectivity
}
pub fn coords(&self) -> Handle<Coords> {
self.coords.clone()
}
pub fn poi1_from_nodes(nodes: &[Node]) -> Result<SubMesh> {
let coords = nodes
.first()
.ok_or_else(|| {
PyrucastError::Message("SubMesh::poi1_from_nodes: nodes must not be empty".into())
})?
.coords();
let ids: Vec<NodeId> = nodes.iter().map(|n| n.id()).collect();
SubMesh::poi1_from_node_ids(coords, &ids)
}
pub fn poi1_from_node_ids(coords: Handle<Coords>, nodes: &[NodeId]) -> Result<SubMesh> {
let mut sm = SubMesh::new(coords, ElementType::POI1);
for &nid in nodes {
sm.add_cell(&[nid])?;
}
Ok(sm)
}
pub fn to_poi1(&self) -> Result<Handle<SubMesh>> {
if let Some(h) = self.poi1_companion.get() {
return Ok(h.clone());
}
let mut seen: Vec<NodeId> = Vec::with_capacity(self.connectivity.len());
let mut known: HashSet<NodeId> = HashSet::with_capacity(self.connectivity.len());
for &nid in &self.connectivity {
if known.insert(nid) {
seen.push(nid);
}
}
let handle = insert(SubMesh::poi1_from_node_ids(self.coords.clone(), &seen)?);
seal(&handle)?;
if self.sealed {
let _ = self.poi1_companion.set(handle);
Ok(self
.poi1_companion
.get()
.expect("populated on this path")
.clone())
} else {
Ok(handle)
}
}
#[cfg(feature = "viz")]
pub fn plot(
&self,
view: Option<crate::viz::View>,
save: Option<&std::path::Path>,
) -> Result<()> {
self.plot_styled(view, save, crate::viz::MeshStyle::default(), None)
}
#[cfg(feature = "viz")]
pub fn plot_styled(
&self,
view: Option<crate::viz::View>,
save: Option<&std::path::Path>,
style: crate::viz::MeshStyle,
title: Option<&str>,
) -> Result<()> {
crate::viz::render_submesh_styled(self, view, save, style, title)
}
}
pub fn seal(handle: &Handle<SubMesh>) -> Result<Handle<SubMesh>> {
if read(handle)?.is_sealed() {
return Ok(handle.clone());
}
write(handle)?.seal();
Ok(handle.clone())
}
impl Drop for SubMesh {
fn drop(&mut self) {
if let Ok(mut c) = write(&self.coords) {
for &n in &self.connectivity {
let _ = c.decref(n);
}
}
}
}
impl fmt::Debug for SubMesh {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SubMesh")
.field("element_type", &self.element_type)
.field("coords", &self.coords)
.field("cell_count", &self.cell_count())
.field("face_color", &self.face_color)
.field("sealed", &self.sealed)
.finish()
}
}
impl fmt::Display for SubMesh {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"SubMesh<{}>: {} cell(s)",
self.element_type,
self.cell_count()
)
}
}
impl crate::dump::Dump for SubMesh {
fn render(&self, opts: &crate::dump::DumpOptions) -> String {
use crate::dump::table;
let npc = self.element_type.nodes_per_cell();
let mut headers = vec!["cell".to_string()];
headers.extend((0..npc).map(|i| format!("n{i}")));
let rows: Vec<Vec<String>> = if npc > 0 {
self.connectivity
.chunks(npc)
.enumerate()
.map(|(i, chunk)| {
let mut row = vec![i.to_string()];
row.extend(chunk.iter().map(|nid| nid.to_string()));
row
})
.collect()
} else {
Vec::new()
};
format!("{self}\n{}", table(&headers, &rows, opts))
}
}
#[derive(Serialize, Deserialize, Default)]
pub struct Mesh {
subs: Vec<Handle<SubMesh>>,
}
crate::impl_aggregate!(Mesh, SubMesh, submesh, "submesh(es)", {
fn display_extra(&self) -> Option<String> {
Some(format!(
", {} cell(s) total",
self.cell_count().unwrap_or(0)
))
}
fn check_push(&self, h: &Handle<SubMesh>) -> Result<()> {
if self.is_empty() {
return Ok(());
}
let a = self.coords()?;
let b = read(h)?.coords();
if a.index() != b.index() || a.generation() != b.generation() {
Err(PyrucastError::Message("mismatched Coords".into()))
} else {
Ok(())
}
}
});
crate::impl_aggregate_dump!(Mesh);
impl Node {
pub fn union(&self, other: &Node) -> Result<Mesh> {
let sm = SubMesh::poi1_from_nodes(&[self.clone(), other.clone()])?;
Ok(Mesh::from_submesh(sm))
}
}
impl Mesh {
pub fn union_node(&self, node: &Node) -> Result<Mesh> {
let sub = self.unit()?;
let (et, coords, mut ids) = {
let s = read(&sub)?;
(s.element_type(), s.coords(), s.connectivity().to_vec())
};
if et != ElementType::POI1 {
return Err(PyrucastError::Message(
"Mesh | Node: expected a unitary POI1 mesh".into(),
));
}
ids.push(node.id());
Ok(Mesh::from_submesh(SubMesh::poi1_from_node_ids(
coords, &ids,
)?))
}
}
impl Mesh {
pub fn cell_count(&self) -> Result<usize> {
let mut total = 0usize;
for sm in self {
total += read(sm)?.cell_count();
}
Ok(total)
}
pub fn coords(&self) -> Result<Handle<Coords>> {
let sm = self
.items()
.first()
.ok_or_else(|| PyrucastError::Message("coords: mesh has no submeshes".into()))?;
Ok(read(sm)?.coords())
}
pub fn from_submesh(sub: SubMesh) -> Self {
let mut mesh = Self::default();
mesh.subs.push(insert(sub));
mesh
}
pub fn duplicate(&self) -> Result<Mesh> {
let mut copy = Self::default();
for sm in self {
let dup = read(sm)?.duplicate()?;
copy.subs.push(insert(dup));
}
Ok(copy)
}
pub fn add_cell(&mut self, nodes: &[NodeId]) -> Result<usize> {
if self.len() != 1 {
return Err(PyrucastError::Message(
"add_cell: mesh must have exactly one submesh".into(),
));
}
write(&self.subs[0])?.add_cell(nodes)
}
pub fn element_types(&self) -> Result<Vec<ElementType>> {
self.iter().map(|sm| Ok(read(sm)?.element_type())).collect()
}
pub fn cell_counts(&self) -> Result<Vec<usize>> {
self.iter().map(|sm| Ok(read(sm)?.cell_count())).collect()
}
pub fn poi1_from_nodes(nodes: &[Node]) -> Result<Mesh> {
Ok(Mesh::from_submesh(SubMesh::poi1_from_nodes(nodes)?))
}
pub fn nearest_node(&self, point: &[f64]) -> Result<Node> {
let coords_handle = self.coords()?;
let mut seen: HashSet<NodeId> = HashSet::new();
for sm in self {
let s = read(sm)?;
for &nid in s.connectivity() {
seen.insert(nid);
}
}
let best = {
let c = read(&coords_handle)?;
if point.len() != c.dim() as usize {
return Err(PyrucastError::Message(format!(
"nearest_node: point has {} coordinates, mesh is {}-D",
point.len(),
c.dim()
)));
}
let mut best: Option<(NodeId, f64)> = None;
for &nid in &seen {
let x = c.coord(nid)?;
let d2: f64 = x.iter().zip(point).map(|(a, b)| (a - b) * (a - b)).sum();
match best {
Some((bid, bd2)) if bd2 < d2 || (bd2 == d2 && bid.0 <= nid.0) => {}
_ => best = Some((nid, d2)),
}
}
best
};
let (nid, _) = best.ok_or_else(|| {
PyrucastError::Message("nearest_node: mesh references no nodes".into())
})?;
Node::acquire(coords_handle, nid)
}
pub fn node(&self, submesh_idx: usize, cell_idx: usize, node_idx: usize) -> Result<Node> {
let sm = self.get(submesh_idx)?;
let (nid, coords) = {
let s = read(&sm)?;
let npc = s.element_type.nodes_per_cell();
let n = s.cell_count();
if cell_idx >= n {
return Err(PyrucastError::Message(format!(
"node: cell index {} ≥ cell_count {}",
cell_idx, n
)));
}
let nid = s
.connectivity()
.get(cell_idx * npc + node_idx)
.copied()
.ok_or_else(|| {
PyrucastError::Message(format!(
"node: node index {} ≥ nodes_per_cell {}",
node_idx, npc
))
})?;
(nid, s.coords())
};
Node::acquire(coords, nid)
}
pub fn cell(&self, submesh_idx: usize, cell_idx: usize) -> Result<Cell> {
let sm = self.get(submesh_idx)?;
Cell::new(sm, cell_idx)
}
pub fn cells(&self, submesh_idx: usize) -> Result<CellIter> {
let sm = self.get(submesh_idx)?;
let end = read(&sm)?.cell_count();
Ok(CellIter::new(sm, end))
}
#[cfg(feature = "viz")]
pub fn plot(
&self,
view: Option<crate::viz::View>,
save: Option<&std::path::Path>,
) -> Result<()> {
self.plot_styled(view, save, crate::viz::MeshStyle::default(), None)
}
#[cfg(feature = "viz")]
pub fn plot_styled(
&self,
view: Option<crate::viz::View>,
save: Option<&std::path::Path>,
style: crate::viz::MeshStyle,
title: Option<&str>,
) -> Result<()> {
crate::viz::render_mesh_styled(self, view, save, style, title)
}
#[allow(clippy::too_many_arguments)]
#[cfg(feature = "viz")]
pub fn plot_with_field(
&self,
view: Option<crate::viz::View>,
save: Option<&std::path::Path>,
field: crate::viz::FieldArg<'_>,
component: Option<&str>,
scale: crate::viz::ColorScale,
smooth: usize,
title: Option<&str>,
) -> Result<()> {
crate::viz::render_mesh_with_field(self, field, component, scale, smooth, view, save, title)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::store::insert;
#[test]
fn submesh_poi1_is_node_list() {
let coords = insert(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 mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
sm.add_cell(&[a.id()]).unwrap();
sm.add_cell(&[b.id()]).unwrap();
assert_eq!(sm.cell_count(), 2);
assert_eq!(sm.connectivity()[0], a.id());
assert_eq!(sm.connectivity()[1], b.id());
}
#[test]
fn poi1_from_nodes_derives_config_and_builds() {
let coords = insert(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 sm = SubMesh::poi1_from_nodes(&[a.clone(), b.clone()]).unwrap();
assert_eq!(sm.element_type(), ElementType::POI1);
assert_eq!(sm.cell_count(), 2);
assert_eq!(sm.connectivity(), &[a.id(), b.id()]);
let sm2 = SubMesh::poi1_from_node_ids(coords.clone(), &[a.id(), b.id()]).unwrap();
assert_eq!(sm.connectivity(), sm2.connectivity());
}
#[test]
fn poi1_from_nodes_empty_is_error() {
assert!(SubMesh::poi1_from_nodes(&[]).is_err());
}
#[test]
fn submesh_tri3_increfs_and_drop_decrefs() {
let coords = insert(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, 1.0]).unwrap();
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
{
let cf = read(&coords).unwrap();
assert_eq!(cf.refcount(a.id()), 2);
assert_eq!(cf.refcount(b.id()), 2);
assert_eq!(cf.refcount(c.id()), 2);
}
drop(sm);
{
let cf = read(&coords).unwrap();
assert_eq!(cf.refcount(a.id()), 1);
assert_eq!(cf.refcount(b.id()), 1);
assert_eq!(cf.refcount(c.id()), 1);
}
}
#[test]
fn node_index_maps_distinct_nodes_in_first_appearance_order() {
let coords = insert(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(), &[1.0, 1.0]).unwrap();
let d = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
let mut sm = SubMesh::new(coords.clone(), ElementType::QUA4);
sm.add_cell(&[a.id(), b.id(), c.id(), d.id()]).unwrap();
let e = Node::create_in(coords.clone(), &[2.0, 0.0]).unwrap();
let f = Node::create_in(coords.clone(), &[2.0, 1.0]).unwrap();
sm.add_cell(&[b.id(), e.id(), f.id(), c.id()]).unwrap();
let map = sm.node_index();
assert_eq!(map.len(), 6);
assert_eq!(map[&a.id()], 0);
assert_eq!(map[&b.id()], 1);
assert_eq!(map[&c.id()], 2);
assert_eq!(map[&d.id()], 3);
assert_eq!(map[&e.id()], 4);
assert_eq!(map[&f.id()], 5);
assert_eq!(sm.node_index().len(), 6);
}
#[test]
fn sealed_submesh_refuses_add_cell() {
let coords = insert(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 mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
sm.add_cell(&[a.id()]).unwrap();
assert!(!sm.is_sealed());
sm.seal();
assert!(sm.is_sealed());
assert!(matches!(
sm.add_cell(&[b.id()]).unwrap_err(),
PyrucastError::MeshSealed
));
assert!(matches!(
sm.add_cell_taking(&[b.id()]).unwrap_err(),
PyrucastError::MeshSealed
));
assert_eq!(sm.cell_count(), 1);
assert_eq!(read(&coords).unwrap().refcount(b.id()), 1);
}
#[test]
fn seal_via_handle_and_is_idempotent() {
let coords = insert(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let h = insert({
let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
sm.add_cell(&[a.id()]).unwrap();
sm
});
seal(&h).unwrap();
seal(&h).unwrap(); assert!(read(&h).unwrap().is_sealed());
assert!(matches!(
write(&h).unwrap().add_cell(&[a.id()]).unwrap_err(),
PyrucastError::MeshSealed
));
}
#[test]
fn duplicate_is_unsealed_and_reincrefs() {
let coords = insert(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, 1.0]).unwrap();
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
sm.seal();
let mut copy = sm.duplicate().unwrap();
assert!(!copy.is_sealed());
assert_eq!(copy.connectivity(), sm.connectivity());
{
let cf = read(&coords).unwrap();
assert_eq!(cf.refcount(a.id()), 3);
}
let d = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();
copy.add_cell(&[a.id(), b.id(), d.id()]).unwrap();
assert_eq!(copy.cell_count(), 2);
assert_eq!(sm.cell_count(), 1);
}
#[test]
fn mesh_duplicate_yields_editable_copy() {
let coords = insert(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 mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
sm.add_cell(&[a.id()]).unwrap();
sm.seal();
let mesh = Mesh::from_submesh(sm);
let mut copy = mesh.duplicate().unwrap();
assert_eq!(copy.cell_count().unwrap(), 1);
copy.add_cell(&[b.id()]).unwrap();
assert_eq!(copy.cell_count().unwrap(), 2);
}
#[test]
fn submesh_add_cell_invalid_arity() {
let coords = insert(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
let err = sm.add_cell(&[a.id()]).unwrap_err();
assert!(matches!(err, PyrucastError::Message(_)));
assert_eq!(read(&coords).unwrap().refcount(a.id()), 1);
}
#[test]
fn submesh_add_cell_collected_node_rollback() {
let coords = insert(Coords::new(1).unwrap());
let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
let dead_id = write(&coords).unwrap().add_node(&[2.0]).unwrap();
{
let mut c = write(&coords).unwrap();
c.decref(dead_id).unwrap();
assert_eq!(c.gc(), 1);
}
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
let err = sm.add_cell(&[a.id(), b.id(), dead_id]).unwrap_err();
assert!(matches!(err, PyrucastError::Message(_)));
{
let cf = read(&coords).unwrap();
assert_eq!(cf.refcount(a.id()), 1, "a must be rolled back");
assert_eq!(cf.refcount(b.id()), 1, "b must be rolled back");
}
assert_eq!(sm.cell_count(), 0);
}
#[test]
fn mesh_aggregates_submeshes_same_config() {
let coords = insert(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 cc = Node::create_in(coords.clone(), &[0.5, 1.0]).unwrap();
let sm_pts = {
let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
sm.add_cell(&[a.id()]).unwrap();
sm.add_cell(&[b.id()]).unwrap();
insert(sm)
};
let sm_tri = {
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
sm.add_cell(&[a.id(), b.id(), cc.id()]).unwrap();
insert(sm)
};
let mut mesh = Mesh::empty();
mesh.add_sub(sm_pts).unwrap();
mesh.add_sub(sm_tri).unwrap();
assert_eq!(mesh.len(), 2);
assert_eq!(mesh.cell_count().unwrap(), 3); }
#[test]
fn mesh_element_types_and_cell_counts() {
let coords = insert(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, 1.0]).unwrap();
let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
m.add_cell(&[a.id()]).unwrap();
m.add_cell(&[b.id()]).unwrap();
let sm_tri = {
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
insert(sm)
};
m.add_sub(sm_tri).unwrap();
assert_eq!(
m.element_types().unwrap(),
vec![ElementType::POI1, ElementType::TRI3]
);
assert_eq!(m.cell_counts().unwrap(), vec![2, 1]);
}
#[test]
fn mesh_index_and_iter_sugar() {
let coords = insert(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, 1.0]).unwrap();
let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
m.add_cell(&[a.id()]).unwrap();
let sm_tri = {
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
insert(sm)
};
m.add_sub(sm_tri).unwrap();
let et0 = read(&m[0]).unwrap().element_type();
let et1 = read(&m[1]).unwrap().element_type();
assert_eq!(et0, ElementType::POI1);
assert_eq!(et1, ElementType::TRI3);
let types: Vec<ElementType> = (&m)
.into_iter()
.map(|h| read(h).unwrap().element_type())
.collect();
assert_eq!(types, vec![ElementType::POI1, ElementType::TRI3]);
}
#[test]
fn mesh_node_access_by_indices() {
let coords = insert(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, 1.0]).unwrap();
let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
m.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
let n = m.node(0, 0, 0).unwrap();
assert_eq!(n.id(), a.id()); assert!(m.node(1, 0, 0).is_err()); assert!(m.node(0, 1, 0).is_err()); assert!(m.node(0, 0, 3).is_err()); }
#[test]
fn mesh_merge_combines_submeshes() {
let coords = insert(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, 1.0]).unwrap();
let mut m1 = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
m1.add_cell(&[a.id()]).unwrap();
m1.add_cell(&[b.id()]).unwrap();
let mut m2 = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
m2.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
let merged = m1.union(&m2).unwrap();
assert_eq!(merged.len(), 2);
assert_eq!(merged.cell_count().unwrap(), 3); }
#[test]
fn debug_and_display_submesh_and_mesh() {
let coords = insert(Coords::new(1).unwrap());
let sm = SubMesh::new(coords.clone(), ElementType::SEG2);
let d = format!("{:?}", sm);
let s = format!("{}", sm);
assert!(d.contains("SubMesh"));
assert!(s.contains("SEG2"));
let mesh = Mesh::empty();
assert!(format!("{:?}", mesh).contains("Mesh"));
assert!(format!("{}", mesh).contains("submesh"));
}
#[test]
fn aggregate_union_sub_and_sub_union_sub() {
let coords = insert(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 s1 = insert(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
let s2 = insert(SubMesh::poi1_from_nodes(std::slice::from_ref(&b)).unwrap());
let m = Mesh::union_subs(&s1, &s2).unwrap();
assert_eq!(m.len(), 2);
let s3 = insert(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
let m2 = m.union_sub(&s3).unwrap();
assert_eq!(m2.len(), 3);
}
#[test]
fn node_union_node_and_mesh_union_node() {
let coords = insert(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 m = a.union(&b).unwrap();
assert_eq!(m.len(), 1);
assert_eq!(read(&m.unit().unwrap()).unwrap().cell_count(), 2);
let m2 = m.union_node(&c).unwrap();
assert_eq!(read(&m2.unit().unwrap()).unwrap().cell_count(), 3);
}
#[test]
fn mesh_union_node_rejects_non_unitary_poi1() {
let coords = insert(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, 1.0]).unwrap();
let mut tri = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
tri.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
assert!(tri.union_node(&a).is_err());
}
#[test]
fn to_poi1_caches_companion_on_a_sealed_submesh() {
let coords = insert(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.0, 1.0]).unwrap();
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
let h = insert(sm);
let u1 = read(&h).unwrap().to_poi1().unwrap();
let u2 = read(&h).unwrap().to_poi1().unwrap();
assert!(!u1.same_slot(&u2), "unsealed submesh is not memoized");
seal(&h).unwrap();
let p1 = read(&h).unwrap().to_poi1().unwrap();
let p2 = read(&h).unwrap().to_poi1().unwrap();
assert!(
p1.same_slot(&p2),
"sealed submesh memoizes its POI1 companion"
);
assert_eq!(read(&p1).unwrap().element_type(), ElementType::POI1);
assert_eq!(read(&p1).unwrap().cell_count(), 3); }
}
#[cfg(test)]
mod nearest_node_tests {
use super::*;
use crate::atoms::ElementType;
use crate::atoms::Node;
use crate::containers::mesh::SubMesh;
use crate::coords::Coords;
use crate::store::insert;
#[test]
fn nearest_on_grid() {
let coords = insert(Coords::new(2).unwrap());
let n00 = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let n10 = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
let n11 = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
sm.add_cell(&[n00.id(), n10.id(), n11.id()]).unwrap();
let mesh = Mesh::from_submesh(sm);
let found = mesh.nearest_node(&[0.9, 0.9]).unwrap();
assert_eq!(found.id(), n11.id());
let found = mesh.nearest_node(&[-0.2, 0.1]).unwrap();
assert_eq!(found.id(), n00.id());
}
#[test]
fn dimension_mismatch_errors() {
let coords = insert(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 mut sm = SubMesh::new(coords, ElementType::SEG2);
sm.add_cell(&[a.id(), b.id()]).unwrap();
let mesh = Mesh::from_submesh(sm);
assert!(mesh.nearest_node(&[0.0, 0.0, 0.0]).is_err());
}
}