ifc_alignment/cant/layout.rs
1//! Ordering, continuity, and station-query assembly for `IfcAlignmentCant`.
2//!
3//! This is the "parent/layout curve assembly" `ALIGN-CANT` names: given the
4//! parent `IfcAlignmentCant`, resolve its nested segments in authored order,
5//! validate that each segment's start cant agrees with the previous
6//! segment's end cant (C0 continuity -- cant profiles are not required to be
7//! tangent-continuous the way horizontal/vertical curves are), and expose a
8//! single station-domain query across the whole profile.
9
10use ifc_model::{EntityId, Model};
11
12use crate::cant::evaluate::{cant_within, CantAtStation};
13use crate::cant::segment::{read_cant_segment, CantSegment, CantSegmentType};
14use crate::curve::terminal::split_closing;
15use crate::curve::SeamTolerance;
16use crate::error::{AlignmentError, AlignmentResult};
17use crate::horizontal::AlignmentUnits;
18use crate::view::AlignmentView;
19
20/// One resolved, ordered, continuity-checked cant profile.
21#[derive(Debug, Clone, PartialEq)]
22#[non_exhaustive]
23pub struct CantLayout {
24 /// The `IfcAlignmentCant` entity this layout was resolved from.
25 pub entity: EntityId,
26 /// `RailHeadDistance`: track gauge used to convert cant to superelevation
27 /// angle, in metres.
28 pub rail_head_distance: f64,
29 segments: Vec<CantSegment>,
30 /// How far a Viennese bend's two rotation points may differ and still
31 /// stay put: the model's declared precision, as the banked lowering
32 /// compares them.
33 pivot_tolerance: SeamTolerance,
34}
35
36impl CantLayout {
37 /// Resolve `IfcAlignmentCant#entity`'s nested `IfcAlignmentSegment`
38 /// chain into an ordered, continuity-checked cant profile.
39 ///
40 /// The zero-length segment IFC4.3 requires at the end of a layout is
41 /// kept in [`Self::segments`]; its station and start cant are checked
42 /// against the previous segment's end like any seam. A zero-length
43 /// segment anywhere else, or as the only segment, is refused
44 /// ([`AlignmentError::SemanticViolation`]).
45 ///
46 /// A layout with a `VIENNESEBEND` also reads the model's declared
47 /// precision ([`SeamTolerance::for_model`]), the tolerance its rotation
48 /// points are compared at, and refuses what that refuses.
49 pub fn resolve(
50 model: &Model,
51 entity: EntityId,
52 units: AlignmentUnits,
53 ) -> AlignmentResult<Self> {
54 let view = AlignmentView::for_model(model)?;
55 let cant_entity = model
56 .get(entity)
57 .ok_or(AlignmentError::MissingEntity { entity })?;
58 if !view.schema.is_a(&cant_entity.type_name, "IfcAlignmentCant") {
59 return Err(AlignmentError::WrongType {
60 entity,
61 expected: "IfcAlignmentCant",
62 actual: cant_entity.type_name.to_string(),
63 });
64 }
65 // IFC4X3_ADD2: IfcAlignmentCant contributes exactly one attribute,
66 // RailHeadDistance, past the inherited IfcRoot/IfcObject/IfcProduct/
67 // IfcLinearElement slots.
68 let rail_head_distance = cant_entity
69 .attributes
70 .last()
71 .and_then(|value| value.unwrap_typed().as_f64())
72 .ok_or(AlignmentError::InvalidAttribute {
73 entity,
74 index: cant_entity.attributes.len().saturating_sub(1),
75 name: "RailHeadDistance",
76 })?
77 * units.length_to_metres;
78 if !(rail_head_distance.is_finite() && rail_head_distance > 0.0) {
79 return Err(AlignmentError::InvalidAttribute {
80 entity,
81 index: cant_entity.attributes.len().saturating_sub(1),
82 name: "RailHeadDistance",
83 });
84 }
85
86 let ids = view.segment_chain(entity, "IfcAlignmentCantSegment")?;
87 if ids.is_empty() {
88 return Err(AlignmentError::SemanticViolation {
89 entity: Some(entity),
90 rule: "IfcAlignmentCant must nest at least one IfcAlignmentSegment",
91 });
92 }
93 let mut segments = Vec::with_capacity(ids.len());
94 for id in ids {
95 segments.push(read_cant_segment(model, id, units)?);
96 }
97 // IFC4.3 closes every layout with a zero-length segment; one
98 // anywhere else is refused. The closing segment stays in the layout
99 // and its start cant is checked below like any seam.
100 split_closing(&segments, |s| s.horizontal_length, |s| s.entity)?;
101
102 // Ordering by nesting order is authoritative (IFC4X3 does not use a
103 // numeric sequence field here), but a malformed file could still
104 // nest segments out of distance order or with gaps/overlaps; check
105 // explicitly rather than trusting nesting order blindly.
106 for pair in segments.windows(2) {
107 let [previous, next] = pair else {
108 unreachable!()
109 };
110 let previous_end = previous.start_dist_along + previous.horizontal_length;
111 if (next.start_dist_along - previous_end).abs() > 1e-6 {
112 return Err(AlignmentError::SemanticViolation {
113 entity: Some(next.entity),
114 rule: "cant segments must be contiguous in StartDistAlong order",
115 });
116 }
117 let previous_end_left = previous.end_cant_left.unwrap_or(previous.start_cant_left);
118 let previous_end_right = previous.end_cant_right.unwrap_or(previous.start_cant_right);
119 if (previous_end_left - next.start_cant_left).abs() > 1e-9
120 || (previous_end_right - next.start_cant_right).abs() > 1e-9
121 {
122 return Err(AlignmentError::SemanticViolation {
123 entity: Some(next.entity),
124 rule: "cant segments must be C0 continuous: end cant must equal the next segment's start cant",
125 });
126 }
127 }
128
129 // Only a Viennese bend compares rotation points, so only a layout
130 // with one reads the precision; every other layout resolves as it
131 // did before #312.
132 let pivot_tolerance = if segments
133 .iter()
134 .any(|segment| segment.predefined_type == CantSegmentType::VienneseBend)
135 {
136 SeamTolerance::for_model(model, units)?
137 } else {
138 SeamTolerance::strict()
139 };
140
141 Ok(Self {
142 entity,
143 rail_head_distance,
144 segments,
145 pivot_tolerance,
146 })
147 }
148
149 /// The cant layout of `IfcAlignment#alignment`.
150 ///
151 /// Unlike the gradient-curve composition, where a road without cant is
152 /// ordinary, this is the call for work that NEEDS cant (the section
153 /// frames, the `IfcSegmentedReferenceCurve` role), so its absence is a
154 /// refusal rather than `None`.
155 ///
156 /// # Errors
157 ///
158 /// Refuses a model that is not IFC4X3, an entity that is not an
159 /// `IfcAlignment`, an alignment nesting no `IfcAlignmentCant` or several
160 /// of them (`SemanticViolation`: picking one would silently choose a
161 /// track), and everything [`Self::resolve`] refuses.
162 pub fn for_alignment(
163 model: &Model,
164 alignment: EntityId,
165 units: AlignmentUnits,
166 ) -> AlignmentResult<Self> {
167 let view = AlignmentView::for_model(model)?;
168 let entity = model
169 .get(alignment)
170 .ok_or(AlignmentError::MissingEntity { entity: alignment })?;
171 if !view.schema.is_a(&entity.type_name, "IfcAlignment") {
172 return Err(AlignmentError::WrongType {
173 entity: alignment,
174 expected: "IfcAlignment",
175 actual: entity.type_name.to_string(),
176 });
177 }
178 match view
179 .nested_children(alignment, "IfcAlignmentCant")?
180 .as_slice()
181 {
182 [only] => Self::resolve(model, *only, units),
183 [] => Err(AlignmentError::SemanticViolation {
184 entity: Some(alignment),
185 rule: "the alignment nests no IfcAlignmentCant layout",
186 }),
187 _ => Err(AlignmentError::SemanticViolation {
188 entity: Some(alignment),
189 rule: "an alignment with several cant layouts is ambiguous to compose",
190 }),
191 }
192 }
193
194 /// Segments in authored (distance-along) order.
195 #[must_use]
196 pub fn segments(&self) -> &[CantSegment] {
197 &self.segments
198 }
199
200 /// Total distance-along span covered by this profile.
201 #[must_use]
202 pub fn length(&self) -> f64 {
203 self.segments
204 .last()
205 .map(|last| {
206 last.start_dist_along + last.horizontal_length - self.segments[0].start_dist_along
207 })
208 .unwrap_or(0.0)
209 }
210
211 /// Cant at an absolute distance-along value within this profile's span.
212 ///
213 /// Each segment evaluates as [`cant_at`](crate::cant::cant_at) does; a
214 /// `VIENNESEBEND`'s rotation points are compared at the model's declared
215 /// precision, as the banked lowering compares them.
216 ///
217 /// # Errors
218 ///
219 /// Refuses a non-finite distance or one outside the profile's span, and
220 /// everything [`cant_at`](crate::cant::cant_at) refuses, including the
221 /// inside of a Viennese bend whose rotation point moves with neither
222 /// rail held.
223 pub fn cant_at_distance(&self, distance_along: f64) -> AlignmentResult<CantAtStation> {
224 if !distance_along.is_finite() {
225 return Err(AlignmentError::InvalidUnits {
226 detail: "distance along must be finite",
227 });
228 }
229 let segment = self
230 .segments
231 .iter()
232 .find(|segment| {
233 let start = segment.start_dist_along;
234 let end = start + segment.horizontal_length;
235 distance_along >= start - 1e-9 && distance_along <= end + 1e-9
236 })
237 .ok_or(AlignmentError::InvalidUnits {
238 detail: "distance along lies outside the cant profile's span",
239 })?;
240 let xi = if segment.horizontal_length > 0.0 {
241 ((distance_along - segment.start_dist_along) / segment.horizontal_length)
242 .clamp(0.0, 1.0)
243 } else {
244 0.0
245 };
246 cant_within(
247 segment,
248 xi,
249 Some(self.rail_head_distance),
250 self.pivot_tolerance,
251 )
252 }
253}