Skip to main content

ifc_geometry/curve/
trimmed.rs

1//! `IfcTrimmedCurve`: the single most misread entity in IFC geometry.
2//!
3//! # What the file gives you
4//!
5//! A basis curve, two trims, a sense flag and a preference. Each trim is a
6//! `SET [1:2] OF IfcTrimmingSelect`, and `IfcTrimmingSelect` is a select over
7//! `IfcCartesianPoint` and `IfcParameterValue`. So a single trim may carry a
8//! point, a parameter, or **both**, and when both are present they can
9//! disagree -- exporters round the parameter or snap the point. That is what
10//! `MasterRepresentation` is for: it names which of the two is authoritative.
11//!
12//! # The four-arc problem
13//!
14//! When the basis curve is closed (`IfcCircle`, `IfcEllipse`), one basis curve
15//! plus one pair of trim points defines **four** different arcs. Two come from
16//! which trim is start and which is end; each of those doubles depending on
17//! `SenseAgreement`, because on a closed curve you can reach the same end
18//! point going either way round. The spec says so explicitly and notes that
19//! informal proposition IP3 (sense implies parameter 1 < parameter 2) does
20//! *not* apply to closed basis curves.
21//!
22//! This module therefore refuses to collapse the four into one. [`TrimSpec`]
23//! keeps `Trim1`, `Trim2` and `SenseAgreement` as three independent facts, and
24//! nothing here reorders trims to make parameters ascending. A kernel that
25//! sorts them will silently draw the complementary arc -- 350 degrees where 10
26//! were meant -- and the model will look plausible while being wrong.
27//!
28//! # Parameter units
29//!
30//! `IfcParameterValue` on a conic basis curve is an *angle* in the model's
31//! declared plane-angle unit, so a file in degrees writes `90.` where a file in
32//! radians writes `1.5707963`. This view returns the number as written;
33//! converting requires the unit context and belongs to [`crate::units`].
34
35use crate::error::GeometryResult;
36use crate::resource::point::CartesianPoint;
37use crate::resource::resolve;
38use crate::slots::Slots;
39use ifc_model::{Entity, EntityId, Model, Value};
40
41/// `IfcTrimmedCurve` attribute slots.
42///
43/// From IFC4 ADD2 TC1: `IfcBoundedCurve` and above declare no explicit
44/// attributes, so all five slots belong to `IfcTrimmedCurve` itself.
45pub(crate) mod slot {
46    /// `BasisCurve`: the `IfcCurve` being trimmed.
47    pub const BASIS_CURVE: usize = 0;
48    /// `Trim1`: `SET [1:2] OF IfcTrimmingSelect`.
49    pub const TRIM_1: usize = 1;
50    /// `Trim2`: `SET [1:2] OF IfcTrimmingSelect`.
51    pub const TRIM_2: usize = 2;
52    /// `SenseAgreement`: `IfcBoolean`.
53    pub const SENSE_AGREEMENT: usize = 3;
54    /// `MasterRepresentation`: `IfcTrimmingPreference`.
55    pub const MASTER_REPRESENTATION: usize = 4;
56}
57
58/// `IfcTrimmingPreference`: which trim representation is authoritative.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum TrimmingPreference {
61    /// The `IfcCartesianPoint` wins where both are supplied.
62    Cartesian,
63    /// The `IfcParameterValue` wins where both are supplied.
64    Parameter,
65    /// Neither is preferred; the consumer must choose.
66    ///
67    /// Common in exported files even when both forms are present, which is
68    /// exactly when a choice is needed. Treat it as "use what you have, prefer
69    /// the parameter for a conic" rather than as an error.
70    Unspecified,
71}
72
73impl TrimmingPreference {
74    /// Parse the enumeration token, e.g. `CARTESIAN`.
75    ///
76    /// Returns `None` for an unrecognised token rather than defaulting, so a
77    /// caller can tell a typo in the file from an honest `.UNSPECIFIED.`.
78    pub fn from_token(token: &str) -> Option<Self> {
79        match token.to_ascii_uppercase().as_str() {
80            "CARTESIAN" => Some(Self::Cartesian),
81            "PARAMETER" => Some(Self::Parameter),
82            "UNSPECIFIED" => Some(Self::Unspecified),
83            _ => None,
84        }
85    }
86
87    /// The EXPRESS token, the inverse of [`Self::from_token`].
88    ///
89    /// Kept beside the parser so the two cannot drift: a token added to
90    /// one without the other stops compiling here.
91    pub fn token(self) -> &'static str {
92        match self {
93            Self::Cartesian => "CARTESIAN",
94            Self::Parameter => "PARAMETER",
95            Self::Unspecified => "UNSPECIFIED",
96        }
97    }
98}
99
100/// One member of an `IfcTrimmingSelect` set.
101#[derive(Debug, Clone, Copy, PartialEq)]
102pub enum TrimPoint {
103    /// An `IfcCartesianPoint` reference giving a position on the basis curve.
104    ///
105    /// Kept as a reference so the enum stays a plain value; resolve it with
106    /// [`Trim::cartesian_point`].
107    Cartesian(EntityId),
108    /// An `IfcParameterValue` in the basis curve's own parameterisation.
109    ///
110    /// For a conic this is an angle in the model's plane-angle unit, not a
111    /// length and not necessarily radians.
112    Parameter(f64),
113}
114
115/// One end of the trim: up to one point and up to one parameter.
116///
117/// The schema's `SET [1:2]` means "at least one, at most one of each kind".
118/// Modelling it as two `Option`s rather than a list makes the both-present
119/// case impossible to overlook and the duplicate-kind case impossible to
120/// represent.
121#[derive(Debug, Clone, Copy, PartialEq, Default)]
122pub struct Trim {
123    /// The Cartesian form, if the file supplied one.
124    pub cartesian: Option<EntityId>,
125    /// The parameter form, if the file supplied one.
126    pub parameter: Option<f64>,
127}
128
129impl Trim {
130    /// The representation `preference` selects, falling back to whichever
131    /// exists.
132    ///
133    /// Under `Unspecified` the parameter is preferred: it is exact for conics,
134    /// whereas a Cartesian trim point must be inverted back to a parameter
135    /// with a tolerance the schema never specifies.
136    pub fn preferred(&self, preference: TrimmingPreference) -> Option<TrimPoint> {
137        let cartesian = self.cartesian.map(TrimPoint::Cartesian);
138        let parameter = self.parameter.map(TrimPoint::Parameter);
139        match preference {
140            TrimmingPreference::Cartesian => cartesian.or(parameter),
141            TrimmingPreference::Parameter | TrimmingPreference::Unspecified => {
142                parameter.or(cartesian)
143            }
144        }
145    }
146
147    /// Does this trim carry both a point and a parameter?
148    ///
149    /// When true, `MasterRepresentation` is not decoration: the two forms may
150    /// disagree by more than any sane tolerance in a rounded export.
151    pub fn is_over_specified(&self) -> bool {
152        self.cartesian.is_some() && self.parameter.is_some()
153    }
154
155    /// Is this trim empty, i.e. the file supplied neither form?
156    ///
157    /// The schema forbids it (`SET [1:2]`), so an empty trim means a broken
158    /// file, not a defaultable value.
159    pub fn is_empty(&self) -> bool {
160        self.cartesian.is_none() && self.parameter.is_none()
161    }
162
163    /// The Cartesian form as a typed point view, `Ok(None)` when absent.
164    ///
165    /// `referrer` is the `IfcTrimmedCurve` holding this trim, so a dangling
166    /// point is reported against the record that is wrong.
167    pub fn cartesian_point<'v>(
168        &self,
169        model: &'v Model,
170        referrer: EntityId,
171    ) -> GeometryResult<Option<CartesianPoint<'v>>> {
172        self.cartesian
173            .map(|id| resolve::cartesian_point(model, referrer, id))
174            .transpose()
175    }
176}
177
178/// The complete, uncollapsed trim of a curve.
179///
180/// Every field is kept because dropping any one of them loses a distinguishable
181/// arc. See the module docs on the four-arc problem.
182#[derive(Debug, Clone, Copy, PartialEq)]
183pub struct TrimSpec {
184    /// The `IfcCurve` being trimmed.
185    pub basis_curve: EntityId,
186    /// The trim at the **start** of the resulting curve.
187    pub trim1: Trim,
188    /// The trim at the **end** of the resulting curve.
189    pub trim2: Trim,
190    /// Does the trimmed curve run along the basis curve's own direction?
191    ///
192    /// `false` means traverse from `trim1` to `trim2` the other way round the
193    /// basis curve. On an open basis curve this only reverses the direction;
194    /// on a closed one it selects the complementary arc.
195    pub sense_agreement: bool,
196    /// Which trim form is authoritative.
197    pub master_representation: TrimmingPreference,
198}
199
200impl TrimSpec {
201    /// The start and end trims in traversal order.
202    ///
203    /// Always `(trim1, trim2)`: `SenseAgreement` changes *which way round the
204    /// basis curve* the traversal goes, it does not swap the endpoints. Files
205    /// are frequently misread the other way, so this accessor exists to state
206    /// the rule once.
207    pub fn endpoints(&self) -> (Trim, Trim) {
208        (self.trim1, self.trim2)
209    }
210
211    /// The start trim resolved through `MasterRepresentation`.
212    pub fn start(&self) -> Option<TrimPoint> {
213        self.trim1.preferred(self.master_representation)
214    }
215
216    /// The end trim resolved through `MasterRepresentation`.
217    pub fn end(&self) -> Option<TrimPoint> {
218        self.trim2.preferred(self.master_representation)
219    }
220
221    /// Both trims carry a parameter, so the arc is fully defined numerically.
222    ///
223    /// A kernel can take the fast path only when this holds; otherwise it must
224    /// project the Cartesian trim points onto the basis curve.
225    pub fn is_parametrically_complete(&self) -> bool {
226        self.trim1.parameter.is_some() && self.trim2.parameter.is_some()
227    }
228}
229
230/// A borrowed view of an `IfcTrimmedCurve`.
231#[derive(Debug, Clone, Copy)]
232pub struct TrimmedCurve<'m> {
233    slots: Slots<'m>,
234}
235
236impl<'m> TrimmedCurve<'m> {
237    /// Wrap an entity known to be an `IfcTrimmedCurve`.
238    pub fn new(id: EntityId, entity: &'m Entity) -> Self {
239        Self {
240            slots: Slots::new(id, entity),
241        }
242    }
243
244    /// The entity id.
245    pub fn id(&self) -> EntityId {
246        self.slots.id()
247    }
248
249    /// The `IfcCurve` being trimmed.
250    ///
251    /// May itself be trimmed, offset or composite; nesting is legal and this
252    /// view does not follow the chain.
253    pub fn basis_curve_ref(&self) -> GeometryResult<EntityId> {
254        self.slots.req_ref(slot::BASIS_CURVE, "BasisCurve")
255    }
256
257    /// Does the trimmed curve follow the basis curve's own direction?
258    pub fn sense_agreement(&self) -> GeometryResult<bool> {
259        self.slots.req_bool(slot::SENSE_AGREEMENT, "SenseAgreement")
260    }
261
262    /// Which trim form wins, defaulting to `Unspecified` when absent.
263    ///
264    /// A missing or unreadable token is not worth failing the whole curve for:
265    /// `Unspecified` is the schema's own "no preference" and callers already
266    /// have to handle it.
267    pub fn master_representation(&self) -> TrimmingPreference {
268        self.slots
269            .opt_enum(slot::MASTER_REPRESENTATION)
270            .and_then(TrimmingPreference::from_token)
271            .unwrap_or(TrimmingPreference::Unspecified)
272    }
273
274    /// The start trim.
275    pub fn trim1(&self) -> GeometryResult<Trim> {
276        self.read_trim(slot::TRIM_1, "Trim1")
277    }
278
279    /// The end trim.
280    pub fn trim2(&self) -> GeometryResult<Trim> {
281        self.read_trim(slot::TRIM_2, "Trim2")
282    }
283
284    /// The whole trim, with nothing collapsed.
285    ///
286    /// Prefer this over the individual accessors: a consumer that reads the
287    /// trims without also reading `SenseAgreement` will draw the wrong arc for
288    /// a closed basis curve, and gathering them together makes forgetting it
289    /// harder.
290    pub fn spec(&self) -> GeometryResult<TrimSpec> {
291        Ok(TrimSpec {
292            basis_curve: self.basis_curve_ref()?,
293            trim1: self.trim1()?,
294            trim2: self.trim2()?,
295            sense_agreement: self.sense_agreement()?,
296            master_representation: self.master_representation(),
297        })
298    }
299
300    /// Read one `SET [1:2] OF IfcTrimmingSelect`.
301    fn read_trim(&self, index: usize, name: &'static str) -> GeometryResult<Trim> {
302        let value = self.slots.req(index, name)?;
303        // Conforming files write a set, but a single-member set is sometimes
304        // written unwrapped. Accepting the bare member costs nothing and
305        // rejecting it would fail on files every other viewer reads.
306        let members: &[Value] = match value {
307            Value::List(items) => items,
308            single => std::slice::from_ref(single),
309        };
310
311        let mut trim = Trim::default();
312        for member in members {
313            match member {
314                Value::Ref(id) => {
315                    if trim.cartesian.replace(*id).is_some() {
316                        return Err(self.slots.degenerate(format!(
317                            "{name} holds two Cartesian trim points; \
318                             IfcTrimmingSelect allows at most one of each kind"
319                        )));
320                    }
321                }
322                other => {
323                    // `IFCPARAMETERVALUE(1.5)`, or a bare number where a
324                    // writer dropped the measure wrapper.
325                    let Some(p) = other.unwrap_typed().as_f64() else {
326                        return Err(self.slots.degenerate(format!(
327                            "{name} member is neither an IfcCartesianPoint reference \
328                             nor an IfcParameterValue"
329                        )));
330                    };
331                    if trim.parameter.replace(p).is_some() {
332                        return Err(self.slots.degenerate(format!(
333                            "{name} holds two parameter values; \
334                             IfcTrimmingSelect allows at most one of each kind"
335                        )));
336                    }
337                }
338            }
339        }
340
341        if trim.is_empty() {
342            return Err(self
343                .slots
344                .degenerate(format!("{name} is empty; SET [1:2] requires a member")));
345        }
346        Ok(trim)
347    }
348}
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353
354    fn parameter(v: f64) -> Value {
355        Value::Typed {
356            type_name: "IFCPARAMETERVALUE".into(),
357            value: Box::new(Value::Real(v)),
358        }
359    }
360
361    fn curve(trim1: Value, trim2: Value, sense: bool, preference: &str) -> Entity {
362        Entity::new(
363            "IFCTRIMMEDCURVE",
364            vec![
365                Value::Ref(EntityId(50)),
366                trim1,
367                trim2,
368                Value::Bool(sense),
369                Value::Enum(preference.into()),
370            ],
371        )
372    }
373
374    #[test]
375    fn a_trim_may_carry_a_point_and_a_parameter_at_once() {
376        let e = curve(
377            Value::List(vec![Value::Ref(EntityId(1)), parameter(0.0)]),
378            Value::List(vec![Value::Ref(EntityId(2)), parameter(90.0)]),
379            true,
380            "PARAMETER",
381        );
382        let spec = TrimmedCurve::new(EntityId(9), &e).spec().unwrap();
383        assert_eq!(spec.trim1.cartesian, Some(EntityId(1)));
384        assert_eq!(spec.trim1.parameter, Some(0.0));
385        assert!(spec.trim1.is_over_specified());
386        assert!(spec.is_parametrically_complete());
387    }
388
389    #[test]
390    fn a_cartesian_trim_resolves_to_its_point_and_a_parameter_trim_to_none() {
391        let mut model = Model::new();
392        let coords = Value::List(vec![Value::Real(1.0), Value::Real(0.0)]);
393        model.insert(EntityId(1), Entity::new("IFCCARTESIANPOINT", vec![coords]));
394        let e = curve(
395            Value::List(vec![Value::Ref(EntityId(1))]),
396            Value::List(vec![parameter(90.0)]),
397            true,
398            "CARTESIAN",
399        );
400        let spec = TrimmedCurve::new(EntityId(9), &e).spec().unwrap();
401        let point = spec.trim1.cartesian_point(&model, EntityId(9)).unwrap();
402        assert_eq!(point.unwrap().coordinates().unwrap(), vec![1.0, 0.0]);
403        assert!(spec
404            .trim2
405            .cartesian_point(&model, EntityId(9))
406            .unwrap()
407            .is_none());
408    }
409
410    #[test]
411    fn a_cartesian_trim_naming_a_non_point_is_a_typed_error() {
412        let mut model = Model::new();
413        model.insert(EntityId(1), Entity::new("IFCDIRECTION", vec![]));
414        let trim = Trim {
415            cartesian: Some(EntityId(1)),
416            parameter: None,
417        };
418        let err = trim.cartesian_point(&model, EntityId(9)).unwrap_err();
419        assert!(matches!(
420            err,
421            crate::GeometryError::WrongEntityType {
422                entity: EntityId(1),
423                ..
424            }
425        ));
426        let err = trim
427            .cartesian_point(&Model::new(), EntityId(9))
428            .unwrap_err();
429        assert_eq!(err.entity(), Some(EntityId(9)));
430    }
431
432    /// The whole point of MasterRepresentation: with both forms present it
433    /// decides, and the two forms genuinely disagree in rounded exports.
434    #[test]
435    fn master_representation_decides_between_the_two_trim_forms() {
436        let both = Value::List(vec![Value::Ref(EntityId(1)), parameter(0.25)]);
437
438        let cartesian = curve(both.clone(), both.clone(), true, "CARTESIAN");
439        assert_eq!(
440            TrimmedCurve::new(EntityId(1), &cartesian)
441                .spec()
442                .unwrap()
443                .start(),
444            Some(TrimPoint::Cartesian(EntityId(1)))
445        );
446
447        let param = curve(both.clone(), both.clone(), true, "PARAMETER");
448        assert_eq!(
449            TrimmedCurve::new(EntityId(1), &param)
450                .spec()
451                .unwrap()
452                .start(),
453            Some(TrimPoint::Parameter(0.25))
454        );
455    }
456
457    /// Under UNSPECIFIED the parameter is exact while inverting a point needs
458    /// an undefined tolerance, so the parameter is chosen.
459    #[test]
460    fn unspecified_preference_falls_back_to_the_parameter_form() {
461        let both = Value::List(vec![Value::Ref(EntityId(1)), parameter(0.5)]);
462        let e = curve(both.clone(), both, true, "UNSPECIFIED");
463        assert_eq!(
464            TrimmedCurve::new(EntityId(1), &e).spec().unwrap().start(),
465            Some(TrimPoint::Parameter(0.5))
466        );
467    }
468
469    /// A preference for a form the file did not supply must not yield None.
470    #[test]
471    fn a_preference_for_an_absent_form_falls_back_to_the_present_one() {
472        let only_point = Value::List(vec![Value::Ref(EntityId(1))]);
473        let e = curve(only_point.clone(), only_point, true, "PARAMETER");
474        assert_eq!(
475            TrimmedCurve::new(EntityId(1), &e).spec().unwrap().start(),
476            Some(TrimPoint::Cartesian(EntityId(1)))
477        );
478    }
479
480    /// One circle and one pair of trim points describe four distinct arcs.
481    /// If any two of these compare equal, the model has collapsed an arc a
482    /// file can legitimately express.
483    #[test]
484    fn four_distinct_arcs_come_from_one_basis_curve_and_one_trim_pair() {
485        let a = Value::List(vec![parameter(0.0)]);
486        let b = Value::List(vec![parameter(90.0)]);
487
488        let mut specs = Vec::new();
489        for (t1, t2) in [(a.clone(), b.clone()), (b.clone(), a.clone())] {
490            for sense in [true, false] {
491                let e = curve(t1.clone(), t2.clone(), sense, "PARAMETER");
492                specs.push(TrimmedCurve::new(EntityId(1), &e).spec().unwrap());
493            }
494        }
495
496        assert_eq!(specs.len(), 4);
497        for i in 0..specs.len() {
498            for j in (i + 1)..specs.len() {
499                assert_ne!(
500                    specs[i], specs[j],
501                    "arcs {i} and {j} collapsed into one specification"
502                );
503            }
504        }
505    }
506
507    /// Trim1 is the start and Trim2 the end regardless of sense; sense picks
508    /// the way round, not the endpoints.
509    #[test]
510    fn sense_agreement_does_not_swap_the_endpoints() {
511        let a = Value::List(vec![parameter(10.0)]);
512        let b = Value::List(vec![parameter(350.0)]);
513        for sense in [true, false] {
514            let e = curve(a.clone(), b.clone(), sense, "PARAMETER");
515            let spec = TrimmedCurve::new(EntityId(1), &e).spec().unwrap();
516            assert_eq!(spec.start(), Some(TrimPoint::Parameter(10.0)));
517            assert_eq!(spec.end(), Some(TrimPoint::Parameter(350.0)));
518            assert_eq!(spec.sense_agreement, sense);
519        }
520    }
521
522    /// Descending parameters are legal on a closed basis curve: informal
523    /// proposition IP3 does not apply there, so no reordering may happen.
524    #[test]
525    fn descending_trim_parameters_are_preserved_not_sorted() {
526        let e = curve(
527            Value::List(vec![parameter(270.0)]),
528            Value::List(vec![parameter(45.0)]),
529            true,
530            "PARAMETER",
531        );
532        let spec = TrimmedCurve::new(EntityId(1), &e).spec().unwrap();
533        assert_eq!(spec.trim1.parameter, Some(270.0));
534        assert_eq!(spec.trim2.parameter, Some(45.0));
535    }
536
537    #[test]
538    fn an_empty_trim_set_is_rejected() {
539        let e = curve(
540            Value::List(vec![]),
541            Value::List(vec![parameter(1.0)]),
542            true,
543            "PARAMETER",
544        );
545        let err = TrimmedCurve::new(EntityId(3), &e).spec().unwrap_err();
546        assert!(err.to_string().contains("Trim1"), "got: {err}");
547    }
548
549    #[test]
550    fn two_parameters_in_one_trim_set_is_rejected() {
551        let e = curve(
552            Value::List(vec![parameter(1.0), parameter(2.0)]),
553            Value::List(vec![parameter(3.0)]),
554            true,
555            "PARAMETER",
556        );
557        assert!(TrimmedCurve::new(EntityId(1), &e).spec().is_err());
558    }
559
560    /// Some writers omit the set brackets for a single member; every other
561    /// viewer reads those files.
562    #[test]
563    fn a_single_unwrapped_trim_member_is_accepted() {
564        let e = curve(parameter(0.0), Value::Ref(EntityId(2)), true, "UNSPECIFIED");
565        let spec = TrimmedCurve::new(EntityId(1), &e).spec().unwrap();
566        assert_eq!(spec.trim1.parameter, Some(0.0));
567        assert_eq!(spec.trim2.cartesian, Some(EntityId(2)));
568    }
569
570    #[test]
571    fn an_absent_master_representation_reads_as_unspecified() {
572        let e = Entity::new(
573            "IFCTRIMMEDCURVE",
574            vec![
575                Value::Ref(EntityId(50)),
576                Value::List(vec![parameter(0.0)]),
577                Value::List(vec![parameter(1.0)]),
578                Value::Bool(true),
579            ],
580        );
581        assert_eq!(
582            TrimmedCurve::new(EntityId(1), &e).master_representation(),
583            TrimmingPreference::Unspecified
584        );
585    }
586
587    #[test]
588    fn unknown_preference_tokens_are_not_silently_accepted() {
589        assert_eq!(TrimmingPreference::from_token("NONSENSE"), None);
590        assert_eq!(
591            TrimmingPreference::from_token("cartesian"),
592            Some(TrimmingPreference::Cartesian)
593        );
594    }
595}