use crate::atoms::ElementType;
use crate::containers::mesh::Mesh;
use crate::error::{PyrucastError, Result};
use crate::interrupt::{Cancel, NoCancel};
use crate::ops::mesh::paving::FrontRelax;
use crate::ops::mesh::{contour, paving};
pub fn pave_surface(
contour: &Mesh,
element_type: ElementType,
target_size: Option<f64>,
all_quad: bool,
relax: FrontRelax,
) -> Result<Mesh> {
pave_surface_cancellable(
contour,
element_type,
target_size,
all_quad,
relax,
&NoCancel,
)
}
pub fn pave_surface_cancellable(
contour: &Mesh,
element_type: ElementType,
target_size: Option<f64>,
all_quad: bool,
relax: FrontRelax,
cancel: &dyn Cancel,
) -> Result<Mesh> {
if !matches!(
element_type,
ElementType::QUA4 | ElementType::QUA8 | ElementType::QUA9
) {
return Err(PyrucastError::Message(format!(
"pave_surface: element_type must be QUA4, QUA8 or QUA9, got {element_type}"
)));
}
if let Some(h) = target_size
&& (h <= 0.0 || h.is_nan())
{
return Err(PyrucastError::Message(format!(
"pave_surface: target_size must be > 0, got {h}"
)));
}
let parsed = contour::parse(contour, "pave_surface")?;
let mut fabrics = Vec::with_capacity(parsed.domains.len());
for d in &parsed.domains {
fabrics.push(paving::pave(
d,
target_size,
all_quad,
relax,
cancel,
"pave_surface",
)?);
}
let qua4 = paving::materialize(&parsed, fabrics, "pave_surface")?;
super::sweep::finish_surface(qua4, element_type, "pave_surface")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::aggregate::Aggregate;
use crate::atoms::{Node, NodeId, Point2};
use crate::containers::mesh::SubMesh;
use crate::coords::Coords;
use crate::handle::Handle;
use crate::named::Named;
use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
fn loop_mesh(coords: crate::handle::Handle<Coords>, pts: &[(f64, f64)]) -> Mesh {
let ids: Vec<NodeId> = pts
.iter()
.map(|&(x, y)| Node::create_in(coords.clone(), &[x, y]).unwrap().id())
.collect();
let mut sm = SubMesh::new(coords, ElementType::SEG2);
let n = ids.len();
for i in 0..n {
sm.add_cell(&[ids[i], ids[(i + 1) % n]]).unwrap();
}
Mesh::from_submesh(sm)
}
fn rect_loop(w: f64, h: f64, nx: usize, ny: usize) -> Vec<(f64, f64)> {
let mut v = Vec::new();
for i in 0..nx {
v.push((w * i as f64 / nx as f64, 0.0));
}
for i in 0..ny {
v.push((w, h * i as f64 / ny as f64));
}
for i in 0..nx {
v.push((w - w * i as f64 / nx as f64, h));
}
for i in 0..ny {
v.push((0.0, h - h * i as f64 / ny as f64));
}
v
}
fn circle_loop(cx: f64, cy: f64, r: f64, n: usize, clockwise: bool) -> Vec<(f64, f64)> {
(0..n)
.map(|i| {
let mut t = i as f64 / n as f64 * std::f64::consts::TAU;
if clockwise {
t = -t;
}
(cx + r * t.cos(), cy + r * t.sin())
})
.collect()
}
struct Report {
quads: usize,
tris: usize,
area: f64,
min_quality: f64,
non_conforming: usize,
boundary: usize,
}
fn inspect(mesh: &Mesh) -> Report {
use crate::ops::mesh::paving::geom::{orient, quad_quality, tri_quality};
let coords = mesh.coords().unwrap();
let c = coords.read();
let at = |id: NodeId| {
let v = c.position(id).unwrap();
Point2::new(v[0], v[1])
};
let mut r = Report {
quads: 0,
tris: 0,
area: 0.0,
min_quality: f64::INFINITY,
non_conforming: 0,
boundary: 0,
};
let mut edges: HashMap<(NodeId, NodeId), usize> = HashMap::new();
let mut bump = |a: NodeId, b: NodeId| {
let k = if a.0 < b.0 { (a, b) } else { (b, a) };
*edges.entry(k).or_insert(0) += 1;
};
for sm in mesh {
let s = sm.read();
let npc = s.element_type().nodes_per_cell();
for cell in s.connectivity().chunks(npc) {
for i in 0..npc {
bump(cell[i], cell[(i + 1) % npc]);
}
let p: Vec<Point2> = cell.iter().map(|&n| at(n)).collect();
if npc == 4 {
r.quads += 1;
r.area += 0.5 * (orient(p[0], p[1], p[2]) + orient(p[0], p[2], p[3]));
r.min_quality = r.min_quality.min(quad_quality([p[0], p[1], p[2], p[3]]));
} else {
r.tris += 1;
r.area += 0.5 * orient(p[0], p[1], p[2]);
r.min_quality = r.min_quality.min(tri_quality(p[0], p[1], p[2]));
}
}
}
r.non_conforming = edges.values().filter(|&&v| v > 2).count();
r.boundary = edges.values().filter(|&&v| v == 1).count();
r
}
#[test]
fn a_square_is_paved_with_quadrangles_only() {
let coords = Handle::new(Coords::new(2).unwrap());
let contour = loop_mesh(coords, &rect_loop(1.0, 1.0, 8, 8));
let mesh = pave_surface(
&contour,
ElementType::QUA4,
Some(0.125),
false,
FrontRelax::Free,
)
.unwrap();
let r = inspect(&mesh);
assert_eq!(r.tris, 0, "{} quads, {} tris", r.quads, r.tris);
assert!((r.area - 1.0).abs() < 1e-9, "area {}", r.area);
assert_eq!(r.non_conforming, 0);
assert!(r.min_quality > 0.0, "min quality {}", r.min_quality);
}
type Loop = Vec<(f64, f64)>;
fn crenellated_frame(
width: f64,
height: f64,
inset: f64,
teeth: usize,
tooth_w: f64,
tooth_d: f64,
h: f64,
) -> (Loop, Loop) {
let cut = |corners: &[(f64, f64)]| {
let mut pts: Loop = Vec::new();
let n = corners.len();
for i in 0..n {
let (a, b) = (corners[i], corners[(i + 1) % n]);
let len = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();
let k = ((len / h).round() as usize).max(1);
for j in 0..k {
let t = j as f64 / k as f64;
pts.push((a.0 + t * (b.0 - a.0), a.1 + t * (b.1 - a.1)));
}
}
pts
};
let outer = cut(&[(0.0, 0.0), (width, 0.0), (width, height), (0.0, height)]);
let mut inner = vec![(inset, inset)];
let pitch = (width - 2.0 * inset) / teeth as f64;
for i in 0..teeth {
let x0 = inset + pitch * i as f64 + 0.5 * (pitch - tooth_w);
inner.extend([
(x0, inset),
(x0, inset - tooth_d),
(x0 + tooth_w, inset - tooth_d),
(x0 + tooth_w, inset),
]);
}
inner.extend([
(width - inset, inset),
(width - inset, height - inset),
(inset, height - inset),
]);
let mut inner = cut(&inner);
inner.reverse();
(outer, inner)
}
fn wall_layer(mesh: &Mesh, loop_pts: &[(f64, f64)]) -> Vec<f64> {
let bits = |x: f64, y: f64| (x.to_bits(), y.to_bits());
let n = loop_pts.len();
let mut wall: std::collections::HashSet<((u64, u64), (u64, u64))> = Default::default();
for i in 0..n {
let (a, b) = (loop_pts[i], loop_pts[(i + 1) % n]);
let (x, y) = (bits(a.0, a.1), bits(b.0, b.1));
wall.insert(if x < y { (x, y) } else { (y, x) });
}
let coords = mesh.coords().unwrap();
let c = coords.read();
let mut out = Vec::new();
for sm in mesh {
let s = sm.read();
let npc = s.element_type().nodes_per_cell();
for cell in s.connectivity().chunks(npc) {
let p: Vec<Point2> = cell
.iter()
.map(|&id| {
let v = c.position(id).unwrap();
Point2::new(v[0], v[1])
})
.collect();
let touches = (0..npc).any(|i| {
let (u, v) = (p[i], p[(i + 1) % npc]);
let (x, y) = (bits(u.x, u.y), bits(v.x, v.y));
wall.contains(&if x < y { (x, y) } else { (y, x) })
});
if touches {
let a: f64 = (0..npc)
.map(|i| p[i].x * p[(i + 1) % npc].y - p[(i + 1) % npc].x * p[i].y)
.sum();
out.push(0.5 * a.abs());
}
}
}
out.sort_by(|a, b| a.partial_cmp(b).unwrap());
out
}
#[test]
fn every_boundary_gets_its_first_row_before_any_gets_a_second() {
let h = 1.0;
for (w, height, inset, teeth, tw, td) in [
(16.0, 10.0, 3.0, 5, 1.4, 1.5),
(24.0, 14.0, 4.0, 6, 1.8, 1.5),
] {
let (outer, inner) = crenellated_frame(w, height, inset, teeth, tw, td, h);
let coords = Handle::new(Coords::new(2).unwrap());
let contour = loop_mesh(coords.clone(), &outer)
.union(&loop_mesh(coords, &inner))
.unwrap();
let mesh = pave_surface(
&contour,
ElementType::QUA4,
Some(h),
false,
FrontRelax::Free,
)
.unwrap();
let layer = wall_layer(&mesh, &outer);
assert!(!layer.is_empty());
assert!(
layer[0] > 0.6 * h * h,
"the {teeth}-toothed frame has a cell of {:.3} h² on its outer wall",
layer[0] / (h * h)
);
}
}
#[test]
fn a_seam_beside_a_leftover_triangle_does_not_crack_the_mesh() {
let h = 1.0;
for (w, height, inset, teeth, tw, td) in [
(16.0, 10.0, 3.0, 5, 1.4, 1.5),
(24.0, 14.0, 4.0, 6, 1.8, 1.5),
] {
let (outer, inner) = crenellated_frame(w, height, inset, teeth, tw, td, h);
let coords = Handle::new(Coords::new(2).unwrap());
let contour = loop_mesh(coords.clone(), &outer)
.union(&loop_mesh(coords, &inner))
.unwrap();
let mesh = pave_surface(
&contour,
ElementType::QUA4,
Some(h),
false,
FrontRelax::Free,
)
.unwrap();
let r = inspect(&mesh);
assert_eq!(
r.boundary,
outer.len() + inner.len(),
"holes: the mesh of the {teeth}-toothed frame is not whole"
);
assert_eq!(r.non_conforming, 0);
assert!(r.min_quality > 0.0, "quality {}", r.min_quality);
}
}
#[test]
fn a_plate_with_a_hole_is_paved_and_covers_its_area() {
let coords = Handle::new(Coords::new(2).unwrap());
let outer = loop_mesh(coords.clone(), &rect_loop(3.0, 1.0, 30, 10));
let hole = loop_mesh(coords, &circle_loop(2.25, 0.5, 0.35, 32, true));
let contour = outer.union(&hole).unwrap();
let mesh = pave_surface(
&contour,
ElementType::QUA4,
Some(0.1),
false,
FrontRelax::Free,
)
.unwrap();
let r = inspect(&mesh);
{
let all: std::collections::HashSet<NodeId> = mesh
.into_iter()
.flat_map(|sm| sm.read().connectivity().to_vec())
.collect();
for sub in [&outer[0], &hole[0]] {
for n in sub.read().connectivity() {
assert!(all.contains(n), "contour node {n:?} was seamed away");
}
}
}
let expect = 3.0 - std::f64::consts::PI * 0.35 * 0.35;
println!(
"plate: {} quads, {} tris, area {:.6} (hole polygon {:.6}), q_min {:.3}",
r.quads, r.tris, r.area, expect, r.min_quality
);
assert_eq!(r.non_conforming, 0);
assert!(r.min_quality > 0.0);
assert!((r.area - expect).abs() < 0.01, "area {}", r.area);
}
#[test]
fn cancellable_stops_on_a_preset_flag() {
let coords = Handle::new(Coords::new(2).unwrap());
let contour = loop_mesh(coords, &rect_loop(1.0, 1.0, 20, 20));
let flag = AtomicBool::new(true);
let err = pave_surface_cancellable(
&contour,
ElementType::QUA4,
Some(0.02),
false,
FrontRelax::Free,
&flag,
)
.unwrap_err();
assert!(matches!(err, PyrucastError::Interrupted));
}
#[test]
fn relaxing_the_front_along_itself_keeps_a_square_square() {
let (side, h) = (20.0, 1.0);
let n = (side / h) as usize;
let coords = Handle::new(Coords::new(2).unwrap());
let contour = loop_mesh(coords, &rect_loop(side, side, n, n));
let free = pave_surface(
&contour,
ElementType::QUA4,
Some(h),
false,
FrontRelax::Free,
)
.unwrap();
let along = pave_surface(
&contour,
ElementType::QUA4,
Some(h),
false,
FrontRelax::Along,
)
.unwrap();
assert!(free.cell_count() > 500, "{}", free.cell_count());
assert_eq!(along.cell_count(), 400);
for si in 0..along.len() {
for cell in along.cells(si).unwrap() {
let p: Vec<Point2> = cell
.nodes()
.unwrap()
.iter()
.map(|nd| {
let v = nd.position().unwrap();
Point2::new(v[0], v[1])
})
.collect();
assert_eq!(p.len(), 4);
let area = 0.5
* (0..4)
.map(|i| p[i].x * p[(i + 1) % 4].y - p[(i + 1) % 4].x * p[i].y)
.sum::<f64>();
assert!((area.abs() - 1.0).abs() < 1e-9, "area {area}");
}
}
}
#[test]
fn an_unknown_relaxation_name_is_not_read_as_the_default() {
assert_eq!(FrontRelax::from_name("along"), Some(FrontRelax::Along));
assert_eq!(FrontRelax::from_name("none"), Some(FrontRelax::Off));
assert_eq!(FrontRelax::from_name("Along"), Some(FrontRelax::Along));
assert_eq!(FrontRelax::from_name("OFF"), Some(FrontRelax::Off));
assert_eq!(FrontRelax::from_name("nope"), None);
assert_eq!(FrontRelax::from_name(""), None);
for m in [FrontRelax::Free, FrontRelax::Along, FrontRelax::Off] {
assert_eq!(FrontRelax::from_name(m.name()), Some(m));
}
}
#[test]
fn a_concave_l_shape_is_paved_without_leaving_the_material() {
let coords = Handle::new(Coords::new(2).unwrap());
let mut pts = Vec::new();
let step = 0.1;
for i in 0..20 {
pts.push((i as f64 * step, 0.0));
}
for i in 0..10 {
pts.push((2.0, i as f64 * step));
}
for i in 0..15 {
pts.push((2.0 - i as f64 * step, 1.0));
}
for i in 0..10 {
pts.push((0.5, 1.0 + i as f64 * step));
}
for i in 0..5 {
pts.push((0.5 - i as f64 * step, 2.0));
}
for i in 0..20 {
pts.push((0.0, 2.0 - i as f64 * step));
}
let contour = loop_mesh(coords, &pts);
let mesh = pave_surface(
&contour,
ElementType::QUA4,
Some(0.1),
false,
FrontRelax::Free,
)
.unwrap();
let r = inspect(&mesh);
assert_eq!(r.non_conforming, 0);
assert!(r.min_quality > 0.0, "min quality {}", r.min_quality);
assert!((r.area - 2.5).abs() < 1e-3, "area {}", r.area);
}
#[test]
fn narrow_bands_meeting_head_on_do_not_turn_the_front_inside_out() {
let coords = Handle::new(Coords::new(2).unwrap());
let (u, v) = (0.6 / 9.0, 0.3 / 40.0);
let levels = [40.0, 3.0, 6.0, 4.0, 6.0, 4.0, 6.0, 3.0, 40.0];
let mut corners: Vec<(f64, f64)> = vec![(0.0, 0.0), (0.6, 0.0)];
for (i, l) in levels.iter().enumerate().rev() {
corners.push(((i + 1) as f64 * u, l * v));
corners.push((i as f64 * u, l * v));
}
let size = 2.0 * v / 4.0; let mut pts = Vec::new();
let n = corners.len();
for i in 0..n {
let (a, b) = (corners[i], corners[(i + 1) % n]);
let len = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();
let k = (len / size).round().max(4.0) as usize;
for j in 0..k {
let t = j as f64 / k as f64;
pts.push((a.0 + t * (b.0 - a.0), a.1 + t * (b.1 - a.1)));
}
}
let contour = loop_mesh(coords, &pts);
let mesh = pave_surface(
&contour,
ElementType::QUA4,
Some(size),
false,
FrontRelax::Free,
)
.unwrap();
let r = inspect(&mesh);
assert_eq!(r.non_conforming, 0);
assert!(r.min_quality > 0.0, "min quality {}", r.min_quality);
let area: f64 = levels.iter().map(|l| u * l * v).sum();
assert!((r.area - area).abs() < 1e-3, "area {} for {area}", r.area);
}
#[test]
fn all_quad_on_an_odd_contour_is_an_error_rather_than_a_silent_triangle() {
let coords = Handle::new(Coords::new(2).unwrap());
let mut pts = rect_loop(1.0, 1.0, 4, 4);
pts.push((0.0, 0.125));
assert_eq!(pts.len() % 2, 1);
let contour = loop_mesh(coords, &pts);
let err = pave_surface(
&contour,
ElementType::QUA4,
Some(0.25),
true,
FrontRelax::Free,
)
.unwrap_err();
let msg = format!("{err}");
assert!(msg.starts_with("pave_surface:"), "{msg}");
assert!(
msg.contains("17 segments"),
"the count should be named: {msg}"
);
assert!(msg.contains("odd"), "{msg}");
let r = inspect(
&pave_surface(
&contour,
ElementType::QUA4,
Some(0.25),
false,
FrontRelax::Free,
)
.unwrap(),
);
assert!(r.tris <= 1, "odd parity costs at most one: {}", r.tris);
assert_eq!(r.non_conforming, 0);
assert!((r.area - 1.0).abs() < 2e-2, "area {}", r.area);
}
#[test]
fn the_contour_nodes_come_back_untouched() {
let coords = Handle::new(Coords::new(2).unwrap());
let pts = rect_loop(1.0, 1.0, 6, 6);
let contour = loop_mesh(coords.clone(), &pts);
let before: Vec<(NodeId, Vec<f64>)> = {
let c = coords.read();
let s = contour[0].read();
s.connectivity()
.iter()
.map(|&n| (n, c.position(n).unwrap().to_vec()))
.collect()
};
let mesh = pave_surface(
&contour,
ElementType::QUA4,
Some(0.15),
false,
FrontRelax::Free,
)
.unwrap();
let c = coords.read();
for (id, coord) in &before {
assert_eq!(
&c.position(*id).unwrap().to_vec(),
coord,
"node {id:?} moved"
);
}
let used: HashMap<NodeId, ()> = mesh
.into_iter()
.flat_map(|sm| sm.read().connectivity().to_vec())
.map(|n| (n, ()))
.collect();
for (id, _) in &before {
assert!(used.contains_key(id), "contour node {id:?} was abandoned");
}
}
#[test]
fn the_mesh_boundary_is_exactly_the_contour() {
let coords = Handle::new(Coords::new(2).unwrap());
let pts = rect_loop(3.0, 1.0, 30, 10);
let contour = loop_mesh(coords, &pts);
let mesh = pave_surface(
&contour,
ElementType::QUA4,
Some(0.1),
false,
FrontRelax::Free,
)
.unwrap();
let mut used: HashMap<(NodeId, NodeId), usize> = HashMap::new();
for sm in &mesh {
let s = sm.read();
let npc = s.element_type().nodes_per_cell();
for cell in s.connectivity().chunks(npc) {
for i in 0..npc {
let (a, b) = (cell[i], cell[(i + 1) % npc]);
let key = if a.0 < b.0 { (a, b) } else { (b, a) };
*used.entry(key).or_insert(0) += 1;
}
}
}
let contour_conn = contour[0].read();
for seg in contour_conn.connectivity().chunks(2) {
let key = if seg[0].0 < seg[1].0 {
(seg[0], seg[1])
} else {
(seg[1], seg[0])
};
assert_eq!(
used.get(&key),
Some(&1),
"contour segment {key:?} is not on the boundary"
);
}
let boundary = used.values().filter(|&&u| u == 1).count();
assert_eq!(
boundary,
pts.len(),
"the mesh boundary has {boundary} edges for {} contour segments",
pts.len()
);
}
#[test]
fn a_planar_contour_in_3d_is_paved_in_its_own_plane() {
let coords = Handle::new(Coords::new(3).unwrap());
let ids: Vec<NodeId> = rect_loop(1.0, 1.0, 6, 6)
.iter()
.map(|&(x, z)| Node::create_in(coords.clone(), &[x, 0.0, z]).unwrap().id())
.collect();
let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
let n = ids.len();
for i in 0..n {
sm.add_cell(&[ids[i], ids[(i + 1) % n]]).unwrap();
}
let contour = Mesh::from_submesh(sm);
let mesh = pave_surface(
&contour,
ElementType::QUA4,
Some(0.2),
false,
FrontRelax::Free,
)
.unwrap();
let c = coords.read();
for sm in &mesh {
for &node in sm.read().connectivity() {
assert!(
c.position(node).unwrap()[1].abs() < 1e-12,
"a node left the y = 0 plane"
);
}
}
}
#[test]
fn quadratic_forms_are_derived_from_the_quadrangles() {
let coords = Handle::new(Coords::new(2).unwrap());
let contour = loop_mesh(coords, &rect_loop(1.0, 1.0, 4, 4));
for (et, npc) in [(ElementType::QUA8, 8), (ElementType::QUA9, 9)] {
let mesh = pave_surface(&contour, et, Some(0.25), true, FrontRelax::Free).unwrap();
assert_eq!(mesh.element_types().unwrap(), vec![et]);
assert_eq!(mesh[0].read().element_type().nodes_per_cell(), npc);
}
}
#[test]
fn bad_input_is_rejected_with_a_named_error() {
let coords = Handle::new(Coords::new(2).unwrap());
let contour = loop_mesh(coords.clone(), &rect_loop(1.0, 1.0, 4, 4));
for err in [
pave_surface(&contour, ElementType::TRI3, None, false, FrontRelax::Free).unwrap_err(),
pave_surface(
&contour,
ElementType::QUA4,
Some(0.0),
false,
FrontRelax::Free,
)
.unwrap_err(),
pave_surface(
&contour,
ElementType::QUA4,
Some(-1.0),
false,
FrontRelax::Free,
)
.unwrap_err(),
] {
assert!(
format!("{err}").starts_with("pave_surface:"),
"unhelpful error: {err}"
);
}
let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
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 d = Node::create_in(coords, &[0.0, 1.0]).unwrap();
sm.add_cell(&[a.id(), b.id(), d.id()]).unwrap();
let err = pave_surface(
&Mesh::from_submesh(sm),
ElementType::QUA4,
None,
false,
FrontRelax::Free,
)
.unwrap_err();
assert!(format!("{err}").starts_with("pave_surface:"), "{err}");
}
#[test]
fn the_default_size_follows_the_contour_discretisation() {
let coords = Handle::new(Coords::new(2).unwrap());
let contour = loop_mesh(coords, &rect_loop(1.0, 1.0, 10, 10));
let mesh =
pave_surface(&contour, ElementType::QUA4, None, false, FrontRelax::Free).unwrap();
let r = inspect(&mesh);
assert_eq!(r.non_conforming, 0);
assert!((r.area - 1.0).abs() < 1e-9);
assert!(
(40..400).contains(&(r.quads + r.tris)),
"{} cells",
r.quads + r.tris
);
}
#[test]
#[ignore = "performance check, run explicitly with --ignored"]
fn perf_and_quality_plate_with_hole_under_30s() {
use crate::ops::mesh::paving::geom::{quad_quality, tri_quality};
let coords = Handle::new(Coords::new(2).unwrap());
let outer = loop_mesh(coords.clone(), &rect_loop(0.30, 0.10, 60, 20));
let hole = loop_mesh(coords, &circle_loop(0.225, 0.05, 0.035, 64, true));
let contour = outer.union(&hole).unwrap();
let t0 = std::time::Instant::now();
let mesh = pave_surface(
&contour,
ElementType::QUA4,
Some(0.00029),
false,
FrontRelax::Free,
)
.unwrap();
let dt = t0.elapsed();
let c = mesh.coords().unwrap().read();
let at = |id: NodeId| {
let v = c.position(id).unwrap();
Point2::new(v[0], v[1])
};
let (mut nq, mut nt) = (0usize, 0usize);
let mut worst = f64::INFINITY;
let mut under = 0usize;
for sm in &mesh {
let s = sm.read();
let npc = s.element_type().nodes_per_cell();
for cell in s.connectivity().chunks(npc) {
let p: Vec<Point2> = cell.iter().map(|&n| at(n)).collect();
let q = if npc == 4 {
nq += 1;
quad_quality([p[0], p[1], p[2], p[3]])
} else {
nt += 1;
tri_quality(p[0], p[1], p[2])
};
worst = worst.min(q);
if q < 0.5 {
under += 1;
}
}
}
let total = nq + nt;
let rate = total as f64 / dt.as_secs_f64();
println!(
"pave_surface: {total} cells ({nq} QUA4 + {nt} TRI3) in {:.2} s\n\
\x20 rate {:.0} cells/s | quads {:.1} % | worst scaled Jacobian {:.3} | below 0.5: {:.2} %",
dt.as_secs_f64(),
rate,
100.0 * nq as f64 / total as f64,
worst,
100.0 * under as f64 / total as f64,
);
assert!(dt.as_secs_f64() < 30.0, "took {:?}", dt);
assert!(rate > 10_000.0, "only {rate:.0} cells/s");
assert!(worst > 0.0, "an inverted cell got through: {worst}");
assert!(
nq as f64 / total as f64 > 0.95,
"only {:.1} % quadrangles",
100.0 * nq as f64 / total as f64
);
}
#[test]
#[ignore = "reporting run, not an assertion"]
fn quality_report_plate_with_hole() {
use crate::ops::mesh::paving::geom::{quad_quality, tri_quality};
let coords = Handle::new(Coords::new(2).unwrap());
let outer = loop_mesh(coords.clone(), &rect_loop(0.30, 0.10, 60, 20));
let hole = loop_mesh(coords, &circle_loop(0.225, 0.05, 0.035, 64, true));
let contour = outer.union(&hole).unwrap();
let target = 0.0016;
let t0 = std::time::Instant::now();
let mesh = pave_surface(
&contour,
ElementType::QUA4,
Some(target),
false,
FrontRelax::Free,
)
.unwrap();
let dt = t0.elapsed();
let c = mesh.coords().unwrap().read();
let at = |id: NodeId| {
let v = c.position(id).unwrap();
Point2::new(v[0], v[1])
};
let mut jac: Vec<f64> = Vec::new();
let mut angles: Vec<f64> = Vec::new();
let mut aspect: Vec<f64> = Vec::new();
let mut edges: Vec<f64> = Vec::new();
let mut valence: HashMap<NodeId, usize> = HashMap::new();
let mut edge_use: HashMap<(NodeId, NodeId), usize> = HashMap::new();
let (mut nq, mut nt) = (0usize, 0usize);
for sm in &mesh {
let s = sm.read();
let npc = s.element_type().nodes_per_cell();
for cell in s.connectivity().chunks(npc) {
let p: Vec<Point2> = cell.iter().map(|&n| at(n)).collect();
if npc == 4 {
nq += 1;
jac.push(quad_quality([p[0], p[1], p[2], p[3]]));
} else {
nt += 1;
jac.push(tri_quality(p[0], p[1], p[2]));
}
let mut lo = f64::INFINITY;
let mut hi: f64 = 0.0;
for i in 0..npc {
let (prev, cur, next) = (p[(i + npc - 1) % npc], p[i], p[(i + 1) % npc]);
let (u, w) = (prev - cur, next - cur);
let ang = (u.dot(&w) / (u.norm() * w.norm())).clamp(-1.0, 1.0).acos();
angles.push(ang.to_degrees());
let l = w.norm();
lo = lo.min(l);
hi = hi.max(l);
edges.push(l);
*valence.entry(cell[i]).or_insert(0) += 1;
let (a, b) = (cell[i], cell[(i + 1) % npc]);
let key = if a.0 < b.0 { (a, b) } else { (b, a) };
*edge_use.entry(key).or_insert(0) += 1;
}
aspect.push(hi / lo);
}
}
let pct = |v: &mut Vec<f64>, q: f64| {
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[((v.len() - 1) as f64 * q) as usize]
};
let total = nq + nt;
let boundary: usize = edge_use.values().filter(|&&u| u == 1).count();
let interior_nodes: Vec<NodeId> = {
let mut on_boundary: std::collections::HashSet<NodeId> =
std::collections::HashSet::new();
for ((a, b), &u) in &edge_use {
if u == 1 {
on_boundary.insert(*a);
on_boundary.insert(*b);
}
}
valence
.keys()
.filter(|n| !on_boundary.contains(n))
.copied()
.collect()
};
let mut hist: HashMap<usize, usize> = HashMap::new();
for n in &interior_nodes {
*hist.entry(valence[n]).or_insert(0) += 1;
}
let irregular = interior_nodes.iter().filter(|n| valence[n] != 4).count();
println!("\n┌─ pave_surface — plaque 30 × 10 cm, trou r = 3,5 cm, taille visée {target} m");
println!("│");
println!(
"│ mailles {total} ({nq} QUA4 + {nt} TRI3, {:.2} % quadrangles)",
100.0 * nq as f64 / total as f64
);
println!(
"│ temps {:.2} s ({:.0} mailles/s)",
dt.as_secs_f64(),
total as f64 / dt.as_secs_f64()
);
println!(
"│ nœuds {} (dont {} intérieurs)",
valence.len(),
interior_nodes.len()
);
println!("│ arêtes de bord {boundary}");
println!(
"│ conformité {}",
if edge_use.values().all(|&u| u <= 2) {
"OK — aucune arête à plus de 2 mailles"
} else {
"ROMPUE"
}
);
println!("│");
println!("│ Jacobien normalisé (1 = carré, ≤ 0 = inintégrable)");
println!(
"│ min {:.3} p1 {:.3} p5 {:.3} médiane {:.3} moyenne {:.3}",
pct(&mut jac.clone(), 0.0),
pct(&mut jac.clone(), 0.01),
pct(&mut jac.clone(), 0.05),
pct(&mut jac.clone(), 0.5),
jac.iter().sum::<f64>() / jac.len() as f64
);
for seuil in [0.0, 0.2, 0.5, 0.7] {
println!(
"│ sous {seuil:.1} : {:.3} % ({} mailles)",
100.0 * jac.iter().filter(|&&j| j < seuil).count() as f64 / total as f64,
jac.iter().filter(|&&j| j < seuil).count()
);
}
println!("│");
println!("│ Angles (degrés)");
println!(
"│ min {:.1} p1 {:.1} médiane {:.1} p99 {:.1} max {:.1}",
pct(&mut angles.clone(), 0.0),
pct(&mut angles.clone(), 0.01),
pct(&mut angles.clone(), 0.5),
pct(&mut angles.clone(), 0.99),
pct(&mut angles.clone(), 1.0)
);
println!(
"│ sous 30° : {:.2} % au-dessus de 150° : {:.2} %",
100.0 * angles.iter().filter(|&&a| a < 30.0).count() as f64 / angles.len() as f64,
100.0 * angles.iter().filter(|&&a| a > 150.0).count() as f64 / angles.len() as f64
);
println!("│");
println!("│ Élancement (arête la plus longue / la plus courte)");
println!(
"│ médiane {:.2} p99 {:.2} max {:.2}",
pct(&mut aspect.clone(), 0.5),
pct(&mut aspect.clone(), 0.99),
pct(&mut aspect.clone(), 1.0)
);
println!("│");
println!("│ Taille d'arête (visée {target})");
println!(
"│ p1 {:.5} médiane {:.5} p99 {:.5}",
pct(&mut edges.clone(), 0.01),
pct(&mut edges.clone(), 0.5),
pct(&mut edges.clone(), 0.99)
);
println!("│");
println!("│ Valence des nœuds intérieurs (4 = régulier)");
let mut ks: Vec<usize> = hist.keys().copied().collect();
ks.sort_unstable();
for k in ks {
println!(
"│ {k} : {:>6} ({:.2} %)",
hist[&k],
100.0 * hist[&k] as f64 / interior_nodes.len() as f64
);
}
println!(
"│ irréguliers : {irregular} sur {} ({:.2} %)",
interior_nodes.len(),
100.0 * irregular as f64 / interior_nodes.len() as f64
);
println!("└─");
}
}