1use super::{GeometryError, Point, Positions, Rect};
8
9pub const DEFAULT_MAX_NEIGHBOURS: usize = 32;
11
12#[derive(Clone, Debug, PartialEq)]
14pub struct SpreadParams {
15 pub min_distance: f64,
17 pub steps: u32,
19 pub max_neighbours: usize,
22 pub bounds: Option<Rect>,
25}
26
27impl SpreadParams {
28 #[must_use]
30 pub fn new(min_distance: f64, steps: u32) -> Self {
31 Self {
32 min_distance,
33 steps,
34 max_neighbours: DEFAULT_MAX_NEIGHBOURS,
35 bounds: None,
36 }
37 }
38}
39
40#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct SpreadReport {
43 pub comparisons: u64,
45 pub overlaps_left: usize,
48}
49
50const H: f64 = std::f64::consts::FRAC_1_SQRT_2;
52
53const DIRECTIONS: [Point; 16] = [
55 (1.0, 0.0),
56 (0.9238795325112867, 0.3826834323650898),
57 (H, H),
58 (0.3826834323650898, 0.9238795325112867),
59 (0.0, 1.0),
60 (-0.3826834323650898, 0.9238795325112867),
61 (-H, H),
62 (-0.9238795325112867, 0.3826834323650898),
63 (-1.0, 0.0),
64 (-0.9238795325112867, -0.3826834323650898),
65 (-H, -H),
66 (-0.3826834323650898, -0.9238795325112867),
67 (0.0, -1.0),
68 (0.3826834323650898, -0.9238795325112867),
69 (H, -H),
70 (0.9238795325112867, -0.3826834323650898),
71];
72
73fn fnv1a(bytes: &[u8]) -> u64 {
75 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
76 for byte in bytes {
77 hash ^= u64::from(*byte);
78 hash = hash.wrapping_mul(0x0100_0000_01b3);
79 }
80 hash
81}
82
83fn direction(hash: u64) -> Point {
84 DIRECTIONS[(hash & 15) as usize]
85}
86
87type Cell = (i64, i64, usize);
88
89fn cell_of(at: Point, side: f64) -> (i64, i64) {
90 ((at.1 / side).floor() as i64, (at.0 / side).floor() as i64)
92}
93
94fn sorted_cells(points: &[Point], side: f64) -> Vec<Cell> {
95 let mut cells: Vec<Cell> = points
96 .iter()
97 .enumerate()
98 .map(|(k, at)| {
99 let (r, c) = cell_of(*at, side);
100 (r, c, k)
101 })
102 .collect();
103 cells.sort_unstable();
104 cells
105}
106
107fn in_cell(cells: &[Cell], row: i64, col: i64) -> &[Cell] {
109 let start = cells.partition_point(|&(r, c, _)| (r, c) < (row, col));
110 let end = cells.partition_point(|&(r, c, _)| (r, c) <= (row, col));
111 &cells[start..end]
112}
113
114fn scan_pairs(
118 points: &[Point],
119 cells: &[Cell],
120 side: f64,
121 max_neighbours: usize,
122 mut visit: impl FnMut(usize, usize, f64),
123) -> u64 {
124 let mut comparisons: u64 = 0;
125 for (i, at) in points.iter().enumerate() {
126 let (row, col) = cell_of(*at, side);
127 let mut examined = 0usize;
128 'cells: for dr in -1i64..=1 {
129 for dc in -1i64..=1 {
130 let (Some(r), Some(c)) = (row.checked_add(dr), col.checked_add(dc)) else {
132 continue;
133 };
134 let cell = in_cell(cells, r, c);
135 let cell = &cell[cell.partition_point(|&(_, _, j)| j <= i)..];
137 for &(_, _, j) in cell {
138 if examined >= max_neighbours {
139 break 'cells;
140 }
141 examined += 1;
142 comparisons += 1;
143 let (dx, dy) = (points[j].0 - at.0, points[j].1 - at.1);
144 visit(i, j, (dx * dx + dy * dy).sqrt());
145 }
146 }
147 }
148 }
149 comparisons
150}
151
152fn validate(
153 positions: &Positions,
154 obstacles: &[Point],
155 params: &SpreadParams,
156) -> Result<(), GeometryError> {
157 let d = params.min_distance;
158 if !(d.is_finite() && d > 0.0) {
159 return Err(GeometryError::BadParameter {
160 name: "min_distance",
161 value: d,
162 });
163 }
164 if params.max_neighbours < 1 {
165 return Err(GeometryError::BadParameter {
166 name: "max_neighbours",
167 value: 0.0,
168 });
169 }
170 if let Some((x0, y0, x1, y1)) = params.bounds {
171 for value in [x0, y0, x1, y1] {
172 if !value.is_finite() {
173 return Err(GeometryError::BadParameter {
174 name: "bounds",
175 value,
176 });
177 }
178 }
179 if x0 > x1 {
180 return Err(GeometryError::BadParameter {
181 name: "bounds",
182 value: x0,
183 });
184 }
185 if y0 > y1 {
186 return Err(GeometryError::BadParameter {
187 name: "bounds",
188 value: y0,
189 });
190 }
191 }
192 for (id, at) in positions.iter() {
193 if !(at.0.is_finite() && at.1.is_finite()) {
194 return Err(GeometryError::NonFinitePosition {
195 item: id.to_owned(),
196 });
197 }
198 }
199 for (k, at) in obstacles.iter().enumerate() {
200 if !(at.0.is_finite() && at.1.is_finite()) {
201 return Err(GeometryError::NonFinitePosition {
202 item: format!("#{k}"),
203 });
204 }
205 }
206 Ok(())
207}
208
209fn step(
211 positions: &mut Positions,
212 hashes: &[u64],
213 obstacles: &[Point],
214 obstacle_cells: &[Cell],
215 params: &SpreadParams,
216) -> u64 {
217 let d = params.min_distance;
218 let half = d / 2.0;
219 let points: Vec<Point> = positions.iter().map(|(_, at)| at).collect();
220 let cells = sorted_cells(&points, d);
221 let mut shift: Vec<Point> = vec![(0.0, 0.0); points.len()];
222
223 let mut comparisons = {
224 let view: &Positions = positions;
225 scan_pairs(&points, &cells, d, params.max_neighbours, |i, j, dist| {
226 if dist >= d {
227 return;
228 }
229 let (dx, dy) = (points[j].0 - points[i].0, points[j].1 - points[i].1);
230 let push = if dist == 0.0 {
232 let (small, large) = if view.id_at(i) < view.id_at(j) {
233 (i, j)
234 } else {
235 (j, i)
236 };
237 let u = direction(hashes[small].wrapping_mul(31) ^ hashes[large]);
238 let sign = if i == large { 1.0 } else { -1.0 };
239 (sign * u.0 * half, sign * u.1 * half)
240 } else {
241 let amount = (d - dist) / 2.0;
242 (-(dx / dist) * amount, -(dy / dist) * amount)
243 };
244 shift[i].0 += push.0;
245 shift[i].1 += push.1;
246 shift[j].0 -= push.0;
247 shift[j].1 -= push.1;
248 })
249 };
250
251 for s in &mut shift {
252 let len = (s.0 * s.0 + s.1 * s.1).sqrt();
253 if len > half {
254 let scale = half / len;
255 s.0 *= scale;
256 s.1 *= scale;
257 }
258 }
259
260 if !obstacles.is_empty() {
261 for (i, at) in points.iter().enumerate() {
262 let (row, col) = cell_of(*at, d);
263 let mut examined = 0usize;
264 'cells: for dr in -1i64..=1 {
265 for dc in -1i64..=1 {
266 let (Some(r), Some(c)) = (row.checked_add(dr), col.checked_add(dc)) else {
267 continue;
268 };
269 let cell = in_cell(obstacle_cells, r, c);
272 let room = params.max_neighbours - examined;
273 for &(_, _, k) in &cell[..cell.len().min(room)] {
274 examined += 1;
275 comparisons += 1;
276 let (dx, dy) = (at.0 - obstacles[k].0, at.1 - obstacles[k].1);
277 let dist = (dx * dx + dy * dy).sqrt();
278 if dist >= d {
279 continue;
280 }
281 if dist == 0.0 {
282 let u = direction(hashes[i]);
283 shift[i].0 += u.0 * d;
284 shift[i].1 += u.1 * d;
285 } else {
286 let amount = d - dist;
287 shift[i].0 += dx / dist * amount;
288 shift[i].1 += dy / dist * amount;
289 }
290 }
291 if examined >= params.max_neighbours {
292 break 'cells;
293 }
294 }
295 }
296 }
297 }
298
299 for (i, s) in shift.iter().enumerate() {
300 let at = positions.point_mut(i);
301 at.0 += s.0;
302 at.1 += s.1;
303 if let Some((x0, y0, x1, y1)) = params.bounds {
304 at.0 = at.0.max(x0).min(x1);
305 at.1 = at.1.max(y0).min(y1);
306 }
307 }
308 comparisons
309}
310
311pub fn spread(
328 positions: &mut Positions,
329 obstacles: &[Point],
330 params: &SpreadParams,
331) -> Result<SpreadReport, GeometryError> {
332 spread_counted(positions, obstacles, params).map(|(report, _)| report)
333}
334
335fn spread_counted(
338 positions: &mut Positions,
339 obstacles: &[Point],
340 params: &SpreadParams,
341) -> Result<(SpreadReport, u64), GeometryError> {
342 validate(positions, obstacles, params)?;
343 let hashes: Vec<u64> = (0..positions.len())
344 .map(|i| fnv1a(positions.id_at(i).as_bytes()))
345 .collect();
346 let obstacle_cells = sorted_cells(obstacles, params.min_distance);
347 let mut comparisons: u64 = 0;
348 for _ in 0..params.steps {
349 comparisons += step(positions, &hashes, obstacles, &obstacle_cells, params);
350 }
351
352 let d = params.min_distance;
353 let points: Vec<Point> = positions.iter().map(|(_, at)| at).collect();
354 let cells = sorted_cells(&points, d);
355 let mut overlaps_left = 0usize;
356 let final_scan = scan_pairs(&points, &cells, d, params.max_neighbours, |_, _, dist| {
357 if dist < d * (1.0 - 1e-9) {
358 overlaps_left += 1;
359 }
360 });
361 Ok((
362 SpreadReport {
363 comparisons,
364 overlaps_left,
365 },
366 comparisons + final_scan,
367 ))
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373
374 #[test]
375 fn twenty_five_thousand_points_on_one_spot_examine_a_bounded_count_of_pairs() {
376 let mut p = Positions::new();
377 for k in 0..25_000usize {
378 p.insert(format!("n{k:05}"), (1.0, 1.0));
379 }
380 let (_, examined) = spread_counted(&mut p, &[], &SpreadParams::new(0.1, 2)).unwrap();
381 assert!(examined <= 25_000 * 32 * 3, "{examined} pairs");
384 }
385
386 #[test]
387 fn a_pile_of_obstacles_on_one_spot_examines_a_bounded_count() {
388 let mut p = Positions::new();
389 for k in 0..500usize {
390 p.insert(format!("n{k:03}"), (1.0 + k as f64 * 1e-3, 1.0));
391 }
392 let obstacles = vec![(1.0, 1.0); 20_000];
393 let (_, examined) = spread_counted(&mut p, &obstacles, &SpreadParams::new(1.0, 2)).unwrap();
394 assert!(
396 examined <= 500 * 32 * 2 * 2 + 500 * 32,
397 "{examined} examined"
398 );
399 }
400}