pub mod cleanup;
pub mod close;
pub mod front;
pub mod geom;
pub mod proximity;
pub mod row;
pub mod smooth;
use crate::containers::mesh::{NodeId, Point2};
use crate::error::{PyrucastError, Result};
use crate::interrupt::Cancel;
use crate::ops::mesher::contour::Domain;
use front::Front;
use geom::segments_cross;
use proximity::EdgeGrid;
use row::{Corner, RowPlan};
use std::collections::HashMap;
const CLOSE_AT: usize = 6;
const RETREAT: f64 = 0.55;
const RETREAT_NEIGHBOUR: f64 = 0.8;
const RETREAT_STEPS: usize = 8;
const SEAM_FACTOR: f64 = 0.72;
const CHORD_RADIUS_STEPS: usize = 4;
const CHORD_CANDIDATES: usize = 8;
const MAX_STALL: u32 = 2;
const FOLD_TOLERANCE: f64 = 0.5;
const FINAL_SWEEPS: usize = 12;
const FRONT_SWEEPS: usize = 4;
const FRONT_RELAX: f64 = 0.5;
pub struct Fabric {
pub pts: Vec<Point2>,
pub movable: Vec<bool>,
pub quads: Vec<[u32; 4]>,
pub tris: Vec<[u32; 3]>,
pub contour_ids: Vec<NodeId>,
incident: Vec<Vec<u32>>,
}
impl Fabric {
fn add(&mut self, p: Point2, movable: bool) -> u32 {
self.pts.push(p);
self.movable.push(movable);
self.incident.push(Vec::new());
(self.pts.len() - 1) as u32
}
fn push_quad(&mut self, q: [u32; 4]) {
let i = self.quads.len() as u32;
self.quads.push(q);
for &c in &q {
self.incident[c as usize].push(i);
}
}
}
pub fn pave(
domain: &Domain,
target: Option<f64>,
all_quad: bool,
cancel: &dyn Cancel,
) -> Result<Fabric> {
let mut fab = Fabric {
pts: Vec::new(),
movable: Vec::new(),
quads: Vec::new(),
tris: Vec::new(),
contour_ids: Vec::new(),
incident: Vec::new(),
};
let mut loops: Vec<Vec<u32>> = Vec::new();
let mut perimeter = 0.0;
let mut segments = 0usize;
for l in std::iter::once(&domain.outer).chain(&domain.holes) {
let mut verts = Vec::with_capacity(l.pts.len());
for (k, p) in l.pts.iter().enumerate() {
fab.contour_ids.push(l.node_ids[k]);
verts.push(fab.add(*p, false));
}
let n = l.pts.len();
for i in 0..n {
perimeter += (l.pts[(i + 1) % n] - l.pts[i]).norm();
}
segments += n;
loops.push(verts);
}
let target = match target {
Some(t) => t,
None => perimeter / segments.max(1) as f64,
};
if all_quad {
for (k, verts) in loops.iter().enumerate() {
if !verts.len().is_multiple_of(2) {
let which = if k == 0 { "outer boundary" } else { "hole" };
return Err(PyrucastError::Message(format!(
"pave_surface: all_quad was asked for, but the {which} loop has {} \
segments — an odd number. A polygon with an odd number of sides has no \
filling by quadrangles alone, and paving cannot change that parity. \
Re-mesh that loop with an even number of segments.",
verts.len()
)));
}
}
}
let mut front = Front::new();
let mut stack: Vec<(u32, u32)> = Vec::new();
for verts in &loops {
if verts.len() >= 3 {
stack.push((front.add_loop(verts), 0));
}
}
let cap = 64 * segments + 4096;
let mut steps = 0usize;
while let Some((rep, stalls)) = stack.pop() {
if !front.is_alive(rep) {
continue;
}
cancel.check()?;
steps += 1;
let n = front.loop_len(rep);
if n < 3 {
front.kill_loop(rep);
continue;
}
if n <= CLOSE_AT || steps > cap {
close_loop(&mut fab, &mut front, rep, target)?;
continue;
}
if stalls > MAX_STALL {
if !unstick(&fab, &mut front, rep, target, all_quad, &mut stack) {
close_loop(&mut fab, &mut front, rep, target)?;
}
continue;
}
match try_row(&mut fab, &mut front, rep, target, all_quad) {
Some(None) => {}
Some(Some(new_rep)) => {
let seamed = match find_seam(&front, &fab, new_rep, target, all_quad) {
Some((a, b)) => seam(&mut fab, &mut front, a, b, &mut stack),
None => false,
};
if !seamed {
stack.push((new_rep, 0));
}
}
None => {
let seamed = match find_seam(&front, &fab, rep, target, all_quad) {
Some((a, b)) => seam(&mut fab, &mut front, a, b, &mut stack),
None => false,
};
if !seamed {
stack.push((rep, stalls + 1));
}
}
}
}
cleanup::run(&fab.pts, &fab.movable, &mut fab.quads, &fab.tris);
compact(&mut fab);
let patch = smooth::Patch {
quads: &fab.quads,
tris: &fab.tris,
movable: &fab.movable,
};
let inc = smooth::Incidence::build(&patch, fab.pts.len());
let mut pts = std::mem::take(&mut fab.pts);
smooth::smooth(&mut pts, &patch, &inc, None, FINAL_SWEEPS);
fab.pts = pts;
Ok(fab)
}
fn compact(fab: &mut Fabric) {
let n_contour = fab.contour_ids.len();
let mut used = vec![false; fab.pts.len()];
used[..n_contour].fill(true);
for q in &fab.quads {
for &v in q {
used[v as usize] = true;
}
}
for t in &fab.tris {
for &v in t {
used[v as usize] = true;
}
}
if used.iter().all(|&u| u) {
return;
}
let mut remap = vec![u32::MAX; fab.pts.len()];
let (mut pts, mut movable) = (Vec::new(), Vec::new());
for i in 0..fab.pts.len() {
if used[i] {
remap[i] = pts.len() as u32;
pts.push(fab.pts[i]);
movable.push(fab.movable[i]);
}
}
for q in fab.quads.iter_mut() {
*q = q.map(|v| remap[v as usize]);
}
for t in fab.tris.iter_mut() {
*t = t.map(|v| remap[v as usize]);
}
fab.pts = pts;
fab.movable = movable;
fab.incident.clear();
}
fn try_row(
fab: &mut Fabric,
front: &mut Front,
rep: u32,
target: f64,
all_quad: bool,
) -> Option<Option<u32>> {
let slots = front.loop_slots(rep);
let n = slots.len();
let p: Vec<Point2> = slots
.iter()
.map(|&s| fab.pts[front.vertex(s) as usize])
.collect();
let base: Vec<f64> = (0..n)
.map(|i| {
let span = 0.5 * ((p[(i + 1) % n] - p[i]).norm() + (p[i] - p[(i + n - 1) % n]).norm());
(0.5 * span + 0.5 * target).clamp(0.5 * target, 2.0 * target)
})
.collect();
let grid = EdgeGrid::build(front, &fab.pts, target);
let mut scale = vec![1.0f64; n];
for _ in 0..RETREAT_STEPS {
let sz = |i: usize| base[i] * scale[i];
let want = |i: usize| base[i];
match row::plan(front, &fab.pts, rep, &sz, &want, all_quad) {
Ok(plan) => {
if chain_is_free(front, fab, &grid, &plan) {
let out = commit(fab, front, rep, plan);
if let Some(new_rep) = out {
relax_front(fab, front, new_rep);
}
return Some(out);
}
for s in scale.iter_mut() {
*s *= RETREAT;
}
}
Err(blame) => {
if blame.is_empty() {
return None;
}
for i in blame {
scale[i] *= RETREAT;
scale[(i + 1) % n] *= RETREAT_NEIGHBOUR;
scale[(i + n - 1) % n] *= RETREAT_NEIGHBOUR;
}
}
}
}
None
}
fn chain_is_free(front: &Front, fab: &Fabric, grid: &EdgeGrid, plan: &RowPlan) -> bool {
let m = plan.chain.len();
if m < 3 {
return true;
}
let at = |i: u32| plan.pts[i as usize];
for i in 0..m {
let (a, b) = (at(plan.chain[i]), at(plan.chain[(i + 1) % m]));
for s in grid.near_segment(a, b) {
let c = fab.pts[front.vertex(s) as usize];
let d = fab.pts[front.vertex(front.next(s)) as usize];
if segments_cross(a, b, c, d) {
return false;
}
}
}
let ring: Vec<Point2> = plan.chain.iter().map(|&i| at(i)).collect();
let own = EdgeGrid::of_ring(&ring, 0.0);
for i in 0..m {
let (a, b) = (ring[i], ring[(i + 1) % m]);
for j in own.near_segment(a, b) {
let j = j as usize;
if j == i || (j + 1) % m == i || (i + 1) % m == j {
continue;
}
if segments_cross(a, b, ring[j], ring[(j + 1) % m]) {
return false;
}
}
}
true
}
fn commit(fab: &mut Fabric, front: &mut Front, rep: u32, plan: RowPlan) -> Option<u32> {
let base = fab.pts.len() as u32;
for p in &plan.pts {
fab.add(*p, true);
}
let map = |c: Corner| match c {
Corner::Old(i) => i,
Corner::New(i) => base + i,
};
for q in &plan.quads {
fab.push_quad([map(q[0]), map(q[1]), map(q[2]), map(q[3])]);
}
let verts: Vec<u32> = plan.chain.iter().map(|&i| base + i).collect();
if verts.len() < 3 {
front.kill_loop(rep);
return None;
}
Some(front.relink_loop(rep, &verts))
}
fn relax_front(fab: &mut Fabric, front: &Front, rep: u32) {
let slots = front.loop_slots(rep);
let n = slots.len();
if n < 4 {
return;
}
let verts: Vec<u32> = slots.iter().map(|&s| front.vertex(s)).collect();
for _ in 0..FRONT_SWEEPS {
let old: Vec<Point2> = verts.iter().map(|&v| fab.pts[v as usize]).collect();
for i in 0..n {
let v = verts[i];
if !fab.movable[v as usize] {
continue;
}
let cand = Point2::from(
old[i].coords * FRONT_RELAX
+ (old[(i + n - 1) % n].coords + old[(i + 1) % n].coords)
* ((1.0 - FRONT_RELAX) * 0.5),
);
let keep = fab.pts[v as usize];
fab.pts[v as usize] = cand;
let ok = fab.incident[v as usize].iter().all(|&qi| {
let q = fab.quads[qi as usize];
geom::quad_is_valid([
fab.pts[q[0] as usize],
fab.pts[q[1] as usize],
fab.pts[q[2] as usize],
fab.pts[q[3] as usize],
])
});
if !ok {
fab.pts[v as usize] = keep;
}
}
}
}
fn close_loop(fab: &mut Fabric, front: &mut Front, rep: u32, target: f64) -> Result<()> {
let verts: Vec<u32> = front
.loop_slots(rep)
.iter()
.map(|&s| front.vertex(s))
.collect();
let poly: Vec<Point2> = verts.iter().map(|&v| fab.pts[v as usize]).collect();
let area = crate::ops::mesher::triangulation::signed_area(&poly);
if area <= 0.0 {
if -area <= FOLD_TOLERANCE * target * target {
weld(fab, front, rep);
front.kill_loop(rep);
return Ok(());
}
let centre = poly
.iter()
.fold(Point2::origin(), |acc, p| acc + p.coords)
.coords
/ poly.len() as f64;
return Err(PyrucastError::Message(format!(
"pave_surface: the advancing front folded onto itself near ({:.6}, {:.6}) in the \
meshing plane, leaving a region that cannot be filled. The contour there is too \
coarse or too uneven for the element size asked of it: discretise it closer to \
the target size, or ask for a larger one.",
centre.x, centre.y
)));
}
let filled = close::close(&fab.pts, &verts);
for p in &filled.added {
fab.add(*p, true);
}
for q in filled.quads {
fab.push_quad(q);
}
fab.tris.extend(filled.tris);
front.kill_loop(rep);
Ok(())
}
fn unstick(
fab: &Fabric,
front: &mut Front,
rep: u32,
target: f64,
all_quad: bool,
stack: &mut Vec<(u32, u32)>,
) -> bool {
let slots = front.loop_slots(rep);
let n = slots.len();
if n < 8 {
return false;
}
let rank: HashMap<u32, usize> = slots.iter().enumerate().map(|(i, &s)| (s, i)).collect();
let grid = EdgeGrid::build(front, &fab.pts, target);
for step in 0..CHORD_RADIUS_STEPS {
let radius = target * (1 << step) as f64;
let mut cand: Vec<(f64, usize, usize)> = Vec::new();
for (i, &sa) in slots.iter().enumerate() {
let pa = fab.pts[front.vertex(sa) as usize];
for sb in grid.near_point(pa, radius) {
let Some(&j) = rank.get(&sb) else { continue };
let gap = (j + n - i) % n;
if gap < 3 || n - gap < 3 || (all_quad && gap.is_multiple_of(2)) {
continue;
}
let d = (fab.pts[front.vertex(sb) as usize] - pa).norm();
if d < radius {
cand.push((d, i, j));
}
}
}
cand.sort_by(|x, y| x.partial_cmp(y).unwrap());
let best = cand
.iter()
.take(CHORD_CANDIDATES)
.find(|&&(_, i, j)| seam_is_clear(front, fab, &grid, slots[i], slots[j]))
.copied();
if let Some((_, i, j)) = best {
let (ra, rb) = front.split_by_chord(slots[i], slots[j]);
stack.push((ra, 0));
stack.push((rb, 0));
return true;
}
}
false
}
fn weld(fab: &mut Fabric, front: &Front, rep: u32) {
let mut verts: Vec<u32> = front
.loop_slots(rep)
.iter()
.map(|&s| front.vertex(s))
.collect();
while verts.len() >= 4 {
let n = verts.len();
let mut best: Option<(f64, usize, usize)> = None;
for i in 0..n {
for j in (i + 2)..n {
if i == 0 && j == n - 1 {
continue;
}
let d = (fab.pts[verts[j] as usize] - fab.pts[verts[i] as usize]).norm();
if best.is_none_or(|(bd, _, _)| d < bd) {
best = Some((d, i, j));
}
}
}
let Some((_, i, j)) = best else { break };
let (a, b) = (verts[i], verts[j]);
if !merge_into(fab, a, b) && !merge_into(fab, b, a) {
break;
}
verts.remove(j);
}
}
fn find_seam(
front: &Front,
fab: &Fabric,
rep: u32,
target: f64,
all_quad: bool,
) -> Option<(u32, u32)> {
let radius = SEAM_FACTOR * target;
let slots = front.loop_slots(rep);
let n = slots.len();
let rank: HashMap<u32, usize> = slots.iter().enumerate().map(|(i, &s)| (s, i)).collect();
let grid = EdgeGrid::build(front, &fab.pts, target);
let mut best: Option<(f64, u32, u32)> = None;
for (i, &a) in slots.iter().enumerate() {
let pa = fab.pts[front.vertex(a) as usize];
for b in grid.near_point(pa, radius) {
if b == a || front.next(a) == b || front.next(b) == a {
continue;
}
if front.vertex(a) == front.vertex(b) {
continue;
}
let pb = fab.pts[front.vertex(b) as usize];
let d = (pb - pa).norm();
if d >= radius {
continue;
}
if let Some(&j) = rank.get(&b) {
let gap = (j + n - i) % n;
if gap < 2 || gap > n - 2 {
continue;
}
if all_quad && gap % 2 == 1 {
continue;
}
}
if !seam_is_clear(front, fab, &grid, a, b) {
continue;
}
let key = (d, a.min(b), a.max(b));
if best.is_none_or(|cur| key < cur) {
best = Some(key);
}
}
}
best.map(|(_, a, b)| (a, b))
}
fn seam_is_clear(front: &Front, fab: &Fabric, grid: &EdgeGrid, a: u32, b: u32) -> bool {
let pa = fab.pts[front.vertex(a) as usize];
let pb = fab.pts[front.vertex(b) as usize];
for (s, from, to) in [(a, pa, pb), (b, pb, pa)] {
let prev = fab.pts[front.vertex(front.prev(s)) as usize];
let next = fab.pts[front.vertex(front.next(s)) as usize];
let convex = geom::orient(prev, from, next) > 0.0;
let left = geom::orient(from, next, to) > 0.0;
let right = geom::orient(prev, from, to) > 0.0;
let inside = if convex { left && right } else { left || right };
if !inside {
return false;
}
}
for s in grid.near_segment(pa, pb) {
let (u, w) = (s, front.next(s));
if u == a || u == b || w == a || w == b {
continue;
}
if segments_cross(
pa,
pb,
fab.pts[front.vertex(u) as usize],
fab.pts[front.vertex(w) as usize],
) {
return false;
}
}
true
}
fn seam(fab: &mut Fabric, front: &mut Front, a: u32, b: u32, stack: &mut Vec<(u32, u32)>) -> bool {
for (x, y) in [(a, b), (b, a)] {
if merge_into(fab, front.vertex(x), front.vertex(y)) {
let (m1, m2) = front.merge(a, b, front.vertex(x));
stack.push((m1, 0));
stack.push((m2, 0));
return true;
}
}
false
}
fn merge_into(fab: &mut Fabric, keep: u32, drop: u32) -> bool {
if keep == drop {
return false;
}
if !fab.movable[drop as usize] {
return false;
}
let touching = fab.incident[drop as usize].clone();
let rewrite = |q: [u32; 4]| q.map(|c| if c == drop { keep } else { c });
for &qi in &touching {
let q = fab.quads[qi as usize];
if q.contains(&keep) {
return false;
}
let q = rewrite(q);
if !geom::quad_is_valid([
fab.pts[q[0] as usize],
fab.pts[q[1] as usize],
fab.pts[q[2] as usize],
fab.pts[q[3] as usize],
]) {
return false;
}
}
let mut around: HashMap<u32, usize> = HashMap::new();
for &qi in touching.iter().chain(&fab.incident[keep as usize]) {
let q = rewrite(fab.quads[qi as usize]);
for t in 0..4 {
if q[t] == keep {
*around.entry(q[(t + 1) % 4]).or_insert(0) += 1;
*around.entry(q[(t + 3) % 4]).or_insert(0) += 1;
}
}
}
if around.values().any(|&c| c > 2) {
return false;
}
for &qi in &touching {
fab.quads[qi as usize] = rewrite(fab.quads[qi as usize]);
fab.incident[keep as usize].push(qi);
}
fab.incident[drop as usize].clear();
true
}