VectorCraft: An open-source, vector art tool written by scratch in pure Rust
refactor(pathops): extract planar sweep graph builder
Dylan M. Taylor542a5ae58c4d
diff --git a/crates/pathops/src/planar/map.rs b/crates/pathops/src/planar/map.rsindex 311f7f889..2b673c3a3 100644--- a/crates/pathops/src/planar/map.rs+++ b/crates/pathops/src/planar/map.rs@@ -68,12 +68,131 @@ fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<Map> {if !crate::budget::sweep_fits(inputs.iter().map(|p| &p.0)) {return None;}+ let tidy = Tidy::keeping(precision, inputs.iter().map(|p| &p.0));+ let (points, edges) = sweep_graph(&inputs, eps, precision)?;+ let nv = points.len();++ // Half-edges leaving each vertex, sorted by direction; walking a face, the next half-edge is+ // the one just clockwise of the way back, so bounded faces come out with positive area and+ // the outer boundary of each connected piece with negative area.+ let mut around: Vec<Vec<usize>> = vec![Vec::new(); nv];+ for h in 0..2 * edges.len() {+ if let Some(list) = origin(&edges, h).and_then(|v| around.get_mut(v)) {+ list.push(h);+ }+ }+ let mut slot_of = vec![0usize; 2 * edges.len()];+ for (v, list) in around.iter_mut().enumerate() {+ let Some(&at) = points.get(v) else { continue };+ // Half the shortest chord of the edges here: every one of them gets that far from it.+ let r = 0.5 * list.iter().filter_map(|&h| far_end(&edges, h).map(|p| p.distance(at))).fold(f64::INFINITY, f64::min);+ let mut keyed: Vec<(f64, usize)> = list.iter().map(|&h| (leaving_angle(&edges, h, at, r), h)).collect();+ keyed.sort_by(|a, b| a.0.total_cmp(&b.0));+ *list = keyed.into_iter().map(|(_, h)| h).collect();+ for (k, &h) in list.iter().enumerate() {+ if let Some(s) = slot_of.get_mut(h) {+ *s = k;+ }+ }+ }+ let next = |h: usize| -> Option<usize> {+ let back = twin(h);+ let list = around.get(origin(&edges, back)?)?;+ let k = *slot_of.get(back)?;+ list.get((k + list.len() - 1) % list.len()).copied()+ };++ // Connected pieces of the graph.+ let mut parent: Vec<usize> = (0..nv).collect();+ for e in &edges {+ let (a, b) = (find(&mut parent, e.ends[0]), find(&mut parent, e.ends[1]));+ if let Some(p) = parent.get_mut(a) {+ *p = b;+ }+ }+ let piece: Vec<usize> = (0..nv).map(|v| find(&mut parent, v)).collect();+ let piece_of = |cycle: &[usize]| cycle.first().and_then(|&h| origin(&edges, h)).and_then(|v| piece.get(v)).copied();++ // Walk every cycle: positive ones are faces, negative ones outer boundaries (holes in the+ // face around them, if any).+ let mut seen = vec![false; 2 * edges.len()];+ let mut faces: Vec<(Vec<usize>, BezPath, f64)> = Vec::new();+ let mut slivers: Vec<(Vec<usize>, BezPath)> = Vec::new();+ let mut holes: Vec<(Vec<usize>, BezPath)> = Vec::new();+ for start in 0..2 * edges.len() {+ if seen.get(start).copied().unwrap_or(true) {+ continue;+ }+ let mut cycle = vec![];+ let mut h = start;+ while let Some(s) = seen.get_mut(h).filter(|s| !**s) {+ *s = true;+ cycle.push(h);+ match next(h) {+ Some(n) => h = n,+ None => break,+ }+ }+ let cycle = without_spurs(&cycle);+ if cycle.is_empty() {+ continue;+ }+ let bp = cycle_bezpath(&edges, &cycle);+ let area = bp.area();+ if area > 0.0 && !is_sliver(&bp, tidy.precision) {+ faces.push((cycle, bp, area));+ } else if area > 0.0 {+ slivers.push((cycle, bp));+ } else if area < -(tidy.precision * tidy.precision) {+ holes.push((cycle, bp));+ }+ }++ // Each hole goes in the smallest face of another piece around it.+ let face_index = RectIndex::new(faces.iter().enumerate().map(|(i, (_, bp, _))| (bp.bounding_box(), i)).collect());+ let mut face_holes: Vec<Vec<usize>> = vec![Vec::new(); faces.len()];+ for (k, (cycle, _)) in holes.iter().enumerate() {+ let Some(p) = cycle.first().and_then(|&h| origin(&edges, h)).and_then(|v| points.get(v)).copied() else { continue };+ let own = piece_of(cycle);+ let around_it = face_index+ .at(p, 0.0)+ .filter_map(|&i| faces.get(i).map(|f| (i, f)))+ .filter(|(_, (fc, bp, _))| piece_of(fc) != own && bp.winding(p) != 0)+ .min_by(|a, b| a.1.2.total_cmp(&b.1.2))+ .map(|(i, _)| i);+ if let Some(list) = around_it.and_then(|i| face_holes.get_mut(i)) {+ list.push(k);+ }+ }++ // The inputs that cover each sliver, tested at a point inside it.+ let fills: Vec<Fill> = if slivers.is_empty() || !cover { Vec::new() } else { shapes.iter().map(Fill::new).collect() };+ let slivers: Vec<(Vec<usize>, Vec<usize>)> = slivers+ .into_iter()+ .map(|(cycle, mut bp)| {+ if !cover {+ return (cycle, Vec::new());+ }+ bp.apply_affine(UNSHEAR);+ let sources = interior_point(&PathData::from_bezpath(&bp))+ .map(|p| fills.iter().enumerate().filter(|(_, f)| f.contains(p)).map(|(i, _)| i).collect())+ .unwrap_or_default();+ (cycle, sources)+ })+ .collect();++ // The inputs' anchors, which results land on again up to the sweep's tolerance.+ let snap = 2.0 * eps;+ let mut anchors: Vec<Point> = shapes.iter().flat_map(|s| s.path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))).collect();+ anchors.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)));+ Some(Map { edges, around, slot_of, faces, face_index, slivers, holes, face_holes, tidy, anchors, snap })+}++fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64) -> Option<(Vec<Point>, Vec<Edge>)> {// The sweep can panic on rare near-degenerate input; that must never take the app down.let sweep =std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Topology::<Crossings>::from_paths(inputs.iter().map(|(p, i)| (p, *i)), eps)));let top = sweep.ok()?.ok()?;- let tidy = Tidy::keeping(precision, inputs.iter().map(|p| &p.0));-// The planar graph: vertices are the sweep's points, edges its segments. Points closer than// the sweep's tolerance are one vertex (it can put a corner that lies on another path's edge// a rounding error away from where it cuts that edge).@@ -173,7 +292,7 @@ fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<Map> {}let mut edges: Vec<Edge> = Vec::new();let mut between: HashMap<(usize, usize), Vec<usize>> = HashMap::new();- let outlines = Outlines::new(&inputs, eps);+ let outlines = Outlines::new(inputs, eps);for (mut segs, ends) in pieces {let ends = ends.map(|v| find(&mut joined, v));let (Some(&p0), Some(&p1)) = (points.get(ends[0]), points.get(ends[1])) else { continue };@@ -205,122 +324,7 @@ fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<Map> {between.entry(key).or_default().push(edges.len());edges.push(Edge { segs, ends, source });}- let nv = points.len();-- // Half-edges leaving each vertex, sorted by direction; walking a face, the next half-edge is- // the one just clockwise of the way back, so bounded faces come out with positive area and- // the outer boundary of each connected piece with negative area.- let mut around: Vec<Vec<usize>> = vec![Vec::new(); nv];- for h in 0..2 * edges.len() {- if let Some(list) = origin(&edges, h).and_then(|v| around.get_mut(v)) {- list.push(h);- }- }- let mut slot_of = vec![0usize; 2 * edges.len()];- for (v, list) in around.iter_mut().enumerate() {- let Some(&at) = points.get(v) else { continue };- // Half the shortest chord of the edges here: every one of them gets that far from it.- let r = 0.5 * list.iter().filter_map(|&h| far_end(&edges, h).map(|p| p.distance(at))).fold(f64::INFINITY, f64::min);- let mut keyed: Vec<(f64, usize)> = list.iter().map(|&h| (leaving_angle(&edges, h, at, r), h)).collect();- keyed.sort_by(|a, b| a.0.total_cmp(&b.0));- *list = keyed.into_iter().map(|(_, h)| h).collect();- for (k, &h) in list.iter().enumerate() {- if let Some(s) = slot_of.get_mut(h) {- *s = k;- }- }- }- let next = |h: usize| -> Option<usize> {- let back = twin(h);- let list = around.get(origin(&edges, back)?)?;- let k = *slot_of.get(back)?;- list.get((k + list.len() - 1) % list.len()).copied()- };-- // Connected pieces of the graph.- let mut parent: Vec<usize> = (0..nv).collect();- for e in &edges {- let (a, b) = (find(&mut parent, e.ends[0]), find(&mut parent, e.ends[1]));- if let Some(p) = parent.get_mut(a) {- *p = b;- }- }- let piece: Vec<usize> = (0..nv).map(|v| find(&mut parent, v)).collect();- let piece_of = |cycle: &[usize]| cycle.first().and_then(|&h| origin(&edges, h)).and_then(|v| piece.get(v)).copied();-- // Walk every cycle: positive ones are faces, negative ones outer boundaries (holes in the- // face around them, if any).- let mut seen = vec![false; 2 * edges.len()];- let mut faces: Vec<(Vec<usize>, BezPath, f64)> = Vec::new();- let mut slivers: Vec<(Vec<usize>, BezPath)> = Vec::new();- let mut holes: Vec<(Vec<usize>, BezPath)> = Vec::new();- for start in 0..2 * edges.len() {- if seen.get(start).copied().unwrap_or(true) {- continue;- }- let mut cycle = vec![];- let mut h = start;- while let Some(s) = seen.get_mut(h).filter(|s| !**s) {- *s = true;- cycle.push(h);- match next(h) {- Some(n) => h = n,- None => break,- }- }- let cycle = without_spurs(&cycle);- if cycle.is_empty() {- continue;- }- let bp = cycle_bezpath(&edges, &cycle);- let area = bp.area();- if area > 0.0 && !is_sliver(&bp, tidy.precision) {- faces.push((cycle, bp, area));- } else if area > 0.0 {- slivers.push((cycle, bp));- } else if area < -(tidy.precision * tidy.precision) {- holes.push((cycle, bp));- }- }-- // Each hole goes in the smallest face of another piece around it.- let face_index = RectIndex::new(faces.iter().enumerate().map(|(i, (_, bp, _))| (bp.bounding_box(), i)).collect());- let mut face_holes: Vec<Vec<usize>> = vec![Vec::new(); faces.len()];- for (k, (cycle, _)) in holes.iter().enumerate() {- let Some(p) = cycle.first().and_then(|&h| origin(&edges, h)).and_then(|v| points.get(v)).copied() else { continue };- let own = piece_of(cycle);- let around_it = face_index- .at(p, 0.0)- .filter_map(|&i| faces.get(i).map(|f| (i, f)))- .filter(|(_, (fc, bp, _))| piece_of(fc) != own && bp.winding(p) != 0)- .min_by(|a, b| a.1.2.total_cmp(&b.1.2))- .map(|(i, _)| i);- if let Some(list) = around_it.and_then(|i| face_holes.get_mut(i)) {- list.push(k);- }- }-- // The inputs that cover each sliver, tested at a point inside it.- let fills: Vec<Fill> = if slivers.is_empty() || !cover { Vec::new() } else { shapes.iter().map(Fill::new).collect() };- let slivers: Vec<(Vec<usize>, Vec<usize>)> = slivers- .into_iter()- .map(|(cycle, mut bp)| {- if !cover {- return (cycle, Vec::new());- }- bp.apply_affine(UNSHEAR);- let sources = interior_point(&PathData::from_bezpath(&bp))- .map(|p| fills.iter().enumerate().filter(|(_, f)| f.contains(p)).map(|(i, _)| i).collect())- .unwrap_or_default();- (cycle, sources)- })- .collect();-- // The inputs' anchors, which results land on again up to the sweep's tolerance.- let snap = 2.0 * eps;- let mut anchors: Vec<Point> = shapes.iter().flat_map(|s| s.path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))).collect();- anchors.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)));- Some(Map { edges, around, slot_of, faces, face_index, slivers, holes, face_holes, tidy, anchors, snap })+ Some((points, edges))}impl Map {