use super::grid::{band_loops, boundary_loops, column, preferred_angle, tidy, turn, Core, Frame2};
use super::Fabric;
use crate::atoms::Point2;
use crate::ops::mesh::contour::{point_in_polygon, Domain};
use std::collections::{HashMap, HashSet};
const ALIGN_SLOPE: f64 = 0.25;
const ANCHOR_REACH: f64 = 0.25;
const ANCHOR_FLOOR: f64 = 0.3;
pub struct Grid {
pub xs: Vec<f64>,
pub ys: Vec<f64>,
pub moved: HashMap<(usize, usize), Point2>,
mean: (f64, f64),
}
impl Grid {
pub fn over(domain: &Domain, _target: f64) -> Grid {
let pts = &domain.outer.pts;
let (mut x0, mut x1) = (f64::INFINITY, f64::NEG_INFINITY);
let (mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY);
for p in pts {
x0 = x0.min(p.x);
x1 = x1.max(p.x);
y0 = y0.min(p.y);
y1 = y1.max(p.y);
}
let (mut sx, mut sy) = (vec![x0, x1], vec![y0, y1]);
let (mut step_x, mut step_y) = ((0.0, 0usize), (0.0, 0usize));
for l in std::iter::once(&domain.outer).chain(&domain.holes) {
for run in runs(l, ALIGN_SLOPE) {
let (lines, step) = if run.horizontal {
(&mut sx, &mut step_x)
} else {
(&mut sy, &mut step_y)
};
lines.extend_from_slice(&run.along);
step.0 += run.along[run.along.len() - 1] - run.along[0];
step.1 += run.along.len() - 1;
}
}
let mean_of = |(total, count): (f64, usize), extent: f64| match count {
0 => extent,
n => total / n as f64,
};
let mean = (mean_of(step_x, x1 - x0), mean_of(step_y, y1 - y0));
let mut grid = Grid {
xs: split_or_leave(tidy_lines(sx), mean.0),
ys: split_or_leave(tidy_lines(sy), mean.1),
moved: HashMap::new(),
mean,
};
let pts: Vec<Point2> = std::iter::once(&domain.outer)
.chain(&domain.holes)
.flat_map(|l| l.pts.iter().copied())
.collect();
let cell = ((x1 - x0) / grid.nx() as f64).max((y1 - y0) / grid.ny() as f64);
let near = super::proximity::PointGrid::build(&pts, cell.max(f64::MIN_POSITIVE));
grid.collapse_thin_bands(&pts, &near);
grid
}
fn collapse_thin_bands(&mut self, pts: &[Point2], near: &super::proximity::PointGrid) {
let grid = self;
for axis in [false, true] {
let lines = if axis { &grid.xs } else { &grid.ys };
if lines.len() < 3 {
continue;
}
let mean = if axis { grid.mean.0 } else { grid.mean.1 };
let (floor, tol) = (0.5 * mean, 1e-9 * mean);
let (mut keep, mut weld) = (vec![true; lines.len()], vec![0usize; lines.len()]);
let mut anchor = 0usize;
for k in 1..lines.len() {
weld[k] = k;
if lines[k] - lines[anchor] < floor {
if k == lines.len() - 1 {
keep[anchor] = anchor != 0;
weld[anchor] = k;
anchor = k;
} else {
keep[k] = false;
weld[k] = anchor;
}
} else {
anchor = k;
}
}
for k in 0..lines.len() {
let mut to = weld[k];
while !keep[to] {
to = weld[to];
}
weld[k] = to;
}
let survivors: Vec<usize> = (0..lines.len()).filter(|&k| keep[k]).collect();
if survivors.len() == lines.len() {
continue;
}
let index: HashMap<usize, usize> = survivors
.iter()
.enumerate()
.map(|(new, &old)| (old, new))
.collect();
let across = if axis { grid.ys.len() } else { grid.xs.len() };
let mut placed: Vec<((usize, usize), Point2)> = Vec::new();
for (k, &to) in weld.iter().enumerate() {
if k == to {
continue;
}
for c in 0..across {
let end = |line: usize| {
let ij = if axis { (line, c) } else { (c, line) };
grid.node(ij.0, ij.1)
};
let (a, b) = (end(k), end(to));
let at = |p: Point2| near.nearest_index_within(pts, p, tol).map(|_| p);
let p = at(b)
.or_else(|| at(a))
.unwrap_or_else(|| Point2::new(0.5 * (a.x + b.x), 0.5 * (a.y + b.y)));
let ij = if axis {
(index[&to], c)
} else {
(c, index[&to])
};
placed.push((ij, p));
}
}
let surviving: Vec<f64> = survivors.iter().map(|&k| lines[k]).collect();
let old = std::mem::take(&mut grid.moved);
grid.moved = old
.into_iter()
.filter_map(|((i, j), p)| {
let k = if axis { i } else { j };
index.get(&k).map(|&n| {
let ij = if axis { (n, j) } else { (i, n) };
(ij, p)
})
})
.collect();
if axis {
grid.xs = surviving;
} else {
grid.ys = surviving;
}
grid.moved.extend(placed);
}
}
pub fn nx(&self) -> usize {
self.xs.len() - 1
}
pub fn ny(&self) -> usize {
self.ys.len() - 1
}
fn node(&self, i: usize, j: usize) -> Point2 {
self.moved
.get(&(i, j))
.copied()
.unwrap_or_else(|| Point2::new(self.xs[i], self.ys[j]))
}
}
struct Run {
horizontal: bool,
along: Vec<f64>,
}
fn runs(l: &crate::ops::mesh::contour::Loop2D, slope: f64) -> Vec<Run> {
let n = l.pts.len();
if n < 2 {
return Vec::new();
}
let class = |i: usize| -> Option<bool> {
let (a, b) = (l.pts[i], l.pts[(i + 1) % n]);
let (dx, dy) = ((b.x - a.x).abs(), (b.y - a.y).abs());
if dy <= slope * dx && dx > 0.0 {
Some(true)
} else if dx <= slope * dy && dy > 0.0 {
Some(false)
} else {
None
}
};
let start = (0..n)
.find(|&i| class(i) != class((i + n - 1) % n))
.unwrap_or(0);
let mut out = Vec::new();
let mut i = 0;
while i < n {
let Some(horizontal) = class((start + i) % n) else {
i += 1;
continue;
};
let mut j = i + 1;
while j < n && class((start + j) % n) == Some(horizontal) {
j += 1;
}
let mut along = Vec::with_capacity(j - i + 1);
for t in i..=j {
let p = l.pts[(start + t) % n];
along.push(if horizontal { p.x } else { p.y });
}
if along[0] > along[along.len() - 1] {
along.reverse();
}
out.push(Run { horizontal, along });
i = j;
}
out
}
fn tidy_lines(mut v: Vec<f64>) -> Vec<f64> {
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
let span = v[v.len() - 1] - v[0];
v.dedup_by(|a, b| (*a - *b).abs() <= 1e-12 * span.max(1.0));
v
}
fn split_or_leave(lines: Vec<f64>, mean: f64) -> Vec<f64> {
if lines.len() < 2 {
return lines;
}
let mut out = vec![lines[0]];
for w in lines.windows(2) {
let (a, b) = (w[0], w[1]);
let span = b - a;
if span > 2.0 * mean && span <= 3.0 * mean {
let k = ((span / mean).round() as usize).max(2);
for i in 1..k {
out.push(a + span * i as f64 / k as f64);
}
}
out.push(b);
}
out
}
pub fn build(
fab: &mut Fabric,
domain: &Domain,
contour_loops: &[Vec<u32>],
target: f64,
band: usize,
) -> Core {
let frame = Frame2::at(preferred_angle(domain));
let turned = Domain {
outer: turn(&domain.outer, frame),
holes: domain.holes.iter().map(|h| turn(h, frame)).collect(),
};
let domain = &turned;
let grid = Grid::over(domain, target);
let (nx, ny) = (grid.nx(), grid.ny());
if nx == 0 || ny == 0 {
return Core {
band: contour_loops.iter().map(|l| (l.clone(), false)).collect(),
};
}
let known = ContourNodes::build(fab, contour_loops, frame);
let mut anchors = Anchors::build(&grid, &known, target);
let mut solid = classify(&grid, &anchors, domain, nx, ny);
while anchors.settle(&grid, &solid, nx, ny) {
solid = classify(&grid, &anchors, domain, nx, ny);
}
let mut keep = clear_of_unmet(&solid, nx, ny, &anchors, contour_loops, band);
tidy(&mut keep, nx, ny);
let mut vert: HashMap<(usize, usize), u32> = HashMap::new();
for j in 0..ny {
for i in 0..nx {
if !keep[j * nx + i] {
continue;
}
let mut q = [0u32; 4];
for (k, (di, dj)) in [(0, 0), (1, 0), (1, 1), (0, 1)].into_iter().enumerate() {
q[k] = *vert.entry((i + di, j + dj)).or_insert_with(|| {
anchors.id(i + di, j + dj).unwrap_or_else(|| {
fab.add(frame.to_local(grid.node(i + di, j + dj)), false, false)
})
});
}
fab.push_quad(q);
}
}
let core_loops = boundary_loops(&keep, nx, ny, &vert);
Core {
band: band_loops(contour_loops, &core_loops),
}
}
struct ContourNodes {
pts: Vec<Point2>,
ids: Vec<u32>,
}
impl ContourNodes {
fn build(fab: &Fabric, loops: &[Vec<u32>], frame: Frame2) -> ContourNodes {
let ids: Vec<u32> = loops.iter().flatten().copied().collect();
let pts: Vec<Point2> = ids
.iter()
.map(|&v| frame.to_grid(fab.pts[v as usize]))
.collect();
ContourNodes { pts, ids }
}
}
struct Anchors {
to: HashMap<(usize, usize), (u32, Point2)>,
}
impl Anchors {
fn build(grid: &Grid, known: &ContourNodes, target: f64) -> Anchors {
let reach = ANCHOR_REACH * target;
let mut want: Vec<(f64, usize, (usize, usize))> = Vec::new();
for (k, p) in known.pts.iter().enumerate() {
let ij = (nearest_line(&grid.xs, p.x), nearest_line(&grid.ys, p.y));
let d = (grid.node(ij.0, ij.1) - *p).norm();
if d <= reach {
want.push((d, k, ij));
}
}
want.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap().then(a.1.cmp(&b.1)));
let mut to: HashMap<(usize, usize), (u32, Point2)> = HashMap::new();
let mut taken = vec![false; known.pts.len()];
for (_, k, ij) in want {
if taken[k] || to.contains_key(&ij) {
continue;
}
taken[k] = true;
to.insert(ij, (known.ids[k], known.pts[k]));
}
Anchors { to }
}
fn settle(&mut self, grid: &Grid, solid: &[bool], nx: usize, ny: usize) -> bool {
let mut giving_back: Vec<(usize, usize)> = Vec::new();
for j in 0..ny {
for i in 0..nx {
if !solid[j * nx + i] {
continue;
}
let corners = [(i, j), (i + 1, j), (i + 1, j + 1), (i, j + 1)];
if !corners.iter().any(|c| self.to.contains_key(c)) {
continue;
}
if super::geom::quad_quality(self.cell(grid, i, j)) < ANCHOR_FLOOR {
giving_back.extend(corners.iter().filter(|c| self.to.contains_key(c)));
}
}
}
for c in &giving_back {
self.to.remove(c);
}
!giving_back.is_empty()
}
fn id(&self, i: usize, j: usize) -> Option<u32> {
self.to.get(&(i, j)).map(|&(v, _)| v)
}
fn point(&self, grid: &Grid, i: usize, j: usize) -> Point2 {
self.to
.get(&(i, j))
.map_or_else(|| grid.node(i, j), |&(_, p)| p)
}
fn cell(&self, grid: &Grid, i: usize, j: usize) -> [Point2; 4] {
[(0, 0), (1, 0), (1, 1), (0, 1)].map(|(di, dj)| self.point(grid, i + di, j + dj))
}
}
fn nearest_line(lines: &[f64], v: f64) -> usize {
let k = lines.partition_point(|&x| x < v);
if k == 0 {
return 0;
}
if k == lines.len() || v - lines[k - 1] <= lines[k] - v {
k - 1
} else {
k
}
}
fn cells_touching(
grid: &Grid,
anchors: &Anchors,
nx: usize,
ny: usize,
a: Point2,
b: Point2,
) -> Vec<(usize, usize)> {
let span = |lines: &[f64], lo: f64, hi: f64, n: usize| {
(
column(lines, lo).saturating_sub(1),
(column(lines, hi) + 1).min(n - 1),
)
};
let (i0, i1) = span(&grid.xs, a.x.min(b.x), a.x.max(b.x), nx);
let (j0, j1) = span(&grid.ys, a.y.min(b.y), a.y.max(b.y), ny);
let mut out = Vec::new();
for j in j0..=j1 {
for i in i0..=i1 {
if enters(a, b, anchors.cell(grid, i, j)) {
out.push((i, j));
}
}
}
out
}
fn enters(a: Point2, b: Point2, q: [Point2; 4]) -> bool {
let d = b - a;
let (mut t0, mut t1) = (0.0f64, 1.0f64);
for k in 0..4 {
let (p0, p1) = (q[k], q[(k + 1) % 4]);
let e = p1 - p0;
let n = Point2::new(-e.y, e.x);
let len = n.coords.norm();
if len == 0.0 {
continue;
}
let num = n.x * (a.x - p0.x) + n.y * (a.y - p0.y) - 1e-9 * len;
let den = n.x * d.x + n.y * d.y;
if den == 0.0 {
if num < 0.0 {
return false; }
} else {
let r = -num / den;
if den > 0.0 {
t0 = t0.max(r);
} else {
t1 = t1.min(r);
}
if t0 > t1 {
return false;
}
}
}
true
}
fn classify(grid: &Grid, anchors: &Anchors, domain: &Domain, nx: usize, ny: usize) -> Vec<bool> {
let mut cut = vec![false; nx * ny];
for l in std::iter::once(&domain.outer).chain(&domain.holes) {
let n = l.pts.len();
for i in 0..n {
let (a, b) = (l.pts[i], l.pts[(i + 1) % n]);
for (ci, cj) in cells_touching(grid, anchors, nx, ny, a, b) {
cut[cj * nx + ci] = true;
}
}
}
let mut solid = vec![false; nx * ny];
for j in 0..ny {
for i in 0..nx {
if cut[j * nx + i] {
continue;
}
let (w, h) = (grid.xs[i + 1] - grid.xs[i], grid.ys[j + 1] - grid.ys[j]);
if w > 2.0 * grid.mean.0 || h > 2.0 * grid.mean.1 {
continue;
}
let q = anchors.cell(grid, i, j);
let c = Point2::new(
0.25 * (q[0].x + q[1].x + q[2].x + q[3].x),
0.25 * (q[0].y + q[1].y + q[2].y + q[3].y),
);
solid[j * nx + i] = point_in_polygon(c, &domain.outer.pts)
&& !domain.holes.iter().any(|h| point_in_polygon(c, &h.pts));
}
}
solid
}
fn clear_of_unmet(
solid: &[bool],
nx: usize,
ny: usize,
anchors: &Anchors,
contour_loops: &[Vec<u32>],
band: usize,
) -> Vec<bool> {
let mut on_contour: HashSet<(u32, u32)> = HashSet::new();
for l in contour_loops {
let n = l.len();
for i in 0..n {
let (a, b) = (l[i], l[(i + 1) % n]);
on_contour.insert((a.min(b), a.max(b)));
}
}
let met =
|a: (usize, usize), b: (usize, usize)| match (anchors.id(a.0, a.1), anchors.id(b.0, b.1)) {
(Some(u), Some(v)) => on_contour.contains(&(u.min(v), u.max(v))),
_ => false,
};
let at = |i: i64, j: i64| -> bool {
i >= 0
&& j >= 0
&& (i as usize) < nx
&& (j as usize) < ny
&& solid[j as usize * nx + i as usize]
};
let mut unmet = vec![false; nx * ny];
for j in 0..ny as i64 {
for i in 0..nx as i64 {
if !at(i, j) {
continue;
}
let (u, v) = (i as usize, j as usize);
let faces = [
((1, 0), (u + 1, v), (u + 1, v + 1)),
((-1, 0), (u, v + 1), (u, v)),
((0, 1), (u + 1, v + 1), (u, v + 1)),
((0, -1), (u, v), (u + 1, v)),
];
for ((di, dj), a, b) in faces {
if at(i + di, j + dj) {
continue;
}
if !met(a, b) {
unmet[v * nx + u] = true;
break;
}
}
if !unmet[v * nx + u] {
for (di, dj) in [(1, 1), (1, -1), (-1, 1), (-1, -1)] {
if !at(i + di, j + dj) && at(i + di, j) && at(i, j + dj) {
unmet[v * nx + u] = true;
break;
}
}
}
}
}
let mut out = solid.to_vec();
for j in 0..ny as i64 {
for i in 0..nx as i64 {
let r = band as i64;
let near = (-r..=r).any(|dj| {
(-r..=r).any(|di| {
let (ii, jj) = (i + di, j + dj);
ii >= 0
&& jj >= 0
&& (ii as usize) < nx
&& (jj as usize) < ny
&& unmet[jj as usize * nx + ii as usize]
})
});
if near {
out[j as usize * nx + i as usize] = false;
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::atoms::NodeId;
use crate::ops::mesh::contour::Loop2D;
fn loop2d(pts: &[(f64, f64)]) -> Loop2D {
Loop2D {
node_ids: (0..pts.len() as u32).map(NodeId).collect(),
pts: pts.iter().map(|&(x, y)| Point2::new(x, y)).collect(),
}
}
fn only(outer: Loop2D) -> Domain {
Domain {
outer,
holes: Vec::new(),
}
}
fn cut(corners: &[(f64, f64)], h: f64) -> Loop2D {
let n = corners.len();
let mut pts = Vec::new();
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)));
}
}
loop2d(&pts)
}
fn nodes(g: &Grid) -> Vec<Point2> {
(0..g.xs.len())
.flat_map(|i| (0..g.ys.len()).map(move |j| (i, j)))
.map(|(i, j)| g.node(i, j))
.collect()
}
#[test]
fn a_wall_is_reached_whatever_its_pieces_measure() {
let h = 0.1;
for tenths in 2..9u32 {
let step = tenths as f64 * 0.1 + 0.01;
let d = only(cut(
&[
(0.0, 0.0),
(1.0, 0.0),
(1.0, 1.0),
(0.53, 1.0),
(0.53, step),
(0.0, step),
],
h,
));
let g = Grid::over(&d, h);
let on_it = nodes(&g)
.iter()
.filter(|p| (p.x - 0.53).abs() < 1e-9)
.count();
assert!(
on_it >= 2,
"the wall at x=0.53 was reached by {on_it} nodes, step at y={step}"
);
}
}
#[test]
fn one_row_reaches_both_of_two_walls_that_disagree() {
let d = only(cut(
&[
(0.0, 0.0),
(1.03, 0.0),
(1.03, 0.47),
(0.41, 0.47),
(0.41, 0.98),
(0.0, 0.98),
],
0.1,
));
let g = Grid::over(&d, 0.1);
let all = nodes(&g);
let sits = |x: f64, y: f64| {
all.iter()
.any(|p| (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9)
};
for k in 1..10 {
let y = 0.98 * k as f64 / 10.0;
assert!(sits(0.0, y), "left wall node at y={y} is off the grid");
}
for k in 1..5 {
let y = 0.47 * k as f64 / 5.0;
assert!(sits(1.03, y), "right wall node at y={y} is off the grid");
}
}
#[test]
fn the_lines_follow_the_contour_rather_than_recompute_it() {
let mut pts = Vec::new();
for i in 0..10 {
pts.push((i as f64 * 0.1, 0.0));
}
for i in 0..5 {
pts.push((1.0, i as f64 * 0.11));
}
for i in 0..10 {
pts.push((1.0 - i as f64 * 0.1, 0.55));
}
for i in 0..5 {
pts.push((0.0, 0.55 - i as f64 * 0.11));
}
let g = Grid::over(&only(loop2d(&pts)), 0.1);
let want = [0.0, 0.11, 0.22, 0.33, 0.44, 0.55];
assert_eq!(g.ys.len(), want.len(), "ys = {:?}", g.ys);
for (got, w) in g.ys.iter().zip(want) {
assert!((got - w).abs() < 1e-9, "ys = {:?}", g.ys);
}
}
}