Skip to main content

ifc_geometry/constraint/placement/derive/
path.rs

1//! A basis curve that lowers to a curve relation, as Axiolid's neutral
2//! [`CurvePath`] (#418).
3//!
4//! A plain `IfcCompositeCurve`, an `IfcTrimmedCurve`, a composite of
5//! `IfcCurveSegment`s placed by `IfcAxis2PlacementLinear`s and an offset
6//! curve (`IfcOffsetCurve2D`, `IfcOffsetCurve3D`,
7//! `IfcOffsetCurveByDistances`, #414) lower to curve relations (#346), which the evaluator's single-curve queries cannot
8//! read. Since `axiolid-curve-evaluate-contract` 0.3.4 (axiolid/kernel#290)
9//! an evaluator reads such a basis as a `CurvePath`: spans of atomic curves
10//! laid end to end in their station measure, each forwards or backwards and
11//! carried by a rigid placement, through its `path_*` queries.
12//!
13//! The path is built here from the stored relation the station lowering
14//! already reads (`lower::station::relation`), never from an execution
15//! provider (ADR 0004): the pieces, their spans and their senses are data.
16//! The one step that is evaluation, framing the station a segment is placed
17//! at, is asked of the caller's evaluator, and composed as Axiolid composes
18//! a node placed at a station (`axiolid-mesh-compile`'s
19//! `station::placement`): the station's section frame `(tangent, left, up)`,
20//! in plan when the station says so, turned by its orientation, at the point
21//! its offsets locate. A segment on a seam of the curve it is placed along
22//! is framed from the side its station names. Each placement is exact only
23//! where the frame it is read in is (a line, or a path the evaluator calls
24//! exact there).
25//!
26//! A piece's span is stated in its own measure, an offset piece's in its
27//! own length. Where that is a quadrature (an offset beside a gradient
28//! curve, a spiral, an ellipse or a B-spline, a variable offset of a
29//! circle, an ellipse or a B-spline piece whole) only an execution provider
30//! computes it, so the piece is left open (#427): `PathPiece::whole`, which
31//! runs to its curve's end, resolved by the evaluator to its own length of
32//! the curve (`axiolid-curve-evaluate-contract` 0.3.6, axiolid/kernel#298),
33//! so the distance runs through the path as through the stated path the
34//! kernel flattens the same relation into. A trim of an ellipse or a
35//! B-spline at an interior parameter, at a point, or at an arc length in
36//! its sense from a parameter `0` where its measure starts (the CUBIC
37//! transition's Bezier) is bounded there (#436): `PathPiece::bounded`, a
38//! `PathBound::Parameter` or `PathBound::Point` in the curve's own
39//! coordinates, or a stated distance for the arc length
40//! (`axiolid-curve-evaluate-contract` 0.3.7, axiolid/kernel#304). The
41//! evaluator resolves a point to the one parameter naming it, refusing
42//! one off the curve ([`GeometryError::PathPointOffCurve`]) or one several
43//! parameters name ([`GeometryError::PathPointAmbiguous`]), and a closed
44//! conic's span runs across its parameter seam as the compiler's periodic
45//! trim does. A span between distances along a relation (a trim of it, an
46//! offset by distances along it) may reach such a piece only if it is the
47//! last and every piece before it is stated; any other is refused by
48//! [`GeometryError::PathPieceLengthUnstated`] (`relation::pieces_between`).
49//!
50//! # Joints of an open path (#427, #436)
51//!
52//! Where a joint follows an open or bounded piece, its distance is the
53//! evaluator's, not stored data, so it is not snapped to here as a stated
54//! path's joints are. As the kernel does for the same basis's station
55//! (#423, axiolid/kernel#294), the joints are certified instead: those
56//! that can fall within the window this crate snaps within (the model's
57//! precision, capped at 1 mm, or rounding: `seams::window`), each by
58//! [`CurveEvaluator::path_joint_distances_within`] (axiolid/kernel#305) to
59//! a thousandth of it (`open::WINDOW_CERTIFICATION`), and a stated piece's
60//! own seams after them, offset by the same interval. A `DistanceAlong`
61//! whose window holds exactly one of them wholly is read ON it, from the
62//! incoming side (IFC4.3 ADD2 8.9.3.48.3; [`SeamSide::Incoming`]): the end
63//! of the path cut there, read backwards from its end, so the point is the
64//! joint's own wherever the evaluator measures it. Two seams in the window,
65//! a seam whose interval straddles its edge, and a joint the evaluator
66//! cannot certify are refused by
67//! [`GeometryError::PlacementSeamWindowRefused`], as the kernel refuses the
68//! station. Only the pieces before the window and within reach of it are
69//! certified: a piece the evaluator cannot certify after the placement no
70//! longer refuses it, one before it does. The kernel's own station
71//! resolution (`axiolid-evaluate` 0.3.13) also certifies the piece that
72//! holds the station, so where that piece is the uncertifiable one the
73//! lowered station is refused while the placement derives. An evaluator
74//! that reads stated paths but not open ends or bounds, or does not
75//! certify joints, is refused by
76//! [`GeometryError::CurvePathOpenEndUnsupported`],
77//! [`GeometryError::CurvePathBoundUnsupported`] or
78//! [`GeometryError::PathJointDistancesUnsupported`], never read on an
79//! estimate.
80//!
81//! The tests build the same relation's path with `axiolid-mesh-compile`'s
82//! `station::curve_path` and compare the two.
83
84use axiolid_contracts::GeomError;
85use axiolid_core::{Scalar, Transform3, Vec3};
86use axiolid_curve::{Curve2, Curve3, CurvePath, PathCurve, PathOffset, PathPiece};
87use axiolid_curve_evaluate_contract::{
88    CurveEvaluator, CurveMeasure, CurveMeasure as KernelMeasure, DistanceConvention, SeamSide,
89    CURVE_PATH_UNSUPPORTED, OPEN_PATH_END_UNSUPPORTED, PATH_JOINT_DISTANCES_UNSUPPORTED,
90    PATH_PIECE_BOUND_UNSUPPORTED, PATH_POINT_AMBIGUOUS, PATH_POINT_OFF_CURVE,
91    SEAM_SIDE_UNSUPPORTED,
92};
93use axiolid_model::{NodeId, OrientedCurveStation, StationFrame};
94use ifc_alignment::{CurveMeasure as IfcMeasure, PointByDistance};
95use ifc_model::{EntityId, Model};
96
97use super::{basis_curve, model_precision, offset_frame, refusal_detail, snap, Basis};
98
99use crate::error::{GeometryError, GeometryResult};
100use crate::lower::curve::lower_curve_node;
101use crate::lower::session::{AtomicCurve, LoweringSession};
102use crate::lower::station::relation::{relation_pieces, relation_run, Piece, INEXACT};
103use crate::lower::station::seams::{window, Seam};
104
105mod open;
106
107#[cfg(test)]
108pub(crate) use open::WINDOW_CERTIFICATION;
109use open::{read_open, OpenRefusal};
110
111use crate::transform::Transform;
112use crate::units::UnitScale;
113
114/// Most stations a basis may be placed through, nested, before it is
115/// refused (Axiolid's own limit on nested relations and placements).
116const MAX_DEPTH: usize = 64;
117
118/// A basis curve read as a curve path.
119#[derive(Debug, Clone)]
120pub(super) struct PathBasis {
121    /// The path, its placements resolved.
122    pub path: CurvePath,
123    /// Where its tangent may jump.
124    pub seams: PathSeams,
125    /// The distance IFC states along it: plan distance when every piece is
126    /// a gradient curve, arc length when none is.
127    pub convention: DistanceConvention,
128}
129
130/// Where a path's tangent may jump.
131#[derive(Debug, Clone)]
132pub(super) enum PathSeams {
133    /// Every length stated: every interior joint and every seam of a piece
134    /// inside it, ascending, in the path's distance.
135    Stated(Vec<Seam>),
136    /// A piece left open (#427) or bounded (#436): each stated piece's own
137    /// seams, at their distance into it, with its index. The joints are the
138    /// evaluator's.
139    Open(Vec<(usize, Seam)>),
140}
141
142/// Derive the placement along a basis read as a curve path (#418, module
143/// documentation).
144pub(super) fn derive_on_path(
145    model: &Model,
146    units: &UnitScale,
147    placement: EntityId,
148    expression: &PointByDistance,
149    basis: &PathBasis,
150    evaluator: &dyn CurveEvaluator,
151) -> GeometryResult<Transform> {
152    let unsupported = |detail: &'static str| GeometryError::Unsupported {
153        entity: placement,
154        type_name: "IFCLINEARPLACEMENT".into(),
155        detail,
156    };
157    let basis_id = expression.basis_curve;
158    let typed = |error: &GeomError| path_refusal(error, placement, basis_id);
159    // A parameter is refused with the basis (`basis_curve`).
160    let IfcMeasure::Length(value) = expression.distance_along else {
161        return Err(unsupported(RELATION_PARAMETER));
162    };
163    let distance = units.length(value);
164    let path = &basis.path;
165    let convention = evaluator.path_distance_convention(path);
166    if convention != basis.convention {
167        if convention != DistanceConvention::Unsupported {
168            return Err(unsupported(DIFFERENT_DISTANCE));
169        }
170        // An evaluator that cannot measure the path: one without curve
171        // paths at all, or one that refuses this path (pieces that do not
172        // meet, a piece it does not know). Its answer tells which.
173        return Err(
174            match evaluator.path_frame_at(path, KernelMeasure::Distance(distance)) {
175                Err(error) => typed(&error).unwrap_or(unsupported(UNMEASURED_PATH)),
176                Ok(_) => unsupported(UNMEASURED_PATH),
177            },
178        );
179    }
180    let seams = match &basis.seams {
181        PathSeams::Stated(seams) => seams,
182        PathSeams::Open(inner) => {
183            let precision = model_precision(model, units, placement)?;
184            let frame = read_open(
185                evaluator,
186                path,
187                inner,
188                distance,
189                window(precision, distance),
190                SeamSide::Incoming,
191            )
192            .map_err(|refusal| match refusal {
193                OpenRefusal::Window(refusal) => GeometryError::PlacementSeamWindowRefused {
194                    placement,
195                    basis: basis_id,
196                    distance,
197                    refusal,
198                },
199                OpenRefusal::Evaluator(error) => {
200                    typed(&error).unwrap_or_else(|| unsupported(refusal_detail(&error)))
201                }
202            })?;
203            return offset_frame(&frame, expression, units).ok_or(unsupported(VERTICAL_BASIS));
204        }
205    };
206    let frame = match snap(model, units, placement, seams, distance)? {
207        // On a joint or a seam the previous segment governs (8.9.3.48.3).
208        Some(seam) => evaluator
209            .path_frame_at_on(path, KernelMeasure::Distance(seam), SeamSide::Incoming)
210            .map_err(|error| match error {
211                GeomError::UnsupportedInput { input, .. } if input == SEAM_SIDE_UNSUPPORTED => {
212                    GeometryError::SeamSideUnsupported {
213                        placement,
214                        basis: expression.basis_curve,
215                        distance: seam,
216                    }
217                }
218                other => typed(&other).unwrap_or_else(|| unsupported(refusal_detail(&other))),
219            })?,
220        None => evaluator
221            .path_frame_at(path, KernelMeasure::Distance(distance))
222            .map_err(|error| {
223                typed(&error).unwrap_or_else(|| unsupported(refusal_detail(&error)))
224            })?,
225    };
226    offset_frame(&frame, expression, units).ok_or(unsupported(VERTICAL_BASIS))
227}
228
229/// The basis curve of `placement` read as the neutral [`CurvePath`] its
230/// derivation evaluates (#418): a plain `IfcCompositeCurve`, an
231/// `IfcTrimmedCurve` or a composite of segments placed at stations, as the
232/// station lowering flattens it, each segment's placement framed through
233/// `evaluator` (module documentation).
234///
235/// This is the path [`derive_placement_transform`](super::derive_placement_transform) hands to
236/// [`CurveEvaluator::path_frame_at_on`]. It is public so a caller can check
237/// it, or read the same basis through the contract's other `path_*`
238/// queries.
239///
240/// # Errors
241///
242/// A basis that is not a curve relation this module reads, a relation the
243/// station lowering refuses (an offset of an offset, say), a relation
244/// holding a span whose ends its data states in no form a path piece takes
245/// ([`GeometryError::PathPieceLengthUnstated`]), and a placement
246/// `evaluator` refuses to frame,
247/// by name; [`GeometryError::CurvePathUnsupported`] when a segment is placed
248/// along a curve relation and `evaluator` reads single curves only.
249pub fn basis_curve_path(
250    model: &Model,
251    units: &UnitScale,
252    placement: EntityId,
253    basis: EntityId,
254    evaluator: &dyn CurveEvaluator,
255) -> GeometryResult<CurvePath> {
256    match basis_curve(model, units, placement, basis, false, evaluator)? {
257        Basis::Path(basis) => Ok(basis.path),
258        Basis::Curve(..) => Err(GeometryError::Unsupported {
259            entity: placement,
260            type_name: model
261                .get(basis)
262                .map_or_else(String::new, |entity| entity.type_name.to_string()),
263            detail: "the basis curve is a single curve, not a curve relation",
264        }),
265    }
266}
267
268/// Why a relation basis the evaluator measures differently is refused.
269const DIFFERENT_DISTANCE: &str =
270    "the evaluator measures a different distance along this basis curve than IFC states (plan \
271     distance on an alignment, arc length on a polyline or a composite curve)";
272
273/// Why a relation basis the evaluator cannot measure is refused.
274const UNMEASURED_PATH: &str =
275    "the evaluator cannot measure a distance along this basis curve relation: its pieces do not \
276     meet, are measured differently, or include a curve family it does not read";
277
278/// Why a placement on a vertical tangent is refused.
279pub(super) const VERTICAL_BASIS: &str =
280    "the basis curve is vertical there, so OffsetLateral has no \
281                              horizontal direction and the placement no roll";
282
283/// Why an `IfcParameterValue` along a curve relation is refused.
284pub(super) const RELATION_PARAMETER: &str =
285    "an IfcParameterValue DistanceAlong on a basis curve that is a curve relation (a composite \
286     or trimmed curve): its segments' parameters do not run through it, and IFC4.3 ADD2 measures \
287     IfcCurveSegments by length; state an IfcLengthMeasure";
288
289/// Why a segment whose placement the evaluator refused is refused.
290const PLACED_SEGMENT: &str =
291    "a segment of the basis curve is placed at a station of another curve, and the curve \
292     evaluator refused to frame that station";
293
294/// Why a segment placed on a seam the evaluator reads only one side of is
295/// refused.
296const PLACED_ON_SEAM: &str =
297    "a segment of the basis curve is placed at a station on a tangent discontinuity of another \
298     curve, where IFC4.3 ADD2 (8.9.3.48.3) takes the previous segment's tangent, and the curve \
299     evaluator reads only the segment that starts there";
300
301/// Why a placement whose station frame this bridge does not know is
302/// refused.
303const STATION_FRAME: &str =
304    "a segment of the basis curve is placed at a station in a frame other than the section or \
305     the plan frame";
306
307/// Why a segment placed at a station whose orientation is degenerate is
308/// refused.
309const ORIENTATION: &str =
310    "a segment of the basis curve is placed at a station whose Axis or RefDirection is zero, \
311     not finite, or whose Axis and RefDirection are parallel";
312
313/// Why a segment placed where the curve is vertical is refused.
314const VERTICAL: &str =
315    "a segment of the basis curve is placed at a station where the curve it is placed along is \
316     vertical, so its left and its plan direction are undefined";
317
318/// `basis`, the basis curve of `placement`, lowered and read as a
319/// [`PathBasis`]: a curve relation's pieces, or an atomic curve as one
320/// piece, whole.
321///
322/// # Errors
323///
324/// A basis that does not lower, or whose relation the station lowering
325/// refuses (an offset of an offset, a mix of plan-measured and arc-length
326/// pieces, a piece whose length its data does not state), by name; a placement
327/// the evaluator refuses to frame, and an evaluator without curve paths,
328/// as [`resolve_placement`].
329pub(super) fn path_basis(
330    model: &Model,
331    units: &UnitScale,
332    placement: EntityId,
333    basis: EntityId,
334    type_name: &str,
335    evaluator: &dyn CurveEvaluator,
336) -> GeometryResult<PathBasis> {
337    let mut session = LoweringSession::new(model, units);
338    let node = lower_curve_node(&mut session, basis, Transform::identity())?;
339    let reader = Reader {
340        session: &session,
341        evaluator,
342        placement,
343        basis,
344    };
345    let refused = |reason: &'static str| {
346        if reason == INEXACT {
347            GeometryError::PathPieceLengthUnstated { placement, basis }
348        } else {
349            GeometryError::Unsupported {
350                entity: placement,
351                type_name: type_name.to_owned(),
352                detail: reason,
353            }
354        }
355    };
356    let convention = |plan: bool| {
357        if plan {
358            DistanceConvention::PlanDistance
359        } else {
360            DistanceConvention::ArcLength3d
361        }
362    };
363    match relation_run(&session, node) {
364        Ok(run) => Ok(PathBasis {
365            path: reader.path(&run.pieces, 0)?,
366            seams: PathSeams::Stated(run.seams),
367            convention: convention(run.plan),
368        }),
369        // A piece whose length is a quadrature: read open (#427).
370        Err(reason) if reason == INEXACT => {
371            let (pieces, plan) = relation_pieces(&session, node).map_err(refused)?;
372            Ok(PathBasis {
373                path: reader.path(&pieces, 0)?,
374                seams: PathSeams::Open(inner_seams(&pieces)),
375                convention: convention(plan),
376            })
377        }
378        Err(reason) => Err(refused(reason)),
379    }
380}
381
382/// Each piece's own seams strictly inside it, with its index.
383fn inner_seams(pieces: &[Piece<'_>]) -> Vec<(usize, Seam)> {
384    pieces
385        .iter()
386        .enumerate()
387        .flat_map(|(index, piece)| piece.inner_seams().map(move |seam| (index, seam)))
388        .collect()
389}
390
391/// The typed refusal an evaluator's answer names, if it is one of a
392/// capability it lacks (curve paths, open ends, piece bounds, certified
393/// joints) or a trim point it cannot resolve (#436).
394fn path_refusal(error: &GeomError, placement: EntityId, basis: EntityId) -> Option<GeometryError> {
395    let GeomError::UnsupportedInput { input, .. } = error else {
396        return None;
397    };
398    let input = *input;
399    if input == CURVE_PATH_UNSUPPORTED {
400        Some(GeometryError::CurvePathUnsupported { placement, basis })
401    } else if input == OPEN_PATH_END_UNSUPPORTED {
402        Some(GeometryError::CurvePathOpenEndUnsupported { placement, basis })
403    } else if input == PATH_PIECE_BOUND_UNSUPPORTED {
404        Some(GeometryError::CurvePathBoundUnsupported { placement, basis })
405    } else if input == PATH_POINT_OFF_CURVE {
406        Some(GeometryError::PathPointOffCurve { placement, basis })
407    } else if input == PATH_POINT_AMBIGUOUS {
408        Some(GeometryError::PathPointAmbiguous { placement, basis })
409    } else if input == PATH_JOINT_DISTANCES_UNSUPPORTED {
410        Some(GeometryError::PathJointDistancesUnsupported { placement, basis })
411    } else {
412        None
413    }
414}
415
416/// The lowered basis and what is needed to read it.
417struct Reader<'r, 'a> {
418    session: &'r LoweringSession<'a>,
419    evaluator: &'r dyn CurveEvaluator,
420    /// The `IfcLinearPlacement` being derived.
421    placement: EntityId,
422    /// Its basis curve.
423    basis: EntityId,
424}
425
426impl Reader<'_, '_> {
427    /// The pieces as path pieces, their placements resolved.
428    fn path(&self, pieces: &[Piece<'_>], depth: usize) -> GeometryResult<CurvePath> {
429        pieces
430            .iter()
431            .map(|piece| self.piece(piece, depth))
432            .collect()
433    }
434
435    /// One piece as a path piece, its placements resolved: an offset piece
436    /// (#414) as `PathCurve::Offset` of its base span and law, in its own
437    /// measure `[0, L]`, as `axiolid-mesh-compile` hands it out.
438    fn piece(&self, piece: &Piece<'_>, depth: usize) -> GeometryResult<PathPiece> {
439        let curve = match &piece.offset {
440            Some(offset) => PathCurve::Offset(Box::new(PathOffset::new(
441                self.piece(&offset.base, depth)?,
442                offset.law,
443            ))),
444            None => path_curve(piece.curve),
445        };
446        let mut out = span(curve, piece);
447        if piece.reversed {
448            out = out.reversed();
449        }
450        for station in &piece.placements {
451            let (rigid, exact) = self.placement(station, depth + 1)?;
452            out = out.placed(rigid, exact);
453        }
454        Ok(out)
455    }
456
457    /// The rigid motion of a node placed at `station`, and whether it is
458    /// exact (module documentation).
459    fn placement(
460        &self,
461        station: &OrientedCurveStation,
462        depth: usize,
463    ) -> GeometryResult<(Transform3, bool)> {
464        if depth > MAX_DEPTH {
465            return Err(self.unsupported(crate::lower::station::relation::TOO_DEEP));
466        }
467        let at = station.station.station.distance;
468        let measure = CurveMeasure::Distance(at);
469        let side = station.seam;
470        let basis = station.station.basis;
471        let (frame, exact) = match self.session.atomic_curve(basis) {
472            Some(AtomicCurve::Three(curve)) => (
473                self.evaluator.frame_at_on(curve, measure, side),
474                matches!(curve, Curve3::Line(_)),
475            ),
476            Some(AtomicCurve::Two(curve)) => {
477                // The contract reads a 2D curve as a path piece: the whole
478                // curve, or for a line, which a station reads unbounded,
479                // the span from its origin through the station.
480                let (piece, distance) = match curve {
481                    Curve2::Line(line) => {
482                        let length = line.direction.length();
483                        let start = at.min(0.0);
484                        (
485                            PathPiece::new(path_curve2(curve), start, length.max(at)),
486                            at - start,
487                        )
488                    }
489                    _ => {
490                        let run = self.run(basis)?;
491                        let Some(piece) = run.first() else {
492                            return Err(self.unsupported(PLACED_SEGMENT));
493                        };
494                        (span(path_curve2(curve), piece), at)
495                    }
496                };
497                let path = CurvePath::from(piece);
498                let distance = CurveMeasure::Distance(distance);
499                (
500                    self.evaluator.path_frame_at_on(&path, distance, side),
501                    matches!(curve, Curve2::Line(_)),
502                )
503            }
504            None => {
505                let pieces = self.run(basis)?;
506                let path = self.path(&pieces, depth)?;
507                if !pieces.iter().all(Piece::is_stated) {
508                    // Along a path with an open or bounded piece (#427,
509                    // #436) the station is read within its own
510                    // seam-snapping window, as the kernel reads it (module
511                    // documentation); never exact.
512                    let frame = read_open(
513                        self.evaluator,
514                        &path,
515                        &inner_seams(&pieces),
516                        at,
517                        station.seam_window,
518                        side,
519                    )
520                    .map_err(|refusal| match refusal {
521                        OpenRefusal::Window(refusal) => GeometryError::PlacementSeamWindowRefused {
522                            placement: self.placement,
523                            basis: self.basis,
524                            distance: at,
525                            refusal,
526                        },
527                        OpenRefusal::Evaluator(error) => self.placement_refused(&error),
528                    })?;
529                    (Ok(frame), false)
530                } else {
531                    (
532                        self.evaluator.path_frame_at_on(&path, measure, side),
533                        self.evaluator.path_frame_is_exact_at(&path, measure, side),
534                    )
535                }
536            }
537        };
538        let frame = frame.map_err(|error| self.placement_refused(&error))?;
539        let section = Section::from_tangent(frame.origin, frame.x)
540            .ok_or_else(|| self.unsupported(VERTICAL))?;
541        let section = match station.station.frame {
542            StationFrame::Section => section,
543            StationFrame::Plan => section.plan().ok_or_else(|| self.unsupported(VERTICAL))?,
544            _ => return Err(self.unsupported(STATION_FRAME)),
545        };
546        let offsets = station.station.station.offsets;
547        let point = section.place(offsets.lateral, offsets.vertical, offsets.longitudinal);
548        let turned = if station.orientation.is_base() {
549            section
550        } else {
551            let (axis, reference) = station
552                .orientation
553                .unit_axes()
554                .map_err(|_| self.unsupported(ORIENTATION))?;
555            section
556                .oriented(axis, reference)
557                .ok_or_else(|| self.unsupported(ORIENTATION))?
558        };
559        Ok((
560            Transform3::from_cols(turned.tangent, turned.lateral, turned.up, point),
561            exact,
562        ))
563    }
564
565    /// The pieces of the curve a segment is placed along, any whose length
566    /// is a quadrature left open (#427), any trim of an ellipse or a
567    /// B-spline bounded (#436).
568    fn run(&self, node: NodeId) -> GeometryResult<Vec<Piece<'_>>> {
569        relation_pieces(self.session, node)
570            .map(|(pieces, _)| pieces)
571            .map_err(|reason| {
572                if reason == INEXACT {
573                    GeometryError::PathPieceLengthUnstated {
574                        placement: self.placement,
575                        basis: self.basis,
576                    }
577                } else {
578                    self.unsupported(reason)
579                }
580            })
581    }
582
583    fn unsupported(&self, detail: &'static str) -> GeometryError {
584        GeometryError::Unsupported {
585            entity: self.placement,
586            type_name: "IFCLINEARPLACEMENT".into(),
587            detail,
588        }
589    }
590
591    /// The evaluator's refusal to frame a placement's station, by name.
592    fn placement_refused(&self, error: &GeomError) -> GeometryError {
593        if let Some(typed) = path_refusal(error, self.placement, self.basis) {
594            return typed;
595        }
596        match error {
597            GeomError::UnsupportedInput { input, .. } if *input == SEAM_SIDE_UNSUPPORTED => {
598                self.unsupported(PLACED_ON_SEAM)
599            }
600            _ => self.unsupported(PLACED_SEGMENT),
601        }
602    }
603}
604
605/// The span `piece` keeps of `curve`, forwards and unplaced: stated, or
606/// with an end the evaluator resolves. A piece whose length is a
607/// quadrature runs to its curve's end (#427); a trim of an ellipse or a
608/// B-spline at an interior parameter or a point is bounded there (#436),
609/// either end possibly a stated distance.
610fn span(curve: PathCurve, piece: &Piece<'_>) -> PathPiece {
611    let mut out = if piece.open {
612        PathPiece::to_end(curve, piece.start)
613    } else {
614        PathPiece::new(curve, piece.start, piece.end)
615    };
616    if let Some(bound) = piece.start_bound {
617        out = out.with_start(bound);
618    }
619    if let Some(bound) = piece.end_bound {
620        out = out.with_end(bound);
621    }
622    out
623}
624
625/// A stored curve as a path piece's curve.
626fn path_curve(curve: &AtomicCurve) -> PathCurve {
627    match curve {
628        AtomicCurve::Two(curve) => path_curve2(curve),
629        AtomicCurve::Three(curve) => PathCurve::Three(curve.clone()),
630    }
631}
632
633fn path_curve2(curve: &Curve2) -> PathCurve {
634    PathCurve::Two(curve.clone())
635}
636
637/// A section frame: point, unit tangent, left lateral and up, as Axiolid's
638/// `SectionFrame` (repeated here because that crate is not linked).
639#[derive(Debug, Clone, Copy)]
640struct Section {
641    point: Vec3,
642    tangent: Vec3,
643    lateral: Vec3,
644    up: Vec3,
645}
646
647impl Section {
648    /// The reference-up section at `point` with unit `tangent`, built from
649    /// the tangent alone as the derived placement frame is (the module
650    /// documentation of `derive`): `lateral = normalise(Z x tangent)`,
651    /// `up = tangent x lateral`. `None` where the tangent is vertical.
652    fn from_tangent(point: Vec3, tangent: Vec3) -> Option<Self> {
653        let horizontal = (tangent.x * tangent.x + tangent.y * tangent.y).sqrt();
654        if !horizontal.is_finite() || horizontal <= 1e-12 {
655            return None;
656        }
657        let lateral = Vec3::new(-tangent.y / horizontal, tangent.x / horizontal, 0.0);
658        Some(Self {
659            point,
660            tangent,
661            lateral,
662            up: tangent.cross(lateral),
663        })
664    }
665
666    /// The same point framed vertically: the tangent's horizontal
667    /// projection, the horizontal left normal and `+Z`.
668    fn plan(&self) -> Option<Self> {
669        let horizontal = Vec3::new(self.tangent.x, self.tangent.y, 0.0);
670        let length = horizontal.length();
671        if !length.is_finite() || length <= 1e-12 {
672            return None;
673        }
674        let tangent = horizontal / length;
675        Some(Self {
676            point: self.point,
677            tangent,
678            lateral: Vec3::new(-tangent.y, tangent.x, 0.0),
679            up: Vec3::Z,
680        })
681    }
682
683    /// The point `lateral` to the left, `vertical` up and `longitudinal`
684    /// along the tangent.
685    fn place(&self, lateral: Scalar, vertical: Scalar, longitudinal: Scalar) -> Vec3 {
686        self.point + lateral * self.lateral + vertical * self.up + longitudinal * self.tangent
687    }
688
689    /// The axes turned by a unit `axis` and unit `reference`, components in
690    /// this frame: Gram-Schmidt with the axis primary, as the station
691    /// lowering states an `IfcAxis2PlacementLinear`'s `Axis` and
692    /// `RefDirection` (`lower::station::axes`). `None` when they are
693    /// parallel.
694    fn oriented(&self, axis: Vec3, reference: Vec3) -> Option<Self> {
695        let unit = |vector: Vec3| {
696            let length = vector.length();
697            (vector.is_finite() && length.is_finite() && length > 1e-12).then(|| vector / length)
698        };
699        let axis = unit(axis)?;
700        let reference = unit(reference)?;
701        // Axiolid's `ORIENTATION_TOLERANCE`.
702        if axis.cross(reference).length() <= 1e-9 {
703            return None;
704        }
705        let x = (reference - reference.dot(axis) * axis).normalize();
706        let y = axis.cross(x);
707        let world = |v: Vec3| v.x * self.tangent + v.y * self.lateral + v.z * self.up;
708        Some(Self {
709            point: self.point,
710            tangent: world(x),
711            lateral: world(y),
712            up: world(axis),
713        })
714    }
715}