Skip to main content

ifc_geometry/lower/profile/
open.rs

1//! Lower authored IFC open profiles without manufacturing area semantics.
2
3use axiolid_core::{Interval, Vec2};
4use axiolid_curve::linear::Polyline2;
5use axiolid_curve::Curve2;
6use axiolid_model::{GeometryNode, NodeId, OpenProfile};
7use axiolid_profile::{Contour, ProfileSegment};
8use ifc_model::{EntityId, Model};
9
10use super::{slot, OPEN_PROFILE};
11use crate::error::{GeometryError, GeometryResult};
12use crate::input::profile::{describe_profile, open_cross_vertices, ProfileParameters};
13use crate::lower::session::LoweringSession;
14use crate::slots::Slots;
15use crate::transform::Transform;
16use crate::units::UnitScale;
17
18/// Append one authored open profile without implying area.
19///
20/// Admits `IfcArbitraryOpenProfileDef`, whose path is its `Curve`, and the
21/// IFC4X3 `IfcOpenCrossProfileDef`, whose path is the polyline its widths and
22/// slopes construct (see `input::profile::open_cross` for the convention).
23///
24/// Area-profile callers deliberately use [`super::lower_profile_node`] instead.
25/// This separate entry point prevents an open path from becoming a swept-area
26/// input merely because IFC derives both declarations from `IfcProfileDef`.
27pub fn lower_open_profile_node(
28    session: &mut LoweringSession<'_>,
29    id: EntityId,
30) -> GeometryResult<NodeId> {
31    let frame = Transform::identity();
32    if let Some(node) = session.memoized(id, OPEN_PROFILE, frame) {
33        return Ok(node);
34    }
35
36    let type_name = session.type_name(id)?;
37    let path = match type_name.as_str() {
38        "IFCARBITRARYOPENPROFILEDEF" => {
39            let path_ref = session.slots(id)?.req_ref(slot::OUTER_CURVE, "Curve")?;
40            let path_curve = open_curve2(session.model(), path_ref, session.units())?;
41            session.node_for(path_ref, GeometryNode::Curve2(path_curve))?
42        }
43        // The chain has no curve entity of its own: the profile states it as
44        // widths and slopes, so the path node is attributed to the profile.
45        "IFCOPENCROSSPROFILEDEF" => {
46            let path_curve = open_cross_curve2(session.model(), id, session.units())?;
47            session.node_for(id, GeometryNode::Curve2(path_curve))?
48        }
49        _ => {
50            return Err(session.unsupported(
51                id,
52                &type_name,
53                "only IfcArbitraryOpenProfileDef and IfcOpenCrossProfileDef have \
54                 authored open-path semantics",
55            ))
56        }
57    };
58    let node = session.node_for(id, GeometryNode::OpenProfile(OpenProfile::new(path)))?;
59    session.memoize(id, OPEN_PROFILE, frame, node);
60    Ok(node)
61}
62
63/// The exact open polyline an `IfcOpenCrossProfileDef` states.
64///
65/// The vertices are closed-form sums of the authored widths and slopes, one
66/// per tag, so the polyline is the profile exactly. A chain whose last vertex
67/// returns onto its first (all widths zero, for instance) is not an open path
68/// and is refused, as for an arbitrary open profile.
69fn open_cross_curve2(model: &Model, id: EntityId, units: &UnitScale) -> GeometryResult<Curve2> {
70    let description = describe_profile(model, units, id)?;
71    let ProfileParameters::OpenCross {
72        horizontal_widths,
73        widths,
74        slopes,
75        offset_point,
76        ..
77    } = &description.parameters
78    else {
79        return Err(GeometryError::Unsupported {
80            entity: id,
81            type_name: description.type_name,
82            detail: "expected an IfcOpenCrossProfileDef description",
83        });
84    };
85    let points: Vec<Vec2> = open_cross_vertices(*horizontal_widths, widths, slopes, *offset_point)
86        .into_iter()
87        .map(Vec2::from_array)
88        .collect();
89    if points.iter().any(|point| !point.is_finite()) {
90        return Err(GeometryError::Degenerate {
91            entity: id,
92            type_name: description.type_name,
93            detail: "open cross profile vertex is not finite".to_string(),
94        });
95    }
96    if points[0] == *points.last().expect("at least one segment") {
97        return Err(GeometryError::Degenerate {
98            entity: id,
99            type_name: description.type_name,
100            detail: "open cross profile chain returns to its start point".to_string(),
101        });
102    }
103    Ok(Curve2::Polyline(Polyline2 {
104        points,
105        closed: false,
106    }))
107}
108
109/// Extract the exact `Curve2` used by an authored open profile.
110fn open_curve2(model: &Model, id: EntityId, units: &UnitScale) -> GeometryResult<Curve2> {
111    let mut path = open_polyline_path(model, id, units)?;
112    let segment = path
113        .segments
114        .pop()
115        .expect("open_polyline_path always emits one segment");
116    debug_assert!(path.segments.is_empty());
117    Ok(segment.curve)
118}
119
120/// Read an open polyline path.
121///
122/// Deliberately not `curve_to_contour`: that reader closes the ring by wrapping
123/// the last point back to the first and demands three distinct points. A centre
124/// line is open, so closing it would add a segment the source never stated and
125/// turn a two-point straight bar into a degenerate zero-area triangle.
126pub(super) fn open_polyline_path(
127    model: &Model,
128    id: EntityId,
129    units: &UnitScale,
130) -> GeometryResult<Contour> {
131    let entity = model.get(id).ok_or(GeometryError::MissingEntity {
132        referrer: id,
133        missing: id,
134    })?;
135    let type_name = entity.type_name.to_ascii_uppercase();
136    if type_name != "IFCPOLYLINE" {
137        return Err(GeometryError::Unsupported {
138            entity: id,
139            type_name,
140            detail: "only polyline open paths are lowered so far",
141        });
142    }
143
144    let slots = Slots::new(id, entity);
145    let mut points = Vec::new();
146    for point_id in slots.req_ref_list(0, "Points")? {
147        let point = model.get(point_id).ok_or(GeometryError::MissingEntity {
148            referrer: id,
149            missing: point_id,
150        })?;
151        let coordinates = Slots::new(point_id, point).req_f64_list(0, "Coordinates")?;
152        if coordinates.len() < 2 {
153            return Err(GeometryError::Degenerate {
154                entity: point_id,
155                type_name: point.type_name.to_string(),
156                detail: "open profile path point is not at least 2D".to_string(),
157            });
158        }
159        points.push(Vec2::new(
160            units.length(coordinates[0]),
161            units.length(coordinates[1]),
162        ));
163    }
164    if points.len() < 2 {
165        return Err(slots.degenerate("open profile path has fewer than 2 points"));
166    }
167    // Axiolid's neutral OpenProfile contract rejects exact closure. A near-gap
168    // remains authored-open; introducing a tolerance here would invent topology.
169    if points[0] == *points.last().expect("length checked") {
170        return Err(slots.degenerate("open profile path is geometrically closed"));
171    }
172
173    // One polyline segment carries the whole open path. Splitting it into
174    // per-edge lines here would only add joins the kernel must re-derive.
175    let last = (points.len() - 1) as f64;
176    Ok(Contour::new(vec![ProfileSegment {
177        curve: Curve2::Polyline(Polyline2 {
178            points,
179            closed: false,
180        }),
181        domain: Interval::new(0.0, last),
182        same_sense: true,
183    }]))
184}