Skip to main content

neco_geometry/
types.rs

1use alloc::boxed::Box;
2use alloc::vec::Vec;
3use core::cmp::Ordering;
4
5use neco_algnum::{AlgnumError, RealAlgebraic};
6use neco_bigint::{BigInt, Dyadic};
7use neco_calculus::{
8    CalculusFailure, Enclosure, ExactExpressionRequirement, NecoImplementationSource, OwnerId,
9    RationalSurfacePolynomials,
10};
11use neco_geometry_foundation::{
12    ChartDefinition2, ChartDefinition3, ChartDisplayName, ChartDomainId, Point2, Point3,
13};
14
15#[derive(Debug, Eq, PartialEq)]
16pub struct ParameterInterval {
17    lower: RealAlgebraic,
18    upper: RealAlgebraic,
19    lower_closed: bool,
20    upper_closed: bool,
21}
22
23impl ParameterInterval {
24    pub fn new(
25        lower: RealAlgebraic,
26        upper: RealAlgebraic,
27        lower_closed: bool,
28        upper_closed: bool,
29    ) -> Result<Self, GeometryFailure> {
30        let ordering = lower
31            .compare(&upper)
32            .map_err(GeometryFailure::AlgebraFailure)?;
33        if ordering == Ordering::Greater {
34            return Err(GeometryFailure::ParameterOutsideDomain);
35        }
36        if ordering == Ordering::Equal && !(lower_closed && upper_closed) {
37            return Err(GeometryFailure::ParameterOutsideDomain);
38        }
39        Ok(Self {
40            lower,
41            upper,
42            lower_closed,
43            upper_closed,
44        })
45    }
46
47    pub fn contains(&self, value: &RealAlgebraic) -> Result<bool, GeometryFailure> {
48        let lower = value
49            .compare(&self.lower)
50            .map_err(GeometryFailure::AlgebraFailure)?;
51        let upper = value
52            .compare(&self.upper)
53            .map_err(GeometryFailure::AlgebraFailure)?;
54        Ok(
55            (lower == Ordering::Greater || (lower == Ordering::Equal && self.lower_closed))
56                && (upper == Ordering::Less || (upper == Ordering::Equal && self.upper_closed)),
57        )
58    }
59
60    pub fn lower(&self) -> &RealAlgebraic {
61        &self.lower
62    }
63    pub fn upper(&self) -> &RealAlgebraic {
64        &self.upper
65    }
66    pub fn lower_closed(&self) -> bool {
67        self.lower_closed
68    }
69    pub fn upper_closed(&self) -> bool {
70        self.upper_closed
71    }
72}
73
74#[derive(Debug, Eq, PartialEq)]
75pub struct SurfaceParameterDomain {
76    u: ParameterInterval,
77    v: ParameterInterval,
78}
79
80impl SurfaceParameterDomain {
81    pub fn new(u: ParameterInterval, v: ParameterInterval) -> Self {
82        Self { u, v }
83    }
84    pub fn u(&self) -> &ParameterInterval {
85        &self.u
86    }
87    pub fn v(&self) -> &ParameterInterval {
88        &self.v
89    }
90    pub fn contains(&self, u: &RealAlgebraic, v: &RealAlgebraic) -> Result<bool, GeometryFailure> {
91        Ok(self.u.contains(u)? && self.v.contains(v)?)
92    }
93}
94
95#[derive(Clone, Copy, Debug, Eq, PartialEq)]
96pub enum SurfaceOrientation {
97    Preserve,
98    Reverse,
99}
100
101#[derive(Debug, Eq, PartialEq)]
102pub struct SurfaceChartIdentity {
103    domain_id: ChartDomainId,
104    version: u64,
105}
106
107impl SurfaceChartIdentity {
108    pub fn new(domain_id: ChartDomainId, version: u64) -> Self {
109        Self { domain_id, version }
110    }
111    pub fn domain_id(&self) -> &ChartDomainId {
112        &self.domain_id
113    }
114    pub fn version(&self) -> u64 {
115        self.version
116    }
117}
118
119#[derive(Debug, Eq, PartialEq)]
120pub struct ParametricSurfaceChart2 {
121    identity: SurfaceChartIdentity,
122    display_name: ChartDisplayName,
123    orientation: SurfaceOrientation,
124    surface: RationalSurfacePolynomials,
125}
126
127impl ParametricSurfaceChart2 {
128    pub fn try_new(
129        domain_id: ChartDomainId,
130        display_name: ChartDisplayName,
131        version: u64,
132        orientation: SurfaceOrientation,
133        surface: RationalSurfacePolynomials,
134    ) -> Result<Self, GeometryFailure> {
135        if surface.denominator.terms().is_empty() {
136            return Err(GeometryFailure::InvalidSurfaceChart);
137        }
138        Ok(Self {
139            identity: SurfaceChartIdentity::new(domain_id, version),
140            display_name,
141            orientation,
142            surface,
143        })
144    }
145    pub fn identity(&self) -> &SurfaceChartIdentity {
146        &self.identity
147    }
148    pub fn display_name(&self) -> &ChartDisplayName {
149        &self.display_name
150    }
151    pub fn orientation(&self) -> SurfaceOrientation {
152        self.orientation
153    }
154    pub fn surface(&self) -> &RationalSurfacePolynomials {
155        &self.surface
156    }
157}
158
159#[derive(Debug, Eq, PartialEq)]
160pub enum CurveChart {
161    Chart2(ChartDefinition2),
162    Chart3(ChartDefinition3),
163}
164
165#[derive(Debug, Eq, PartialEq)]
166pub struct ParametricCurveDeclaration {
167    chart: CurveChart,
168    domain: ParameterInterval,
169}
170
171impl ParametricCurveDeclaration {
172    pub fn new(chart: CurveChart, domain: ParameterInterval) -> Self {
173        Self { chart, domain }
174    }
175    pub fn chart(&self) -> &CurveChart {
176        &self.chart
177    }
178    pub fn domain(&self) -> &ParameterInterval {
179        &self.domain
180    }
181}
182
183#[derive(Debug, Eq, PartialEq)]
184pub struct ParametricSurfaceDeclaration {
185    chart: ParametricSurfaceChart2,
186    domain: SurfaceParameterDomain,
187}
188
189impl ParametricSurfaceDeclaration {
190    pub fn new(chart: ParametricSurfaceChart2, domain: SurfaceParameterDomain) -> Self {
191        Self { chart, domain }
192    }
193    pub fn chart(&self) -> &ParametricSurfaceChart2 {
194        &self.chart
195    }
196    pub fn domain(&self) -> &SurfaceParameterDomain {
197        &self.domain
198    }
199}
200
201#[derive(Clone, Copy, Debug, Eq, PartialEq)]
202pub enum TrimLoopRole {
203    Outer,
204    Hole,
205}
206
207#[derive(Debug, Eq, PartialEq)]
208pub struct SurfaceParameterPoint {
209    u: RealAlgebraic,
210    v: RealAlgebraic,
211}
212
213impl SurfaceParameterPoint {
214    pub fn new(u: RealAlgebraic, v: RealAlgebraic) -> Self {
215        Self { u, v }
216    }
217    pub fn u(&self) -> &RealAlgebraic {
218        &self.u
219    }
220    pub fn v(&self) -> &RealAlgebraic {
221        &self.v
222    }
223}
224
225#[derive(Debug, Eq, PartialEq)]
226pub struct SurfaceTrimLoop2 {
227    role: TrimLoopRole,
228    vertices: Vec<SurfaceParameterPoint>,
229}
230
231impl SurfaceTrimLoop2 {
232    pub fn try_new(
233        role: TrimLoopRole,
234        vertices: Vec<SurfaceParameterPoint>,
235        domain: &SurfaceParameterDomain,
236    ) -> Result<Self, GeometryFailure> {
237        if vertices.len() < 3 {
238            return Err(GeometryFailure::SelfIntersectingTrimLoop);
239        }
240        for vertex in &vertices {
241            if !domain.contains(vertex.u(), vertex.v())? {
242                return Err(GeometryFailure::PCurveOutsideDomain);
243            }
244        }
245        if loop_self_intersects(&vertices)? {
246            return Err(GeometryFailure::SelfIntersectingTrimLoop);
247        }
248        Ok(Self { role, vertices })
249    }
250    pub fn role(&self) -> TrimLoopRole {
251        self.role
252    }
253    pub fn vertices(&self) -> &[SurfaceParameterPoint] {
254        &self.vertices
255    }
256}
257
258#[derive(Debug, Eq, PartialEq)]
259pub struct PairedSurfaceSeam {
260    first: SeamEnd,
261    second: SeamEnd,
262}
263
264#[derive(Debug, Eq, PartialEq)]
265pub struct SeamEnd {
266    identity: SurfaceChartIdentity,
267    parameter: SurfaceParameterPoint,
268    orientation: SurfaceOrientation,
269}
270
271impl SeamEnd {
272    pub fn new(
273        identity: SurfaceChartIdentity,
274        parameter: SurfaceParameterPoint,
275        orientation: SurfaceOrientation,
276    ) -> Self {
277        Self {
278            identity,
279            parameter,
280            orientation,
281        }
282    }
283    pub fn identity(&self) -> &SurfaceChartIdentity {
284        &self.identity
285    }
286    pub fn parameter(&self) -> &SurfaceParameterPoint {
287        &self.parameter
288    }
289    pub fn orientation(&self) -> SurfaceOrientation {
290        self.orientation
291    }
292}
293
294impl PairedSurfaceSeam {
295    pub fn new(first: SeamEnd, second: SeamEnd) -> Self {
296        Self { first, second }
297    }
298    pub fn first(&self) -> &SeamEnd {
299        &self.first
300    }
301    pub fn second(&self) -> &SeamEnd {
302        &self.second
303    }
304}
305
306#[derive(Clone, Copy, Debug, Eq, PartialEq)]
307pub enum TrimClassification {
308    Outer,
309    Hole,
310    TrimExterior,
311    TrimBoundary,
312}
313
314#[derive(Debug, Eq, PartialEq)]
315pub enum SeamContact {
316    Paired(PairedSurfaceSeam),
317    Undetermined { first: SeamEnd, second: SeamEnd },
318}
319
320#[derive(Debug, Eq, PartialEq)]
321pub struct TrimmedSurfaceDeclaration {
322    chart: ParametricSurfaceChart2,
323    domain: SurfaceParameterDomain,
324    outer: SurfaceTrimLoop2,
325    holes: Vec<SurfaceTrimLoop2>,
326    seams: Vec<SeamContact>,
327}
328
329impl TrimmedSurfaceDeclaration {
330    pub fn try_new(
331        chart: ParametricSurfaceChart2,
332        domain: SurfaceParameterDomain,
333        mut outer: SurfaceTrimLoop2,
334        mut holes: Vec<SurfaceTrimLoop2>,
335        seams: Vec<PairedSurfaceSeam>,
336    ) -> Result<Self, GeometryFailure> {
337        if outer.role != TrimLoopRole::Outer {
338            return Err(GeometryFailure::SelfIntersectingTrimLoop);
339        }
340        for hole in &holes {
341            if hole.role != TrimLoopRole::Hole {
342                return Err(GeometryFailure::SelfIntersectingTrimLoop);
343            }
344            if loops_intersect(&outer.vertices, &hole.vertices)? {
345                return Err(GeometryFailure::HoleIntersectsOuterLoop);
346            }
347        }
348        canonicalize_loop(&mut outer.vertices)?;
349        for hole in &mut holes {
350            canonicalize_loop(&mut hole.vertices)?;
351        }
352        holes.sort_by(|left, right| compare_loop_keys(&left.vertices, &right.vertices));
353        let mut seams = seams
354            .into_iter()
355            .map(|seam| classify_seam(&chart.identity, canonicalize_seam(seam)))
356            .collect::<Vec<_>>();
357        seams.sort_by(compare_seam_contacts);
358        Ok(Self {
359            chart,
360            domain,
361            outer,
362            holes,
363            seams,
364        })
365    }
366    pub fn chart(&self) -> &ParametricSurfaceChart2 {
367        &self.chart
368    }
369    pub fn domain(&self) -> &SurfaceParameterDomain {
370        &self.domain
371    }
372    pub fn outer(&self) -> &SurfaceTrimLoop2 {
373        &self.outer
374    }
375    pub fn holes(&self) -> &[SurfaceTrimLoop2] {
376        &self.holes
377    }
378    pub fn seams(&self) -> &[SeamContact] {
379        &self.seams
380    }
381    pub fn classify(
382        &self,
383        u: &RealAlgebraic,
384        v: &RealAlgebraic,
385    ) -> Result<TrimClassification, GeometryFailure> {
386        if !self.domain.contains(u, v)? {
387            return Err(GeometryFailure::ParameterOutsideDomain);
388        }
389        if point_on_loop(u, v, &self.outer.vertices)? {
390            return Ok(TrimClassification::TrimBoundary);
391        }
392        for hole in &self.holes {
393            if point_on_loop(u, v, &hole.vertices)? {
394                return Ok(TrimClassification::TrimBoundary);
395            }
396        }
397        let inside_outer = point_in_loop(u, v, &self.outer.vertices)?;
398        if !inside_outer {
399            return Ok(TrimClassification::TrimExterior);
400        }
401        for hole in &self.holes {
402            if point_in_loop(u, v, &hole.vertices)? {
403                return Ok(TrimClassification::Hole);
404            }
405        }
406        Ok(TrimClassification::Outer)
407    }
408}
409
410#[derive(Debug, Eq, PartialEq)]
411pub enum SurfaceEvaluationWitness {
412    Exact {
413        identity: SurfaceChartIdentity,
414        point: Point3,
415    },
416    Certified {
417        identity: SurfaceChartIdentity,
418        x: Enclosure,
419        y: Enclosure,
420        z: Box<Enclosure>,
421        owner: OwnerId,
422        requirement: ExactExpressionRequirement,
423        source: NecoImplementationSource,
424    },
425}
426
427#[derive(Debug, Eq, PartialEq)]
428pub struct SurfaceCrossingCandidate {
429    declaration: TrimmedSurfaceDeclaration,
430}
431
432impl SurfaceCrossingCandidate {
433    pub fn new(declaration: TrimmedSurfaceDeclaration) -> Self {
434        Self { declaration }
435    }
436    pub fn identity(&self) -> &SurfaceChartIdentity {
437        self.declaration.chart.identity()
438    }
439    pub fn domain(&self) -> &SurfaceParameterDomain {
440        self.declaration.domain()
441    }
442    pub fn orientation(&self) -> SurfaceOrientation {
443        self.declaration.chart.orientation()
444    }
445    pub fn declaration(&self) -> &TrimmedSurfaceDeclaration {
446        &self.declaration
447    }
448    pub fn classify(
449        &self,
450        u: &RealAlgebraic,
451        v: &RealAlgebraic,
452    ) -> Result<TrimClassification, GeometryFailure> {
453        self.declaration.classify(u, v)
454    }
455}
456
457fn classify_seam(chart_identity: &SurfaceChartIdentity, seam: PairedSurfaceSeam) -> SeamContact {
458    if identities_match(chart_identity, seam.first.identity())
459        && identities_match(chart_identity, seam.second.identity())
460    {
461        SeamContact::Paired(seam)
462    } else {
463        SeamContact::Undetermined {
464            first: seam.first,
465            second: seam.second,
466        }
467    }
468}
469
470fn identities_match(left: &SurfaceChartIdentity, right: &SurfaceChartIdentity) -> bool {
471    left.domain_id().as_str() == right.domain_id().as_str() && left.version() == right.version()
472}
473
474fn canonicalize_loop(vertices: &mut [SurfaceParameterPoint]) -> Result<(), GeometryFailure> {
475    rotate_loop_to_minimum(vertices);
476    if loop_is_clockwise(vertices)? {
477        vertices[1..].reverse();
478    }
479    Ok(())
480}
481
482fn rotate_loop_to_minimum(vertices: &mut [SurfaceParameterPoint]) {
483    let mut minimum = 0;
484    for index in 1..vertices.len() {
485        if compare_points(&vertices[index], &vertices[minimum]) == Ordering::Less {
486            minimum = index;
487        }
488    }
489    vertices.rotate_left(minimum);
490}
491
492fn loop_is_clockwise(vertices: &[SurfaceParameterPoint]) -> Result<bool, GeometryFailure> {
493    let zero = RealAlgebraic::from_integer(neco_bigint::BigInt::zero())?;
494    let mut twice_area = zero.try_clone()?;
495    for index in 0..vertices.len() {
496        let current = &vertices[index];
497        let next = &vertices[(index + 1) % vertices.len()];
498        let term = current
499            .u()
500            .mul(next.v())?
501            .sub(&next.u().mul(current.v())?)?;
502        twice_area = twice_area.add(&term)?;
503    }
504    Ok(twice_area.compare(&zero)? == Ordering::Less)
505}
506
507fn canonicalize_seam(seam: PairedSurfaceSeam) -> PairedSurfaceSeam {
508    if compare_seam_ends(seam.first(), seam.second()) == Ordering::Greater {
509        PairedSurfaceSeam::new(seam.second, seam.first)
510    } else {
511        seam
512    }
513}
514
515fn compare_seam_contacts(left: &SeamContact, right: &SeamContact) -> Ordering {
516    match (left, right) {
517        (SeamContact::Paired(left), SeamContact::Paired(right)) => compare_seams(left, right),
518        (
519            SeamContact::Undetermined {
520                first: left_first,
521                second: left_second,
522            },
523            SeamContact::Undetermined {
524                first: right_first,
525                second: right_second,
526            },
527        ) => compare_seam_ends(left_first, right_first)
528            .then(compare_seam_ends(left_second, right_second)),
529        (SeamContact::Paired(_), SeamContact::Undetermined { .. }) => Ordering::Less,
530        (SeamContact::Undetermined { .. }, SeamContact::Paired(_)) => Ordering::Greater,
531    }
532}
533
534fn compare_seams(left: &PairedSurfaceSeam, right: &PairedSurfaceSeam) -> Ordering {
535    compare_seam_ends(left.first(), right.first())
536        .then(compare_seam_ends(left.second(), right.second()))
537}
538
539fn compare_seam_ends(left: &SeamEnd, right: &SeamEnd) -> Ordering {
540    left.identity()
541        .domain_id()
542        .as_str()
543        .cmp(right.identity().domain_id().as_str())
544        .then(left.identity().version().cmp(&right.identity().version()))
545        .then(compare_points(left.parameter(), right.parameter()))
546        .then(orientation_order(left.orientation()).cmp(&orientation_order(right.orientation())))
547}
548
549fn orientation_order(orientation: SurfaceOrientation) -> u8 {
550    match orientation {
551        SurfaceOrientation::Preserve => 0,
552        SurfaceOrientation::Reverse => 1,
553    }
554}
555
556fn compare_loop_keys(left: &[SurfaceParameterPoint], right: &[SurfaceParameterPoint]) -> Ordering {
557    match (left.first(), right.first()) {
558        (Some(first), Some(second)) => compare_points(first, second),
559        (None, Some(_)) => Ordering::Less,
560        (Some(_), None) => Ordering::Greater,
561        (None, None) => Ordering::Equal,
562    }
563}
564
565fn compare_points(left: &SurfaceParameterPoint, right: &SurfaceParameterPoint) -> Ordering {
566    match left.u().compare(right.u()) {
567        Ok(Ordering::Equal) => left.v().compare(right.v()).unwrap_or(Ordering::Equal),
568        Ok(ordering) => ordering,
569        Err(_) => Ordering::Equal,
570    }
571}
572
573fn loop_self_intersects(vertices: &[SurfaceParameterPoint]) -> Result<bool, GeometryFailure> {
574    let count = vertices.len();
575    for first in 0..count {
576        let first_end = (first + 1) % count;
577        for second in (first + 1)..count {
578            let second_end = (second + 1) % count;
579            if first == second
580                || first_end == second
581                || second_end == first
582                || (first == 0 && second_end == 0)
583            {
584                continue;
585            }
586            if segments_intersect(
587                &vertices[first],
588                &vertices[first_end],
589                &vertices[second],
590                &vertices[second_end],
591            )? {
592                return Ok(true);
593            }
594        }
595    }
596    Ok(false)
597}
598
599fn loops_intersect(
600    left: &[SurfaceParameterPoint],
601    right: &[SurfaceParameterPoint],
602) -> Result<bool, GeometryFailure> {
603    for first in 0..left.len() {
604        let first_end = (first + 1) % left.len();
605        for second in 0..right.len() {
606            let second_end = (second + 1) % right.len();
607            if segments_intersect(
608                &left[first],
609                &left[first_end],
610                &right[second],
611                &right[second_end],
612            )? {
613                return Ok(true);
614            }
615        }
616    }
617    Ok(false)
618}
619
620pub(crate) fn point_on_loop(
621    u: &RealAlgebraic,
622    v: &RealAlgebraic,
623    vertices: &[SurfaceParameterPoint],
624) -> Result<bool, GeometryFailure> {
625    let point = SurfaceParameterPoint::new(u.try_clone()?, v.try_clone()?);
626    for index in 0..vertices.len() {
627        let next = (index + 1) % vertices.len();
628        if point_on_segment(&point, &vertices[index], &vertices[next])? {
629            return Ok(true);
630        }
631    }
632    Ok(false)
633}
634
635fn point_in_loop(
636    u: &RealAlgebraic,
637    v: &RealAlgebraic,
638    vertices: &[SurfaceParameterPoint],
639) -> Result<bool, GeometryFailure> {
640    let mut winding = 0_i32;
641    for index in 0..vertices.len() {
642        let current = &vertices[index];
643        let next = &vertices[(index + 1) % vertices.len()];
644        let current_v = current.v().compare(v)?;
645        let next_v = next.v().compare(v)?;
646        if current_v == Ordering::Greater
647            && next_v != Ordering::Greater
648            && is_left(u, v, current, next)? == Ordering::Greater
649        {
650            winding += 1;
651        } else if current_v != Ordering::Greater
652            && next_v == Ordering::Greater
653            && is_left(u, v, current, next)? == Ordering::Less
654        {
655            winding -= 1;
656        }
657    }
658    Ok(winding != 0)
659}
660
661fn is_left(
662    u: &RealAlgebraic,
663    v: &RealAlgebraic,
664    start: &SurfaceParameterPoint,
665    end: &SurfaceParameterPoint,
666) -> Result<Ordering, GeometryFailure> {
667    let dx = end.u().sub(start.u())?;
668    let dy = end.v().sub(start.v())?;
669    let px = u.sub(start.u())?;
670    let py = v.sub(start.v())?;
671    Ok(dx
672        .mul(&py)?
673        .sub(&dy.mul(&px)?)?
674        .compare(&RealAlgebraic::from_integer(neco_bigint::BigInt::zero())?)?)
675}
676
677fn segments_intersect(
678    a: &SurfaceParameterPoint,
679    b: &SurfaceParameterPoint,
680    c: &SurfaceParameterPoint,
681    d: &SurfaceParameterPoint,
682) -> Result<bool, GeometryFailure> {
683    let abc = is_left(c.u(), c.v(), a, b)?;
684    let abd = is_left(d.u(), d.v(), a, b)?;
685    let cda = is_left(a.u(), a.v(), c, d)?;
686    let cdb = is_left(b.u(), b.v(), c, d)?;
687    Ok(abc != abd && cda != cdb)
688}
689
690fn point_on_segment(
691    point: &SurfaceParameterPoint,
692    start: &SurfaceParameterPoint,
693    end: &SurfaceParameterPoint,
694) -> Result<bool, GeometryFailure> {
695    if is_left(point.u(), point.v(), start, end)? != Ordering::Equal {
696        return Ok(false);
697    }
698    let min_u = if start.u().compare(end.u())? == Ordering::Less {
699        start.u()
700    } else {
701        end.u()
702    };
703    let max_u = if start.u().compare(end.u())? == Ordering::Greater {
704        start.u()
705    } else {
706        end.u()
707    };
708    let min_v = if start.v().compare(end.v())? == Ordering::Less {
709        start.v()
710    } else {
711        end.v()
712    };
713    let max_v = if start.v().compare(end.v())? == Ordering::Greater {
714        start.v()
715    } else {
716        end.v()
717    };
718    Ok(point.u().compare(min_u)? != Ordering::Less
719        && point.u().compare(max_u)? != Ordering::Greater
720        && point.v().compare(min_v)? != Ordering::Less
721        && point.v().compare(max_v)? != Ordering::Greater)
722}
723
724#[derive(Debug, Eq, PartialEq)]
725pub struct PolynomialTerm3 {
726    coefficient: RealAlgebraic,
727    exponent_x: u32,
728    exponent_y: u32,
729    exponent_z: u32,
730}
731
732impl PolynomialTerm3 {
733    pub fn new(
734        coefficient: RealAlgebraic,
735        exponent_x: u32,
736        exponent_y: u32,
737        exponent_z: u32,
738    ) -> Result<Self, GeometryFailure> {
739        if coefficient.is_zero() {
740            return Err(GeometryFailure::EvaluationIndeterminacy {
741                family: ShapeFamily::ImplicitSurface,
742                reason: ShapeEvaluationIndeterminacy::DomainValidity,
743            });
744        }
745        Ok(Self {
746            coefficient,
747            exponent_x,
748            exponent_y,
749            exponent_z,
750        })
751    }
752    pub fn coefficient(&self) -> &RealAlgebraic {
753        &self.coefficient
754    }
755    pub fn exponent_x(&self) -> u32 {
756        self.exponent_x
757    }
758    pub fn exponent_y(&self) -> u32 {
759        self.exponent_y
760    }
761    pub fn exponent_z(&self) -> u32 {
762        self.exponent_z
763    }
764}
765
766#[derive(Debug, Eq, PartialEq)]
767pub struct MultivariatePolynomial3 {
768    terms: Vec<PolynomialTerm3>,
769}
770
771impl MultivariatePolynomial3 {
772    pub fn try_from_terms(mut terms: Vec<PolynomialTerm3>) -> Result<Self, GeometryFailure> {
773        terms.sort_unstable_by_key(|term| (term.exponent_x, term.exponent_y, term.exponent_z));
774        if terms.windows(2).any(|pair| {
775            (pair[0].exponent_x, pair[0].exponent_y, pair[0].exponent_z)
776                == (pair[1].exponent_x, pair[1].exponent_y, pair[1].exponent_z)
777        }) {
778            return Err(GeometryFailure::EvaluationIndeterminacy {
779                family: ShapeFamily::ImplicitSurface,
780                reason: ShapeEvaluationIndeterminacy::DomainValidity,
781            });
782        }
783        Ok(Self { terms })
784    }
785    pub fn zero() -> Self {
786        Self { terms: Vec::new() }
787    }
788    pub fn terms(&self) -> &[PolynomialTerm3] {
789        &self.terms
790    }
791}
792
793#[derive(Debug, Eq, PartialEq)]
794pub struct ImplicitSurfaceDeclaration {
795    equation: MultivariatePolynomial3,
796}
797impl ImplicitSurfaceDeclaration {
798    pub fn new(equation: MultivariatePolynomial3) -> Self {
799        Self { equation }
800    }
801    pub fn equation(&self) -> &MultivariatePolynomial3 {
802        &self.equation
803    }
804}
805
806#[derive(Debug, Eq, PartialEq)]
807pub enum ShapeDeclaration {
808    ParametricCurve(ParametricCurveDeclaration),
809    ParametricSurface(ParametricSurfaceDeclaration),
810    ImplicitSurface(ImplicitSurfaceDeclaration),
811}
812
813impl ShapeDeclaration {
814    pub fn family(&self) -> ShapeFamily {
815        match self {
816            Self::ParametricCurve(_) => ShapeFamily::ParametricCurve,
817            Self::ParametricSurface(_) => ShapeFamily::ParametricSurface,
818            Self::ImplicitSurface(_) => ShapeFamily::ImplicitSurface,
819        }
820    }
821}
822
823#[derive(Clone, Copy, Debug, Eq, PartialEq)]
824pub enum ShapeFamily {
825    ParametricCurve,
826    ParametricSurface,
827    ImplicitSurface,
828}
829
830#[derive(Debug, Eq, PartialEq)]
831pub enum ShapeEvaluationInput {
832    ParametricCurve { parameter: RealAlgebraic },
833    ParametricSurface { u: RealAlgebraic, v: RealAlgebraic },
834    ImplicitSurface { point: Point3 },
835}
836
837impl ShapeEvaluationInput {
838    pub fn family(&self) -> ShapeFamily {
839        match self {
840            Self::ParametricCurve { .. } => ShapeFamily::ParametricCurve,
841            Self::ParametricSurface { .. } => ShapeFamily::ParametricSurface,
842            Self::ImplicitSurface { .. } => ShapeFamily::ImplicitSurface,
843        }
844    }
845}
846
847#[derive(Debug, Eq, PartialEq)]
848pub struct ShapeEvaluationRequest {
849    declaration: ShapeDeclaration,
850    input: ShapeEvaluationInput,
851}
852impl ShapeEvaluationRequest {
853    pub fn new(declaration: ShapeDeclaration, input: ShapeEvaluationInput) -> Self {
854        Self { declaration, input }
855    }
856    pub fn declaration(&self) -> &ShapeDeclaration {
857        &self.declaration
858    }
859    pub fn input(&self) -> &ShapeEvaluationInput {
860        &self.input
861    }
862}
863
864#[derive(Debug, Eq, PartialEq)]
865pub enum ShapeCoordinate {
866    Planar(Point2),
867    Spatial(Point3),
868}
869#[derive(Debug, Eq, PartialEq)]
870pub struct CoordinateEnclosure2 {
871    pub x: Enclosure,
872    pub y: Enclosure,
873}
874#[derive(Debug, Eq, PartialEq)]
875pub struct CoordinateEnclosure3 {
876    pub x: Enclosure,
877    pub y: Enclosure,
878    pub z: Enclosure,
879}
880#[derive(Debug, Eq, PartialEq)]
881pub enum ShapeCoordinateEnclosure {
882    Planar(CoordinateEnclosure2),
883    Spatial(Box<CoordinateEnclosure3>),
884}
885
886#[derive(Debug, Eq, PartialEq)]
887pub enum ExactShapeEvaluation {
888    ParametricCurve { coordinate: ShapeCoordinate },
889    ParametricSurface { coordinate: Point3 },
890    ImplicitSurface { scalar: RealAlgebraic },
891}
892
893#[derive(Debug, Eq, PartialEq)]
894pub enum CertifiedShapeEvaluation {
895    ParametricCurve {
896        coordinate: ShapeCoordinateEnclosure,
897        owner: OwnerId,
898        requirement: ExactExpressionRequirement,
899        source: NecoImplementationSource,
900    },
901    ParametricSurface {
902        coordinate: Box<CoordinateEnclosure3>,
903        owner: OwnerId,
904        requirement: ExactExpressionRequirement,
905        source: NecoImplementationSource,
906    },
907    ImplicitSurface {
908        scalar: Enclosure,
909        owner: OwnerId,
910        requirement: ExactExpressionRequirement,
911        source: NecoImplementationSource,
912    },
913}
914
915#[derive(Clone, Copy, Debug, Eq, PartialEq)]
916pub enum ShapeEvaluationIndeterminacy {
917    DomainValidity,
918    CalculusResult,
919}
920
921#[derive(Debug, Eq, PartialEq)]
922pub enum ShapeEvaluation {
923    Exact(ExactShapeEvaluation),
924    CertifiedEnclosure(CertifiedShapeEvaluation),
925    Undetermined { family: ShapeFamily },
926}
927
928#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
929pub struct PositiveRayParameterRange;
930
931impl PositiveRayParameterRange {
932    pub const fn new() -> Self {
933        Self
934    }
935
936    pub fn contains_exact(&self, value: &RealAlgebraic) -> Result<bool, GeometryFailure> {
937        Ok(!value.is_zero()
938            && value.compare(&RealAlgebraic::from_integer(BigInt::zero())?)? == Ordering::Greater)
939    }
940
941    pub fn contains_checked(&self, value: f64) -> Result<bool, GeometryFailure> {
942        Ok(value.is_finite() && value > 0.0)
943    }
944}
945
946#[derive(Debug, Eq, PartialEq)]
947pub struct Ray2ParameterRange {
948    lower: Dyadic,
949    upper: Dyadic,
950}
951
952impl Ray2ParameterRange {
953    pub fn new(lower: Dyadic, upper: Dyadic) -> Result<Self, GeometryFailure> {
954        if lower.integer().sign() == neco_bigint::Sign::Negative || upper < lower {
955            return Err(GeometryFailure::InvalidRayParameterRange);
956        }
957        Ok(Self { lower, upper })
958    }
959
960    pub fn lower(&self) -> &Dyadic {
961        &self.lower
962    }
963
964    pub fn upper(&self) -> &Dyadic {
965        &self.upper
966    }
967}
968
969#[derive(Debug, PartialEq)]
970pub struct CheckedRay2ParameterRange {
971    lower: f64,
972    upper: f64,
973}
974
975impl CheckedRay2ParameterRange {
976    pub fn new(lower: f64, upper: f64) -> Result<Self, GeometryFailure> {
977        if !lower.is_finite() || !upper.is_finite() || lower < 0.0 || upper < lower {
978            return Err(GeometryFailure::InvalidRayParameterRange);
979        }
980        Ok(Self { lower, upper })
981    }
982
983    pub fn lower(&self) -> f64 {
984        self.lower
985    }
986
987    pub fn upper(&self) -> f64 {
988        self.upper
989    }
990}
991
992#[derive(Debug, Eq, PartialEq)]
993pub enum ExactRayEvaluation2 {
994    Point(Point2),
995}
996#[derive(Debug, Eq, PartialEq)]
997pub enum ExactRayEvaluation3 {
998    Point(Point3),
999}
1000#[derive(Debug, PartialEq)]
1001pub enum CheckedRayEvaluation2 {
1002    Candidate([f64; 2]),
1003    Undetermined,
1004}
1005#[derive(Debug, PartialEq)]
1006pub enum CheckedRayEvaluation3 {
1007    Candidate([f64; 3]),
1008    Undetermined,
1009}
1010
1011#[derive(Debug, Eq, PartialEq)]
1012pub enum GeometryFailure {
1013    FoundationFailure {
1014        error: neco_geometry_foundation::GeometryFailure,
1015    },
1016    ZeroDirection,
1017    NonOrthogonalMatrix,
1018    NonUnitQuaternion,
1019    AlgebraFailure(AlgnumError),
1020    ShapeFamilyMismatch,
1021    ParameterOutsideDomain,
1022    InvalidRayParameterRange,
1023    DenominatorValidity {
1024        error: CalculusFailure,
1025    },
1026    CalculusFailure {
1027        error: CalculusFailure,
1028    },
1029    EvaluationIndeterminacy {
1030        family: ShapeFamily,
1031        reason: ShapeEvaluationIndeterminacy,
1032    },
1033    DuplicateRegionAtom,
1034    DuplicateRegionCanonicalKey,
1035    RegionCanonicalAtomLimit {
1036        requested_atoms: usize,
1037        maximum_atoms: usize,
1038    },
1039    RegionPolynomialTermLimit {
1040        requested_terms: usize,
1041        maximum_terms: usize,
1042    },
1043    RegionExponentOverflow,
1044    RegionExponentOperationLimit {
1045        requested_operations: usize,
1046        maximum_operations: usize,
1047    },
1048    InvalidRegionAffineMap,
1049    MalformedRegionFormula,
1050    RegionAmbientDimensionMismatch,
1051    RegionKindMismatch,
1052    RegionPointDimensionMismatch,
1053    RootIsolationPolicyInvalid,
1054    RootIsolationResourceLimit {
1055        requested_depth: usize,
1056        maximum_depth: usize,
1057    },
1058    RootPartitionCellLimit {
1059        requested_cells: usize,
1060        maximum_cells: usize,
1061    },
1062    RootPartitionIdentifierOverflow {
1063        current_identifier: usize,
1064        increment: usize,
1065    },
1066    BoundaryResourceLimit {
1067        resource: BoundaryResource,
1068        requested: usize,
1069        maximum: usize,
1070    },
1071    EmptyFinitePointComponents,
1072    EmptyCurveBranchComponents,
1073    DuplicateIntersectionComponentIdentity,
1074    ComponentIdentityEvidenceMismatch,
1075    ComponentIdentityCanonicalizationFailure,
1076    InvalidSurfaceChart,
1077    SelfIntersectingTrimLoop,
1078    HoleIntersectsOuterLoop,
1079    PCurveOutsideDomain,
1080    EmptyRayCrossingTargetSet,
1081    DuplicateRayCrossingTargetIdentity,
1082    MixedRayCrossingTargetFamily,
1083    DegenerateTriangle,
1084    InvalidRayCrossingPolicy,
1085    RayCrossingTargetLimitExceeded,
1086    RayCrossingHitLimitExceeded,
1087}
1088
1089#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1090pub enum BoundaryResource {
1091    CandidateLoci,
1092    CandidateParameters,
1093    SideSamples,
1094    Intersections,
1095}
1096
1097impl From<AlgnumError> for GeometryFailure {
1098    fn from(error: AlgnumError) -> Self {
1099        Self::AlgebraFailure(error)
1100    }
1101}
1102
1103impl From<neco_geometry_foundation::GeometryFailure> for GeometryFailure {
1104    fn from(error: neco_geometry_foundation::GeometryFailure) -> Self {
1105        Self::FoundationFailure { error }
1106    }
1107}