pub mod cleanup;
pub mod close;
pub mod front;
pub mod geom;
pub mod grid;
pub mod grid2;
pub mod proximity;
pub mod row;
pub mod smooth;
use crate::aggregate::Aggregate;
use crate::atoms::{ElementType, NodeId, Point2};
use crate::containers::mesh::{Mesh, SubMesh};
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::interrupt::Cancel;
use crate::ops::mesh::contour::{Contour, Domain};
use front::Front;
use geom::segments_cross;
use proximity::EdgeGrid;
use row::{Corner, RowPlan};
use std::collections::{HashMap, HashSet};
const CLOSE_AT: usize = 6;
const RETREAT: f64 = 0.55;
const RETREAT_NEIGHBOUR: f64 = 0.8;
const RETREAT_STEPS: usize = 8;
const RETREAT_FLOOR: f64 = 0.5;
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;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FrontRelax {
#[default]
Free,
Along,
Off,
}
impl FrontRelax {
pub fn name(self) -> &'static str {
match self {
FrontRelax::Free => "free",
FrontRelax::Along => "along",
FrontRelax::Off => "none",
}
}
}
impl crate::named::Named for FrontRelax {
const LABEL: &'static str = "front relaxation";
const VALUES: &'static [Self] = &[Self::Free, Self::Along, Self::Off];
fn name(self) -> &'static str {
FrontRelax::name(self)
}
fn aliases() -> &'static [(&'static str, Self)] {
&[("off", Self::Off)]
}
}
pub struct Fabric {
pub pts: Vec<Point2>,
pub movable: Vec<bool>,
pinned: Vec<bool>,
pub quads: Vec<[u32; 4]>,
dead: Vec<bool>,
pub tris: Vec<[u32; 3]>,
pub contour_ids: Vec<NodeId>,
contour_edges: HashSet<(u32, u32)>,
incident: Vec<Vec<u32>>,
}
impl Fabric {
fn add(&mut self, p: Point2, movable: bool, pinned: bool) -> u32 {
self.pts.push(p);
self.movable.push(movable);
self.pinned.push(pinned);
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);
self.dead.push(false);
for &c in &q {
self.incident[c as usize].push(i);
}
}
fn kill_quad(&mut self, qi: u32) {
self.dead[qi as usize] = true;
for c in self.quads[qi as usize] {
self.incident[c as usize].retain(|&x| x != qi);
}
}
}
fn bury_dead_quads(fab: &mut Fabric) {
if !fab.dead.iter().any(|&d| d) {
return;
}
let mut kept = Vec::with_capacity(fab.quads.len());
for (i, q) in fab.quads.iter().enumerate() {
if !fab.dead[i] {
kept.push(*q);
}
}
fab.quads = kept;
fab.dead.clear();
fab.incident.clear();
}
pub fn pave(
domain: &Domain,
target: Option<f64>,
all_quad: bool,
relax: FrontRelax,
cancel: &dyn Cancel,
op: &str,
) -> Result<Fabric> {
pave_inner(domain, target, all_quad, relax, None, cancel, op)
}
pub fn pave_grid(
domain: &Domain,
target: Option<f64>,
all_quad: bool,
relax: FrontRelax,
band: usize,
cancel: &dyn Cancel,
op: &str,
) -> Result<Fabric> {
pave_inner(
domain,
target,
all_quad,
relax,
Some((band, false)),
cancel,
op,
)
}
pub fn pave_grid2(
domain: &Domain,
target: Option<f64>,
all_quad: bool,
relax: FrontRelax,
band: usize,
cancel: &dyn Cancel,
op: &str,
) -> Result<Fabric> {
pave_inner(
domain,
target,
all_quad,
relax,
Some((band, true)),
cancel,
op,
)
}
fn pave_inner(
domain: &Domain,
target: Option<f64>,
all_quad: bool,
relax: FrontRelax,
band: Option<(usize, bool)>,
cancel: &dyn Cancel,
op: &str,
) -> Result<Fabric> {
let seed_first = band.is_none();
let mut fab = Fabric {
pts: Vec::new(),
movable: Vec::new(),
pinned: Vec::new(),
quads: Vec::new(),
dead: Vec::new(),
tris: Vec::new(),
contour_ids: Vec::new(),
contour_edges: HashSet::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, true));
}
let n = l.pts.len();
for i in 0..n {
perimeter += (l.pts[(i + 1) % n] - l.pts[i]).norm();
}
segments += n;
for i in 0..n {
let (a, b) = (verts[i], verts[(i + 1) % n]);
fab.contour_edges
.insert(if a < b { (a, b) } else { (b, a) });
}
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!(
"{op}: 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 seeds: Vec<(Vec<u32>, bool)> = match band {
None => loops.iter().map(|l| (l.clone(), false)).collect(),
Some((band, false)) => grid::build(&mut fab, domain, &loops, target, band).band,
Some((band, true)) => grid2::build(&mut fab, domain, &loops, target, band).band,
};
let mut front = Front::new();
let mut stack: Vec<(u32, u32)> = Vec::new();
let mut seeded: std::collections::VecDeque<(u32, u32)> = Default::default();
for (verts, frozen) in &seeds {
if verts.len() < 3 {
continue;
}
if *frozen {
front.add_frozen_loop(verts);
} else if seed_first {
seeded.push_back((front.add_loop(verts), 0));
} else {
stack.push((front.add_loop(verts), 0));
}
}
let cap = 64 * segments + 4096;
let mut steps = 0usize;
while let Some((rep, stalls)) = seeded.pop_front().or_else(|| 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 steps > cap {
return Err(PyrucastError::Message(format!(
"{op}: the advancing front did not converge — it has taken {steps} turns on a \
contour of {segments} segments and is still not done. This is what a front \
that cannot settle looks like: try the default front relaxation \
(relax = \"{}\"), a target size closer to the contour's own spacing, or a \
contour discretised more evenly.",
FrontRelax::Free.name()
)));
}
if n <= CLOSE_AT {
close_loop(&mut fab, &mut front, rep, target, op)?;
continue;
}
if stalls > MAX_STALL {
if !unstick(&fab, &mut front, rep, target, all_quad, &mut stack) {
close_loop(&mut fab, &mut front, rep, target, op)?;
}
continue;
}
match try_row(&mut fab, &mut front, rep, target, all_quad, relax) {
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));
}
}
}
}
erase_thin_triangle_pairs(&mut fab);
bury_dead_quads(&mut fab);
cleanup::run(&mut fab.pts, &fab.movable, &mut fab.quads, &mut 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;
all_cells_are_the_right_way_round(&fab, op)?;
Ok(fab)
}
fn all_cells_are_the_right_way_round(fab: &Fabric, op: &str) -> Result<()> {
crate::ops::mesh::triangulation::reject_cells_turned_the_wrong_way(
&fab.pts,
|| {
fab.quads
.iter()
.map(|q| q.as_slice())
.chain(fab.tris.iter().map(|t| t.as_slice()))
},
op,
)
}
pub fn materialize(parsed: &Contour, fabrics: Vec<Fabric>, op: &str) -> Result<Mesh> {
let coords = &parsed.coords;
const RANK: u32 = 1 << 31;
let mut interior: Vec<f64> = Vec::new();
let mut n_interior = 0u32;
let mut quad_conn: Vec<NodeId> = Vec::new();
let mut tri_conn: Vec<NodeId> = Vec::new();
for fab in fabrics {
let mut flat: Vec<NodeId> = fab.contour_ids.clone();
for p in &fab.pts[fab.contour_ids.len()..] {
interior.extend_from_slice(&parsed.frame.to_world(*p, parsed.dim));
flat.push(NodeId(RANK | n_interior));
n_interior += 1;
}
for q in &fab.quads {
quad_conn.extend(q.iter().map(|&i| flat[i as usize]));
}
for t in &fab.tris {
tri_conn.extend(t.iter().map(|&i| flat[i as usize]));
}
}
let first = coords.write().add_nodes(&interior)?.start;
let resolve = |conn: &mut Vec<NodeId>| {
for slot in conn.iter_mut() {
if slot.0 & RANK != 0 {
*slot = NodeId(first + (slot.0 & !RANK));
}
}
};
resolve(&mut quad_conn);
resolve(&mut tri_conn);
let mut mesh = Mesh::empty();
if !quad_conn.is_empty() {
mesh.add_sub(Handle::new(SubMesh::from_connectivity(
coords.clone(),
ElementType::QUA4,
quad_conn,
)?))?;
}
if !tri_conn.is_empty() {
mesh.add_sub(Handle::new(SubMesh::from_connectivity(
coords.clone(),
ElementType::TRI3,
tri_conn,
)?))?;
}
let owned: Vec<NodeId> = (first..first + n_interior).map(NodeId).collect();
coords.write().decref_all(&owned)?;
if mesh.is_empty() {
return Err(PyrucastError::Message(format!("{op}: produced no cell")));
}
Ok(mesh)
}
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, mut pinned) = (Vec::new(), 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]);
pinned.push(fab.pinned[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.pinned = pinned;
fab.incident.clear();
}
fn try_row(
fab: &mut Fabric,
front: &mut Front,
rep: u32,
target: f64,
all_quad: bool,
relax: FrontRelax,
) -> 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 mut base: Vec<f64> = vec![target; n];
aim_at_frozen(front, fab, &p, &mut base, target);
let grid = EdgeGrid::build(front, &fab.pts, target);
let was = crate::ops::mesh::triangulation::signed_area(&p);
let mut scale = vec![1.0f64; n];
for _ in 0..RETREAT_STEPS {
if (0..n).all(|i| base[i] * scale[i] < RETREAT_FLOOR * target) {
return None;
}
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 keeps_orientation(&plan, was) && 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, relax);
}
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
}
const AIM_RANGE: f64 = 4.5;
fn aim_at_frozen(front: &Front, fab: &Fabric, p: &[Point2], base: &mut [f64], target: f64) {
let frozen: Vec<Point2> = front
.frozen_slots()
.map(|s| fab.pts[front.vertex(s) as usize])
.collect();
if frozen.is_empty() {
return;
}
let reach = AIM_RANGE * target;
let cells = proximity::PointGrid::build(&frozen, target);
for (i, b) in base.iter_mut().enumerate() {
if let Some(d) = cells.nearest_within(&frozen, p[i], reach) {
let rows = (d / target).round().max(1.0);
*b = (d / rows).clamp(0.5 * target, 2.0 * target);
}
}
}
fn keeps_orientation(plan: &RowPlan, was: f64) -> bool {
if plan.chain.len() < 3 {
return true;
}
let ring: Vec<Point2> = plan.chain.iter().map(|&i| plan.pts[i as usize]).collect();
let now = crate::ops::mesh::triangulation::signed_area(&ring);
now == 0.0 || was == 0.0 || now.is_sign_positive() == was.is_sign_positive()
}
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();
geom::polygon_is_simple(&ring)
}
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, false);
}
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, relax: FrontRelax) {
if relax == FrontRelax::Off {
return;
}
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();
let before: Vec<Point2> = verts.iter().map(|&v| fab.pts[v as usize]).collect();
let was_simple = geom::polygon_is_simple(&before);
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 mid = Point2::from((old[(i + n - 1) % n].coords + old[(i + 1) % n].coords) * 0.5);
let step = (mid - old[i]) * (1.0 - FRONT_RELAX);
let cand = match relax {
FrontRelax::Free | FrontRelax::Off => old[i] + step,
FrontRelax::Along => {
let t = old[(i + 1) % n] - old[(i + n - 1) % n];
let nt = t.norm();
if nt == 0.0 {
old[i]
} else {
let t = t / nt;
old[i] + t * step.dot(&t)
}
}
};
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;
}
}
}
let now: Vec<Point2> = verts.iter().map(|&v| fab.pts[v as usize]).collect();
if was_simple && !geom::polygon_is_simple(&now) {
for (i, &v) in verts.iter().enumerate() {
fab.pts[v as usize] = before[i];
}
}
}
fn close_loop(fab: &mut Fabric, front: &mut Front, rep: u32, target: f64, op: &str) -> Result<()> {
let verts: Vec<u32> = front
.loop_slots(rep)
.iter()
.map(|&s| front.vertex(s))
.collect();
front.kill_loop(rep);
let poly: Vec<Point2> = verts.iter().map(|&v| fab.pts[v as usize]).collect();
let area = crate::ops::mesh::triangulation::signed_area(&poly);
if area <= 0.0 || !geom::polygon_is_simple(&poly) {
let perimeter: f64 = (0..poly.len())
.map(|i| (poly[(i + 1) % poly.len()] - poly[i]).norm())
.sum();
if area.abs() <= FOLD_TOLERANCE * target * 0.5 * perimeter {
weld(fab, &verts);
return Ok(());
}
if area <= 0.0 {
let centre = poly
.iter()
.fold(Point2::origin(), |acc, p| acc + p.coords)
.coords
/ poly.len() as f64;
return Err(PyrucastError::Message(format!(
"{op}: 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, false);
}
for q in filled.quads {
fab.push_quad(q);
}
fab.tris.extend(filled.tris);
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, ring: &[u32]) {
let mut verts: Vec<u32> = ring.to_vec();
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);
}
close_cracks(fab, verts);
}
fn close_cracks(fab: &mut Fabric, mut verts: Vec<u32>) {
if splice_bypassed_chain(fab, &verts) {
return;
}
for _ in 0..verts.len() {
let n = verts.len();
if n < 3 || !ring_has_a_crack(fab, &verts) {
return;
}
let mut pairs: Vec<(f64, usize, usize)> = Vec::new();
for i in 0..n {
for j in (i + 1)..n {
let d = (fab.pts[verts[j] as usize] - fab.pts[verts[i] as usize]).norm();
pairs.push((d, i, j));
}
}
pairs.sort_by(|x, y| x.partial_cmp(y).unwrap());
let done = pairs.iter().find_map(|&(_, i, j)| {
let (a, b) = (verts[i], verts[j]);
if collapse_into(fab, a, b) {
Some(j)
} else if collapse_into(fab, b, a) {
Some(i)
} else {
None
}
});
let Some(gone) = done else { return };
verts.remove(gone);
}
}
fn ring_has_a_crack(fab: &Fabric, verts: &[u32]) -> bool {
let n = verts.len();
(0..n).any(|i| {
let (a, b) = (verts[i], verts[(i + 1) % n]);
if fab.pinned[a as usize] && fab.pinned[b as usize] {
return false;
}
let quads = fab.incident[a as usize]
.iter()
.filter(|&&qi| fab.quads[qi as usize].contains(&b))
.count();
let tris = fab
.tris
.iter()
.filter(|t| t.contains(&a) && t.contains(&b))
.count();
quads + tris == 1
})
}
fn merge_into(fab: &mut Fabric, keep: u32, drop: u32) -> bool {
identify(fab, keep, drop, false)
}
fn collapse_into(fab: &mut Fabric, keep: u32, drop: u32) -> bool {
identify(fab, keep, drop, true)
}
fn identify(fab: &mut Fabric, keep: u32, drop: u32, may_collapse: bool) -> bool {
if keep == drop || fab.pinned[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 });
let point = |v: u32| fab.pts[v as usize];
let turns_right = |t: [u32; 3]| geom::orient(point(t[0]), point(t[1]), point(t[2])) > 0.0;
let mut fate: Vec<(u32, Option<[u32; 4]>)> = Vec::with_capacity(touching.len());
for &qi in &touching {
let q = fab.quads[qi as usize];
let Some(d) = q.iter().position(|&c| c == drop) else {
continue;
};
match q.iter().position(|&c| c == keep) {
Some(_) if !may_collapse => return false,
Some(k) => {
if (k + 2) % 4 == d {
return false;
}
if !turns_right([q[(d + 1) % 4], q[(d + 2) % 4], q[(d + 3) % 4]]) {
return false;
}
fate.push((qi, None));
}
None => {
let r = rewrite(q);
if !geom::quad_is_valid([point(r[0]), point(r[1]), point(r[2]), point(r[3])]) {
return false;
}
fate.push((qi, Some(r)));
}
}
}
let mut tri_fate: Vec<(usize, Option<[u32; 3]>)> = Vec::new();
for (i, t) in fab.tris.iter().enumerate() {
if !t.contains(&drop) {
continue;
}
if t.contains(&keep) {
tri_fate.push((i, None));
continue;
}
let r = t.map(|c| if c == drop { keep } else { c });
if !turns_right(r) {
return false;
}
tri_fate.push((i, Some(r)));
}
let mut around: HashMap<u32, usize> = HashMap::new();
let mut count = |cell: &[u32]| {
let k = cell.len();
for t in 0..k {
if cell[t] == keep {
*around.entry(cell[(t + 1) % k]).or_insert(0) += 1;
*around.entry(cell[(t + k - 1) % k]).or_insert(0) += 1;
}
}
};
for &(qi, r) in &fate {
match r {
Some(r) => count(&r),
None => {
let q = fab.quads[qi as usize];
let d = q.iter().position(|&c| c == drop).unwrap();
count(&[q[(d + 1) % 4], q[(d + 2) % 4], q[(d + 3) % 4]]);
}
}
}
for &qi in fab.incident[keep as usize].iter() {
if !touching.contains(&qi) {
count(&fab.quads[qi as usize]);
}
}
for (i, t) in fab.tris.iter().enumerate() {
match tri_fate.iter().find(|&&(j, _)| j == i) {
Some(&(_, Some(r))) => count(&r),
Some(&(_, None)) => {}
None => count(t),
}
}
if around.values().any(|&c| c > 2) {
return false;
}
for (qi, r) in fate {
match r {
Some(r) => {
fab.quads[qi as usize] = r;
fab.incident[keep as usize].push(qi);
}
None => {
let q = fab.quads[qi as usize];
let d = q.iter().position(|&c| c == drop).unwrap();
fab.tris
.push([q[(d + 1) % 4], q[(d + 2) % 4], q[(d + 3) % 4]]);
fab.kill_quad(qi);
}
}
}
let mut gone: Vec<usize> = Vec::new();
for (i, r) in tri_fate {
match r {
Some(r) => fab.tris[i] = r,
None => gone.push(i),
}
}
gone.sort_unstable_by(|a, b| b.cmp(a));
for i in gone {
fab.tris.swap_remove(i);
}
fab.incident[drop as usize].clear();
true
}
const ERASE_ROUNDS: usize = 4;
fn erase_thin_triangle_pairs(fab: &mut Fabric) -> usize {
let mut erased = 0;
for _ in 0..ERASE_ROUNDS {
let side = |t: [u32; 3], k: usize| {
(fab.pts[t[(k + 1) % 3] as usize] - fab.pts[t[k] as usize]).norm()
};
let mut shared: HashMap<(u32, u32), Vec<usize>> = HashMap::new();
for (i, t) in fab.tris.iter().enumerate() {
for k in 0..3 {
let (a, b) = (t[k], t[(k + 1) % 3]);
shared
.entry(if a < b { (a, b) } else { (b, a) })
.or_default()
.push(i);
}
}
let mut targets: Vec<(f64, u32, u32)> = Vec::new();
for (&(a, b), owners) in &shared {
if owners.len() != 2 {
continue;
}
let len = (fab.pts[b as usize] - fab.pts[a as usize]).norm();
let shortest = owners.iter().all(|&i| {
let t = fab.tris[i];
(0..3).all(|k| side(t, k) >= len)
});
if shortest {
targets.push((len, a, b));
}
}
targets.sort_by(|x, y| x.partial_cmp(y).unwrap());
let mut spent = vec![false; fab.pts.len()];
let mut done = 0;
for (_, a, b) in targets {
if spent[a as usize] || spent[b as usize] {
continue;
}
if collapse_into(fab, a, b) || collapse_into(fab, b, a) {
spent[a as usize] = true;
spent[b as usize] = true;
done += 1;
}
}
erased += done;
if done == 0 {
break;
}
}
erased
}
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
}
#[derive(Clone, Copy)]
enum Cell {
Quad(u32),
Tri(usize),
}
fn cells_on(fab: &Fabric, a: u32, b: u32) -> usize {
fab.incident[a as usize]
.iter()
.filter(|&&qi| !fab.dead[qi as usize] && fab.quads[qi as usize].contains(&b))
.count()
+ fab
.tris
.iter()
.filter(|t| t.contains(&a) && t.contains(&b))
.count()
}
fn sole_cell_on(fab: &Fabric, a: u32, b: u32) -> Option<Cell> {
let mut found = None;
let mut count = 0;
for &qi in &fab.incident[a as usize] {
if !fab.dead[qi as usize] && fab.quads[qi as usize].contains(&b) {
count += 1;
found = Some(Cell::Quad(qi));
}
}
for (i, t) in fab.tris.iter().enumerate() {
if t.contains(&a) && t.contains(&b) {
count += 1;
found = Some(Cell::Tri(i));
}
}
if count == 1 {
found
} else {
None
}
}
fn splice_bypassed_chain(fab: &mut Fabric, ring: &[u32]) -> bool {
let n = ring.len();
if n < 3 {
return false;
}
for i in 0..n {
let (a, b) = (ring[i], ring[(i + 1) % n]);
let Some(cell) = sole_cell_on(fab, a, b) else {
continue;
};
let chain: Vec<u32> = (1..n).map(|k| ring[(i + 1 + k) % n]).collect();
let room = |fab: &Fabric, u: u32, v: u32| {
if u == v {
return false;
}
let key = if u < v { (u, v) } else { (v, u) };
let cap = if fab.contour_edges.contains(&key) {
1
} else {
2
};
cells_on(fab, u, v) < cap
};
if !std::iter::once((b, chain[0]))
.chain(chain.windows(2).map(|w| (w[0], w[1])))
.all(|(u, v)| room(fab, u, v))
{
continue;
}
let walk: Vec<u32> = match cell {
Cell::Quad(qi) => fab.quads[qi as usize].to_vec(),
Cell::Tri(ti) => fab.tris[ti].to_vec(),
};
let m = walk.len();
let Some(t) = (0..m).find(|&t| {
let (x, y) = (walk[t], walk[(t + 1) % m]);
(x == a && y == b) || (x == b && y == a)
}) else {
continue;
};
let x = walk[t];
let mut inner: Vec<u32> = if x == b {
chain[..chain.len() - 1].to_vec()
} else {
let mut v = chain[..chain.len() - 1].to_vec();
v.reverse();
v
};
if inner.is_empty() {
continue;
}
let mut poly: Vec<u32> = (0..m).map(|k| walk[(t + 1 + k) % m]).collect();
poly.append(&mut inner);
let pts: Vec<Point2> = poly.iter().map(|&v| fab.pts[v as usize]).collect();
if crate::ops::mesh::triangulation::signed_area(&pts) <= 0.0
|| !geom::polygon_is_simple(&pts)
{
continue;
}
let filled = close::close(&fab.pts, &poly);
let at = |v: u32, added: &[Point2]| match (v as usize).checked_sub(fab.pts.len()) {
Some(k) => added[k],
None => fab.pts[v as usize],
};
let sound = filled.quads.iter().all(|q| {
geom::quad_is_valid([
at(q[0], &filled.added),
at(q[1], &filled.added),
at(q[2], &filled.added),
at(q[3], &filled.added),
])
}) && filled.tris.iter().all(|t| {
geom::orient(
at(t[0], &filled.added),
at(t[1], &filled.added),
at(t[2], &filled.added),
) > 0.0
});
if !sound {
continue;
}
for p in &filled.added {
fab.add(*p, true, false);
}
match cell {
Cell::Quad(qi) => fab.kill_quad(qi),
Cell::Tri(ti) => {
fab.tris.swap_remove(ti);
}
}
for q in filled.quads {
fab.push_quad(q);
}
fab.tris.extend(filled.tris);
return true;
}
false
}
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)] {
let (keep, drop) = (front.vertex(x), front.vertex(y));
if merge_into(fab, keep, drop) {
let (m1, m2) = front.merge(a, b, front.vertex(x));
stack.push((m1, 0));
stack.push((m2, 0));
return true;
}
}
false
}