1use 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
114const MAX_DEPTH: usize = 64;
117
118#[derive(Debug, Clone)]
120pub(super) struct PathBasis {
121 pub path: CurvePath,
123 pub seams: PathSeams,
125 pub convention: DistanceConvention,
128}
129
130#[derive(Debug, Clone)]
132pub(super) enum PathSeams {
133 Stated(Vec<Seam>),
136 Open(Vec<(usize, Seam)>),
140}
141
142pub(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 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 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 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
229pub 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
268const 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
273const 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
278pub(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
283pub(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
289const 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
294const 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
301const 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
307const 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
313const 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
318pub(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 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
382fn 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
391fn 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
416struct Reader<'r, 'a> {
418 session: &'r LoweringSession<'a>,
419 evaluator: &'r dyn CurveEvaluator,
420 placement: EntityId,
422 basis: EntityId,
424}
425
426impl Reader<'_, '_> {
427 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 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 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 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 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 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 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
605fn 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
625fn 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#[derive(Debug, Clone, Copy)]
640struct Section {
641 point: Vec3,
642 tangent: Vec3,
643 lateral: Vec3,
644 up: Vec3,
645}
646
647impl Section {
648 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 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 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 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 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}