hypercurve 0.2.0

Hyperreal-backed planar curves, contours, and regions for CAD topology
Documentation
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
//! Normalized topology events for contour-level algorithms.
//!
//! Event collection is deliberately a candidate-filtered pair scan today, not
//! a sweep-line implementation. Bounding boxes only remove pairs whose
//! disjointness is decided; every remaining candidate goes through the exact
//! segment kernels. Bentley and Ottmann, "Algorithms for Reporting and Counting
//! Geometric Intersections" (*IEEE Transactions on Computers* C-28(9),
//! 643-647, 1979), is the reference point for replacing this flat scan with an
//! output-sensitive sweep once the crate needs larger arrangements.

use hyperreal::Real;

use crate::bbox::{Aabb2, aabbs_decided_disjoint, decided_contour_aabb, decided_segment_aabb};
use crate::classify::{compare_reals, is_zero, min_real};
use crate::{
    ArcArcIntersection, Classification, Contour2, CurvePolicy, CurveResult, IntersectionKind,
    LineArcIntersection, LineArcOrder, LineLineIntersection, ParamRange, Point2, Segment2,
    SegmentIntersection, UncertaintyReason,
};

/// Which side of a contour-pair event to inspect.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ContourOperand {
    /// First contour passed to the intersection query.
    First,
    /// Second contour passed to the intersection query.
    Second,
}

/// A normalized set of contour-pair topology events.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ContourIntersectionSet {
    events: Vec<ContourIntersection>,
}

impl ContourIntersectionSet {
    /// Constructs an event set from already-normalized events.
    pub const fn new(events: Vec<ContourIntersection>) -> Self {
        Self { events }
    }

    /// Returns all events in segment-pair scan order.
    pub fn events(&self) -> &[ContourIntersection] {
        &self.events
    }

    /// Consumes the set and returns its events.
    pub fn into_events(self) -> Vec<ContourIntersection> {
        self.events
    }

    /// Returns true when no events were collected.
    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }

    /// Returns the number of collected events.
    pub fn len(&self) -> usize {
        self.events.len()
    }

    /// Returns events for one segment sorted by that segment's local parameter.
    pub fn sorted_events_for_segment<'a>(
        &'a self,
        operand: ContourOperand,
        segment_index: usize,
        policy: &CurvePolicy,
    ) -> Classification<Vec<&'a ContourIntersection>> {
        let mut sorted: Vec<(&ContourIntersection, Real)> = Vec::new();

        for event in self.events.iter() {
            if event.segment_index(operand) != Some(segment_index) {
                continue;
            }

            let order_param = match event.order_param(operand, policy) {
                Ok(order_param) => order_param,
                Err(reason) => return Classification::Uncertain(reason),
            };

            let Some(insert_at) = insertion_index(&sorted, &order_param, policy) else {
                return Classification::Uncertain(UncertaintyReason::Ordering);
            };
            // Sorted local events are the contour-level analogue of the event
            // ordering used by sweep-line clipping algorithms. We keep the
            // order proof explicit because a wrong tie-breaker here can create
            // branch vertices in the downstream boundary graph.
            sorted.insert(insert_at, (event, order_param));
        }

        Classification::Decided(sorted.into_iter().map(|(event, _)| event).collect())
    }
}

/// One normalized contour-pair topology event.
#[derive(Clone, Debug, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum ContourIntersection {
    /// A single point event.
    Point(ContourPointIntersection),
    /// A finite overlap event.
    Overlap(ContourOverlapIntersection),
    /// Segment-pair classification could not be completed.
    Uncertain(ContourUncertainIntersection),
}

impl ContourIntersection {
    /// Returns the segment index on one side of the event.
    pub const fn segment_index(&self, operand: ContourOperand) -> Option<usize> {
        match self {
            Self::Point(event) => Some(match operand {
                ContourOperand::First => event.a_segment_index,
                ContourOperand::Second => event.b_segment_index,
            }),
            Self::Overlap(event) => Some(match operand {
                ContourOperand::First => event.a_segment_index,
                ContourOperand::Second => event.b_segment_index,
            }),
            Self::Uncertain(event) => Some(match operand {
                ContourOperand::First => event.a_segment_index,
                ContourOperand::Second => event.b_segment_index,
            }),
        }
    }

    fn order_param(
        &self,
        operand: ContourOperand,
        policy: &CurvePolicy,
    ) -> Result<Real, UncertaintyReason> {
        match self {
            Self::Point(event) => Ok(match operand {
                ContourOperand::First => event.a_param.clone(),
                ContourOperand::Second => event.b_param.clone(),
            }),
            Self::Overlap(event) => {
                let range = match operand {
                    ContourOperand::First => &event.a_range,
                    ContourOperand::Second => &event.b_range,
                };
                min_real(range.start().clone(), range.end().clone(), policy)
                    .ok_or(UncertaintyReason::Ordering)
            }
            Self::Uncertain(event) => Err(event.reason),
        }
    }
}

/// A point event between two contours.
#[derive(Clone, Debug, PartialEq)]
pub struct ContourPointIntersection {
    /// Segment index in the first contour.
    pub a_segment_index: usize,
    /// Segment index in the second contour.
    pub b_segment_index: usize,
    /// Intersection point.
    pub point: Point2,
    /// Local parameter on the first contour segment.
    pub a_param: Real,
    /// Local parameter on the second contour segment.
    pub b_param: Real,
    /// Local contact kind.
    pub kind: IntersectionKind,
}

/// A finite overlap event between two contours.
#[derive(Clone, Debug, PartialEq)]
pub struct ContourOverlapIntersection {
    /// Segment index in the first contour.
    pub a_segment_index: usize,
    /// Segment index in the second contour.
    pub b_segment_index: usize,
    /// Overlap geometry.
    pub segment: Segment2,
    /// Parameter range on the first contour segment.
    pub a_range: ParamRange,
    /// Parameter range on the second contour segment.
    pub b_range: ParamRange,
}

/// An uncertain segment-pair relation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ContourUncertainIntersection {
    /// Segment index in the first contour.
    pub a_segment_index: usize,
    /// Segment index in the second contour.
    pub b_segment_index: usize,
    /// Why classification stopped.
    pub reason: UncertaintyReason,
}

pub(crate) fn intersect_contours(
    a: &Contour2,
    b: &Contour2,
    policy: &CurvePolicy,
) -> CurveResult<ContourIntersectionSet> {
    // The bounding-box broad phase is only a candidate filter. Bentley and
    // Ottmann's sweep-line algorithm uses ordering structures to reduce
    // candidate pairs asymptotically; this crate currently keeps the simpler
    // pair scan but skips pairs whose boxes are decidably disjoint.
    let a_box = decided_contour_aabb(a, policy);
    let b_box = decided_contour_aabb(b, policy);
    let a_boxes: Vec<_> = a
        .segments()
        .iter()
        .map(|segment| decided_segment_aabb(segment, policy))
        .collect();
    let b_boxes: Vec<_> = b
        .segments()
        .iter()
        .map(|segment| decided_segment_aabb(segment, policy))
        .collect();

    intersect_contours_with_cached_aabbs(
        a,
        b,
        a_box.as_ref(),
        b_box.as_ref(),
        &a_boxes,
        &b_boxes,
        policy,
    )
}

pub(crate) fn intersect_contour_self(
    contour: &Contour2,
    policy: &CurvePolicy,
) -> CurveResult<ContourIntersectionSet> {
    let segment_boxes: Vec<_> = contour
        .segments()
        .iter()
        .map(|segment| decided_segment_aabb(segment, policy))
        .collect();

    intersect_contour_self_with_cached_aabbs(contour, &segment_boxes, policy)
}

pub(crate) fn intersect_contours_with_cached_aabbs(
    a: &Contour2,
    b: &Contour2,
    a_box: Option<&Aabb2>,
    b_box: Option<&Aabb2>,
    a_segment_boxes: &[Option<Aabb2>],
    b_segment_boxes: &[Option<Aabb2>],
    policy: &CurvePolicy,
) -> CurveResult<ContourIntersectionSet> {
    if let (Some(a_box), Some(b_box)) = (a_box, b_box)
        && aabbs_decided_disjoint(a_box, b_box, policy)
    {
        return Ok(ContourIntersectionSet::new(Vec::new()));
    }

    let mut events = Vec::new();

    for (a_segment_index, a_segment) in a.segments().iter().enumerate() {
        for (b_segment_index, b_segment) in b.segments().iter().enumerate() {
            if let (Some(Some(a_box)), Some(Some(b_box))) = (
                a_segment_boxes.get(a_segment_index),
                b_segment_boxes.get(b_segment_index),
            ) && aabbs_decided_disjoint(a_box, b_box, policy)
            {
                continue;
            }

            let relation = a_segment.intersect_segment(b_segment, policy)?;
            append_segment_relation_events(
                &mut events,
                a_segment_index,
                b_segment_index,
                a_segment,
                b_segment,
                relation,
                policy,
            )?;
        }
    }

    Ok(ContourIntersectionSet::new(events))
}

pub(crate) fn intersect_contour_self_with_cached_aabbs(
    contour: &Contour2,
    segment_boxes: &[Option<Aabb2>],
    policy: &CurvePolicy,
) -> CurveResult<ContourIntersectionSet> {
    let segments = contour.segments();
    let mut events = Vec::new();

    for first_index in 0..segments.len() {
        for second_index in (first_index + 1)..segments.len() {
            if let (Some(Some(first_box)), Some(Some(second_box))) = (
                segment_boxes.get(first_index),
                segment_boxes.get(second_index),
            ) && aabbs_decided_disjoint(first_box, second_box, policy)
            {
                continue;
            }

            let relation =
                segments[first_index].intersect_segment(&segments[second_index], policy)?;
            let mut pair_events = Vec::new();
            append_segment_relation_events(
                &mut pair_events,
                first_index,
                second_index,
                &segments[first_index],
                &segments[second_index],
                relation,
                policy,
            )?;

            for event in pair_events {
                if is_contour_connectivity_event(
                    &event,
                    segments,
                    first_index,
                    second_index,
                    policy,
                ) {
                    continue;
                }
                events.push(event);
            }
        }
    }

    Ok(ContourIntersectionSet::new(events))
}

fn append_segment_relation_events(
    events: &mut Vec<ContourIntersection>,
    a_segment_index: usize,
    b_segment_index: usize,
    a_segment: &Segment2,
    b_segment: &Segment2,
    relation: SegmentIntersection,
    policy: &CurvePolicy,
) -> CurveResult<()> {
    match relation {
        SegmentIntersection::LineLine(LineLineIntersection::None) => {}
        SegmentIntersection::LineLine(LineLineIntersection::Point {
            point,
            a_param,
            b_param,
            kind,
        }) => events.push(ContourIntersection::Point(ContourPointIntersection {
            a_segment_index,
            b_segment_index,
            point,
            a_param,
            b_param,
            kind,
        })),
        SegmentIntersection::LineLine(LineLineIntersection::Overlap {
            segment,
            a_range,
            b_range,
        }) => events.push(ContourIntersection::Overlap(ContourOverlapIntersection {
            a_segment_index,
            b_segment_index,
            segment: Segment2::Line(segment),
            a_range,
            b_range,
        })),
        SegmentIntersection::LineLine(LineLineIntersection::Uncertain { reason }) => {
            append_uncertain(events, a_segment_index, b_segment_index, reason);
        }
        SegmentIntersection::LineArc { order, result } => {
            append_line_arc_events(
                events,
                a_segment_index,
                b_segment_index,
                a_segment,
                b_segment,
                order,
                result,
                policy,
            )?;
        }
        SegmentIntersection::ArcArc(ArcArcIntersection::None) => {}
        SegmentIntersection::ArcArc(ArcArcIntersection::Point(hit)) => {
            append_point_from_segments(
                events,
                a_segment_index,
                b_segment_index,
                a_segment,
                b_segment,
                hit.point,
                hit.kind,
            )?;
        }
        SegmentIntersection::ArcArc(ArcArcIntersection::TwoPoints { first, second }) => {
            append_point_from_segments(
                events,
                a_segment_index,
                b_segment_index,
                a_segment,
                b_segment,
                first.point,
                first.kind,
            )?;
            append_point_from_segments(
                events,
                a_segment_index,
                b_segment_index,
                a_segment,
                b_segment,
                second.point,
                second.kind,
            )?;
        }
        SegmentIntersection::ArcArc(ArcArcIntersection::Overlap {
            segment,
            a_range,
            b_range,
        }) => events.push(ContourIntersection::Overlap(ContourOverlapIntersection {
            a_segment_index,
            b_segment_index,
            segment: Segment2::Arc(segment),
            a_range,
            b_range,
        })),
        SegmentIntersection::ArcArc(ArcArcIntersection::Uncertain { reason }) => {
            append_uncertain(events, a_segment_index, b_segment_index, reason);
        }
    }

    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn append_line_arc_events(
    events: &mut Vec<ContourIntersection>,
    a_segment_index: usize,
    b_segment_index: usize,
    a_segment: &Segment2,
    b_segment: &Segment2,
    order: LineArcOrder,
    result: LineArcIntersection,
    policy: &CurvePolicy,
) -> CurveResult<()> {
    match result {
        LineArcIntersection::None => {}
        LineArcIntersection::Point(hit) => {
            append_line_arc_hit(
                events,
                a_segment_index,
                b_segment_index,
                a_segment,
                b_segment,
                order,
                hit,
            )?;
        }
        LineArcIntersection::TwoPoints { first, second } => {
            append_line_arc_hit(
                events,
                a_segment_index,
                b_segment_index,
                a_segment,
                b_segment,
                order,
                first,
            )?;
            append_line_arc_hit(
                events,
                a_segment_index,
                b_segment_index,
                a_segment,
                b_segment,
                order,
                second,
            )?;
        }
        LineArcIntersection::Uncertain { reason } => {
            append_uncertain(events, a_segment_index, b_segment_index, reason);
        }
    }

    let _ = policy;
    Ok(())
}

fn append_line_arc_hit(
    events: &mut Vec<ContourIntersection>,
    a_segment_index: usize,
    b_segment_index: usize,
    a_segment: &Segment2,
    b_segment: &Segment2,
    order: LineArcOrder,
    hit: crate::LineArcIntersectionPoint,
) -> CurveResult<()> {
    let point = hit.point;
    let (a_param, b_param) = match order {
        LineArcOrder::LineThenArc => {
            let arc_param = segment_chord_param(b_segment, &point)?;
            (hit.line_param, arc_param)
        }
        LineArcOrder::ArcThenLine => {
            let arc_param = segment_chord_param(a_segment, &point)?;
            (arc_param, hit.line_param)
        }
    };

    events.push(ContourIntersection::Point(ContourPointIntersection {
        a_segment_index,
        b_segment_index,
        point,
        a_param,
        b_param,
        kind: hit.kind,
    }));

    Ok(())
}

fn append_point_from_segments(
    events: &mut Vec<ContourIntersection>,
    a_segment_index: usize,
    b_segment_index: usize,
    a_segment: &Segment2,
    b_segment: &Segment2,
    point: Point2,
    kind: IntersectionKind,
) -> CurveResult<()> {
    let a_param = segment_chord_param(a_segment, &point)?;
    let b_param = segment_chord_param(b_segment, &point)?;
    events.push(ContourIntersection::Point(ContourPointIntersection {
        a_segment_index,
        b_segment_index,
        point,
        a_param,
        b_param,
        kind,
    }));
    Ok(())
}

fn append_uncertain(
    events: &mut Vec<ContourIntersection>,
    a_segment_index: usize,
    b_segment_index: usize,
    reason: UncertaintyReason,
) {
    events.push(ContourIntersection::Uncertain(
        ContourUncertainIntersection {
            a_segment_index,
            b_segment_index,
            reason,
        },
    ));
}

fn is_contour_connectivity_event(
    event: &ContourIntersection,
    segments: &[Segment2],
    first_index: usize,
    second_index: usize,
    policy: &CurvePolicy,
) -> bool {
    let Some(shared_point) = connected_contour_vertex(segments, first_index, second_index) else {
        return false;
    };

    match event {
        ContourIntersection::Point(point) => {
            points_match_for_connectivity(&point.point, shared_point, policy)
        }
        ContourIntersection::Overlap(_) | ContourIntersection::Uncertain(_) => false,
    }
}

fn connected_contour_vertex(
    segments: &[Segment2],
    first_index: usize,
    second_index: usize,
) -> Option<&Point2> {
    if first_index + 1 == second_index {
        return Some(segments[first_index].end());
    }

    if first_index == 0 && second_index + 1 == segments.len() {
        return Some(segments[first_index].start());
    }

    None
}

fn points_match_for_connectivity(point: &Point2, expected: &Point2, policy: &CurvePolicy) -> bool {
    let distance = point.distance_squared(expected);
    if is_zero(&distance, policy) == Some(true) {
        return true;
    }

    if matches!(policy.numeric_mode, crate::NumericMode::EdgePreview)
        && let (Some(distance), Some(tolerance)) = (distance.to_f64_lossy(), policy.tolerance)
    {
        let tolerance = tolerance.absolute.max(tolerance.relative);
        return distance.is_finite() && distance <= tolerance * tolerance;
    }

    false
}

fn segment_chord_param(segment: &Segment2, point: &Point2) -> CurveResult<Real> {
    let (dx, dy) = segment.end().delta_from(segment.start());
    let (px, py) = point.delta_from(segment.start());
    let numerator = (&px * &dx) + (&py * &dy);
    let denominator = (&dx * &dx) + (&dy * &dy);
    (numerator / denominator).map_err(Into::into)
}

fn insertion_index(
    sorted: &[(&ContourIntersection, Real)],
    order_param: &Real,
    policy: &CurvePolicy,
) -> Option<usize> {
    for (index, (_, existing_param)) in sorted.iter().enumerate() {
        match compare_reals(order_param, existing_param, policy)? {
            std::cmp::Ordering::Less => return Some(index),
            std::cmp::Ordering::Equal | std::cmp::Ordering::Greater => {}
        }
    }
    Some(sorted.len())
}