Skip to main content

ifc_geometry/lower/
surface.rs

1//! Surface lowering: the LOW-EXACT surface half.
2//!
3//! # Scope
4//!
5//! Covers the surface families implemented by this adapter: elementary,
6//! swept, bounded, and the explicit-knot `IfcBSplineSurfaceWithKnots` /
7//! `IfcRationalBSplineSurfaceWithKnots` subtypes. Convention-only
8//! `IfcBSplineSurface` remains unsupported because lowering it would require
9//! inventing a knot convention absent from the record. B-splines are lowered
10//! as neutral values only; evaluation remains an Axiolid provider concern.
11//!
12//! # `Depth` is a hint, not a bound
13//!
14//! `IfcSurfaceOfLinearExtrusion` carries a `Depth`, but the surface it
15//! defines is **unbounded** in the extrusion parameter: the schema's own
16//! definition sweeps the curve infinitely and `Depth` exists so a viewer can
17//! draw something finite. The neutral `SurfaceRelation::LinearExtrusion`
18//! therefore has no depth field.
19//!
20//! Scaling the direction by `Depth` to "keep" the information would change
21//! the surface's parameterisation: a point at parameter `v` would move to
22//! `v * depth`, silently reparameterising every trim taken against this
23//! surface. The direction is lowered as a unit-magnitude direction and the
24//! depth is deliberately dropped, which is lossy in exactly the way the
25//! schema intends.
26
27use axiolid_core::Vec3;
28use axiolid_curve::KnotSpec;
29use axiolid_model::{GeometryNode, NodeId, SurfaceRelation};
30use axiolid_surface::{
31    BSplineSurface as KernelBSpline, Cylinder, Plane as KernelPlane, Sphere, Surface, Torus,
32};
33use ifc_model::EntityId;
34
35use crate::curve::bspline::KnotType;
36use crate::error::GeometryResult;
37use crate::lower::curve::{finite_values, lower_curve_node};
38use crate::lower::session::LoweringSession;
39use crate::resource::direction::resolve_unit;
40use crate::resource::placement::axis_placement_transform;
41use crate::resource::placement::Axis1Placement;
42use crate::resource::point::CartesianPoint;
43use crate::surface::bounded::{CurveBoundedPlane, CurveBoundedSurface, RectangularTrimmedSurface};
44use crate::surface::bspline::BSplineSurface;
45use crate::surface::elementary::{CylindricalSurface, Plane, SphericalSurface, ToroidalSurface};
46use crate::surface::swept::SurfaceOfLinearExtrusion;
47use crate::surface::swept::SurfaceOfRevolution;
48use crate::transform::Transform;
49
50/// Family label used for surface memoization.
51const SURFACE: &str = "surface";
52
53/// Lower any supported `IfcSurface` into a node.
54///
55/// Kept as one entry point so a caller holding only an `IfcSurface` reference
56/// (a half space's `BaseSurface`, a swept solid's `ReferenceSurface`) does not
57/// have to re-dispatch on the concrete subtype itself.
58pub fn lower_surface_node(
59    session: &mut LoweringSession<'_>,
60    id: EntityId,
61    frame: Transform,
62) -> GeometryResult<NodeId> {
63    if let Some(existing) = session.memoized(id, SURFACE, frame) {
64        return Ok(existing);
65    }
66    session.enter(id, SURFACE)?;
67    let result = (|| -> GeometryResult<NodeId> {
68        let type_name = session.type_name(id)?.to_ascii_uppercase();
69        match type_name.as_str() {
70            "IFCPLANE" => lower_plane(session, id, frame),
71            "IFCSURFACEOFLINEAREXTRUSION" => lower_linear_extrusion(session, id, frame),
72            "IFCCYLINDRICALSURFACE" => lower_cylinder(session, id, frame),
73            "IFCSPHERICALSURFACE" => lower_sphere(session, id, frame),
74            "IFCTOROIDALSURFACE" => lower_torus(session, id, frame),
75            "IFCBSPLINESURFACEWITHKNOTS" | "IFCRATIONALBSPLINESURFACEWITHKNOTS" => {
76                lower_bspline(session, id, frame)
77            }
78            "IFCSURFACEOFREVOLUTION" => lower_revolution(session, id, frame),
79            "IFCRECTANGULARTRIMMEDSURFACE" => lower_rectangular_trimmed(session, id, frame),
80            "IFCCURVEBOUNDEDPLANE" => lower_curve_bounded(session, id, frame),
81            "IFCCURVEBOUNDEDSURFACE" => lower_curve_bounded_surface(session, id, frame),
82            "IFCSECTIONEDSURFACE" => crate::lower::sectioned::sectioned_surface(session, id, frame),
83            other => Err(session.unsupported(id, other, "curved and B-spline surfaces")),
84        }
85    })();
86    session.exit(id);
87    let node = result?;
88    session.memoize(id, SURFACE, frame, node);
89    Ok(node)
90}
91
92/// Lower an `IfcPlane` into a kernel plane.
93///
94/// The placement's Z axis is the normal and its origin the reference point;
95/// both are placed by `frame` and the origin converted to metres. The normal
96/// takes the linear part only, so an off-origin plane keeps its orientation.
97pub fn lower_plane(
98    session: &mut LoweringSession<'_>,
99    id: EntityId,
100    frame: Transform,
101) -> GeometryResult<NodeId> {
102    let entity = session.entity(id, id)?;
103    let view = Plane::new(id, entity);
104    let position_id = view.position_ref()?;
105    let position = session.entity(id, position_id)?;
106    let local = axis_placement_transform(session.model(), position_id, position)?
107        .to_metres(session.units());
108    let placed = frame.compose(&local);
109
110    let normal = placed.apply_direction([0.0, 0.0, 1.0]);
111    let length = (normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2]).sqrt();
112    if !length.is_finite() || length <= f64::EPSILON {
113        return Err(session.degenerate(
114            id,
115            "IFCPLANE",
116            "plane normal is zero-length or non-finite",
117        ));
118    }
119
120    let plane = KernelPlane {
121        frame: placed.to_geom_frame(id)?,
122    };
123    session.node_for(id, GeometryNode::Surface(Surface::Plane(plane)))
124}
125
126/// Lower an `IfcSurfaceOfLinearExtrusion` into a linear-extrusion relation.
127///
128/// `Depth` is intentionally not carried: see the module docs. The swept curve
129/// is lowered first so the relation can reference its node.
130pub fn lower_linear_extrusion(
131    session: &mut LoweringSession<'_>,
132    id: EntityId,
133    frame: Transform,
134) -> GeometryResult<NodeId> {
135    let entity = session.entity(id, id)?;
136    let view = SurfaceOfLinearExtrusion::new(id, entity);
137
138    // An optional Position places the whole swept surface.
139    let placed = match view.position_ref() {
140        Some(position_id) => {
141            let position = session.entity(id, position_id)?;
142            let local = axis_placement_transform(session.model(), position_id, position)?
143                .to_metres(session.units());
144            frame.compose(&local)
145        }
146        None => frame,
147    };
148
149    let curve_id = view.swept_curve_ref()?;
150    let swept_curve = swept_generatrix(session, id, curve_id, placed)?;
151
152    // ExtrudedDirection is already unit: `resolve_unit` normalizes at the IFC
153    // boundary, which is where this crate's contract says directions are
154    // normalized exactly once. Under a rigid placement `apply_direction`
155    // preserves that, so re-normalizing here would be dead code. Only the
156    // degenerate case still needs rejecting.
157    let raw = resolve_unit(session.model(), id, view.extruded_direction_ref()?)?;
158    let direction = placed.apply_direction(raw);
159    let length =
160        (direction[0] * direction[0] + direction[1] * direction[1] + direction[2] * direction[2])
161            .sqrt();
162    if !length.is_finite() || length <= f64::EPSILON {
163        return Err(session.degenerate(
164            id,
165            "IFCSURFACEOFLINEAREXTRUSION",
166            "extruded direction is zero-length or non-finite",
167        ));
168    }
169
170    session.node_for(
171        id,
172        GeometryNode::SurfaceRelation(SurfaceRelation::LinearExtrusion {
173            swept_curve,
174            direction: Vec3::from_array(direction),
175        }),
176    )
177}
178
179mod trim;
180pub(crate) use trim::trim_converter;
181
182#[cfg(test)]
183mod revolution_tests;
184#[cfg(test)]
185mod tests;
186
187/// Compose an entity's `Position` with the caller's frame, in metres.
188///
189/// Every elementary surface places itself the same way; sharing this keeps the
190/// unit conversion in exactly one place. A radius converted with a different
191/// factor than its own frame origin puts the surface somewhere the file never
192/// described.
193fn placed_frame(
194    session: &mut LoweringSession<'_>,
195    owner: EntityId,
196    position_id: EntityId,
197    frame: Transform,
198) -> GeometryResult<axiolid_core::Frame3> {
199    let position = session.entity(owner, position_id)?;
200    let local = axis_placement_transform(session.model(), position_id, position)?
201        .to_metres(session.units());
202    frame.compose(&local).to_geom_frame(owner)
203}
204
205/// Convert one length-valued scalar into metres.
206fn to_metres(session: &LoweringSession<'_>, value: f64) -> f64 {
207    value * session.units().length_to_metres
208}
209
210/// Read an `IfcCartesianPoint`'s three coordinates, as written.
211fn cartesian_point_3d(
212    session: &LoweringSession<'_>,
213    referrer: EntityId,
214    id: EntityId,
215) -> GeometryResult<[f64; 3]> {
216    let entity = session.entity(referrer, id)?;
217    let point = CartesianPoint::new(id, entity);
218    point.coordinates_3d()
219}
220
221/// Lower an `IfcCylindricalSurface` into a kernel cylinder.
222///
223/// The radius is a length and converts to metres; the frame axes do not.
224/// Scaling the axes as well would turn a unit basis into a millimetre-long
225/// one and every parameter measured against it would be off by that factor.
226pub fn lower_cylinder(
227    session: &mut LoweringSession<'_>,
228    id: EntityId,
229    frame: Transform,
230) -> GeometryResult<NodeId> {
231    let entity = session.entity(id, id)?;
232    let view = CylindricalSurface::new(id, entity);
233    let placed = placed_frame(session, id, view.position_ref()?, frame)?;
234    let radius = to_metres(session, view.radius()?);
235    session.node_for(
236        id,
237        GeometryNode::Surface(Surface::Cylinder(Cylinder {
238            frame: placed,
239            radius,
240        })),
241    )
242}
243
244/// Lower an `IfcSphericalSurface` into a kernel sphere.
245pub fn lower_sphere(
246    session: &mut LoweringSession<'_>,
247    id: EntityId,
248    frame: Transform,
249) -> GeometryResult<NodeId> {
250    let entity = session.entity(id, id)?;
251    let view = SphericalSurface::new(id, entity);
252    let placed = placed_frame(session, id, view.position_ref()?, frame)?;
253    let radius = to_metres(session, view.radius()?);
254    session.node_for(
255        id,
256        GeometryNode::Surface(Surface::Sphere(Sphere {
257            frame: placed,
258            radius,
259        })),
260    )
261}
262
263/// Lower an `IfcToroidalSurface` into a kernel torus.
264///
265/// Both radii are lengths. A torus with `minor >= major` self-intersects into
266/// a spindle; that is legal IFC and the reader exposes it, so it is preserved
267/// rather than rejected -- discarding it would silently change the shape.
268pub fn lower_torus(
269    session: &mut LoweringSession<'_>,
270    id: EntityId,
271    frame: Transform,
272) -> GeometryResult<NodeId> {
273    let entity = session.entity(id, id)?;
274    let view = ToroidalSurface::new(id, entity);
275    let placed = placed_frame(session, id, view.position_ref()?, frame)?;
276    let major_radius = to_metres(session, view.major_radius()?);
277    let minor_radius = to_metres(session, view.minor_radius()?);
278    session.node_for(
279        id,
280        GeometryNode::Surface(Surface::Torus(Torus {
281            frame: placed,
282            major_radius,
283            minor_radius,
284        })),
285    )
286}
287
288/// Map the IFC knot enumeration onto the kernel's.
289///
290/// The variants correspond one to one, so this is a rename, not a decision.
291fn knot_spec(source: KnotType) -> KnotSpec {
292    match source {
293        KnotType::Uniform => KnotSpec::Uniform,
294        KnotType::QuasiUniform => KnotSpec::QuasiUniform,
295        KnotType::PiecewiseBezier => KnotSpec::PiecewiseBezier,
296        KnotType::Unspecified => KnotSpec::Unspecified,
297    }
298}
299
300/// Lower an `IfcBSplineSurfaceWithKnots` into a kernel B-spline patch.
301///
302/// The control net stays row-major in `u` then `v`, matching both the IFC
303/// `ControlPointsList` and the kernel field. A transposed net still evaluates
304/// and still looks like a surface, so the per-direction degrees, knots and
305/// multiplicities are carried through verbatim rather than inferred from the
306/// net's shape.
307///
308/// `WeightsData` is present only on the rational subtype. Defaulting absent
309/// weights to 1.0 would turn a polynomial patch into a rational one that
310/// happens to agree, so `None` is preserved as `None`.
311pub fn lower_bspline(
312    session: &mut LoweringSession<'_>,
313    id: EntityId,
314    frame: Transform,
315) -> GeometryResult<NodeId> {
316    let entity = session.entity(id, id)?;
317    let view = BSplineSurface::new(id, entity);
318    let type_name = session.type_name(id)?;
319    let u_degree = u16::try_from(view.u_degree()?)
320        .map_err(|_| session.degenerate(id, &type_name, "UDegree exceeds u16"))?;
321    let v_degree = u16::try_from(view.v_degree()?)
322        .map_err(|_| session.degenerate(id, &type_name, "VDegree exceeds u16"))?;
323
324    // Budget the declared aggregate sizes BEFORE materializing anything. The
325    // knot totals are cheap sums of file integers, so they are checked first;
326    // the grid check then bounds the loop below, which is what actually
327    // allocates. Doing this after the loop would defeat the purpose.
328    let u = view.u_knots()?.ok_or_else(|| {
329        session.unsupported(id, &type_name, "B-spline surface without explicit u knots")
330    })?;
331    let v = view.v_knots()?.ok_or_else(|| {
332        session.unsupported(id, &type_name, "B-spline surface without explicit v knots")
333    })?;
334    let u_declared: u128 = u.multiplicities.iter().map(|m| *m as u128).sum();
335    session.check_aggregate(id, &type_name, "u knot multiplicities", u_declared)?;
336    let v_declared: u128 = v.multiplicities.iter().map(|m| *m as u128).sum();
337    session.check_aggregate(id, &type_name, "v knot multiplicities", v_declared)?;
338
339    let grid = view.control_points()?;
340    // The control grid is u_count * v_count points. Both come from the file,
341    // so compute the product in u128: a wrapped usize would pass the budget.
342    session.check_aggregate(
343        id,
344        &type_name,
345        "control grid points",
346        grid.u_count() as u128 * grid.v_count() as u128,
347    )?;
348    let mut control_points = Vec::with_capacity(grid.u_count());
349    for row in grid.rows() {
350        let mut out_row = Vec::with_capacity(row.len());
351        for point_id in row {
352            let raw = cartesian_point_3d(session, id, *point_id)?;
353            let placed = frame.apply(raw.map(|value| to_metres(session, value)));
354            finite_values(
355                session,
356                id,
357                &type_name,
358                "transformed control point",
359                &placed,
360            )?;
361            out_row.push(axiolid_core::Point3::from_array(placed));
362        }
363        control_points.push(out_row);
364    }
365
366    finite_values(session, id, &type_name, "UKnots", &u.values)?;
367    finite_values(session, id, &type_name, "VKnots", &v.values)?;
368    let u_multiplicities = multiplicities(session, id, &type_name, u.multiplicities)?;
369    let v_multiplicities = multiplicities(session, id, &type_name, v.multiplicities)?;
370    let weights = view.weights()?;
371    if let Some(rows) = weights.as_ref() {
372        for row in rows {
373            finite_values(session, id, &type_name, "WeightsData", row)?;
374        }
375    }
376    let u_closed = view.u_closed().ok_or_else(|| {
377        session.unsupported(id, &type_name, "unknown UClosed is not lossless in bool")
378    })?;
379    let v_closed = view.v_closed().ok_or_else(|| {
380        session.unsupported(id, &type_name, "unknown VClosed is not lossless in bool")
381    })?;
382
383    let surface = KernelBSpline {
384        u_degree,
385        v_degree,
386        control_points,
387        u_knots: u.values,
388        u_multiplicities,
389        v_knots: v.values,
390        v_multiplicities,
391        weights,
392        u_closed,
393        v_closed,
394        self_intersect: view.self_intersect(),
395        knot_spec: knot_spec(view.knot_spec()),
396    };
397    session.node_for(id, GeometryNode::Surface(Surface::BSpline(surface)))
398}
399
400fn multiplicities(
401    session: &LoweringSession<'_>,
402    id: EntityId,
403    type_name: &str,
404    values: Vec<usize>,
405) -> GeometryResult<Vec<u32>> {
406    values
407        .into_iter()
408        .map(|value| {
409            u32::try_from(value)
410                .map_err(|_| session.degenerate(id, type_name, "multiplicity exceeds u32"))
411        })
412        .collect()
413}
414
415/// Resolve a swept surface's `SweptCurve` to the curve it actually names.
416///
417/// IFC types this slot as `IfcProfileDef`, so a plain curve arrives wrapped in
418/// an `IfcArbitraryOpenProfileDef`. The wrapper carries no geometry of its own
419/// here -- for a swept SURFACE the profile is a generatrix, not an area -- so
420/// it is unwrapped rather than lowered as a profile. Lowering it as one would
421/// demand a closed contour and reject a legitimately open generatrix.
422fn swept_generatrix(
423    session: &mut LoweringSession<'_>,
424    _owner: EntityId,
425    swept_curve: EntityId,
426    frame: Transform,
427) -> GeometryResult<NodeId> {
428    let kind = session.type_name(swept_curve)?.to_ascii_uppercase();
429    let curve_id = if kind == "IFCARBITRARYOPENPROFILEDEF" || kind == "IFCARBITRARYCLOSEDPROFILEDEF"
430    {
431        // Slot 2 is Curve on IfcArbitraryOpenProfileDef and OuterCurve on
432        // the closed form; both name the generatrix.
433        session.slots(swept_curve)?.req_ref(2, "Curve")?
434    } else {
435        swept_curve
436    };
437    lower_curve_node(session, curve_id, frame)
438}
439
440/// Lower an `IfcSurfaceOfRevolution` into a revolution relation.
441///
442/// `AxisPosition` is an `IfcAxis1Placement`, not the `IfcAxis2Placement3D`
443/// every other surface family uses. Both carry a Location, so reading the
444/// wrong one still yields a surface -- just one revolved about the wrong line.
445/// The axis origin is a length and converts; the direction is placed by the
446/// linear part only so an off-origin frame does not translate it.
447///
448/// `Position` (#547) is composed into the frame for the generatrix and the
449/// axis alike.
450pub fn lower_revolution(
451    session: &mut LoweringSession<'_>,
452    id: EntityId,
453    frame: Transform,
454) -> GeometryResult<NodeId> {
455    let entity = session.entity(id, id)?;
456    let view = SurfaceOfRevolution::new(id, entity);
457
458    // An optional Position places the whole surface, axis included, as it does
459    // for the linear extrusion. A conforming generatrix is 2D (WR12) and lies
460    // in XY until `Position` places it.
461    let placed = match view.position_ref() {
462        Some(position_id) => {
463            let position = session.entity(id, position_id)?;
464            let local = axis_placement_transform(session.model(), position_id, position)?
465                .to_metres(session.units());
466            frame.compose(&local)
467        }
468        None => frame,
469    };
470
471    let swept_curve = swept_generatrix(session, id, view.swept_curve_ref()?, placed)?;
472
473    let axis_id = view.axis_position_ref()?;
474    let axis_entity = session.entity(id, axis_id)?;
475    let axis = Axis1Placement::new(axis_id, axis_entity);
476    let raw_origin = axis.location(session.model())?;
477    let origin = placed.apply([
478        to_metres(session, raw_origin[0]),
479        to_metres(session, raw_origin[1]),
480        to_metres(session, raw_origin[2]),
481    ]);
482    let direction = placed.apply_direction(axis.axis(session.model())?);
483
484    session.node_for(
485        id,
486        GeometryNode::SurfaceRelation(SurfaceRelation::Revolution {
487            swept_curve,
488            axis_origin: axiolid_core::Point3::from_array(origin),
489            axis_direction: axiolid_core::Vec3::from_array(direction),
490        }),
491    )
492}
493
494/// Lower an `IfcRectangularTrimmedSurface` into a parameter-space trim.
495///
496/// The trim parameters are NOT all lengths. A revolution or conic direction
497/// is an angle in the model's plane-angle unit, which is degrees in many real
498/// exports; a plane, and a cylinder's axis, are lengths; a revolved surface's
499/// `v` is its generatrix's own parameter. Scaling everything by one factor
500/// turns a 90-degree patch into a sliver, or a cylinder's height into radians,
501/// and still renders (#589).
502pub fn lower_rectangular_trimmed(
503    session: &mut LoweringSession<'_>,
504    id: EntityId,
505    frame: Transform,
506) -> GeometryResult<NodeId> {
507    let entity = session.entity(id, id)?;
508    let view = RectangularTrimmedSurface::new(id, entity);
509    let basis_id = view.basis_surface_ref()?;
510    let basis = lower_surface_node(session, basis_id, frame)?;
511    let rect = view.rectangle()?;
512
513    let (convert_u, convert_v) = trim_converter(session, id, basis_id)?;
514
515    session.node_for(
516        id,
517        GeometryNode::SurfaceRelation(SurfaceRelation::RectangularTrimmed {
518            basis,
519            u: (convert_u(rect.u1), convert_u(rect.u2)),
520            v: (convert_v(rect.v1), convert_v(rect.v2)),
521            u_sense: rect.usense,
522            v_sense: rect.vsense,
523        }),
524    )
525}
526
527/// Lower an `IfcCurveBoundedPlane` into a curve-bounded relation.
528///
529/// The outer boundary is explicit here, unlike `IfcCurveBoundedSurface` where
530/// it may be implicit, so `implicit_outer` is false and the outer curve leads
531/// the boundary list.
532///
533/// Only the basis plane takes `frame`. The boundaries are authored in the
534/// plane's own parameter space, where a point `(u, v)` lies at `u` along the
535/// plane's x axis and `v` along its y axis from its `Location`. The neutral
536/// relation reads them the same way, so the plane's placement already carries
537/// them to the frame. Placing them too moved every boundary a second time
538/// (#163).
539pub fn lower_curve_bounded(
540    session: &mut LoweringSession<'_>,
541    id: EntityId,
542    frame: Transform,
543) -> GeometryResult<NodeId> {
544    let entity = session.entity(id, id)?;
545    let view = CurveBoundedPlane::new(id, entity);
546    let basis = lower_surface_node(session, view.basis_surface_ref()?, frame)?;
547
548    let parameter_space = Transform::identity();
549    let mut boundaries = vec![lower_curve_node(
550        session,
551        view.outer_boundary_ref()?,
552        parameter_space,
553    )?];
554    for inner in view.inner_boundary_refs() {
555        boundaries.push(lower_curve_node(session, inner, parameter_space)?);
556    }
557
558    session.node_for(
559        id,
560        GeometryNode::SurfaceRelation(SurfaceRelation::CurveBounded {
561            basis,
562            boundaries,
563            implicit_outer: false,
564        }),
565    )
566}
567
568/// Lower a generic `IfcCurveBoundedSurface`, preserving boundary order and
569/// whether the source omitted an explicit outer boundary.
570pub fn lower_curve_bounded_surface(
571    session: &mut LoweringSession<'_>,
572    id: EntityId,
573    frame: Transform,
574) -> GeometryResult<NodeId> {
575    let entity = session.entity(id, id)?;
576    let view = CurveBoundedSurface::new(id, entity);
577    let basis = lower_surface_node(session, view.basis_surface_ref()?, frame)?;
578    let refs = view.boundary_refs()?;
579    let mut boundaries = Vec::with_capacity(refs.len());
580    for boundary in refs {
581        boundaries.push(lower_curve_node(session, boundary, frame)?);
582    }
583
584    session.node_for(
585        id,
586        GeometryNode::SurfaceRelation(SurfaceRelation::CurveBounded {
587            basis,
588            boundaries,
589            implicit_outer: view.implicit_outer(),
590        }),
591    )
592}