ifc_alignment/curve/reference.rs
1//! The cant-carrying 3D centreline: the `IfcSegmentedReferenceCurve` role,
2//! as an exact banked curve (#93).
3//!
4//! IFC4.3 ADD2 represents an alignment with cant as an
5//! `IfcSegmentedReferenceCurve` whose base curve is the `IfcGradientCurve`.
6//! The neutral value is `Curve3::Banked`: the composed centreline
7//! (`Elevated3`, as [`gradient_curve3`](super::gradient_curve3) builds it)
8//! with two laws over plan distance and the rail-head distance:
9//!
10//! - **cant** `D(d) = left - right`, one `CantPiece` per cant segment in the
11//! segment's own `xi = s / L`, exactly the base formula
12//! `IfcAlignmentCantSegmentTypeEnum` (8.7.2.1) states:
13//! `CONSTANTCANT`, `LINEARTRANSITION`, `BLOSSCURVE` `(3 - 2 xi) xi^2`,
14//! `HELMERTCURVE` as its two quadratic halves, `COSINECURVE`, `SINECURVE`,
15//! and `VIENNESEBEND` as its angle form
16//! `psi(xi) = psi1 + dpsi xi^4 (35 - 84 xi + 70 xi^2 - 20 xi^3)` with
17//! `psi = arcsin(D / b)`;
18//! - **pivot** `e(d) = (left + right) / 2`: the rail heads are "measured
19//! relatively to vertical alignment" (`IfcAlignmentCantSegment`), so the
20//! section's rotation point sits midway between them, at the profile for
21//! a rotation about the centreline and at `D / 2` for one about the low
22//! rail. Each rail follows the segment's form, so their mean follows the
23//! same form with the mean values. A `VIENNESEBEND` states the bank angle,
24//! not the rails, so its pivot follows the rule `cant_at` uses (#312,
25//! #364): a rotation point that stays put is a constant piece, and a held
26//! rail (one with the same height at both ends, the low rail say) is a
27//! held-rail piece, `CantPiece::about_rail`, whose rotation point
28//! `held -+ b sin(psi) / 2` Axiolid derives from the bend's angle law
29//! (axiolid/kernel#279, Axiolid ADR 0081 amendment).
30//!
31//! # The convention: rotation about the tangent
32//!
33//! `Banked3` names how a cant reads on a grade, with no default. IFC4.3 ADD2
34//! states cant as an angle: "the cant value D, Railhead distance b and cant
35//! angle psi" are related by `psi = arcsin(D / b)`, psi being the "Angle of
36//! cant (cross slope angle, bank angle)" (`IfcAlignmentCantSegmentTypeEnum`,
37//! 8.7.2.1, Table 8.7.2.1.1.2.A), and the Viennese bend is written for psi
38//! itself. `IfcSegmentedReferenceCurve` (8.9.3.62) carries cant by
39//! interpolating the placement axes (`Axis`, `RefDirection`) between
40//! segments: a rotation of the section frame. So the section is the
41//! level-track section turned by `psi` about the 3D tangent,
42//! `BankConvention::TangentRotation`. On a grade the rail heads then differ
43//! in height by `D cos(theta)`, not `D`; the standard does not ask for the
44//! other reading, and this is the rotation `CantFrame` documents.
45//!
46//! The rail heights `IfcAlignmentCantSegment` states are "measured
47//! relatively to vertical alignment", vertically; the banked section places
48//! them `b / 2` either side of the rotation point square to the point
49//! path's tangent. Where that path climbs at angle `theta` (the grade, plus
50//! the rotation point's own rate when it moves), each rail head therefore
51//! stands `(D / 2)(1 - cos(theta))` closer to the rotation point's height
52//! than `cant_at`'s `e +- D / 2`, and so does a held rail: under
53//! `TangentRotation` it drifts by `(D / 2)(1 - cos(theta))` from its
54//! authored height (Axiolid ADR 0081 amendment), about 0.015 mm for a
55//! 150 mm cant on a 2% grade. On level track the two agree exactly. The
56//! cant, the bank angle and the rotation point agree everywhere.
57//!
58//! # Refusals that remain
59//!
60//! - A Viennese bend whose pivot moves with neither rail held: the
61//! standard does not determine the rails, and `CantLayout` refuses it
62//! with the same error. A pivot that stays put through the bend, such as
63//! rotation about the centreline (#312), or a held rail (#364) lowers, and
64//! agrees with the section frame.
65//! - A cant layout that does not cover the plan from its start to its end:
66//! the banked curve's span is the cant law's, and a station without cant
67//! is not zero cant.
68//! - `USERDEFINED`, `NOTDEFINED` and unknown cant types, which state no law.
69
70use axiolid_curve::{bank_angle, BankConvention, Banked3, CantLaw, CantPiece, Curve3, RailSide};
71use axiolid_model::{GeometryGraphBuilder, GeometryNode};
72use ifc_model::{EntityId, Model};
73
74use super::assemble::{finish, LoweredAlignmentCurve};
75use super::gradient::{compose, sole_layout};
76use super::seam::HorizontalSeam;
77use super::tolerance::SeamTolerance;
78use crate::cant::{viennese_rotation, CantLayout, CantSegment, CantSegmentType, VienneseRotation};
79use crate::error::{AlignmentError, AlignmentResult};
80use crate::horizontal::AlignmentUnits;
81use crate::view::AlignmentView;
82
83/// Lower an `IfcAlignment` with cant to its exact cant-carrying centreline,
84/// a `Curve3::Banked`.
85///
86/// The graph holds one `Curve3::Banked` node: the centreline
87/// [`lower_gradient_curve`](super::lower_gradient_curve) builds, the cant
88/// and pivot laws, and the rail-head distance, under
89/// `BankConvention::TangentRotation` (see the module documentation).
90/// `sources` lists the horizontal, vertical and cant layouts, then the
91/// vertical and cant segments; `seams` are the plan's.
92///
93/// # Errors
94///
95/// - Everything [`CantLayout::for_alignment`] refuses: a wrong entity type,
96/// no `IfcAlignmentCant` or several (`SemanticViolation`), a malformed or
97/// discontinuous cant layout.
98/// - Everything the gradient curve refuses.
99/// - [`AlignmentError::Unsupported`] for a cant layout that does not cover
100/// the whole plan, a cant segment type with no law, and a Viennese bend
101/// whose pivot moves with neither rail held.
102/// - [`AlignmentError::SemanticViolation`] for a cant beyond the rail-head
103/// distance (`|D| > b`) at a segment end; every form is monotone between
104/// its ends, so none exceeds it inside.
105pub fn lower_segmented_reference_curve(
106 model: &Model,
107 alignment: EntityId,
108 units: AlignmentUnits,
109) -> AlignmentResult<LoweredAlignmentCurve> {
110 let banked = banked(model, alignment, units)?;
111 let mut builder = GeometryGraphBuilder::new();
112 let root = builder
113 .push(GeometryNode::Curve3(Curve3::Banked(banked.curve)))
114 .map_err(|error| AlignmentError::Graph {
115 detail: error.to_string(),
116 })?;
117 let mut lowered = finish(builder, root, banked.sources)?;
118 lowered.seams = banked.seams;
119 Ok(lowered)
120}
121
122/// The exact cant-carrying centreline of `alignment`, an `IfcAlignment`.
123///
124/// The composition [`lower_segmented_reference_curve`] uses, returned
125/// directly so a caller can hand it to an evaluator; this crate never
126/// evaluates it.
127///
128/// # Errors
129///
130/// As [`lower_segmented_reference_curve`].
131pub fn segmented_reference_curve3(
132 model: &Model,
133 alignment: EntityId,
134 units: AlignmentUnits,
135) -> AlignmentResult<Curve3> {
136 banked(model, alignment, units).map(|banked| Curve3::Banked(banked.curve))
137}
138
139/// The banked curve and what the graph lowering reports with it.
140struct Lowered {
141 curve: Banked3,
142 sources: Vec<EntityId>,
143 seams: Vec<HorizontalSeam>,
144}
145
146fn banked(model: &Model, alignment: EntityId, units: AlignmentUnits) -> AlignmentResult<Lowered> {
147 // Resolving the cant layout first names a missing or ambiguous one, or a
148 // malformed segment, before anything about the centreline.
149 let cant = CantLayout::for_alignment(model, alignment, units)?;
150 let view = AlignmentView::for_model(model)?;
151 let horizontal = sole_layout(&view, alignment, "IfcAlignmentHorizontal")?;
152 let vertical = sole_layout(&view, alignment, "IfcAlignmentVertical")?;
153 let composed = compose(model, &view, horizontal, vertical, units, Some(&cant))?;
154 let tolerance = SeamTolerance::for_model(model, units)?;
155 let (cant_law, pivot) = cant_laws(&cant, composed.plan_length, tolerance)?;
156 if !(cant_law.is_well_formed() && pivot.is_well_formed()) {
157 return Err(AlignmentError::Graph {
158 detail: format!(
159 "the cant layout {} did not assemble into well-formed laws",
160 cant.entity
161 ),
162 });
163 }
164 let mut sources = vec![horizontal, vertical, cant.entity];
165 sources.extend(composed.vertical_ids);
166 sources.extend(cant.segments().iter().map(|segment| segment.entity));
167 Ok(Lowered {
168 curve: Banked3::new(
169 composed.centreline,
170 cant_law,
171 pivot,
172 cant.rail_head_distance,
173 BankConvention::TangentRotation,
174 ),
175 sources,
176 seams: composed.seams,
177 })
178}
179
180/// The cant and pivot laws of `layout`, from plan distance zero.
181///
182/// The cant layout's stations are distances along the horizontal layout,
183/// the distance the plan is parameterised by, so the laws need no
184/// re-indexing; the layout must start at the plan start and end at its end,
185/// at the model's seam tolerance. The closing zero-length segment adds no
186/// piece.
187fn cant_laws(
188 layout: &CantLayout,
189 plan_length: f64,
190 tolerance: SeamTolerance,
191) -> AlignmentResult<(CantLaw, CantLaw)> {
192 let segments: Vec<&CantSegment> = layout
193 .segments()
194 .iter()
195 .filter(|segment| segment.horizontal_length > 0.0)
196 .collect();
197 let start = segments.first().map_or(0.0, |s| s.start_dist_along);
198 let end = segments
199 .last()
200 .map_or(0.0, |s| s.start_dist_along + s.horizontal_length);
201 if !tolerance.same_length(start, 0.0) || !tolerance.same_length(end, plan_length) {
202 return Err(AlignmentError::Unsupported {
203 entity: layout.entity,
204 type_name: "IfcAlignmentCant".to_owned(),
205 detail: "the cant layout does not cover the whole plan; a banked curve's span is its \
206 cant law's, and a station without cant is not zero cant",
207 });
208 }
209 let b = layout.rail_head_distance;
210 let mut cant = Vec::with_capacity(segments.len());
211 let mut pivot = Vec::with_capacity(segments.len());
212 for segment in segments {
213 let (left, right) = ends(segment)?;
214 let d = [left[0] - right[0], left[1] - right[1]];
215 let e = [0.5 * (left[0] + right[0]), 0.5 * (left[1] + right[1])];
216 if d.iter().any(|value| bank_angle(*value, b).is_err()) {
217 return Err(AlignmentError::SemanticViolation {
218 entity: Some(segment.entity),
219 rule: "cant must not exceed the rail head distance (|D| <= b)",
220 });
221 }
222 let length = segment.horizontal_length;
223 match &segment.predefined_type {
224 CantSegmentType::ConstantCant => {
225 cant.push(CantPiece::constant(length, d[0]));
226 pivot.push(CantPiece::constant(length, e[0]));
227 }
228 CantSegmentType::LinearTransition => {
229 cant.push(CantPiece::linear(length, d[0], d[1]));
230 pivot.push(CantPiece::linear(length, e[0], e[1]));
231 }
232 CantSegmentType::BlossCurve => {
233 cant.push(CantPiece::bloss(length, d[0], d[1]));
234 pivot.push(CantPiece::bloss(length, e[0], e[1]));
235 }
236 CantSegmentType::HelmertCurve => {
237 cant.extend(CantPiece::helmert(length, d[0], d[1]));
238 pivot.extend(CantPiece::helmert(length, e[0], e[1]));
239 }
240 CantSegmentType::CosineCurve => {
241 cant.push(CantPiece::cosine(length, d[0], d[1]));
242 pivot.push(CantPiece::cosine(length, e[0], e[1]));
243 }
244 CantSegmentType::SineCurve => {
245 cant.push(CantPiece::sine(length, d[0], d[1]));
246 pivot.push(CantPiece::sine(length, e[0], e[1]));
247 }
248 CantSegmentType::VienneseBend => {
249 // The bend states the bank angle; the pivot follows the
250 // rule `cant_at` uses, so the two give the same section.
251 let about = match viennese_rotation(segment.entity, left, right, tolerance)? {
252 VienneseRotation::FixedPivot(height) => CantPiece::constant(length, height),
253 VienneseRotation::HeldLeft(height) => {
254 CantPiece::about_rail(length, RailSide::Left, height)
255 }
256 VienneseRotation::HeldRight(height) => {
257 CantPiece::about_rail(length, RailSide::Right, height)
258 }
259 };
260 // |D| <= b was checked above, so both angles exist.
261 let psi = |value: f64| (value / b).asin();
262 cant.push(CantPiece::viennese_bend(length, psi(d[0]), psi(d[1])));
263 pivot.push(about);
264 }
265 _ => {
266 return Err(AlignmentError::Unsupported {
267 entity: segment.entity,
268 type_name: segment.predefined_type_name().to_owned(),
269 detail: "cant PredefinedType has no defined base formula",
270 })
271 }
272 }
273 }
274 Ok((CantLaw::new(cant), CantLaw::new(pivot)))
275}
276
277/// `[start, end]` heights of the left and right rail heads above the
278/// profile. A constant cant may omit its end values; a transition needs
279/// both.
280fn ends(segment: &CantSegment) -> AlignmentResult<([f64; 2], [f64; 2])> {
281 let constant = segment.predefined_type == CantSegmentType::ConstantCant;
282 match (segment.end_cant_left, segment.end_cant_right) {
283 (Some(left), Some(right)) => {
284 if constant && (left != segment.start_cant_left || right != segment.start_cant_right) {
285 return Err(AlignmentError::InvalidSegment {
286 entity: segment.entity,
287 detail: "CONSTANTCANT requires equal (or absent) start and end cant",
288 });
289 }
290 Ok((
291 [segment.start_cant_left, left],
292 [segment.start_cant_right, right],
293 ))
294 }
295 _ if constant => Ok(([segment.start_cant_left; 2], [segment.start_cant_right; 2])),
296 _ => Err(AlignmentError::InvalidSegment {
297 entity: segment.entity,
298 detail: "transition cant segments require both end cant values",
299 }),
300 }
301}