use crate::aggregate::Aggregate;
use crate::atoms::{Cell, CellIter, ElementType, Node, NodeId, RgbColor};
use crate::coords::Coords;
use crate::error::{PyrucastError, Result};
use crate::handle::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 from_connectivity(
coords: Handle<Coords>,
element_type: ElementType,
connectivity: Vec<NodeId>,
) -> Result<Self> {
let npc = element_type.nodes_per_cell();
if npc == 0 || !connectivity.len().is_multiple_of(npc) {
return Err(PyrucastError::Message(format!(
"from_connectivity({element_type}): {} node(s) is not a multiple of {npc}",
connectivity.len()
)));
}
coords.write().incref_all(&connectivity)?;
Ok(Self {
element_type,
coords,
connectivity,
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
})
}
fn invalidate_caches(&mut self) {
self.node_index = OnceLock::new();
self.poi1_companion = OnceLock::new();
}
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 = self.coords.write();
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);
self.invalidate_caches();
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 = self.coords.read();
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);
self.invalidate_caches();
Ok(idx)
}
pub fn duplicate(&self) -> Result<SubMesh> {
let mut copy = SubMesh::from_connectivity(
self.coords.clone(),
self.element_type,
self.connectivity.clone(),
)?;
copy.face_color = self.face_color;
Ok(copy)
}
pub fn remap_nodes(&mut self, map: &HashMap<NodeId, NodeId>) -> Result<usize> {
self.remap_with(|old| map.get(&old).copied().unwrap_or(old))
}
pub(crate) fn remap_nodes_dense(&mut self, table: &[u32]) -> Result<usize> {
self.remap_with(|old| NodeId(table[old.0 as usize]))
}
fn remap_with(&mut self, image: impl Fn(NodeId) -> NodeId) -> Result<usize> {
if self.sealed {
return Err(PyrucastError::MeshSealed);
}
let mut rewritten = 0;
{
let mut c = self.coords.write();
for &old in &self.connectivity {
let new = image(old);
if new != old && !c.is_alive(new) {
return Err(PyrucastError::Message(format!(
"remap_nodes: node {} is not found or collected",
new.0
)));
}
}
for slot in &mut self.connectivity {
let new = image(*slot);
if new != *slot {
c.incref(new)?;
c.decref(*slot)?;
*slot = new;
rewritten += 1;
}
}
}
if rewritten > 0 {
self.invalidate_caches();
}
Ok(rewritten)
}
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> {
SubMesh::from_connectivity(coords, ElementType::POI1, nodes.to_vec())
}
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 = Handle::new(SubMesh::from_connectivity(
self.coords.clone(),
ElementType::POI1,
seen,
)?);
seal(&handle);
let _ = self.poi1_companion.set(handle);
Ok(self
.poi1_companion
.get()
.expect("populated on this path")
.clone())
}
#[cfg(feature = "viz")]
pub fn plot(&self, view: 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: 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>) -> Handle<SubMesh> {
if handle.read().is_sealed() {
return handle.clone();
}
handle.write().seal();
handle.clone()
}
impl Drop for SubMesh {
fn drop(&mut self) {
let mut c = self.coords.write();
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 coords: {}, face_color: {:?}, sealed: {}\n{}",
self.coords,
self.face_color,
self.sealed,
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()))
}
fn check_push(&self, h: &Handle<SubMesh>) -> Result<()> {
if self.is_empty() {
return Ok(());
}
let a = self.coords()?;
let b = h.read().coords();
if !a.same_object(&b) {
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 = sub.read();
(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) -> usize {
let mut total = 0usize;
for sm in self {
total += sm.read().cell_count();
}
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(sm.read().coords())
}
pub fn from_submesh(sub: SubMesh) -> Self {
let mut mesh = Self::default();
mesh.subs.push(Handle::new(sub));
mesh
}
pub fn duplicate(&self) -> Result<Mesh> {
let mut copy = Self::default();
for sm in self {
let dup = sm.read().duplicate()?;
copy.subs.push(Handle::new(dup));
}
Ok(copy)
}
pub fn set_face_color(&self, color: RgbColor) -> Mesh {
let mut same = Self::default();
for sub in self {
sub.write().set_face_color(color);
same.subs.push(sub.clone());
}
same
}
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(),
));
}
self.subs[0].write().add_cell(nodes)
}
pub fn element_types(&self) -> Result<Vec<ElementType>> {
self.iter().map(|sm| Ok(sm.read().element_type())).collect()
}
pub fn cell_counts(&self) -> Result<Vec<usize>> {
self.iter().map(|sm| Ok(sm.read().cell_count())).collect()
}
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 = sm.read();
for &nid in s.connectivity() {
seen.insert(nid);
}
}
let best = {
let c = coords_handle.read();
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.position(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 = sm.read();
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 = sm.read().cell_count();
Ok(CellIter::new(sm, end))
}
#[cfg(feature = "viz")]
pub fn plot(&self, view: 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: 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: 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)
}
}
impl crate::archive::Archivable for SubMesh {
const TAG: &'static str = "SubMesh";
fn on_load(&mut self) {
let mut coords = self.coords.write();
for &n in &self.connectivity {
let _ = coords.incref(n);
}
}
}
impl crate::archive::Archivable for Mesh {
const TAG: &'static str = "Mesh";
}
#[cfg(test)]
mod tests {
use super::*;
use crate::handle::Handle;
#[test]
fn submesh_poi1_is_node_list() {
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 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 = 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 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 = 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, 1.0]).unwrap();
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
{
let cf = coords.read();
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 = coords.read();
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 = 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(), &[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 = 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 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!(coords.read().refcount(b.id()), 1);
}
#[test]
fn seal_via_handle_and_is_idempotent() {
let coords = Handle::new(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let h = Handle::new({
let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
sm.add_cell(&[a.id()]).unwrap();
sm
});
seal(&h);
seal(&h); assert!(h.read().is_sealed());
assert!(matches!(
h.write().add_cell(&[a.id()]).unwrap_err(),
PyrucastError::MeshSealed
));
}
#[test]
fn duplicate_is_unsealed_and_reincrefs() {
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, 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 = coords.read();
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 remap_nodes_rewrites_connectivity_and_moves_refcounts() {
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, 1.0]).unwrap();
let b2 = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
sm.add_cell(&[a.id(), b2.id(), c.id()]).unwrap();
sm.add_cell(&[b2.id(), c.id(), a.id()]).unwrap();
assert_eq!(coords.read().refcount(b2.id()), 3);
assert_eq!(coords.read().refcount(b.id()), 1);
let map = HashMap::from([(b2.id(), b.id()), (a.id(), a.id())]);
assert_eq!(sm.remap_nodes(&map).unwrap(), 2, "two slots rewritten");
assert_eq!(sm.cell_count(), 2, "renaming never changes the cells");
assert_eq!(sm.connectivity()[1], b.id());
assert_eq!(sm.connectivity()[3], b.id());
assert_eq!(coords.read().refcount(b2.id()), 1);
assert_eq!(coords.read().refcount(b.id()), 3);
assert_eq!(sm.remap_nodes(&map).unwrap(), 0);
}
#[test]
fn remap_nodes_drops_the_derived_caches() {
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 b2 = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
sm.add_cell(&[a.id(), b2.id()]).unwrap();
assert!(sm.node_index().contains_key(&b2.id()));
sm.remap_nodes(&HashMap::from([(b2.id(), b.id())])).unwrap();
let index = sm.node_index();
assert!(
index.contains_key(&b.id()),
"cache rebuilt on the new nodes"
);
assert!(!index.contains_key(&b2.id()));
}
#[test]
fn remap_nodes_refuses_a_sealed_submesh() {
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 b2 = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
sm.add_cell(&[a.id(), b2.id()]).unwrap();
sm.seal();
assert!(matches!(
sm.remap_nodes(&HashMap::from([(b2.id(), b.id())]))
.unwrap_err(),
PyrucastError::MeshSealed
));
assert_eq!(sm.connectivity()[1], b2.id(), "left untouched");
}
#[test]
fn mesh_duplicate_yields_editable_copy() {
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 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(), 1);
copy.add_cell(&[b.id()]).unwrap();
assert_eq!(copy.cell_count(), 2);
}
#[test]
fn submesh_add_cell_invalid_arity() {
let coords = Handle::new(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!(coords.read().refcount(a.id()), 1);
}
#[test]
fn submesh_add_cell_collected_node_rollback() {
let coords = Handle::new(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 = coords.write().add_node(&[2.0]).unwrap();
{
let mut c = coords.write();
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 = coords.read();
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 from_connectivity_refuses_a_dead_node_without_increfing_anything() {
let coords = Handle::new(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 = coords.write().add_node(&[2.0]).unwrap();
{
let mut c = coords.write();
c.decref(dead_id).unwrap();
assert_eq!(c.gc(), 1);
}
let err = SubMesh::from_connectivity(
coords.clone(),
ElementType::TRI3,
vec![a.id(), b.id(), dead_id],
)
.unwrap_err();
assert!(matches!(err, PyrucastError::Message(_)));
let cf = coords.read();
assert_eq!((cf.refcount(a.id()), cf.refcount(b.id())), (1, 1));
}
#[test]
fn mesh_aggregates_submeshes_same_config() {
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 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();
Handle::new(sm)
};
let sm_tri = {
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
sm.add_cell(&[a.id(), b.id(), cc.id()]).unwrap();
Handle::new(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(), 3); }
#[test]
fn mesh_element_types_and_cell_counts() {
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, 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();
Handle::new(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 = 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, 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();
Handle::new(sm)
};
m.add_sub(sm_tri).unwrap();
let et0 = m[0].read().element_type();
let et1 = m[1].read().element_type();
assert_eq!(et0, ElementType::POI1);
assert_eq!(et1, ElementType::TRI3);
let types: Vec<ElementType> = (&m).into_iter().map(|h| h.read().element_type()).collect();
assert_eq!(types, vec![ElementType::POI1, ElementType::TRI3]);
}
#[test]
fn mesh_node_access_by_indices() {
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, 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 = 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, 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(), 3); }
#[test]
fn debug_and_display_submesh_and_mesh() {
let coords = Handle::new(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 = 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 s1 = Handle::new(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
let s2 = Handle::new(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 = Handle::new(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 = 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 m = a.union(&b).unwrap();
assert_eq!(m.len(), 1);
assert_eq!(m.unit().unwrap().read().cell_count(), 2);
let m2 = m.union_node(&c).unwrap();
assert_eq!(m2.unit().unwrap().read().cell_count(), 3);
}
#[test]
fn mesh_union_node_rejects_non_unitary_poi1() {
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, 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_even_unsealed() {
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.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 = Handle::new(sm);
let u1 = h.read().to_poi1().unwrap();
let u2 = h.read().to_poi1().unwrap();
assert!(
u1.same_object(&u2),
"companion memoized on an unsealed submesh"
);
assert!(
!h.read().is_sealed(),
"asking for the companion does not seal"
);
assert!(u1.read().is_sealed(), "the companion itself is sealed");
assert_eq!(u1.read().element_type(), ElementType::POI1);
assert_eq!(u1.read().cell_count(), 3);
seal(&h);
assert!(h.read().to_poi1().unwrap().same_object(&u1));
}
#[test]
fn growing_a_submesh_drops_its_poi1_companion() {
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.0, 1.0]).unwrap();
let d = Node::create_in(coords.clone(), &[1.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 = Handle::new(sm);
let before = h.read().to_poi1().unwrap();
assert_eq!(before.read().cell_count(), 3);
h.write().add_cell(&[b.id(), d.id(), c.id()]).unwrap();
let after = h.read().to_poi1().unwrap();
assert!(
!before.same_object(&after),
"the stale companion was dropped"
);
assert_eq!(after.read().cell_count(), 4);
assert_eq!(before.read().cell_count(), 3);
assert_eq!(h.read().node_index()[&d.id()], 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::handle::Handle;
#[test]
fn nearest_on_grid() {
let coords = Handle::new(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 set_face_color_paints_every_zone_even_sealed() {
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.0, 1.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
mesh.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
let seg = {
let mut sm = SubMesh::new(coords, ElementType::SEG2);
sm.add_cell(&[a.id(), b.id()]).unwrap();
sm.set_face_color(RgbColor::new(1, 2, 3));
Handle::new(sm)
};
mesh.add_sub(seg).unwrap();
crate::containers::finite_element_space::FiniteElementSpace::lagrange1(&mesh).unwrap();
assert!(mesh.get(0).unwrap().read().is_sealed());
let rouge = RgbColor::new(220, 60, 60);
let retour = mesh.set_face_color(rouge);
assert_eq!(retour.len(), 2);
for i in 0..2 {
assert!(retour.get(i).unwrap().same_object(&mesh.get(i).unwrap()));
assert_eq!(mesh.get(i).unwrap().read().face_color(), rouge);
}
}
#[test]
fn dimension_mismatch_errors() {
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 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());
}
}