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

Modern-Apps.git / library / map / src / main / rust / tests / plan_perf_verify.rs

plan_perf_verify.rs464 lines · 16.8 KiBRaw
1//! Plan-verification harness: placement/collision + symbol-emit perf refactors.
2//!
3//! The lib-test target cannot compile in this tree (pre-existing breakage:
4//! missing `overlay_tests.rs`, stale `LAYER_EARTH`/`region_links` fixtures —
5//! all committed at HEAD, out of scope). This integration test links the lib
6//! itself and pins the plan's bit-identical refactorings against from-scratch
7//! reimplementations of the replaced algorithms:
8//! 1. `place_segmented` (grid broadphase + area hoist) vs brute force.
9//! 2. `layout_along_line` (monotonic walk + virtual reversed copy) vs the old
10//! rescan/reversed-collect algorithm.
11//! 3. `obb_overlap` AABB path vs the half-open rect rule.
12//! 4. `candidate_id` determinism / distinctness.
13//! 5. `Ramp::at` single-stop fast path vs a constant.
14
15use map_renderer::tess::text::{layout_along_line, CurvedGlyph, ShapedGlyph, ShapedLine};
16use map_renderer::tile::placement::{
17 candidate_id, obb_overlap, place_segmented, Obb, SegmentedCandidate,
18};
19
20// ---------------------------------------------------------------------------
21// 1. Brute-force placer (the pre-grid algorithm, restated from the old code).
22// ---------------------------------------------------------------------------
23
24fn brute_overlap(a: &Obb, b: &Obb) -> bool {
25 // Full SAT, no AABB fast path — independent of the optimized narrowphase.
26 let axes = [(a.cos, a.sin), (-a.sin, a.cos), (b.cos, b.sin), (-b.sin, b.cos)];
27 let dx = b.cx - a.cx;
28 let dy = b.cy - a.cy;
29 let radius = |o: &Obb, ax: f32, ay: f32| {
30 let u = (o.cos, o.sin);
31 let v = (-o.sin, o.cos);
32 o.hx * (u.0 * ax + u.1 * ay).abs() + o.hy * (v.0 * ax + v.1 * ay).abs()
33 };
34 axes.iter().all(|(ax, ay)| {
35 let gap = (dx * ax + dy * ay).abs();
36 // NOTE: strict `>=` separation (edge-touching = separated) matches the
37 // documented half-open rule.
38 gap < radius(a, *ax, *ay) + radius(b, *ax, *ay)
39 })
40}
41
42fn brute_area(c: &SegmentedCandidate) -> f32 {
43 c.boxes.iter().map(|b| b.hx * b.hy).sum::<f32>() * 4.0
44}
45
46fn brute_place(candidates: &[SegmentedCandidate]) -> Vec<(u64, bool)> {
47 let mut ordered: Vec<&SegmentedCandidate> = candidates.iter().collect();
48 ordered.sort_by(|a, b| {
49 a.rank
50 .cmp(&b.rank)
51 .then_with(|| b.pop.cmp(&a.pop))
52 .then_with(|| {
53 brute_area(b).partial_cmp(&brute_area(a)).unwrap_or(std::cmp::Ordering::Equal)
54 })
55 .then_with(|| a.id.cmp(&b.id))
56 });
57 let mut accepted: Vec<Obb> = Vec::new();
58 let mut out = Vec::new();
59 for c in ordered {
60 let free = |boxes: &[Obb], accepted: &[Obb]| {
61 c.rank == 0 || !boxes.iter().any(|b| accepted.iter().any(|a| brute_overlap(a, b)))
62 };
63 let taken = if free(&c.boxes, &accepted) {
64 (&c.boxes, false)
65 } else if let Some(alternate) = c.alternate.as_ref().filter(|a| free(a, &accepted)) {
66 (alternate, true)
67 } else {
68 continue;
69 };
70 accepted.extend_from_slice(taken.0);
71 out.push((c.id, taken.1));
72 }
73 out
74}
75
76/// Deterministic xorshift64 PRNG (fixed seed — the fuzz corpus is stable).
77struct Rng(u64);
78impl Rng {
79 fn next(&mut self) -> u64 {
80 let mut x = self.0;
81 x ^= x << 13;
82 x ^= x >> 7;
83 x ^= x << 17;
84 self.0 = x;
85 x
86 }
87 fn f32(&mut self, lo: f32, hi: f32) -> f32 {
88 lo + (self.next() as f32 / u64::MAX as f32) * (hi - lo)
89 }
90 fn below(&mut self, n: usize) -> usize {
91 (self.next() % n as u64) as usize
92 }
93}
94
95fn random_obb(rng: &mut Rng, axis_aligned_bias: bool) -> Obb {
96 let (cos, sin) = if axis_aligned_bias && rng.below(4) != 0 {
97 (1.0, 0.0) // the point-label majority case
98 } else {
99 let a = rng.f32(0.0, std::f32::consts::TAU);
100 (a.cos(), a.sin())
101 };
102 Obb {
103 cx: rng.f32(0.0, 1024.0),
104 cy: rng.f32(0.0, 1024.0),
105 hx: rng.f32(1.0, 60.0),
106 hy: rng.f32(1.0, 20.0),
107 cos,
108 sin,
109 }
110}
111
112#[test]
113fn grid_broadphase_matches_brute_force_on_fuzz() {
114 let mut rng = Rng(0x1234_5678_9abc_def0);
115 for round in 0..300 {
116 let n = 1 + rng.below(40);
117 let mut candidates: Vec<SegmentedCandidate> = Vec::with_capacity(n);
118 for i in 0..n {
119 let nb = 1 + rng.below(4);
120 let boxes: Vec<Obb> = (0..nb).map(|_| random_obb(&mut rng, true)).collect();
121 let alternate = if rng.below(3) == 0 {
122 let na = 1 + rng.below(3);
123 Some((0..na).map(|_| random_obb(&mut rng, true)).collect())
124 } else {
125 None
126 };
127 candidates.push(SegmentedCandidate {
128 // Forced id/rank/pop collisions to stress tie-breaks.
129 id: (i % 7) as u64,
130 rank: [0, 2, 2, 3, 4, 4, 5][rng.below(7)],
131 pop: (rng.below(4)) as u16,
132 boxes,
133 alternate,
134 feature_id: i as u64 + 1,
135 layer_index: rng.below(3),
136 });
137 }
138 let want = brute_place(&candidates);
139 let got = place_segmented(&candidates);
140 assert_eq!(got, want, "round {round}: grid diverged from brute force");
141 }
142}
143
144#[test]
145fn grid_matches_brute_force_on_degenerate_inputs() {
146 // Empty, single, all-rank-0, identical boxes, edge-touching grid.
147 let empty: Vec<SegmentedCandidate> = vec![];
148 assert_eq!(place_segmented(&empty), brute_place(&empty));
149 let mk = |id: u64, rank: u8, rect: (f32, f32, f32, f32)| SegmentedCandidate {
150 id,
151 rank,
152 pop: 0,
153 boxes: vec![Obb::from_rect(rect)],
154 alternate: None,
155 feature_id: id + 1,
156 layer_index: 0,
157 };
158 // Ten identical boxes: first wins, rest collide.
159 let same: Vec<SegmentedCandidate> = (0..10).map(|i| mk(i, 4, (0.0, 0.0, 50.0, 20.0))).collect();
160 assert_eq!(place_segmented(&same), brute_place(&same));
161 assert_eq!(place_segmented(&same).len(), 1);
162 // Edge-touching chain: all place (half-open rule through the grid).
163 let chain: Vec<SegmentedCandidate> =
164 (0..8).map(|i| mk(i, 4, (i as f32 * 50.0, 0.0, i as f32 * 50.0 + 50.0, 20.0))).collect();
165 assert_eq!(place_segmented(&chain).len(), 8);
166 assert_eq!(place_segmented(&chain), brute_place(&chain));
167 // Negative coordinates (grid floor division with negatives).
168 let neg: Vec<SegmentedCandidate> = (0..6)
169 .map(|i| mk(i, 4, (-400.0 + i as f32 * 30.0, -300.0, -360.0 + i as f32 * 30.0, -280.0)))
170 .collect();
171 assert_eq!(place_segmented(&neg), brute_place(&neg));
172 // Zero-area boxes.
173 let zero = vec![mk(0, 4, (10.0, 10.0, 10.0, 10.0)), mk(1, 4, (0.0, 0.0, 50.0, 20.0))];
174 assert_eq!(place_segmented(&zero), brute_place(&zero));
175}
176
177// ---------------------------------------------------------------------------
178// 2. Old curved-layout algorithm, restated verbatim (rescan + collect).
179// ---------------------------------------------------------------------------
180
181fn old_polyline_length(pts: &[(f32, f32)]) -> f32 {
182 let mut sum = 0.0;
183 for w in pts.windows(2) {
184 let dx = w[1].0 - w[0].0;
185 let dy = w[1].1 - w[0].1;
186 sum += (dx * dx + dy * dy).sqrt();
187 }
188 sum
189}
190
191const MAX_TURN_RAD: f32 = std::f32::consts::FRAC_PI_4;
192
193fn old_longest_smooth_run(pts: &[(f32, f32)]) -> &[(f32, f32)] {
194 if pts.len() < 3 {
195 return pts;
196 }
197 let cos_max = MAX_TURN_RAD.cos();
198 let direction = |a: (f32, f32), b: (f32, f32)| {
199 let (dx, dy) = (b.0 - a.0, b.1 - a.1);
200 let len = (dx * dx + dy * dy).sqrt();
201 (len > 0.0).then_some((dx / len, dy / len))
202 };
203 let (mut best_start, mut best_end) = (0usize, pts.len());
204 let mut best_len = -1.0f32;
205 let mut start = 0usize;
206 let mut previous: Option<(f32, f32)> = None;
207 for i in 0..pts.len() - 1 {
208 let Some(d) = direction(pts[i], pts[i + 1]) else { continue };
209 if let Some(p) = previous {
210 if p.0 * d.0 + p.1 * d.1 < cos_max {
211 let len = old_polyline_length(&pts[start..=i]);
212 if len > best_len {
213 best_len = len;
214 (best_start, best_end) = (start, i + 1);
215 }
216 start = i;
217 }
218 }
219 previous = Some(d);
220 }
221 if old_polyline_length(&pts[start..]) > best_len {
222 (best_start, best_end) = (start, pts.len());
223 }
224 &pts[best_start..best_end]
225}
226
227fn old_sample_polyline(pts: &[(f32, f32)], d: f32) -> ((f32, f32), (f32, f32)) {
228 let d = d.max(0.0);
229 let mut acc = 0.0f32;
230 for w in pts.windows(2) {
231 let dx = w[1].0 - w[0].0;
232 let dy = w[1].1 - w[0].1;
233 let seg = (dx * dx + dy * dy).sqrt();
234 if seg <= 0.0 {
235 continue;
236 }
237 if acc + seg >= d {
238 let t = ((d - acc) / seg).clamp(0.0, 1.0);
239 return ((w[0].0 + dx * t, w[0].1 + dy * t), (dx / seg, dy / seg));
240 }
241 acc += seg;
242 }
243 let last = *pts.last().unwrap_or(&(0.0, 0.0));
244 for w in pts.windows(2).rev() {
245 let dx = w[1].0 - w[0].0;
246 let dy = w[1].1 - w[0].1;
247 let seg = (dx * dx + dy * dy).sqrt();
248 if seg > 0.0 {
249 return (last, (dx / seg, dy / seg));
250 }
251 }
252 (last, (1.0, 0.0))
253}
254
255fn old_layout_along_line(
256 line: &ShapedLine,
257 centreline: &[(f32, f32)],
258 px_per_font_unit: f32,
259 up_em: f32,
260) -> Vec<CurvedGlyph> {
261 if centreline.len() < 2 || line.glyphs.is_empty() || px_per_font_unit <= 0.0 {
262 return Vec::new();
263 }
264 let smooth = old_longest_smooth_run(centreline);
265 if smooth.len() < 2 {
266 return Vec::new();
267 }
268 let total_len = old_polyline_length(smooth);
269 let run_len = line.advance * px_per_font_unit;
270 if run_len <= 0.0 || run_len > total_len {
271 return Vec::new();
272 }
273 let net_dx = smooth[smooth.len() - 1].0 - smooth[0].0;
274 let reversed: Vec<(f32, f32)>;
275 let path: &[(f32, f32)] = if net_dx < 0.0 {
276 reversed = smooth.iter().rev().copied().collect();
277 &reversed
278 } else {
279 smooth
280 };
281 let start = (total_len - run_len) * 0.5;
282 let half_window = up_em * px_per_font_unit;
283 let mut out = Vec::with_capacity(line.glyphs.len());
284 for g in &line.glyphs {
285 let d = start + g.pen_x * px_per_font_unit;
286 let (pen, segment_tangent) = old_sample_polyline(path, d);
287 let (behind, _) = old_sample_polyline(path, d - half_window);
288 let (ahead, _) = old_sample_polyline(path, d + half_window);
289 let (dx, dy) = (ahead.0 - behind.0, ahead.1 - behind.1);
290 let chord = (dx * dx + dy * dy).sqrt();
291 let tangent = if chord > 1e-7 { (dx / chord, dy / chord) } else { segment_tangent };
292 out.push(CurvedGlyph { glyph: *g, pen, tangent });
293 }
294 out
295}
296
297fn block_run(n: usize, up_em: f32) -> ShapedLine {
298 let glyphs: Vec<ShapedGlyph> = (0..n)
299 .map(|i| ShapedGlyph {
300 pen_x: i as f32 * up_em,
301 ch: 'x',
302 advance: up_em,
303 bearing_x: 0.0,
304 top: up_em,
305 w: up_em,
306 h: up_em,
307 })
308 .collect();
309 ShapedLine { glyphs, advance: n as f32 * up_em }
310}
311
312fn assert_same_layout(got: &[CurvedGlyph], want: &[CurvedGlyph], ctx: &str) {
313 assert_eq!(got.len(), want.len(), "{ctx}: glyph count");
314 // Forward walks are bit-identical (same operands, same order). Reversed walks
315 // mirror arcs about the total length instead of accumulating a reversed copy,
316 // so they may differ in the last ulp; anything bigger is a real divergence.
317 for (i, (g, w)) in got.iter().zip(want.iter()).enumerate() {
318 for (field, gv, wv) in [
319 ("pen.x", g.pen.0, w.pen.0),
320 ("pen.y", g.pen.1, w.pen.1),
321 ("tan.x", g.tangent.0, w.tangent.0),
322 ("tan.y", g.tangent.1, w.tangent.1),
323 ] {
324 if gv.to_bits() != wv.to_bits() {
325 let bad = (gv - wv).abs();
326 assert!(
327 bad <= 2.0 * f32::EPSILON * wv.abs().max(1.0),
328 "{ctx}[{i}] {field}: {gv} vs {wv} (diff {bad} exceeds 2ulp)"
329 );
330 }
331 }
332 }
333}
334
335#[test]
336fn linearized_layout_matches_old_algorithm_bit_for_bit() {
337 let up_em = 1000.0f32;
338 let ppfu = 1.0 / up_em;
339 // Straight, reversed (net_dx < 0), elbow, gentle bend, degenerate points,
340 // multi-part join, arc, tiny stub.
341 let mut arc = Vec::new();
342 for i in 0..=48 {
343 let t = std::f32::consts::FRAC_PI_2 * i as f32 / 48.0;
344 arc.push((0.5 + 0.35 * t.cos(), 0.5 + 0.35 * t.sin()));
345 }
346 let cases: Vec<(&str, Vec<(f32, f32)>)> = vec![
347 ("straight", vec![(0.0, 0.0), (12.0, 0.0)]),
348 ("reversed", vec![(12.0, 0.0), (0.0, 0.0)]),
349 ("rev-bend", vec![(9.0, 4.0), (2.0, 0.5), (0.0, 0.0)]),
350 ("elbow", vec![(0.0, 0.0), (4.0, 0.0), (4.0, 9.0)]),
351 ("bend30", {
352 let c = 30.0f32.to_radians();
353 vec![(0.0, 0.0), (6.0, 0.0), (6.0 + 6.0 * c.cos(), 6.0 * c.sin())]
354 }),
355 ("degenerate", vec![(0.0, 0.0), (0.0, 0.0), (6.0, 0.0), (6.0, 0.0), (12.0, 0.0)]),
356 ("join", vec![(0.0, 0.0), (6.0, 0.0), (0.0, 4.0), (9.0, 4.0)]),
357 ("arc", arc),
358 ("zigzag", vec![(0.0, 0.0), (2.0, 1.0), (4.0, 0.0), (6.0, 1.0), (8.0, 0.0), (10.0, 1.0)]),
359 // Net-dx-zero paths: neither forward nor reversed by the sign test — the
360 // walk takes the forward branch (strict `<`), matching the old code's
361 // `net_dx < 0.0` gate exactly.
362 ("vertical", vec![(3.0, 0.0), (3.0, 12.0)]),
363 ("rev-vertical", vec![(3.0, 12.0), (3.0, 0.0)]),
364 ("there-and-back", vec![(0.0, 0.0), (6.0, 0.0), (0.0, 0.0)]),
365 ];
366 for (name, path) in &cases {
367 for n in [1usize, 3, 8, 10] {
368 let run = block_run(n, up_em);
369 let want = old_layout_along_line(&run, path, ppfu, up_em);
370 let got = layout_along_line(&run, path, ppfu);
371 assert_same_layout(&got, &want, &format!("{name}/n={n}"));
372 }
373 }
374}
375
376#[test]
377fn linearized_layout_matches_on_fuzz_polylines() {
378 let up_em = 1000.0f32;
379 let mut rng = Rng(0xfeed_face_cafe_1234);
380 for round in 0..200 {
381 let npts = 2 + rng.below(14);
382 let mut path = Vec::with_capacity(npts);
383 let (mut x, mut y) = (rng.f32(0.0, 1.0), rng.f32(0.0, 1.0));
384 path.push((x, y));
385 for _ in 1..npts {
386 // Random walk, sometimes repeating a vertex (degenerate segment).
387 if rng.below(8) == 0 {
388 path.push((x, y));
389 } else {
390 x += rng.f32(-0.2, 0.2);
391 y += rng.f32(-0.2, 0.2);
392 path.push((x, y));
393 }
394 }
395 let n = 1 + rng.below(12);
396 let run = block_run(n, up_em);
397 // Vary text size over two orders of magnitude.
398 let ppfu = [0.5, 1.0, 3.0][rng.below(3)] / up_em;
399 let want = old_layout_along_line(&run, &path, ppfu, up_em);
400 let got = layout_along_line(&run, &path, ppfu);
401 assert_same_layout(&got, &want, &format!("fuzz round {round}"));
402 }
403}
404
405// ---------------------------------------------------------------------------
406// 3-5. AABB rule, candidate_id, Ramp.
407// ---------------------------------------------------------------------------
408
409#[test]
410fn aabb_fast_path_matches_half_open_rect_rule() {
411 let rect_overlaps = |a: (f32, f32, f32, f32), b: (f32, f32, f32, f32)| {
412 a.0 < b.2 && b.0 < a.2 && a.1 < b.3 && b.1 < a.3
413 };
414 let mut rng = Rng(0x0bad_f00d_dead_beef);
415 for _ in 0..500 {
416 let r = |mut v: (f32, f32, f32, f32)| {
417 if v.0 > v.2 {
418 std::mem::swap(&mut v.0, &mut v.2);
419 }
420 if v.1 > v.3 {
421 std::mem::swap(&mut v.1, &mut v.3);
422 }
423 v
424 };
425 let a = r((
426 rng.f32(-50.0, 50.0),
427 rng.f32(-50.0, 50.0),
428 rng.f32(-50.0, 50.0),
429 rng.f32(-50.0, 50.0),
430 ));
431 let b = r((
432 rng.f32(-50.0, 50.0),
433 rng.f32(-50.0, 50.0),
434 rng.f32(-50.0, 50.0),
435 rng.f32(-50.0, 50.0),
436 ));
437 let oa = Obb::from_rect(a);
438 let ob = Obb::from_rect(b);
439 assert_eq!(obb_overlap(&oa, &ob), rect_overlaps(a, b), "a={a:?} b={b:?}");
440 }
441 // Exact edge touch: separated.
442 let a = Obb::from_rect((0.0, 0.0, 10.0, 10.0));
443 let flush = Obb::from_rect((10.0, 0.0, 20.0, 10.0));
444 assert!(!obb_overlap(&a, &flush));
445}
446
447#[test]
448fn candidate_ids_stable_and_distinct() {
449 let a = candidate_id(6, 10, 24, 33, 4);
450 assert_eq!(a, candidate_id(6, 10, 24, 33, 4));
451 assert_ne!(a, candidate_id(6, 10, 24, 33, 5));
452 assert_ne!(a, candidate_id(6, 10, 25, 33, 4));
453 assert_ne!(a, candidate_id(6, 10, 24, 34, 4));
454 assert_ne!(a, candidate_id(7, 10, 24, 33, 4));
455}
456
457#[test]
458fn ramp_single_stop_answers_constant() {
459 use map_renderer::style::paint::Ramp;
460 let c = Ramp::constant(3.5);
461 for z in [-10.0, 0.0, 5.5, 14.0, 22.0, 100.0] {
462 assert_eq!(c.at(z).to_bits(), 3.5f32.to_bits(), "z={z}");
463 }
464}