Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / maps / tile_build / src / boolean_part2.rs

boolean_part2.rs204 lines · 7.0 KiBRaw
1/// Group rings into `[exterior, hole, ...]` polygons by nesting depth.
2fn assemble(rings: Vec<Vec<Pt>>) -> Vec<Polygon> {
3 // Depth by containment rather than by the sweep's `prev_in_result` chain: the chain is cheaper
4 // but only correct when every ring closes cleanly, and a hard input can leave it inconsistent.
5 // Containment is O(rings^2) point-in-polygon tests, and a tile has few rings.
6 let mut depth = vec![0usize; rings.len()];
7 for i in 0..rings.len() {
8 let probe = rings[i][0];
9 for (j, other) in rings.iter().enumerate() {
10 if i == j {
11 continue;
12 }
13 if point_in_ring(probe, other) {
14 depth[i] += 1;
15 }
16 }
17 }
18
19 let mut out: Vec<Polygon> = Vec::new();
20 let mut index_of: Vec<Option<usize>> = vec![None; rings.len()];
21 // Even depth is an exterior, odd is a hole in the nearest enclosing exterior.
22 for i in 0..rings.len() {
23 if depth[i].is_multiple_of(2) {
24 index_of[i] = Some(out.len());
25 out.push(vec![orient(rings[i].clone(), true)]);
26 }
27 }
28 for i in 0..rings.len() {
29 if !depth[i].is_multiple_of(2) {
30 // The enclosing exterior is the deepest even-depth ring that contains it.
31 let mut best: Option<(usize, usize)> = None;
32 let probe = rings[i][0];
33 for j in 0..rings.len() {
34 if i == j || !depth[j].is_multiple_of(2) {
35 continue;
36 }
37 if point_in_ring(probe, &rings[j]) && best.is_none_or(|(d, _)| depth[j] >= d) {
38 best = Some((depth[j], j));
39 }
40 }
41 if let Some((_, j)) = best {
42 if let Some(at) = index_of[j] {
43 out[at].push(orient(rings[i].clone(), false));
44 }
45 }
46 }
47 }
48 out
49}
50
51/// Force a ring counter-clockwise for an exterior, clockwise for a hole.
52fn orient(mut ring: Vec<Pt>, ccw: bool) -> Vec<Pt> {
53 let mut area = 0.0;
54 for i in 0..ring.len() {
55 let a = ring[i];
56 let b = ring[(i + 1) % ring.len()];
57 area += a.0 * b.1 - b.0 * a.1;
58 }
59 if (area > 0.0) != ccw {
60 ring.reverse();
61 }
62 ring
63}
64
65/// Even-odd ray cast. Matches `rings.rs`'s convention that a point on the boundary is outside.
66fn point_in_ring(p: Pt, ring: &[Pt]) -> bool {
67 let mut inside = false;
68 let n = ring.len();
69 for i in 0..n {
70 let a = ring[i];
71 let b = ring[(i + 1) % n];
72 if (a.1 > p.1) != (b.1 > p.1) {
73 let t = (p.1 - a.1) / (b.1 - a.1);
74 if p.0 < a.0 + t * (b.0 - a.0) {
75 inside = !inside;
76 }
77 }
78 }
79 inside
80}
81
82/// Where two segments meet: 0 not at all, 1 at a point, 2 along a shared stretch.
83fn intersect(a1: Pt, a2: Pt, b1: Pt, b2: Pt) -> (u8, Pt, Pt) {
84 let va = (a2.0 - a1.0, a2.1 - a1.1);
85 let vb = (b2.0 - b1.0, b2.1 - b1.1);
86 let cross = va.0 * vb.1 - va.1 * vb.0;
87 let d = (b1.0 - a1.0, b1.1 - a1.1);
88
89 if cross != 0.0 {
90 let t = (d.0 * vb.1 - d.1 * vb.0) / cross;
91 let u = (d.0 * va.1 - d.1 * va.0) / cross;
92 // Endpoints count: touching is an intersection here, which is the point of using a method
93 // that tolerates degeneracy.
94 if (-EPS..=1.0 + EPS).contains(&t) && (-EPS..=1.0 + EPS).contains(&u) {
95 let p = (a1.0 + t * va.0, a1.1 + t * va.1);
96 return (1, p, p);
97 }
98 return (0, a1, a1);
99 }
100
101 // Parallel. Collinear only if b1 lies on a's line.
102 if (d.0 * va.1 - d.1 * va.0) != 0.0 {
103 return (0, a1, a1);
104 }
105 // Project both onto a's direction and overlap the intervals.
106 let len2 = va.0 * va.0 + va.1 * va.1;
107 if len2 == 0.0 {
108 return (0, a1, a1);
109 }
110 let proj = |p: Pt| ((p.0 - a1.0) * va.0 + (p.1 - a1.1) * va.1) / len2;
111 let (mut s0, mut s1) = (proj(b1), proj(b2));
112 if s0 > s1 {
113 std::mem::swap(&mut s0, &mut s1);
114 }
115 let lo = s0.max(0.0);
116 let hi = s1.min(1.0);
117 if lo > hi + EPS {
118 return (0, a1, a1);
119 }
120 let at = |s: f64| (a1.0 + s * va.0, a1.1 + s * va.1);
121 if (hi - lo).abs() < EPS {
122 let p = at(lo);
123 return (1, p, p);
124 }
125 (2, at(lo), at(hi))
126}
127
128/// Evaluate `op` on two sets of polygons.
129///
130/// Each polygon is `[exterior, hole, ...]`; ring orientation of the input is not significant, and
131/// the output follows the convention in `rings.rs` — counter-clockwise exteriors, clockwise holes.
132pub fn boolean(subject: &[Polygon], clip: &[Polygon], op: Op) -> Vec<Polygon> {
133 // Trivial cases, which are also the common ones: a tile is usually all land or all sea.
134 if subject.is_empty() {
135 return match op {
136 Op::Intersection | Op::Difference => Vec::new(),
137 Op::Union | Op::Xor => clip.to_vec(),
138 };
139 }
140 if clip.is_empty() {
141 return match op {
142 Op::Intersection => Vec::new(),
143 Op::Union | Op::Difference | Op::Xor => subject.to_vec(),
144 };
145 }
146
147 // Xor by composition rather than as its own sweep. `A^B` is `(A-B) | (B-A)` by definition, and
148 // the two halves touch along the boundary of the overlap — a single sweep has to assemble
149 // rings that meet without crossing, and got it wrong where the other three operations were
150 // right. Built this way it is correct exactly as far as difference and union are, which is
151 // what the randomised identities check.
152 if op == Op::Xor {
153 let left = boolean(subject, clip, Op::Difference);
154 let right = boolean(clip, subject, Op::Difference);
155 if left.is_empty() {
156 return right;
157 }
158 if right.is_empty() {
159 return left;
160 }
161 return boolean(&left, &right, Op::Union);
162 }
163
164 let mut sweep = Sweep::new();
165 sweep.add_polygons(subject, Side::Subject);
166 sweep.add_polygons(clip, Side::Clip);
167 sweep.run(op)
168}
169
170/// `subject − clip`. The ocean is `tile rectangle − land`.
171pub fn difference(subject: &[Polygon], clip: &[Polygon]) -> Vec<Polygon> {
172 boolean(subject, clip, Op::Difference)
173}
174
175/// An axis-aligned rectangle as a single polygon, wound counter-clockwise.
176pub fn rect(min_x: f64, min_y: f64, max_x: f64, max_y: f64) -> Polygon {
177 vec![vec![
178 (min_x, min_y),
179 (max_x, min_y),
180 (max_x, max_y),
181 (min_x, max_y),
182 ]]
183}
184
185/// Total signed area of a polygon set, positive for counter-clockwise exteriors.
186///
187/// Exposed because it is how the tests assert a result without depending on vertex order.
188pub fn area(polys: &[Polygon]) -> f64 {
189 let mut total = 0.0;
190 for poly in polys {
191 for (at, ring) in poly.iter().enumerate() {
192 let mut a = 0.0;
193 for i in 0..ring.len() {
194 let p = ring[i];
195 let q = ring[(i + 1) % ring.len()];
196 a += p.0 * q.1 - q.0 * p.1;
197 }
198 a /= 2.0;
199 // A hole subtracts whichever way it happens to be wound.
200 total += if at == 0 { a.abs() } else { -a.abs() };
201 }
202 }
203 total
204}