Skip to main content

ifc_geometry/lower/
curve.rs

1//! Exact curve lowering.
2//!
3//! # Scope
4//!
5//! Covers `IfcPolyline`, `IfcLine`, `IfcCircle`, `IfcTrimmedCurve`,
6//! `IfcCompositeCurve`, the explicit-knot `IfcBSplineCurveWithKnots` /
7//! `IfcRationalBSplineCurveWithKnots`, and the IFC4X3 curves:
8//! `IfcCurveSegment` (`segment.rs`, spiral laws in `spiral.rs`),
9//! `IfcGradientCurve` (`gradient.rs`) and `IfcOffsetCurveByDistances`
10//! (`lower::station`). Other families report a typed `Unsupported` naming
11//! the entity, so a gap is a diagnostic rather than a wrong shape.
12//!
13//! # Trim parameters are not all lengths
14//!
15//! `IfcTrimmedCurve` carries `IfcParameterValue`s in the *basis curve's own*
16//! parameterisation. For an `IfcLine` that parameter is a length along the
17//! direction vector and scales with the length unit. For an `IfcCircle` it is
18//! an **angle** in the model's plane-angle unit. Applying the length factor to
19//! a conic parameter silently rescales every arc: on a millimetre file the
20//! 0.082 rad arc in `swept_disk_composite_arc_crankbar.ifc` would become 82
21//! radians and wrap the circle thirteen times. The basis curve therefore
22//! decides which unit conversion applies.
23//!
24//! # Why the frame is applied here and not deferred
25//!
26//! Curves are lowered as world-space geometry, matching `lower::brep`: the
27//! caller's frame is applied to points and to conic frames as they are built.
28//! Deferring would require every consumer to carry a parallel transform stack.
29
30use axiolid_core::{Frame3, Point3, Vec3};
31use axiolid_curve::{BSplineCurve3, Circle3, Curve3, Ellipse3, KnotSpec, Line3, Polyline3};
32use axiolid_model::{
33    CurveRelation, CurveSegment, GeometryNode, MasterRepresentation, NodeId, SurfaceSides,
34    Transition, TrimSelector, TrimmingPreference as KernelPreference,
35};
36use ifc_model::EntityId;
37
38use crate::curve::bspline::{BSplineCurve, KnotType};
39use crate::curve::composite::{CompositeCurve, CompositeCurveSegment, TransitionCode};
40use crate::curve::conic::{Circle, Ellipse};
41use crate::curve::line::Line;
42use crate::curve::offset::{
43    OffsetCurve2D, OffsetCurve3D, PCurve, PreferredSurfaceCurveRepresentation, SurfaceCurve,
44};
45use crate::curve::polyline::Polyline;
46use crate::curve::trimmed::{TrimmedCurve, TrimmingPreference};
47use crate::error::{GeometryError, GeometryResult};
48use crate::lower::session::LoweringSession;
49use crate::lower::station::offset::offset_curve_by_distances;
50use crate::lower::surface::lower_surface_node;
51use crate::resource::direction::resolve_unit;
52use crate::resource::placement::axis_placement_transform;
53use crate::resource::point::CartesianPoint;
54use crate::transform::Transform;
55
56mod composite_range;
57#[cfg(test)]
58mod fixture;
59pub(crate) mod gradient;
60mod parameter_space;
61pub(crate) mod segment;
62pub(crate) mod spiral;
63
64use parameter_space::parameter_reference_curve;
65
66/// Family label used for curve memoization.
67const KIND: &str = "curve";
68
69/// Lower a sweep's directrix together with its `StartParam`/`EndParam`.
70///
71/// Returns the directrix node and the `parameter_range` the kernel should
72/// apply to it. The range is in the directrix's own parameterisation, which
73/// is not always a length:
74///
75/// - a conic parameter is an angle, a line or polyline parameter is
76///   dimensionless: converted by [`scale_parameter`] and handed on;
77/// - an `IfcCompositeCurve` accumulates each segment's PARAMETRIC length
78///   (1 per polyline edge, an arc's angle), which no kernel arc length
79///   matches. The range is applied here, structurally, and the returned range
80///   is `None`.
81///
82/// One end without the other is refused: a half-open sweep is undefined.
83pub(crate) fn lower_sweep_directrix(
84    session: &mut LoweringSession<'_>,
85    sweep: EntityId,
86    sweep_type: &str,
87    directrix: EntityId,
88    frame: Transform,
89    start: Option<f64>,
90    end: Option<f64>,
91) -> GeometryResult<(NodeId, Option<(f64, f64)>)> {
92    let range = match (start, end) {
93        (Some(start), Some(end)) => Some((start, end)),
94        (None, None) => None,
95        _ => {
96            return Err(session.degenerate(
97                sweep,
98                sweep_type,
99                "only one of StartParam/EndParam is present; a half-open sweep is undefined",
100            ))
101        }
102    };
103    let kind = session.type_name(directrix)?;
104    if composite_range::is_composite(&kind) {
105        let node = composite_range::lower_composite_directrix(
106            session, sweep, sweep_type, directrix, frame, range,
107        )?;
108        return Ok((node, None));
109    }
110    let node = lower_curve_node(session, directrix, frame)?;
111    // A trimmed curve is parameterised by its BASIS (ISO 10303-42): a trimmed
112    // circle's range is an angle, a trimmed line's a vector multiple.
113    let parameter_kind = if kind == "IFCTRIMMEDCURVE" {
114        let entity = session.entity(sweep, directrix)?;
115        let basis = TrimmedCurve::new(directrix, entity).basis_curve_ref()?;
116        session.type_name(basis)?
117    } else {
118        kind
119    };
120    let converted = range
121        .map(|(start, end)| {
122            Ok::<_, GeometryError>((
123                scale_parameter(session, sweep, &parameter_kind, start)?,
124                scale_parameter(session, sweep, &parameter_kind, end)?,
125            ))
126        })
127        .transpose()?;
128    Ok((node, converted))
129}
130
131/// Lower any supported curve, returning its node.
132pub fn lower_curve_node(
133    session: &mut LoweringSession<'_>,
134    id: EntityId,
135    frame: Transform,
136) -> GeometryResult<NodeId> {
137    if let Some(node) = session.memoized(id, KIND, frame) {
138        return Ok(node);
139    }
140    session.enter(id, KIND)?;
141    let result = build(session, id, frame);
142    session.exit(id);
143    let node = result?;
144    session.memoize(id, KIND, frame, node);
145    Ok(node)
146}
147
148fn build(
149    session: &mut LoweringSession<'_>,
150    id: EntityId,
151    frame: Transform,
152) -> GeometryResult<NodeId> {
153    let type_name = session.type_name(id)?;
154    match type_name.as_str() {
155        "IFCPOLYLINE" => polyline(session, id, frame),
156        "IFCINDEXEDPOLYCURVE" => indexed_polycurve(session, id, frame),
157        "IFCLINE" => line(session, id, frame),
158        "IFCCIRCLE" => circle(session, id, frame),
159        "IFCELLIPSE" => ellipse(session, id, frame),
160        "IFCOFFSETCURVE2D" | "IFCOFFSETCURVE3D" => offset(session, id, frame),
161        "IFCPCURVE" => parameter_curve(session, id, frame),
162        "IFCSURFACECURVE" | "IFCINTERSECTIONCURVE" | "IFCSEAMCURVE" => {
163            surface_curve(session, id, frame)
164        }
165        "IFCTRIMMEDCURVE" => trimmed(session, id, frame),
166        "IFCCOMPOSITECURVE"
167        | "IFCCOMPOSITECURVEONSURFACE"
168        | "IFCBOUNDARYCURVE"
169        | "IFCOUTERBOUNDARYCURVE" => composite(session, id, frame),
170        "IFCBSPLINECURVEWITHKNOTS" | "IFCRATIONALBSPLINECURVEWITHKNOTS" => {
171            bspline(session, id, frame)
172        }
173        // IFC4X3: placed segments, alignment centrelines, standalone parents.
174        "IFCCURVESEGMENT" => segment::lower_segment(session, id, frame),
175        "IFCGRADIENTCURVE" => gradient::gradient_curve(session, id, frame),
176        "IFCSEGMENTEDREFERENCECURVE" => gradient::segmented_reference_curve(session, id),
177        "IFCOFFSETCURVEBYDISTANCES" => offset_curve_by_distances(session, id, frame),
178        "IFCPOLYNOMIALCURVE" => {
179            Err(session.unsupported(id, &type_name, segment::STANDALONE_POLYNOMIAL))
180        }
181        other if spiral::is_spiral(other) => {
182            Err(session.unsupported(id, other, spiral::standalone_reason(other)))
183        }
184        // Any planned IFC4X3 curve routed here keeps the ledger's reason.
185        other => Err(session.unsupported(
186            id,
187            other,
188            crate::lower::dispatch::planned_detail(other).unwrap_or("curve family"),
189        )),
190    }
191}
192
193/// `IfcPolyline`: ordered points, closed when the last repeats the first.
194fn polyline(
195    session: &mut LoweringSession<'_>,
196    id: EntityId,
197    frame: Transform,
198) -> GeometryResult<NodeId> {
199    let entity = session.entity(id, id)?;
200    let view = Polyline::new(id, entity);
201    let closed = view.closes_by_repeating_first_point()?;
202    let refs = view.point_refs()?;
203
204    let mut points = Vec::with_capacity(refs.len());
205    for point_ref in &refs {
206        points.push(Point3::from_array(world_point(
207            session, id, *point_ref, frame,
208        )?));
209    }
210    // A closing duplicate is represented by the `closed` flag, not by a
211    // repeated vertex: leaving both produces a zero-length final segment.
212    if closed && points.len() > 1 {
213        points.pop();
214    }
215    session.node_for(
216        id,
217        GeometryNode::Curve3(Curve3::Polyline(Polyline3 { points, closed })),
218    )
219}
220
221mod indexed;
222
223use indexed::indexed_polycurve;
224
225/// `IfcLine`: origin point plus an `IfcVector` direction.
226///
227/// The vector's magnitude is the parameterisation scale and is preserved:
228/// normalizing it would silently reparameterise every trim taken on the line.
229fn line(
230    session: &mut LoweringSession<'_>,
231    id: EntityId,
232    frame: Transform,
233) -> GeometryResult<NodeId> {
234    let entity = session.entity(id, id)?;
235    let view = Line::new(id, entity);
236    let origin = world_point(session, id, view.point_ref()?, frame)?;
237    let vector_ref = view.direction_vector_ref()?;
238    let direction = world_vector(session, id, vector_ref, frame)?;
239    session.node_for(
240        id,
241        GeometryNode::Curve3(Curve3::Line(Line3 {
242            origin: Point3::from_array(origin),
243            direction: Vec3::from_array(direction),
244        })),
245    )
246}
247
248/// `IfcCircle`: a radius in the XY plane of its own placement.
249fn circle(
250    session: &mut LoweringSession<'_>,
251    id: EntityId,
252    frame: Transform,
253) -> GeometryResult<NodeId> {
254    let entity = session.entity(id, id)?;
255    let view = Circle::new(id, entity);
256    let radius = session.units().length(view.radius()?);
257    let position_ref = view.position_ref()?;
258    let position = session.entity(id, position_ref)?;
259    let local = axis_placement_transform(session.model(), position_ref, position)?
260        .to_metres(session.units());
261    let placed = frame.compose(&local);
262    session.node_for(
263        id,
264        GeometryNode::Curve3(Curve3::Circle(Circle3 {
265            frame: frame3(&placed),
266            radius,
267        })),
268    )
269}
270
271/// `IfcEllipse`: exact semi-axes in the placed conic frame.
272fn ellipse(
273    session: &mut LoweringSession<'_>,
274    id: EntityId,
275    frame: Transform,
276) -> GeometryResult<NodeId> {
277    let entity = session.entity(id, id)?;
278    let view = Ellipse::new(id, entity);
279    let semi_axis_x = session.units().length(view.semi_axis_1()?);
280    let semi_axis_y = session.units().length(view.semi_axis_2()?);
281    if !semi_axis_x.is_finite()
282        || !semi_axis_y.is_finite()
283        || semi_axis_x <= 0.0
284        || semi_axis_y <= 0.0
285    {
286        return Err(session.degenerate(id, "IFCELLIPSE", "semi-axes must be finite and positive"));
287    }
288    let position_ref = view.position_ref()?;
289    let position = session.entity(id, position_ref)?;
290    let local = axis_placement_transform(session.model(), position_ref, position)?
291        .to_metres(session.units());
292    let placed = frame.compose(&local);
293    session.node_for(
294        id,
295        GeometryNode::Curve3(Curve3::Ellipse(Ellipse3 {
296            frame: frame3(&placed),
297            semi_axis_x,
298            semi_axis_y,
299        })),
300    )
301}
302
303/// IFC offset curves remain graph relations over the exact basis curve.
304///
305/// Every curve lowers to a 3D curve under its frame, a 2D one in the plane
306/// `z = 0` of that frame. An `IfcOffsetCurve2D` therefore carries the
307/// frame's `+Z` as its reference direction (#414): IFC4.3 ADD2 8.9.3.40
308/// offsets "in the direction which is normal to the curve in the sense of
309/// an anti-clockwise rotation through 90 degrees from the tangent vector
310/// T", which for a tangent in the plane is exactly `Z x T`, the 3D offset's
311/// "V x T" (8.9.3.41). Axiolid refuses a planar (2D) offset law on a 3D
312/// curve, so `None` would leave no station measurable along it.
313fn offset(
314    session: &mut LoweringSession<'_>,
315    id: EntityId,
316    frame: Transform,
317) -> GeometryResult<NodeId> {
318    let entity = session.entity(id, id)?;
319    let type_name = session.type_name(id)?;
320    let (basis_ref, raw_distance, reference_direction) = match type_name.as_str() {
321        "IFCOFFSETCURVE2D" => {
322            let view = OffsetCurve2D::new(id, entity);
323            (
324                view.basis_curve_ref()?,
325                view.distance()?,
326                Some(Vec3::from_array(frame.apply_direction([0.0, 0.0, 1.0]))),
327            )
328        }
329        "IFCOFFSETCURVE3D" => {
330            let view = OffsetCurve3D::new(id, entity);
331            let direction_ref = view.ref_direction_ref()?;
332            let direction = resolve_unit(session.model(), id, direction_ref)?;
333            (
334                view.basis_curve_ref()?,
335                view.distance()?,
336                Some(Vec3::from_array(frame.apply_direction(direction))),
337            )
338        }
339        _ => unreachable!("offset called only for offset curve families"),
340    };
341    let distance = session.units().length(raw_distance);
342    if !distance.is_finite() {
343        return Err(session.degenerate(id, &type_name, "Distance must be finite"));
344    }
345    let basis = lower_curve_node(session, basis_ref, frame)?;
346    session.node_for(
347        id,
348        GeometryNode::CurveRelation(CurveRelation::Offset {
349            basis,
350            distance,
351            reference_direction,
352        }),
353    )
354}
355
356/// Lower an IFC p-curve without applying project length units to `(u, v)`.
357fn parameter_curve(
358    session: &mut LoweringSession<'_>,
359    id: EntityId,
360    frame: Transform,
361) -> GeometryResult<NodeId> {
362    let entity = session.entity(id, id)?;
363    let view = PCurve::new(id, entity);
364    let basis_ref = view.basis_surface_ref()?;
365    let reference_ref = view.reference_curve_ref()?;
366    let basis_surface = lower_surface_node(session, basis_ref, frame)?;
367    let reference_curve = parameter_reference_curve(session, id, reference_ref)?;
368    session.node_for(
369        id,
370        GeometryNode::CurveRelation(CurveRelation::ParameterCurve {
371            basis_surface,
372            reference_curve,
373        }),
374    )
375}
376
377/// Preserve redundant 3D/p-curve geometry and its authoritative selection.
378fn surface_curve(
379    session: &mut LoweringSession<'_>,
380    id: EntityId,
381    frame: Transform,
382) -> GeometryResult<NodeId> {
383    let entity = session.entity(id, id)?;
384    let view = SurfaceCurve::new(id, entity);
385    let curve_3d_ref = view.curve_3d_ref()?;
386    let pcurve_refs = view.associated_pcurve_refs()?;
387    let preferred = view.master_representation();
388
389    // The neutral master names a SIDE, and a side is a (surface, p-curve)
390    // pair, so PCURVE_S2 is only meaningful when a second side exists. A file
391    // naming it with one p-curve is inconsistent per the schema rather than
392    // merely unsupported, so it is refused as degenerate.
393    let master = match preferred {
394        PreferredSurfaceCurveRepresentation::Curve3D => MasterRepresentation::Curve3d,
395        PreferredSurfaceCurveRepresentation::PCurveS1 => MasterRepresentation::ParameterCurveS1,
396        PreferredSurfaceCurveRepresentation::PCurveS2 if pcurve_refs.len() == 2 => {
397            MasterRepresentation::ParameterCurveS2
398        }
399        PreferredSurfaceCurveRepresentation::PCurveS2 => {
400            return Err(session.degenerate(
401                id,
402                &session.type_name(id)?,
403                "MasterRepresentation names PCURVE_S2 but AssociatedGeometry holds \
404                 one p-curve, so the named side does not exist",
405            ));
406        }
407    };
408
409    let curve_3d = lower_curve_node(session, curve_3d_ref, frame)?;
410    // Each side pairs the surface with this curve's image in that surface's
411    // own parameter domain. The pairing comes from the IfcPcurve itself, so
412    // it is read rather than inferred from list order alone.
413    let mut sides = Vec::with_capacity(pcurve_refs.len());
414    for pcurve_ref in pcurve_refs {
415        let basis_ref =
416            PCurve::new(pcurve_ref, session.entity(id, pcurve_ref)?).basis_surface_ref()?;
417        let surface = lower_surface_node(session, basis_ref, frame)?;
418        let pcurve = parameter_curve(session, pcurve_ref, frame)?;
419        sides.push((surface, pcurve));
420    }
421    let sides = match sides.as_slice() {
422        [(s1, p1)] => SurfaceSides::one(*s1, *p1),
423        [(s1, p1), (s2, p2)] => SurfaceSides::two(*s1, *p1, *s2, *p2),
424        _ => unreachable!("associated_pcurve_refs already bounds the list to 1 or 2"),
425    };
426    session.node_for(
427        id,
428        GeometryNode::CurveRelation(CurveRelation::SurfaceCurve {
429            curve_3d,
430            sides,
431            master,
432        }),
433    )
434}
435
436/// `IfcTrimmedCurve`: a basis curve plus two trim selectors.
437///
438/// The basis curve decides how a parameter selector is scaled: length for a
439/// line, plane angle for a conic. See the module note.
440fn trimmed(
441    session: &mut LoweringSession<'_>,
442    id: EntityId,
443    frame: Transform,
444) -> GeometryResult<NodeId> {
445    let entity = session.entity(id, id)?;
446    let view = TrimmedCurve::new(id, entity);
447    let basis_ref = view.basis_curve_ref()?;
448    let basis = lower_curve_node(session, basis_ref, frame)?;
449
450    let basis_kind = session.type_name(basis_ref)?;
451    let sense_agreement = view.sense_agreement()?;
452    let preference = view.master_representation();
453    let spec = view.spec()?;
454    let (t1, t2) = spec.endpoints();
455
456    let cartesian_preferred = matches!(preference, TrimmingPreference::Cartesian);
457    let start = selectors(session, id, t1, &basis_kind, frame, cartesian_preferred)?;
458    let end = selectors(session, id, t2, &basis_kind, frame, cartesian_preferred)?;
459    if start.is_empty() || end.is_empty() {
460        return Err(session.degenerate(
461            id,
462            "IFCTRIMMEDCURVE",
463            "a trim end carries neither a parameter nor a point",
464        ));
465    }
466
467    session.node_for(
468        id,
469        GeometryNode::CurveRelation(CurveRelation::Trimmed {
470            basis,
471            start,
472            end,
473            sense_agreement,
474            preference: match preference {
475                TrimmingPreference::Cartesian => KernelPreference::Cartesian,
476                TrimmingPreference::Parameter => KernelPreference::Parameter,
477                TrimmingPreference::Unspecified => KernelPreference::Unspecified,
478            },
479        }),
480    )
481}
482
483/// Convert one trim end into kernel selectors, scaling by basis curve kind.
484fn selectors(
485    session: &mut LoweringSession<'_>,
486    owner: EntityId,
487    trim: crate::curve::trimmed::Trim,
488    basis_kind: &str,
489    frame: Transform,
490    cartesian_preferred: bool,
491) -> GeometryResult<Vec<TrimSelector>> {
492    let mut out = Vec::new();
493    if let Some(raw) = trim.parameter {
494        match scale_parameter(session, owner, basis_kind, raw) {
495            Ok(scaled) => out.push(TrimSelector::Parameter(scaled)),
496            // A conic's parameter is an angle. When the project declares no
497            // angle unit and the point is the preferred form, the point
498            // carries the trim and the angle is never read (#585).
499            Err(GeometryError::AngleUnitUndeclared { .. })
500                if cartesian_preferred && trim.cartesian.is_some() => {}
501            Err(error) => return Err(error),
502        }
503    }
504    if let Some(point_ref) = trim.cartesian {
505        let placed = world_point(session, owner, point_ref, frame)?;
506        out.push(TrimSelector::Point3(Point3::from_array(placed)));
507    }
508    Ok(out)
509}
510
511/// Scale one trim parameter into kernel units, by basis curve kind.
512///
513/// Three parameterisations, not two:
514///
515/// - A conic (`IfcCircle`, `IfcEllipse`) parameterises by ANGLE.
516/// - A line parameter multiplies its already-scaled `IfcVector`, so it is
517///   dimensionless. A polyline parameter is a point/segment ordinal.
518/// - A composite curve parameter is cumulative path LENGTH and converts.
519/// - Other non-conic families parameterise by length and convert.
520pub(crate) fn scale_parameter(
521    session: &LoweringSession<'_>,
522    entity: EntityId,
523    basis_kind: &str,
524    raw: f64,
525) -> GeometryResult<f64> {
526    Ok(raw * parameter_factor(session, entity, basis_kind)?)
527}
528
529/// The factor [`scale_parameter`] applies for one basis curve kind.
530///
531/// `entity` names the refusal when a conic needs an angle unit the project
532/// does not declare.
533pub(crate) fn parameter_factor(
534    session: &LoweringSession<'_>,
535    entity: EntityId,
536    basis_kind: &str,
537) -> GeometryResult<f64> {
538    match basis_kind {
539        "IFCCIRCLE" | "IFCELLIPSE" => session.units().radians_per_unit(entity),
540        "IFCLINE" | "IFCPOLYLINE" => Ok(1.0),
541        _ => Ok(session.units().length_to_metres),
542    }
543}
544
545/// `IfcCompositeCurve`: ordered segments, each wrapping a parent curve.
546fn composite(
547    session: &mut LoweringSession<'_>,
548    id: EntityId,
549    frame: Transform,
550) -> GeometryResult<NodeId> {
551    let entity = session.entity(id, id)?;
552    let view = CompositeCurve::new(id, entity);
553    let segment_refs = view.segment_refs()?;
554    if segment_refs.is_empty() {
555        return Err(session.degenerate(id, "IFCCOMPOSITECURVE", "no segments"));
556    }
557
558    let mut segments = Vec::with_capacity(segment_refs.len());
559    for (index, segment_ref) in segment_refs.iter().enumerate() {
560        // IFC4X3 composites may hold placed `IfcCurveSegment`s instead.
561        if session.type_name(*segment_ref)? == "IFCCURVESEGMENT" {
562            let last = index + 1 == segment_refs.len();
563            segments.extend(segment::composite_member(
564                session,
565                id,
566                *segment_ref,
567                last,
568                frame,
569            )?);
570            continue;
571        }
572        let segment_entity = session.entity(id, *segment_ref)?;
573        let segment = CompositeCurveSegment::new(*segment_ref, segment_entity);
574        let parent = segment.parent_curve_ref()?;
575        // Segment order is the curve's own traversal order and must be
576        // preserved: sorting or deduplicating segments reorders the path.
577        segments.push(CurveSegment {
578            curve: lower_curve_node(session, parent, frame)?,
579            same_sense: segment.same_sense()?,
580            transition: transition(segment.transition()?),
581        });
582    }
583    if segments.is_empty() {
584        return Err(session.degenerate(id, "IFCCOMPOSITECURVE", "no segment of positive length"));
585    }
586    session.node_for(
587        id,
588        GeometryNode::CurveRelation(CurveRelation::Composite { segments }),
589    )
590}
591
592/// Exact explicit-knot polynomial/rational B-spline curve.
593fn bspline(
594    session: &mut LoweringSession<'_>,
595    id: EntityId,
596    frame: Transform,
597) -> GeometryResult<NodeId> {
598    let type_name = session.type_name(id)?;
599    let entity = session.entity(id, id)?;
600    let view = BSplineCurve::new(id, entity);
601    let degree = u16::try_from(view.degree()?)
602        .map_err(|_| session.degenerate(id, &type_name, "Degree exceeds u16"))?;
603    let knots = view.knots()?.ok_or_else(|| {
604        session.unsupported(
605            id,
606            &type_name,
607            "explicit knots required for lossless lowering",
608        )
609    })?;
610    finite_values(session, id, &type_name, "Knots", &knots.values)?;
611    // The expanded knot vector is what a kernel materializes, and its length is
612    // the SUM of file-declared multiplicities: a handful of integers can name
613    // billions of elements. Check the declared total before anything reserves.
614    let declared: u128 = knots.multiplicities.iter().map(|m| *m as u128).sum();
615    session.check_aggregate(id, &type_name, "knot multiplicities", declared)?;
616    let multiplicities = knots
617        .multiplicities
618        .into_iter()
619        .map(|value| {
620            u32::try_from(value)
621                .map_err(|_| session.degenerate(id, &type_name, "multiplicity exceeds u32"))
622        })
623        .collect::<GeometryResult<Vec<_>>>()?;
624
625    let refs = view.control_point_refs()?;
626    let mut control_points = Vec::with_capacity(refs.len());
627    for point_ref in refs {
628        let placed = world_point(session, id, point_ref, frame)?;
629        finite_values(
630            session,
631            id,
632            &type_name,
633            "transformed control point",
634            &placed,
635        )?;
636        control_points.push(Point3::from_array(placed));
637    }
638    let weights = view.weights()?;
639    if let Some(values) = weights.as_deref() {
640        finite_values(session, id, &type_name, "WeightsData", values)?;
641    }
642    let closed = view.closed_curve().ok_or_else(|| {
643        session.unsupported(
644            id,
645            &type_name,
646            "unknown ClosedCurve is not lossless in bool",
647        )
648    })?;
649    session.node_for(
650        id,
651        GeometryNode::Curve3(Curve3::BSpline(BSplineCurve3 {
652            degree,
653            control_points,
654            knots: knots.values,
655            multiplicities,
656            weights,
657            closed,
658            self_intersect: view.self_intersect(),
659            knot_spec: bspline_knot_spec(view.knot_spec()),
660        })),
661    )
662}
663
664fn bspline_knot_spec(source: KnotType) -> KnotSpec {
665    match source {
666        KnotType::Uniform => KnotSpec::Uniform,
667        KnotType::QuasiUniform => KnotSpec::QuasiUniform,
668        KnotType::PiecewiseBezier => KnotSpec::PiecewiseBezier,
669        KnotType::Unspecified => KnotSpec::Unspecified,
670    }
671}
672
673pub(super) fn finite_values(
674    session: &LoweringSession<'_>,
675    id: EntityId,
676    type_name: &str,
677    field: &'static str,
678    values: &[f64],
679) -> GeometryResult<()> {
680    if values.iter().all(|value| value.is_finite()) {
681        Ok(())
682    } else {
683        Err(session.degenerate(id, type_name, field))
684    }
685}
686
687fn transition(code: TransitionCode) -> Transition {
688    match code {
689        TransitionCode::Discontinuous => Transition::Discontinuous,
690        TransitionCode::Continuous => Transition::Continuous,
691        TransitionCode::ContSameGradient => Transition::ContinuousSameGradient,
692        TransitionCode::ContSameGradientSameCurvature => {
693            Transition::ContinuousSameGradientSameCurvature
694        }
695    }
696}
697
698/// Resolve an `IfcCartesianPoint`, scale to metres, then place it.
699fn world_point(
700    session: &mut LoweringSession<'_>,
701    owner: EntityId,
702    point_ref: EntityId,
703    frame: Transform,
704) -> GeometryResult<[f64; 3]> {
705    let entity = session.entity(owner, point_ref)?;
706    let raw = CartesianPoint::new(point_ref, entity).coordinates_3d()?;
707    let scaled = raw.map(|value| session.units().length(value));
708    Ok(frame.apply(scaled))
709}
710
711/// Resolve an `IfcVector`: unit direction times magnitude, then rotate.
712///
713/// The magnitude is a length and scales; the direction is rotated only.
714fn world_vector(
715    session: &mut LoweringSession<'_>,
716    owner: EntityId,
717    vector_ref: EntityId,
718    frame: Transform,
719) -> GeometryResult<[f64; 3]> {
720    let entity = session.entity(owner, vector_ref)?;
721    let slots = crate::slots::Slots::new(vector_ref, entity);
722    let direction_ref = slots.req_ref(0, "Orientation")?;
723    let magnitude = session.units().length(slots.req_f64(1, "Magnitude")?);
724    let unit = resolve_unit(session.model(), owner, direction_ref)?;
725    let scaled = unit.map(|component| component * magnitude);
726    Ok(frame.apply_direction(scaled))
727}
728
729/// Build a kernel frame from a placed transform.
730fn frame3(t: &Transform) -> Frame3 {
731    Frame3 {
732        origin: Point3::from_array(t.origin),
733        x: Vec3::from_array(t.basis[0]),
734        y: Vec3::from_array(t.basis[1]),
735        z: Vec3::from_array(t.basis[2]),
736    }
737}
738
739#[cfg(test)]
740mod tests;