ifc_geometry/constraint/placement/derive.rs
1//! Deriving a placement frame from the basis curve.
2//!
3//! The cached `CartesianPosition` path resolves a placement without any
4//! computation. When an authoring tool omits it, the frame has to be
5//! derived by evaluating the basis curve at the authored distance, which is
6//! computation and therefore an opt-in capability under ADR 0004.
7//!
8//! This module holds the IFC-side half: it turns an `IfcLinearPlacement`
9//! into a curve, a measure and an offset, then asks an injected
10//! [`CurveEvaluator`] for the frame. It never picks an evaluator, and
11//! `ifc-geometry` links no implementation.
12//!
13//! # What an `IfcParameterValue` means here
14//!
15//! `IfcPointByDistanceExpression.DistanceAlong` is an `IfcCurveMeasureSelect`:
16//! a length, or a parameter of the basis curve (IFC4.3 ADD2 8.9.3.48). A
17//! parameter is only as defined as the basis curve's parameterisation:
18//!
19//! - `IfcPolyline` counts one per segment (8.9.3.51), and so does a
20//! line-only `IfcIndexedPolyCurve` (see the `polyline` submodule); the
21//! neutral polyline uses the same convention, so the parameter crosses
22//! unchanged. Only where every segment is one unit long does it equal a
23//! length.
24//! - `IfcGradientCurve` takes the parameter of its `BaseCurve` (8.9.3.34.1),
25//! an `IfcCompositeCurve` of `IfcCurveSegment`s. A composite accumulates
26//! the parametric ranges of its parent curves (8.9.3.20.1, after
27//! ISO 10303-42), which are not lengths (an `IfcCircle` counts its angle,
28//! 8.9.3.18.1; an `IfcClothoid` `u = s / (A sqrt(pi))`, 8.9.3.19.1), while
29//! `IfcCurveSegment` (8.9.3.28.1) states that no parametric space is yet
30//! defined for its parent curves and measures segments by length. The
31//! parameter of an alignment centreline is therefore undefined, and is
32//! refused by name rather than handed to an evaluator, whose own parameter
33//! on that curve is plan distance (axiolid ADR 0082), a different quantity.
34//! An `IfcAlignment` basis names the same centreline and is refused alike.
35//! This matches the station lowering, which refuses a parameter too.
36//!
37//! # The derived frame (#355)
38//!
39//! IFC4.3 ADD2 fixes the frame, so it is built here from the evaluator's
40//! point and unit tangent alone, never from the evaluator's own axis
41//! labelling. That labelling is `x` the tangent, `y` up and `z` to the
42//! right (the contract's text, corrected by axiolid/kernel#242 to what the
43//! reference provider always returned), so the frame below is `(x, -z, y)`
44//! of it for a reference-up evaluator; reading only `x` keeps the frame
45//! right for any provider whatever it calls its other axes, and a banked
46//! curve's roll never reaches it.
47//!
48//! - `x` is the tangent: `IfcAxis2PlacementLinear.RefDirection` defaults to
49//! it (8.9.3.4), and `OffsetLongitudinal` runs along it.
50//! - `y` is the horizontal left, `normalise(Z x tangent)`:
51//! `IfcPointByDistanceExpression.OffsetLateral` is horizontal and
52//! "positive values indicate to the left of the basis curve".
53//! - `z = x x y` is up, perpendicular to the tangent in its vertical plane:
54//! that is where `OffsetVertical` points, and what `Axis` defaults to,
55//! "the normal vector of the basis curve that lies within the vertical
56//! plane containing the RefDirection".
57//!
58//! Explicit `Axis`/`RefDirection` on the placement are components in that
59//! `(tangent, left, up)` frame (8.9.3.4), the reading the station lowering
60//! uses too, and [`derive_linear_placement_transform`] composes them.
61//!
62//! # Tangent discontinuities (#409)
63//!
64//! IFC4.3 ADD2 8.9.3.48.3: "If DistanceAlong coincides with a point of
65//! tangential discontinuity (within precision limits), then the tangent of
66//! the previous segment governs." The derivation reads such a placement as
67//! the station lowering does (`lower::station`, #346): the seams are read
68//! from the basis curve's stored data, a `DistanceAlong` within the model's
69//! declared `Precision` (capped at 1 mm) or rounding of one is snapped to
70//! the seam's own distance, and the evaluator is asked for the frame there
71//! with [`CurveEvaluator::frame_at_on`] and [`SeamSide::Incoming`]. Off a
72//! seam it is asked side-lessly, as before. The derived placement thus
73//! equals the lowered station's frame on and near a seam, and `Verify`
74//! compares a cache against the incoming frame.
75//!
76//! A native parameter on a polyline vertex is located by its distance, an
77//! exact running sum of edge lengths, and read at that distance: the
78//! contract lets a provider refuse the incoming side of a polyline's native
79//! parameter, and the distance names the same place.
80//!
81//! An evaluator that does not implement seam sides refuses `Incoming` with
82//! `SEAM_SIDE_UNSUPPORTED`; that is [`GeometryError::SeamSideUnsupported`]
83//! naming the placement, its basis curve and the seam, never the outgoing
84//! frame in its place.
85//!
86//! # Curve-relation bases (#418)
87//!
88//! A plain `IfcCompositeCurve`, an `IfcTrimmedCurve` (and the other
89//! composites and surface curves the curve lowering reads as relations), and
90//! a composite of `IfcCurveSegment`s placed by `IfcAxis2PlacementLinear`s
91//! lower to a curve relation, which the station lowering measures end to
92//! end through its pieces (#346). The derivation reads the same basis as
93//! Axiolid's neutral `CurvePath` (axiolid/kernel#290), built from the stored
94//! relation in the `path` submodule, through the evaluator's `path_*`
95//! queries: [`CurveEvaluator::path_frame_at`] off a seam, and
96//! [`CurveEvaluator::path_frame_at_on`] with [`SeamSide::Incoming`] on one.
97//! Every joint of the relation is a seam, as for the station, so a
98//! `DistanceAlong` within precision of a joint reads the segment that ends
99//! there, IFC's previous segment. The distance is the relation's: arc
100//! length, or plan distance where every piece is a gradient curve. A native
101//! parameter is refused by name: a relation's pieces have no parameter that
102//! runs through them, and the station lowering refuses one too.
103//!
104//! An evaluator that does not implement curve paths refuses them with
105//! `CURVE_PATH_UNSUPPORTED`; that is [`GeometryError::CurvePathUnsupported`]
106//! naming the placement and its basis curve, never a frame read on one
107//! piece in its place. An offset curve is read the same way (#414): its
108//! pieces are `PathCurve::Offset`s of its basis's spans, measured in the
109//! offset's own length, as the station lowering measures it. Where that
110//! length is a quadrature (an offset beside a gradient curve, a spiral or a
111//! B-spline, and a relation with an ellipse or a B-spline piece), the piece
112//! is handed over open-ended and the evaluator resolves its end with its
113//! own length (#427, axiolid/kernel#298); a placement within the model's
114//! precision of a joint after it is located by the evaluator's certified
115//! joint distances and read from the incoming piece, as the kernel reads
116//! the same basis's station (#423). The `path` submodule states the rule
117//! and its typed refusals; nothing is derived from an estimate this crate
118//! makes.
119//!
120//! # Which distance
121//!
122//! `DistanceAlong` on an alignment centreline is plan distance (an
123//! `IfcGradientCurve` takes its `BaseCurve`'s measure, 8.9.3.34.1), and arc
124//! length along a straight-segment curve. An evaluator states which
125//! distance it measures per curve ([`CurveEvaluator::distance_convention`]);
126//! one that measures something else is refused rather than trusted.
127//!
128//! # Checking a cached position (#354)
129//!
130//! `IfcLinearPlacement.CartesianPosition` is, in IFC4.3's words, "an
131//! optional fallback for the RelativePlacement attribute" for importers that
132//! do not support linear placement. The linear expression is authoritative.
133//! When a caller supplies an evaluator, [`CachedPositionPolicy`] decides what
134//! happens to a cached position; see there.
135
136use axiolid_contracts::GeomError;
137use axiolid_core::Frame3;
138use axiolid_curve::Curve3;
139use axiolid_curve_evaluate_contract::{
140 CurveEvaluator, CurveMeasure as KernelMeasure, DistanceConvention, SeamSide,
141 SEAM_SIDE_UNSUPPORTED,
142};
143use axiolid_model::GeometryNode;
144use ifc_alignment::{
145 AlignmentUnits, CurveMeasure, LinearPlacement, PointByDistance, SeamTolerance,
146};
147use ifc_model::{EntityId, Model, Value};
148
149use crate::constraint::tolerance;
150use crate::error::{GeometryError, GeometryResult};
151use crate::lower::curve::lower_curve_node;
152use crate::lower::session::LoweringSession;
153use crate::lower::station::seams::{nearest, seams3, Seam};
154use crate::resource::direction::resolve_unit;
155use crate::transform::Transform;
156use crate::units::UnitScale;
157
158mod path;
159mod polyline;
160
161pub use path::basis_curve_path;
162#[cfg(test)]
163pub(crate) use path::WINDOW_CERTIFICATION;
164
165/// What lowering does with an `IfcLinearPlacement`'s cached
166/// `CartesianPosition` when the caller supplies a [`CurveEvaluator`] (#354).
167///
168/// Without an evaluator nothing changes: the cache is used as it is, and a
169/// placement without one is refused. With one, an uncached placement is
170/// derived, and a cached one is handled by this policy.
171#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
172#[non_exhaustive]
173pub enum CachedPositionPolicy {
174 /// Derive the position from the linear expression and compare the cache
175 /// with it. The default.
176 ///
177 /// - The cache's location within the model's tolerance (see
178 /// [`cached_position_tolerance`]) of the derived origin: the DERIVED
179 /// frame is used, because the linear expression is authoritative.
180 /// - Beyond it: [`GeometryError::CachedPlacementMismatch`] naming the
181 /// placement and both positions. A stale cache, e.g. after the
182 /// alignment was edited, would otherwise place the product silently
183 /// wrong, and a caller who supplied an evaluator can derive the truth.
184 /// - A derivation the bridge refuses (an `IfcParameterValue` on an
185 /// alignment, a basis curve it cannot lower) is that refusal: a cache
186 /// that cannot be checked is not checked.
187 ///
188 /// Only the location is compared. The cache's axes are not: IFC defaults
189 /// `Axis` to the curve normal in the vertical plane, tilted with the
190 /// grade, and exporters that write the cache with a plumb `Z` are not
191 /// stale.
192 #[default]
193 Verify,
194 /// Use a cached position as it is, without deriving or comparing; derive
195 /// only placements that have no cache.
196 ///
197 /// For a model whose caches are trusted, or whose linear expressions
198 /// this bridge cannot derive (an `IfcParameterValue` on an alignment is
199 /// refused by name, #347) while the cache still places the product as
200 /// the exporter computed it.
201 Trust,
202}
203
204/// A caller-supplied evaluator and what to do with a cached position.
205#[derive(Debug, Clone, Copy)]
206pub(crate) struct Derivation<'e> {
207 pub(crate) evaluator: &'e dyn CurveEvaluator,
208 pub(crate) cached: CachedPositionPolicy,
209}
210
211/// Resolve an `IfcLinearPlacement` with an evaluator, in metres, relative
212/// to the frame its basis curve is stated in (#357).
213///
214/// `resolved` is the placement as `ifc-alignment` read it, in FILE units;
215/// `cached` its `CartesianPosition`, if any, as a transform in metres
216/// relative to the same frame; `parent` that frame's world transform in
217/// metres. The cache is compared in world coordinates, so a mismatch names
218/// world positions.
219pub(crate) fn resolve_linear(
220 model: &Model,
221 units: &UnitScale,
222 placement: EntityId,
223 resolved: &LinearPlacement,
224 cached: Option<Transform>,
225 derivation: Derivation<'_>,
226 parent: &Transform,
227) -> GeometryResult<Transform> {
228 if let (Some(cached), CachedPositionPolicy::Trust) = (cached, derivation.cached) {
229 return Ok(cached);
230 }
231 let derived = linear_transform(model, units, placement, resolved, derivation.evaluator)?;
232 if let Some(cached) = cached {
233 check_cache(
234 model,
235 units,
236 placement,
237 &parent.compose(&cached),
238 &parent.compose(&derived),
239 )?;
240 }
241 Ok(derived)
242}
243
244/// Refuse a cached position farther than the model's tolerance from the
245/// derived one.
246fn check_cache(
247 model: &Model,
248 units: &UnitScale,
249 placement: EntityId,
250 cached: &Transform,
251 derived: &Transform,
252) -> GeometryResult<()> {
253 let precision = cached_position_tolerance(model, units)?;
254 let [a, b] = [cached.origin, derived.origin];
255 let distance = tolerance::distance(a, b);
256 // The floating-point rounding term the alignment seams use
257 // (`ifc_alignment::SeamTolerance`): 1e-9 relative, floor 1.
258 let tolerance = tolerance::point_tolerance(precision, a, b);
259 if distance.is_finite() && distance <= tolerance {
260 return Ok(());
261 }
262 Err(GeometryError::CachedPlacementMismatch {
263 placement,
264 cached: a,
265 derived: b,
266 distance,
267 tolerance,
268 })
269}
270
271/// The tolerance a cached `CartesianPosition` is checked at, in metres
272/// (#354).
273///
274/// IFC defines `IfcGeometricRepresentationContext.Precision` as "the
275/// tolerance under which two given points are still assumed to be
276/// identical", so that is the tolerance: the coarsest `Precision` any 3D
277/// root context declares (sub-contexts derive theirs from it), in the
278/// project length unit and converted to metres. A model that declares none
279/// gets IFC's own default, `1.E-5` project units, which is what
280/// `IfcGeometricRepresentationSubContext.Precision` derives to without a
281/// parent value (`NVL(ParentContext.Precision, 1.E-5)`, IFC4 ADD2 TC1).
282///
283/// # Errors
284///
285/// A declared `Precision` that is not a finite positive number is
286/// [`GeometryError::Degenerate`] naming the context: a check against it
287/// would accept or refuse everything.
288pub fn cached_position_tolerance(model: &Model, units: &UnitScale) -> GeometryResult<f64> {
289 Ok(units.length(tolerance::model_precision(model)?))
290}
291
292/// Resolve an `IfcLinearPlacement` from its linear expression alone, in
293/// metres, ignoring any cached `CartesianPosition`.
294///
295/// Reads `RelativePlacement`: its `IfcPointByDistanceExpression` through
296/// [`derive_placement_transform`], and its optional `Axis`/`RefDirection`,
297/// composed in the `(tangent, left, up)` frame (module documentation).
298///
299/// The result is in the coordinate system the basis curve is stated in --
300/// the object coordinate system of the alignment that carries it -- not
301/// in the world: `PlacementRelTo` and the alignment's own `ObjectPlacement`
302/// are not composed here (#357). [`super::product_world_transform_with_evaluator`]
303/// and the evaluator-taking lowering compose that chain.
304///
305/// # Errors
306///
307/// As [`derive_placement_transform`]; a malformed placement (wrong types,
308/// `Axis` without `RefDirection`) is [`GeometryError::Unsupported`] naming
309/// it, a missing direction [`GeometryError::MissingEntity`], and parallel
310/// axes [`GeometryError::Degenerate`].
311pub fn derive_linear_placement_transform(
312 model: &Model,
313 units: &UnitScale,
314 placement: EntityId,
315 evaluator: &dyn CurveEvaluator,
316) -> GeometryResult<Transform> {
317 let resolved = resolve_in_file_units(model, units, placement)?;
318 linear_transform(model, units, placement, &resolved, evaluator)
319}
320
321/// Read an `IfcLinearPlacement` through `ifc-alignment`, keeping lengths in
322/// file units: [`derive_placement_transform`] converts them itself.
323pub(crate) fn resolve_in_file_units(
324 model: &Model,
325 units: &UnitScale,
326 placement: EntityId,
327) -> GeometryResult<LinearPlacement> {
328 let file_units = AlignmentUnits {
329 length_to_metres: 1.0,
330 angle_to_radians: units.angle_to_radians,
331 };
332 ifc_alignment::resolve_linear_placement(model, placement, file_units).map_err(|_error| {
333 GeometryError::Unsupported {
334 entity: placement,
335 type_name: "IFCLINEARPLACEMENT".into(),
336 detail: "linear placement is malformed; ifc-alignment refused it",
337 }
338 })
339}
340
341/// The derived frame of `resolved`, with explicit axes applied, in metres.
342fn linear_transform(
343 model: &Model,
344 units: &UnitScale,
345 placement: EntityId,
346 resolved: &LinearPlacement,
347 evaluator: &dyn CurveEvaluator,
348) -> GeometryResult<Transform> {
349 let base = derive_placement_transform(
350 model,
351 units,
352 placement,
353 &resolved.relative_placement,
354 evaluator,
355 )?;
356 if !resolved.has_explicit_axes {
357 return Ok(base);
358 }
359 let (axis, ref_direction) = explicit_axes(model, placement)?;
360 let local =
361 Transform::from_axes([0.0; 3], Some(axis), Some(ref_direction)).ok_or_else(|| {
362 GeometryError::Degenerate {
363 entity: placement,
364 type_name: "IFCLINEARPLACEMENT".into(),
365 detail: "IfcAxis2PlacementLinear Axis and RefDirection are parallel (WR2)".into(),
366 }
367 })?;
368 Ok(base.compose(&local))
369}
370
371/// `RelativePlacement.Axis` and `.RefDirection`, as unit components.
372fn explicit_axes(model: &Model, placement: EntityId) -> GeometryResult<([f64; 3], [f64; 3])> {
373 // IFC4X3_ADD2: IfcLinearPlacement.RelativePlacement is slot 1;
374 // IfcAxis2PlacementLinear has Location, Axis, RefDirection at 0..2.
375 let reference = |owner: EntityId, slot: usize| -> GeometryResult<EntityId> {
376 model
377 .get(owner)
378 .and_then(|entity| entity.attributes.get(slot))
379 .and_then(Value::as_ref_id)
380 .ok_or(GeometryError::Unsupported {
381 entity: owner,
382 type_name: "IFCAXIS2PLACEMENTLINEAR".into(),
383 detail: "IfcAxis2PlacementLinear states Axis and RefDirection only in part",
384 })
385 };
386 let linear = reference(placement, 1)?;
387 let axis = resolve_unit(model, linear, reference(linear, 1)?)?;
388 let ref_direction = resolve_unit(model, linear, reference(linear, 2)?)?;
389 Ok((axis, ref_direction))
390}
391
392/// Resolve an `IfcPointByDistanceExpression` by evaluating its basis curve.
393///
394/// `evaluator` supplies the capability; this function supplies the IFC
395/// reading and the unit handling. `expression` is in FILE units (read it
396/// with `ifc_alignment` and a length factor of 1, as
397/// [`derive_linear_placement_transform`] does); the distance and offsets are
398/// converted to metres before they cross the boundary, because the kernel is
399/// unitless.
400///
401/// The frame is `(tangent, left, up)` and the offsets follow IFC4.3: see
402/// the module documentation. The placement's own `Axis`/`RefDirection` are
403/// not read here; [`derive_linear_placement_transform`] applies them.
404///
405/// Refuses, rather than approximating, when:
406///
407/// - the basis curve is not one this bridge can lower to a `Curve3`
408/// - the evaluator reports it cannot measure distance on that curve, or
409/// measures a different distance than IFC states for it
410/// - the authored value is an `IfcParameterValue` on a basis curve whose
411/// IFC parameterisation is undefined (an alignment centreline)
412/// - the tangent is vertical, so there is no horizontal left
413/// - `DistanceAlong` lies on a tangent discontinuity and the evaluator
414/// cannot read its incoming side ([`GeometryError::SeamSideUnsupported`],
415/// module documentation)
416/// - the basis curve is a curve relation and the evaluator reads single
417/// curves only ([`GeometryError::CurvePathUnsupported`]), or the
418/// authored value is an `IfcParameterValue` along one
419pub fn derive_placement_transform(
420 model: &Model,
421 units: &UnitScale,
422 placement: EntityId,
423 expression: &PointByDistance,
424 evaluator: &dyn CurveEvaluator,
425) -> GeometryResult<Transform> {
426 let parameter_requested = matches!(expression.distance_along, CurveMeasure::Parameter(_));
427 let (curve, convention) = match basis_curve(
428 model,
429 units,
430 placement,
431 expression.basis_curve,
432 parameter_requested,
433 evaluator,
434 )? {
435 Basis::Curve(curve, convention) => (curve, convention),
436 Basis::Path(basis) => {
437 return path::derive_on_path(model, units, placement, expression, &basis, evaluator)
438 }
439 };
440
441 // `IfcCurveMeasureSelect` says which method of measurement the file
442 // means. Carry that across rather than collapsing it to a number: a
443 // parameter passed as a distance places the product plausibly wrong.
444 let at = match expression.distance_along {
445 CurveMeasure::Length(value) => {
446 // A distance is only as good as the evaluator's agreement on
447 // which distance it is (the contract says to consult this).
448 if evaluator.distance_convention(&curve) != convention {
449 return Err(GeometryError::Unsupported {
450 entity: placement,
451 type_name: "IFCLINEARPLACEMENT".into(),
452 detail: "the evaluator measures a different distance along this basis \
453 curve than IFC states (plan distance on an alignment, arc \
454 length on a polyline)",
455 });
456 }
457 KernelMeasure::Distance(units.length(value))
458 }
459 CurveMeasure::Parameter(value) => KernelMeasure::Parameter(value),
460 };
461
462 let refused = |error: GeomError| GeometryError::Unsupported {
463 entity: placement,
464 type_name: "IFCLINEARPLACEMENT".into(),
465 detail: refusal_detail(&error),
466 };
467 let frame = match seam_at(model, units, placement, &curve, at)? {
468 // On a tangent discontinuity the previous segment governs
469 // (8.9.3.48.3): the incoming side, read at the seam's own distance,
470 // as `lower::station` stores it (module documentation).
471 Some(seam) => {
472 if !at.is_distance() && evaluator.distance_convention(&curve) != convention {
473 return Err(GeometryError::Unsupported {
474 entity: placement,
475 type_name: "IFCLINEARPLACEMENT".into(),
476 detail: SEAM_PARAMETER_CONVENTION,
477 });
478 }
479 evaluator
480 .frame_at_on(&curve, KernelMeasure::Distance(seam), SeamSide::Incoming)
481 .map_err(|error| match error {
482 GeomError::UnsupportedInput { input, .. } if input == SEAM_SIDE_UNSUPPORTED => {
483 GeometryError::SeamSideUnsupported {
484 placement,
485 basis: expression.basis_curve,
486 distance: seam,
487 }
488 }
489 other => refused(other),
490 })?
491 }
492 None => evaluator.frame_at(&curve, at).map_err(refused)?,
493 };
494
495 offset_frame(&frame, expression, units).ok_or(GeometryError::Unsupported {
496 entity: placement,
497 type_name: "IFCLINEARPLACEMENT".into(),
498 detail: path::VERTICAL_BASIS,
499 })
500}
501
502/// The distance of the tangent discontinuity `at` lies on, in metres, if
503/// any (#409).
504///
505/// The same reading as `lower::station`: the seams are read from the
506/// curve's stored data (`lower::station::seams`), and `at` is on one within
507/// the model's declared `Precision` (capped at 1 mm) or rounding. A native
508/// parameter is located by its distance: on the neutral polyline, the only
509/// curve a parameter reaches here, that is an exact running sum.
510fn seam_at(
511 model: &Model,
512 units: &UnitScale,
513 placement: EntityId,
514 curve: &Curve3,
515 at: KernelMeasure,
516) -> GeometryResult<Option<f64>> {
517 let distance = match at {
518 KernelMeasure::Distance(distance) => Some(distance),
519 KernelMeasure::Parameter(parameter) => polyline_distance(curve, parameter),
520 _ => None,
521 };
522 let Some(distance) = distance.filter(|d| d.is_finite()) else {
523 // Not a place along the curve: the evaluator refuses it by name.
524 return Ok(None);
525 };
526 let seams = seams3(curve).map_err(|reason| GeometryError::Unsupported {
527 entity: placement,
528 type_name: "IFCLINEARPLACEMENT".into(),
529 detail: reason,
530 })?;
531 snap(model, units, placement, &seams, distance)
532}
533
534/// The distance of the seam of `seams` that `distance` lies on within the
535/// model's precision, if any.
536fn snap(
537 model: &Model,
538 units: &UnitScale,
539 placement: EntityId,
540 seams: &[Seam],
541 distance: f64,
542) -> GeometryResult<Option<f64>> {
543 if seams.is_empty() || !distance.is_finite() {
544 return Ok(None);
545 }
546 let precision = model_precision(model, units, placement)?;
547 Ok(nearest(seams, distance, precision).map(|seam| seam.distance))
548}
549
550/// The model's declared precision as a seam tolerance, in metres (capped at
551/// 1 mm), as the station lowering reads it.
552fn model_precision(model: &Model, units: &UnitScale, placement: EntityId) -> GeometryResult<f64> {
553 Ok(SeamTolerance::for_model(
554 model,
555 AlignmentUnits {
556 length_to_metres: units.length_to_metres,
557 angle_to_radians: units.angle_to_radians,
558 },
559 )
560 .map_err(|_| GeometryError::Degenerate {
561 entity: placement,
562 type_name: "IFCLINEARPLACEMENT".into(),
563 detail: "the model's declared Precision is not a usable seam tolerance".into(),
564 })?
565 .length())
566}
567
568/// The distance along a neutral polyline at its native `parameter` (one
569/// unit per segment, see the `polyline` submodule); `None` off its range or
570/// on another curve.
571fn polyline_distance(curve: &Curve3, parameter: f64) -> Option<f64> {
572 let Curve3::Polyline(polyline) = curve else {
573 return None;
574 };
575 let lengths: Vec<f64> = polyline
576 .points
577 .windows(2)
578 .map(|w| (w[1] - w[0]).length())
579 .collect();
580 let segments = lengths.len() as f64;
581 if !parameter.is_finite() || parameter < 0.0 || parameter > segments {
582 return None;
583 }
584 let whole = (parameter.floor() as usize).min(lengths.len().saturating_sub(1));
585 let before: f64 = lengths[..whole].iter().sum();
586 Some(before + (parameter - whole as f64) * lengths.get(whole).copied().unwrap_or(0.0))
587}
588
589/// Why a native parameter on a seam is refused when the evaluator measures
590/// another distance there.
591const SEAM_PARAMETER_CONVENTION: &str =
592 "DistanceAlong is a parameter on a tangent discontinuity of the basis curve, which is \
593 read at the seam's distance from the incoming side (IFC4.3 ADD2 8.9.3.48.3), and the \
594 evaluator measures a different distance along this curve";
595
596/// A basis curve as the evaluator reads it.
597// Large only by the path, which lives for one derivation.
598#[allow(clippy::large_enum_variant)]
599enum Basis {
600 /// One neutral curve and the distance IFC states along it.
601 Curve(Curve3, DistanceConvention),
602 /// A curve relation, as a path (#418).
603 Path(path::PathBasis),
604}
605
606/// The IFC curve types that lower to a curve relation, read as a path
607/// (#418): composites, trims, surface curves whose 3D curve governs, and
608/// offset curves (#414).
609const RELATION_BASES: &[&str] = &[
610 "IFCCOMPOSITECURVE",
611 "IFCCOMPOSITECURVEONSURFACE",
612 "IFCBOUNDARYCURVE",
613 "IFCOUTERBOUNDARYCURVE",
614 "IFCTRIMMEDCURVE",
615 "IFCSURFACECURVE",
616 "IFCINTERSECTIONCURVE",
617 "IFCSEAMCURVE",
618 "IFCOFFSETCURVE2D",
619 "IFCOFFSETCURVE3D",
620 "IFCOFFSETCURVEBYDISTANCES",
621];
622
623/// The basis curve as a neutral `Curve3`, or as a curve path.
624///
625/// An alignment centreline is the case that matters: `IfcGradientCurve`
626/// pairs a plan with a vertical profile, which `ifc-alignment` already
627/// composes exactly. Straight-segment curves (`IfcPolyline`, a line-only
628/// `IfcIndexedPolyCurve`) lower to the neutral polyline, whose arc length is
629/// an exact finite sum. A composite or trimmed curve is read as the curve
630/// path the station lowering measures (module documentation). Other curve
631/// families -- an ellipse, a B-spline -- are refused by name here rather
632/// than lowered approximately, because a placement derived from a curve we
633/// guessed at is worse than one we declined to derive.
634fn basis_curve(
635 model: &Model,
636 units: &UnitScale,
637 placement: EntityId,
638 basis: EntityId,
639 parameter_requested: bool,
640 evaluator: &dyn CurveEvaluator,
641) -> GeometryResult<Basis> {
642 let entity = model.get(basis).ok_or(GeometryError::MissingEntity {
643 referrer: placement,
644 missing: basis,
645 })?;
646 let alignment_units = AlignmentUnits {
647 length_to_metres: units.length_to_metres,
648 angle_to_radians: units.angle_to_radians,
649 };
650 // IFC lets the BasisCurve be the alignment itself or its curve
651 // representation. Both name the same centreline, so both resolve; a
652 // file that uses one is not less valid than one that uses the other.
653 match entity.type_name.as_ref() {
654 // The curve representation lowers exactly through the same path a
655 // representation item takes. `ifc_alignment::gradient_curve3` reads an
656 // `IfcAlignment` only, so handing it the curve always refused.
657 // Refused before lowering: the answer does not depend on the curve.
658 "IFCGRADIENTCURVE" | "IFCALIGNMENT" if parameter_requested => {
659 Err(GeometryError::Unsupported {
660 entity: basis,
661 type_name: entity.type_name.to_string(),
662 detail: UNDEFINED_ALIGNMENT_PARAMETER,
663 })
664 }
665 "IFCGRADIENTCURVE" => Ok(Basis::Curve(
666 gradient_curve(model, units, basis)?,
667 DistanceConvention::PlanDistance,
668 )),
669 "IFCALIGNMENT" => ifc_alignment::gradient_curve3(model, basis, alignment_units)
670 .map(|curve| Basis::Curve(curve, DistanceConvention::PlanDistance))
671 .map_err(|error| match error {
672 ifc_alignment::AlignmentError::AngleUnitUndeclared { entity } => {
673 GeometryError::AngleUnitUndeclared { entity }
674 }
675 _ => GeometryError::Unsupported {
676 entity: placement,
677 type_name: entity.type_name.to_string(),
678 detail: "basis curve does not compose an exact centreline",
679 },
680 }),
681 "IFCPOLYLINE" => Ok(Basis::Curve(
682 polyline::polyline(model, units, basis, entity)?,
683 DistanceConvention::ArcLength3d,
684 )),
685 "IFCINDEXEDPOLYCURVE" => Ok(Basis::Curve(
686 polyline::indexed_polycurve(model, units, basis, entity, parameter_requested)?,
687 DistanceConvention::ArcLength3d,
688 )),
689 // Refused before lowering: the answer does not depend on the curve.
690 kind if RELATION_BASES.contains(&kind) && parameter_requested => {
691 Err(GeometryError::Unsupported {
692 entity: basis,
693 type_name: kind.to_owned(),
694 detail: path::RELATION_PARAMETER,
695 })
696 }
697 kind if RELATION_BASES.contains(&kind) => {
698 path::path_basis(model, units, placement, basis, kind, evaluator).map(Basis::Path)
699 }
700 other => Err(GeometryError::Unsupported {
701 entity: placement,
702 type_name: other.to_owned(),
703 detail: "deriving a placement frame needs an alignment centreline, a \
704 straight-segment polyline or a composite or trimmed curve as basis curve",
705 }),
706 }
707}
708
709/// Why an `IfcParameterValue` along an alignment centreline is refused.
710///
711/// See the module documentation for the IFC4.3 ADD2 clauses.
712const UNDEFINED_ALIGNMENT_PARAMETER: &str =
713 "an IfcParameterValue DistanceAlong on an alignment centreline: the parameter \
714 space of a composite of IfcCurveSegments is undefined in IFC4.3 ADD2; state an \
715 IfcLengthMeasure";
716
717/// An `IfcGradientCurve` basis curve as its exact `Curve3::Elevated`, in metres.
718///
719/// A refusal names the gradient curve (or the nested entity) and its own
720/// reason, such as a vertical arc with no neutral elevation law.
721fn gradient_curve(model: &Model, units: &UnitScale, basis: EntityId) -> GeometryResult<Curve3> {
722 let mut session = LoweringSession::new(model, units);
723 let root = lower_curve_node(&mut session, basis, Transform::identity())?;
724 let lowered = session.finish(root)?;
725 match lowered.graph.get(lowered.root) {
726 Some(GeometryNode::Curve3(curve)) => Ok(curve.clone()),
727 _ => Err(GeometryError::Unsupported {
728 entity: basis,
729 type_name: "IFCGRADIENTCURVE".into(),
730 detail: "the gradient curve did not lower to a single neutral Curve3",
731 }),
732 }
733}
734
735/// The IFC frame at the evaluated point, with the authored offsets applied.
736///
737/// Built from `frame.origin` and the unit tangent `frame.x` only (module
738/// documentation): `left = normalise(Z x tangent)`, `up = tangent x left`.
739/// `OffsetLateral` moves along `left`, `OffsetVertical` along `up` and
740/// `OffsetLongitudinal` along the tangent. `None` when the tangent is
741/// vertical and `left` is undefined.
742fn offset_frame(
743 frame: &Frame3,
744 expression: &PointByDistance,
745 units: &UnitScale,
746) -> Option<Transform> {
747 let tangent = [frame.x.x, frame.x.y, frame.x.z];
748 let horizontal = (tangent[0] * tangent[0] + tangent[1] * tangent[1]).sqrt();
749 if !horizontal.is_finite() || horizontal <= 1e-12 {
750 return None;
751 }
752 // Z x tangent = (-t.y, t.x, 0).
753 let left = [-tangent[1] / horizontal, tangent[0] / horizontal, 0.0];
754 let up = [
755 tangent[1] * left[2] - tangent[2] * left[1],
756 tangent[2] * left[0] - tangent[0] * left[2],
757 tangent[0] * left[1] - tangent[1] * left[0],
758 ];
759
760 let lateral = units.length(expression.offset_lateral.unwrap_or(0.0));
761 let vertical = units.length(expression.offset_vertical.unwrap_or(0.0));
762 let longitudinal = units.length(expression.offset_longitudinal.unwrap_or(0.0));
763 let point = [frame.origin.x, frame.origin.y, frame.origin.z];
764 let origin = std::array::from_fn(|i| {
765 point[i] + left[i] * lateral + up[i] * vertical + tangent[i] * longitudinal
766 });
767 Some(Transform {
768 basis: [tangent, left, up],
769 origin,
770 })
771}
772
773/// Name why the evaluator declined.
774///
775/// The kernel distinguishes an unsupported operation from a rejected
776/// measure and from a degenerate curve, and that difference is actionable:
777/// the first means the file needs a different curve family, the others mean
778/// the placement itself is unusable. Collapsing them to one message would
779/// hide that. The reference evaluator reports an undefined roll (tangent
780/// parallel to the up reference) and a distance past the curve's end as
781/// invalid input, and a degenerate curve piece as degenerate.
782fn refusal_detail(error: &GeomError) -> &'static str {
783 match error {
784 GeomError::Unsupported { .. } | GeomError::UnsupportedInput { .. } => {
785 "the evaluator cannot measure distance on this curve family"
786 }
787 GeomError::InvalidInput(_) => {
788 "the evaluator rejected the measure: it lies off the curve, or roll is \
789 undefined because the curve tangent is parallel to the up reference"
790 }
791 GeomError::Degenerate(_) => "the evaluator found the basis curve degenerate there",
792 _ => "the evaluator refused this placement",
793 }
794}