1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
// src/ops/distance.rs
//! `dwithin`, the exact distance predicate, and `distance`, the measurement
//! with a documented bound and a certified zero.
//!
//! # The two answers, and which to use
//!
//! [`dwithin`]`(a, b, d)` decides "is the distance between `a` and `b` at
//! most `d`?" **exactly**, for every pair of geometries and every finite
//! `d ≥ 0`. It is the answer to use for that question.
//!
//! [`distance`]`(a, b)` returns the distance as an `f64`. It is **exactly
//! `0.0` if and only if `a` and `b` intersect**; otherwise it is an
//! approximation with the absolute bound below. This is the position
//! [`area`](super::area) and [`length`](super::length) hold under this
//! crate's charter: a quantity whose sign (here: zero or not) is certified
//! and whose magnitude has a documented bound. Neither function returns a
//! coordinate.
//!
//! # The decomposition, and why it is exact
//!
//! Both functions rest on one decomposition of "the distance between two
//! geometries":
//!
//! 1. **If `a` and `b` intersect, the distance is 0.** Intersection is
//! decided by the exact [`relate`](crate::predicates::relate) machinery,
//! so this covers every kind of contact (a point inside a polygon, a
//! line crossing an area, boundaries touching) rather than only contacts
//! between boundary elements.
//! 2. **Otherwise the distance is attained between boundary elements:** the
//! segments of lines and of polygon rings, and the isolated points. For
//! puntal and lineal geometries every point lies on an element already.
//! For an areal `a`, suppose the infimum were attained at a point `p`
//! interior to `a` nearest to some `q` in `b`. Every point of `b` is
//! outside `a` (they do not intersect), so `q` is outside, and the
//! segment `pq` leaves `a` through its boundary at some `p′` with
//! `|p′q| < |pq|`, a contradiction. So the nearest point of `a` lies on
//! its boundary, which is made of ring segments, and symmetrically
//! for `b`.
//! 3. **For two segments that do not intersect, the minimum distance is
//! attained at an endpoint of one of them against the other:** the
//! distance between a point moving along one segment and the other
//! segment is a convex function of the position, so its minimum over the
//! closed segment is at an endpoint unless the interiors meet, and
//! step 1 has already excluded every meeting. A composition that skipped
//! step 1 would be wrong exactly there: two crossing segments have
//! distance 0 with all four endpoint distances positive.
//! 4. **Point against segment, and point against point,** are
//! `arithmetica`'s exact predicates
//! ([`compare_segment_distance`](arithmetica::compare_segment_distance),
//! [`compare_point_distance`](arithmetica::compare_point_distance))
//! directly.
//!
//! So `dwithin(a, b, d)` is `true` exactly when step 1 holds, or some pair
//! of boundary elements passes its exact predicate with this `d`. Every
//! decision along the way is exact.
//!
//! # Contact without the matrix
//!
//! The intersection test of step 1 does not need the DE-9IM matrix. Call
//! two elements in contact when one's endpoint is within distance 0 of the
//! other (the step 4 predicates with `d = 0`) or they are segments that
//! cross properly.
//! Then `a` and `b` intersect exactly when some pair of their elements is in
//! contact, or some connected component of one lies wholly in the interior
//! of the other, which is then areal; the component's first vertex shows
//! it.
//!
//! - Contact or a located vertex is a common point, so either gives an
//! intersection.
//! - Conversely, let `x` be common to `a` and `b`. If it lies on an element
//! of each, the two elements meet. Two meeting segments either cross
//! properly or have an endpoint of one on the other. A segment meeting a
//! point has the point on it. So some pair is in contact.
//! - Otherwise `x` is interior to an areal operand, say `a`, and lies in a
//! component `C` of `b` none of whose elements meets an element of `a`.
//! If `C`'s elements meet no element of `a`, then `C`'s boundary, which
//! is connected per ring and does not touch `a`'s boundary, lies wholly
//! inside or wholly outside `a`. For a point or a line, `C` itself is
//! inside, so its first vertex is too. For a polygon part, the argument
//! of `predicates::intersects` for two areas applies (an outer ring in
//! the other's exterior forces a contradiction through the holes), so
//! either `C`'s first exterior vertex is inside `a`, or a component of
//! `a` lies inside `C` and its first vertex shows that.
//!
//! So `dwithin` tests element pairs with the step 3–4 predicates plus the
//! crossing test, and locates one vertex per component; `distance` does the
//! same at `d = 0` for its exact zero. Both give exactly what step 1
//! followed by the element scan gives. A collection operand still goes
//! through `intersects`, which also carries its refusal.
//!
//! # The bound on `distance`
//!
//! Write `u = 2⁻⁵³` and let `M` be the largest coordinate magnitude in
//! either operand. For non-intersecting operands,
//!
//! > **|`distance(a, b)` − true distance| ≤ max(c·u·M, 2⁻¹⁰⁷⁴), with c = 64,**
//!
//! valid whenever every coordinate difference is finite (`M ≤ 2^1022`
//! suffices); past that a difference overflows and the affected pair
//! contributes `+∞`, never a finite wrong value. The derivation, with
//! `γk = kε/(1 − kε)` and every distance at most `2√2·M`:
//!
//! - **`norm`** (the only square root): the squares and their sum cost
//! `(1 + θ3)`, the square root halves that and adds one rounding, and an
//! exact power-of-two prescale keeps everything in range, so the result
//! is within relative `γ3`, an absolute error of `γ3·2√2·M < 9·u·M`.
//! - **A computed difference** `fl(x − y)` is within `ε·|x − y| ≤ 2u·M` of
//! the true difference, and the distance is 1-Lipschitz in each endpoint,
//! so the four differences feeding a pair cost roughly `4·(2√2)u·M`;
//! counted generously, `12·u·M` across both endpoints of both elements.
//! - **The clamped projection** (point to segment): with `w = p − a`,
//! `t = (w·u)/(u·u)` clamped to `[0, 1]`. The dot product's absolute
//! error is at most `γ2·(|wₓuₓ| + |w_yu_y|) ≤ γ2·4M·|u|`, and `|u|²`'s is
//! relative `γ3`, so the clamped `t̂` is within `γ4 + 5γ3·M/|u|` of the
//! true minimizer; the distance is `|u|`-Lipschitz in `t`, so the cost is
//! at most `γ4·|u| + 5γ3·M ≤ 25·u·M`. Forming the residual
//! `w − t̂·u` costs two roundings per coordinate, under `9·u·M` through
//! the norm. A segment-to-segment distance is the minimum of four such
//! values, and **the minimum of values each within `δ` of their true
//! values is within `δ` of the true minimum**: for every pair,
//! `computed ≥ true_min − δ` and the minimizing pair's computed value is
//! `≤ its true + δ`.
//!
//! The terms sum below `55·u·M`; `c = 64` is the published constant, and
//! the test suite's exact oracle measures the realized ratio against it on
//! more than 50,000 cases.
//!
//! **The zero guard** accounts for the `2⁻¹⁰⁷⁴` term. The certified zero comes
//! from the exact intersection test, not from the arithmetic: for operands
//! that do not intersect, every computed pair distance could still round to
//! `0.0` (a point one rounding off a segment, whose residual cancels).
//! Returning that `0.0` would assert contact the exact test has just
//! denied. So a computed `0.0` for non-intersecting operands is returned as
//! the smallest positive `f64`, `2⁻¹⁰⁷⁴`. The true distance is then at most
//! `c·u·M` (the computed value `0` is within that of it), so the returned
//! value is within `max(c·u·M, 2⁻¹⁰⁷⁴)` of the truth.
//!
//! # Pruning never discards the minimum
//!
//! Large operands are searched through a static box index over one side's
//! elements (through the crate's private `situs` seam, so no `situs` type
//! appears in a public signature). For `dwithin` each query window is an
//! element's box **grown by `d`**; for `distance`, by `r = (best + δ)` rounded
//! upward, with `δ = c·u·M`. Growing is the one internal construction here, and
//! the crate-private `grow_outward` helper moves every bound outward with
//! directed rounding, so a grown box contains the exact grown box and a query
//! can only gain candidates. A pair the search skips has an axis gap, and so a
//! true distance, greater than `r ≥ best + δ`; its computed value is at least
//! its true value minus `δ`, hence greater than `best`. Skipping it therefore
//! changes neither `dwithin`'s answer nor the computed minimum, and the indexed
//! forms return **exactly** what the exhaustive scan returns.
//!
//! In fact, for a window grown by a *single* subtraction the directed step
//! is provably redundant: rounding to nearest is monotone, so from
//! `box_lo ≥ lo − d` (reals) follows `box_lo ≥ fl(lo − d)`, and a pair
//! within `d` is never excluded even by a to-nearest window. The directed
//! rounding is kept because its safety argument is local, requiring no
//! reasoning about which expression feeds the bound, and because compound
//! radii (`best + δ`) do need the upward step on the sum.
//!
//! # Errors and empties
//!
//! `d` must be finite and at least 0
//! ([`GeometryError::InvalidTolerance`]). `dwithin` with an empty operand
//! is `false`: no point of one geometry is within anything of the other.
//! `distance` with an empty operand is
//! [`GeometryError::EmptyOperand`]: Returning 0 there, which reads as "they
//! touch", is a plausible wrong answer this crate does not give. Collections
//! follow the `relate` semantics: one whose polygonal leaves overlap is
//! refused ([`GeometryError::CollectionElementsOverlap`]), by both
//! functions, through step 1.
use ControlFlow;
use Sign;
use crateGeometryError;
use crateBoxIndex;
use crate;
use crate;
/// Above this many element pairs, the indexed search replaces the
/// exhaustive scan. The answers are identical (module documentation); the
/// threshold is only a cost choice.
pub const BRUTE_PAIRS: usize = 2_048;
/// `u = 2⁻⁵³`, the unit roundoff.
pub const U: f64 = f64EPSILON / 2.0;
/// The constant of the `distance` bound `c·u·M` (module documentation).
pub const DIST_ERR_C: f64 = 64.0;
// ===========================================================================
// The public functions
// ===========================================================================
/// Whether the distance between `a` and `b` is at most `d`, decided **exactly**.
///
/// `true` when some point of `a` and some point of `b` lie within `d` of
/// each other, endpoints and boundaries included; `d = 0` asks whether the
/// geometries intersect. Decided exactly for every input: between boundary
/// elements by `arithmetica`'s distance predicates and the exact crossing
/// test, and by locating one vertex of each component in the other operand
/// (see the [module documentation](self) for the decomposition and its
/// proof). No distance is ever computed.
///
/// ```
/// use geometres::ops::dwithin;
/// use geometres::types::{Coord2d, Point};
///
/// let p = Point::new(Coord2d::new(0.0, 0.0))?;
/// let q = Point::new(Coord2d::new(3.0, 4.0))?;
/// assert!(dwithin(&p, &q, 5.0)?);
/// assert!(!dwithin(&p, &q, 5.0_f64.next_down())?);
/// # Ok::<(), geometres::GeometryError>(())
/// ```
///
/// An empty operand gives `false`.
///
/// # Errors
///
/// - [`GeometryError::InvalidTolerance`] for a negative or non-finite `d`.
/// - [`GeometryError::CollectionElementsOverlap`] for a collection operand
/// whose polygonal leaves overlap, as `relate` refuses it.
/// - [`GeometryError::TooManyEntries`] for more than `u32::MAX` elements on
/// an indexed side.
/// Whether some element pair of `ea` and `eb` passes its exact predicate
/// with `d`, or is a pair of properly crossing segments: by the filtered
/// scan for few pairs, through the box index for many.
/// Whether `g` is a collection.
/// Whether some connected component of `b` has a representative vertex
/// (the first vertex of each line, the first exterior vertex of each
/// polygon part, every point) not in the exterior of the areal `a`. `false`
/// when `a` is not areal: a line or a point set has no interior to hold a
/// component. Exact (`locate` on a stored coordinate).
/// The distance between `a` and `b`: **exactly `0.0` if and only if they
/// intersect**, and otherwise a positive `f64` within `max(64·u·M, 2⁻¹⁰⁷⁴)`
/// of the true distance, with `u = 2⁻⁵³` and `M` the largest coordinate
/// magnitude in either operand (the derivation, and the zero guard behind
/// the `2⁻¹⁰⁷⁴` term, are in the [module documentation](self)).
///
/// For the question "are they within `d` of each other?", use [`dwithin`],
/// which is exact. **`distance(a, b) <= d` is not that question's answer:**
/// within the bound of the true distance, the comparison can fall on either
/// side of `d`.
/// The two are consistent up to it: if `dwithin(a, b, d)` is `false` then
/// `distance(a, b) > d − 64·u·M`, and if `true` then
/// `distance(a, b) < d + 64·u·M`.
///
/// # Errors
///
/// - [`GeometryError::EmptyOperand`] when either operand has no points: the
/// distance to nothing is undefined, and 0 would read as contact.
/// - [`GeometryError::CollectionElementsOverlap`] and
/// [`GeometryError::TooManyEntries`], as for [`dwithin`].
/// A computed distance between operands the exact test has certified
/// apart: `v` itself when positive, and otherwise `2⁻¹⁰⁷⁴`, the smallest
/// positive `f64`, so a rounded `0.0` never claims contact (the zero guard
/// of the [module documentation](self)).
pub
/// `Ok(())` for a finite `d ≥ 0`.
pub
// ===========================================================================
// Elements: the boundary pieces distance is attained between
// ===========================================================================
/// One boundary element: an isolated point, or a segment of a line or ring.
pub
/// Every boundary element of `g`, in storage order: each polygon's exterior
/// then holes, ring edges in ring order; line segments in order; points.
/// Collections are walked depth first.
pub
/// The largest coordinate magnitude over the elements: the `M` of the
/// bound. An exact maximum of stored values.
pub
// ===========================================================================
// The exact pair predicate (dwithin)
// ===========================================================================
/// The sign `arithmetica` returns, with the `Err` arm written out.
///
/// The error is unreachable: every coordinate comes from a validated
/// geometry, so it is finite, and `d` has passed [`check_distance`]. As in
/// `exact::kernel::orient`, the fallback is stated rather than unwrapped;
/// `Zero` here means "exactly at distance `d`", which is within.
/// Whether two boundary elements of non-intersecting geometries are within
/// `d` of each other, decided exactly.
///
/// The decomposition's intersection test has already excluded every
/// contact, so two segments here never cross or touch and the endpoint
/// reduction (step 3) applies.
pub
/// Every pair, exhaustively.
pub
/// [`within_brute`]'s answer, with each pair first tested by box: a pair
/// whose second element's box misses the first's box grown outward by `d`
/// is skipped. That is the filter the indexed search applies (the grown
/// window rounds outward, so a pair within `d` always passes it), so the
/// answer is the same; only the exact comparisons of far pairs are not made.
pub
/// [`pair_meets`] at `d = 0`, by the orientation kernel: a distance of at
/// most 0 is a distance of exactly 0, so a point is within 0 of a point
/// exactly when they are equal and of a segment exactly when it lies on the
/// closed segment (`on_segment`); two segments meet exactly when an endpoint
/// of one lies on the other or they cross properly. The same answers as the
/// distance predicates at 0, from predicates of lower degree.
/// The box of every element, `None` for none.
/// [`pair_within`], or two segments that cross properly: the pair test of
/// the matrix-free contact (module documentation). A crossing has distance
/// 0 while all four endpoint distances can exceed `d`, which is the one
/// contact the endpoint predicates do not see.
/// Whether the closed box `(lo, hi)` meets `w`: comparisons only.
/// The same answer through the box index (module documentation): index one
/// side, query with each other-side box grown by `d`, stop at the first
/// passing pair.
pub
/// The elements' boxes as an index. More than `u32::MAX` elements is
/// [`GeometryError::TooManyEntries`].
pub
// ===========================================================================
// The grown window
// ===========================================================================
/// The box `(lo, hi)` grown outward by `r ≥ 0`: each lower bound moved to a
/// float **at or below** `lo − r`, each upper to one **at or above**
/// `hi + r`, clamped to the finite range.
///
/// `fl(lo − r)` can land above `lo − r`; one `next_down` then lands at or
/// below it, because consecutive floats bracket every real. So the returned
/// box contains the exact grown box, and a candidate filter over it can
/// only gain candidates, never lose one, which is the safe direction. The
/// clamp loses nothing: every stored coordinate is finite, so no candidate
/// box reaches past `±f64::MAX`. Crate-private; the coverage gap-width
/// check composes the same helper.
pub
// ===========================================================================
// The f64 distances (the `distance` side)
// ===========================================================================
/// `√(dx² + dy²)` with an exact power-of-two prescale, so the bound needs
/// no assumption about the platform's `hypot`.
///
/// The scaling multiplies by `2^±600` exactly and keeps the squares normal
/// (magnitudes land in about `[2^-474, 2^424]` after scaling), the squares
/// and sum cost `(1 + θ3)`, and `sqrt` is correctly rounded, so the result
/// is within relative `γ3` of the true norm. When one component is more
/// than `2^600` below the other, its scaled square may be flushed, a
/// relative effect under `2^-1000` absorbed by the same `γ3`. A
/// non-finite input gives `+∞` (an overflowing difference; module
/// documentation), never a finite wrong value.
/// The `f64` distance from `p` to the closed segment `ab`: the clamped
/// projection, then the norm (bound in the module documentation). When the
/// projection's products overflow, falls back to the nearer endpoint,
/// which errs by at most the segment's (then astronomical) length.
/// The `f64` distance between two elements of non-intersecting geometries.
pub
/// The minimum over every pair, exhaustively.
pub
/// [`distance_brute`]'s minimum, bit for bit, skipping each pair whose
/// second element's box misses the first's box grown by `(best + δ)`,
/// rounded upward: the pruning [`distance_indexed`] applies, by the same
/// argument (a skipped pair's computed value exceeds the running `best`, so
/// it cannot be the minimum). While no pair has been computed the radius is
/// infinite and nothing is skipped.
pub
/// The same minimum through the box index, pruning with the shrinking
/// radius `(best + δ)` rounded upward. A pruned pair's computed value
/// exceeds `best` (module documentation), so the result **equals**
/// [`distance_brute`]'s, bit for bit.
pub