ifc-geometry 0.3.1

IFC semantic views lowered into the format-neutral geometry DAG.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//! Exact lowering of swept-area profile definitions.
//!
//! IFC units and profile-local placements are resolved here, but curves remain
//! exact. Tessellation is a geometry-kernel decision and never occurs in the
//! format adapter.

use axiolid_core::{Interval, Scalar, Transform2, Vec2};
use axiolid_curve::{Curve2, Line2};
use axiolid_model::{GeometryNode, NodeId};
use axiolid_profile::CenterLineProfile;
use axiolid_profile::{
    CircleProfile, Contour, ContourProfile, EllipseProfile, Profile, ProfileSegment,
    RectangleProfile, SectionProfile,
};
use ifc_model::{EntityId, Model};

use crate::error::{GeometryError, GeometryResult};
use crate::lower::session::LoweringSession;
use crate::resource::operator::operator_transform;
use crate::slots::Slots;
use crate::transform::Transform;
use crate::units::UnitScale;

mod composite;
mod open;
pub use open::lower_open_profile_node;

/// Concrete `IfcProfileDef` families represented exactly by the neutral profile model.
pub const IMPLEMENTED_PROFILES: &[&str] = &[
    "IFCARBITRARYCLOSEDPROFILEDEF",
    "IFCARBITRARYOPENPROFILEDEF",
    "IFCARBITRARYPROFILEDEFWITHVOIDS",
    "IFCASYMMETRICISHAPEPROFILEDEF",
    "IFCCENTERLINEPROFILEDEF",
    "IFCCIRCLEHOLLOWPROFILEDEF",
    "IFCCIRCLEPROFILEDEF",
    "IFCCOMPOSITEPROFILEDEF",
    "IFCCSHAPEPROFILEDEF",
    "IFCDERIVEDPROFILEDEF",
    "IFCELLIPSEPROFILEDEF",
    "IFCISHAPEPROFILEDEF",
    "IFCLSHAPEPROFILEDEF",
    "IFCMIRROREDPROFILEDEF",
    "IFCRECTANGLEHOLLOWPROFILEDEF",
    "IFCRECTANGLEPROFILEDEF",
    "IFCROUNDEDRECTANGLEPROFILEDEF",
    "IFCTSHAPEPROFILEDEF",
    "IFCTRAPEZIUMPROFILEDEF",
    "IFCUSHAPEPROFILEDEF",
    "IFCZSHAPEPROFILEDEF",
];

/// Profile families that are recognized but carry no lowerable geometry.
///
/// `IfcProfileDef` is instantiable in IFC4 (it is not declared ABSTRACT), but
/// it is the bare supertype: it declares only `ProfileType`, `ProfileName` and
/// the curve slots its subtypes add. A file authoring one has supplied a
/// profile *label*, not a section, so this is a permanent typed refusal rather
/// than work awaiting a neutral contract. Every concrete subtype lowers.
pub const PLANNED_PROFILES: &[(&str, &str)] = &[(
    "IFCPROFILEDEF",
    "generic profile declaration carries no concrete geometry to lower",
)];

pub(crate) use crate::slots::profile_slot as slot;
use crate::slots::section_slot;

/// Concrete profile families this lowerer does not yet build, with reasons.
///
/// Paired with `tests/schema_coverage.rs`, which fails if a concrete profile
/// appears in neither this table nor a match arm above. That is what makes the
/// gap visible: the committed corpus contains no steel sections, so a
/// corpus-shaped census reported full coverage while 13 families were absent.
///
/// A reason starting with `kernel:` needs a change in `axiolid-profile`; the
/// rest are IFC-side wiring.
pub const UNLOWERED: &[(&str, &str)] = &[];

/// Family label used for profile memoization.
const PROFILE: &str = "profile";
const OPEN_PROFILE: &str = "open-profile";

/// Append one `IfcProfileDef` to a shared session and return its node.
///
/// Profiles are the most-shared geometry in a real model: one section
/// definition backs every beam of a type. Memoizing here is what keeps a
/// shared profile a single node instead of one copy per referencing solid.
/// The frame is the identity because a profile is defined in its own 2D space;
/// placement is applied by the referencing solid, not baked into the section.
pub fn lower_profile_node(
    session: &mut LoweringSession<'_>,
    id: EntityId,
) -> GeometryResult<NodeId> {
    let frame = crate::transform::Transform::identity();
    if let Some(node) = session.memoized(id, PROFILE, frame) {
        return Ok(node);
    }
    let profile = lower_profile(session.model(), id, session.units())?;
    let node = session.node_for(id, GeometryNode::Profile(profile))?;
    session.memoize(id, PROFILE, frame, node);
    Ok(node)
}

/// Lower one `IfcProfileDef` to an exact, format-neutral profile.
pub fn lower_profile(model: &Model, id: EntityId, units: &UnitScale) -> GeometryResult<Profile> {
    lower_profile_depth(model, id, units, 0)
}

/// Maximum profile nesting depth.
///
/// `IfcCompositeProfileDef` and `IfcDerivedProfileDef` both reference other
/// profiles, so a malicious or broken file can nest them without end. A
/// composite of derived sections is realistic; sixteen levels is not.
const MAX_PROFILE_DEPTH: usize = 16;

/// Lower a profile, tracking nesting depth for the recursive families.
fn lower_profile_depth(
    model: &Model,
    id: EntityId,
    units: &UnitScale,
    depth: usize,
) -> GeometryResult<Profile> {
    if depth > MAX_PROFILE_DEPTH {
        return Err(GeometryError::Unsupported {
            entity: id,
            type_name: "IFCPROFILEDEF".to_string(),
            detail: "profile nesting exceeded the depth budget",
        });
    }
    let entity = model.get(id).ok_or(GeometryError::MissingEntity {
        referrer: id,
        missing: id,
    })?;
    let slots = Slots::new(id, entity);
    let type_name = entity.type_name.to_ascii_uppercase();

    let profile = match type_name.as_str() {
        "IFCRECTANGLEPROFILEDEF" => rectangle(&slots, units, None)?,
        "IFCROUNDEDRECTANGLEPROFILEDEF" => {
            let radius = units.length(slots.req_f64(slot::ROUNDED_RECT_RADIUS, "RoundingRadius")?);
            rectangle(&slots, units, Some(radius))?
        }
        "IFCRECTANGLEHOLLOWPROFILEDEF" => rectangle_hollow(&slots, units)?,
        "IFCCIRCLEPROFILEDEF" => circle(&slots, units, None)?,
        "IFCCIRCLEHOLLOWPROFILEDEF" => circle_hollow(&slots, units)?,
        "IFCARBITRARYCLOSEDPROFILEDEF" => arbitrary(model, &slots, units, false)?,
        "IFCARBITRARYPROFILEDEFWITHVOIDS" => arbitrary(model, &slots, units, true)?,
        "IFCISHAPEPROFILEDEF" => i_shape(&slots, units)?,
        "IFCASYMMETRICISHAPEPROFILEDEF" => asymmetric_i(&slots, units)?,
        "IFCLSHAPEPROFILEDEF" => l_shape(&slots, units)?,
        "IFCTSHAPEPROFILEDEF" => t_shape(&slots, units)?,
        "IFCUSHAPEPROFILEDEF" => u_shape(&slots, units)?,
        "IFCCSHAPEPROFILEDEF" => c_shape(&slots, units)?,
        "IFCZSHAPEPROFILEDEF" => z_shape(&slots, units)?,
        "IFCTRAPEZIUMPROFILEDEF" => trapezium(&slots, units)?,
        "IFCELLIPSEPROFILEDEF" => ellipse(&slots, units)?,
        "IFCCOMPOSITEPROFILEDEF" => composite(model, &slots, units, depth)?,
        "IFCDERIVEDPROFILEDEF" => derived(model, id, &slots, units, depth, false)?,
        "IFCMIRROREDPROFILEDEF" => derived(model, id, &slots, units, depth, true)?,
        "IFCCENTERLINEPROFILEDEF" => center_line(model, &slots, units)?,
        // An open profile is a curve, not an area. The neutral profile model
        // is built on closed contours, so there is nothing to map it onto:
        // closing the curve would fabricate a face the file never described,
        // and silently sweeping it would produce a solid from a shape that
        // bounds no area. State that rather than emitting a generic gap.
        "IFCARBITRARYOPENPROFILEDEF" => {
            return Err(GeometryError::Unsupported {
                entity: id,
                type_name: type_name.to_string(),
                detail: "open profiles have no area; use lower_open_profile_node",
            });
        }
        "IFCPROFILEDEF" => {
            return Err(GeometryError::Unsupported {
                entity: id,
                type_name: type_name.to_string(),
                detail: PLANNED_PROFILES[0].1,
            });
        }
        other => {
            // A declared family reports its specific reason; anything else is
            // a family the crate does not know at all.
            let detail = UNLOWERED
                .iter()
                .find(|(name, _)| *name == other)
                .map(|(_, reason)| *reason)
                .unwrap_or("profile subtype is not lowered yet");
            return Err(GeometryError::Unsupported {
                entity: id,
                type_name: other.to_string(),
                detail,
            });
        }
    };

    if type_name.contains("RECTANGLE") || type_name.contains("CIRCLE") {
        apply_parameterized_position(model, &slots, units, profile)
    } else {
        Ok(profile)
    }
}

fn rectangle(
    slots: &Slots<'_>,
    units: &UnitScale,
    outer_radius: Option<f64>,
) -> GeometryResult<Profile> {
    let x = units.length(slots.req_f64(slot::X_DIM, "XDim")?);
    let y = units.length(slots.req_f64(slot::Y_DIM, "YDim")?);
    if x <= 0.0 || y <= 0.0 || outer_radius.is_some_and(|radius| radius < 0.0) {
        return Err(slots.degenerate("rectangle dimensions and radius must be non-negative"));
    }
    Ok(Profile::Rectangle(RectangleProfile {
        x,
        y,
        thickness: None,
        outer_radius,
        inner_radius: None,
    }))
}

fn rectangle_hollow(slots: &Slots<'_>, units: &UnitScale) -> GeometryResult<Profile> {
    let x = units.length(slots.req_f64(slot::X_DIM, "XDim")?);
    let y = units.length(slots.req_f64(slot::Y_DIM, "YDim")?);
    let thickness = units.length(slots.req_f64(slot::RECT_WALL_THICKNESS, "WallThickness")?);
    if x <= 0.0 || y <= 0.0 || thickness <= 0.0 || 2.0 * thickness >= x.min(y) {
        return Err(slots.degenerate("wall thickness consumes the rectangular section"));
    }
    Ok(Profile::Rectangle(RectangleProfile {
        x,
        y,
        thickness: Some(thickness),
        inner_radius: slots
            .opt_f64(slot::RECT_INNER_RADIUS)
            .map(|value| units.length(value)),
        outer_radius: slots
            .opt_f64(slot::RECT_OUTER_RADIUS)
            .map(|value| units.length(value)),
    }))
}

fn circle(slots: &Slots<'_>, units: &UnitScale, thickness: Option<f64>) -> GeometryResult<Profile> {
    let radius = units.length(slots.req_f64(slot::RADIUS, "Radius")?);
    if radius <= 0.0 || thickness.is_some_and(|wall| wall <= 0.0 || wall >= radius) {
        return Err(slots.degenerate("circle radius or wall thickness is non-physical"));
    }
    Ok(Profile::Circle(CircleProfile { radius, thickness }))
}

fn circle_hollow(slots: &Slots<'_>, units: &UnitScale) -> GeometryResult<Profile> {
    let thickness = units.length(slots.req_f64(slot::CIRCLE_WALL_THICKNESS, "WallThickness")?);
    circle(slots, units, Some(thickness))
}

fn arbitrary(
    model: &Model,
    slots: &Slots<'_>,
    units: &UnitScale,
    with_voids: bool,
) -> GeometryResult<Profile> {
    let outer = curve_to_contour(
        model,
        slots.req_ref(slot::OUTER_CURVE, "OuterCurve")?,
        units,
    )?;
    let mut holes = Vec::new();
    if with_voids {
        for curve in slots.req_ref_list(slot::INNER_CURVES, "InnerCurves")? {
            holes.push(curve_to_contour(model, curve, units)?);
        }
    }
    Ok(Profile::Contour(ContourProfile { outer, holes }))
}

/// Lower one closed profile boundary curve into an exact contour.
///
/// `IfcPolyline` is one ring of straight edges. `IfcCompositeCurve` chains
/// polylines, trimmed circles and lines, and nested composites (#43); it is
/// lowered in `composite`, which refuses gaps rather than bridging them.
fn curve_to_contour(model: &Model, id: EntityId, units: &UnitScale) -> GeometryResult<Contour> {
    let entity = model.get(id).ok_or(GeometryError::MissingEntity {
        referrer: id,
        missing: id,
    })?;
    let type_name = entity.type_name.to_ascii_uppercase();
    match type_name.as_str() {
        "IFCPOLYLINE" => {}
        "IFCCOMPOSITECURVE" => return composite::composite_contour(model, id, units),
        _ => {
            return Err(GeometryError::Unsupported {
                entity: id,
                type_name,
                detail: "profile boundaries lower IfcPolyline and IfcCompositeCurve only",
            })
        }
    }

    let slots = Slots::new(id, entity);
    let mut points = polyline_points(model, id, units)?;
    drop_closing_duplicate(&mut points);
    if points.len() < 3 {
        return Err(slots.degenerate("profile boundary has fewer than 3 distinct points"));
    }

    let segments = (0..points.len())
        .map(|index| {
            let origin = points[index];
            let next = points[(index + 1) % points.len()];
            ProfileSegment {
                curve: Curve2::Line(Line2 {
                    origin,
                    direction: next - origin,
                }),
                domain: Interval::UNIT,
                same_sense: true,
            }
        })
        .collect();
    Ok(Contour::new(segments))
}

/// An `IfcPolyline`'s points as 2D metres, in authored order.
///
/// Shared by the closed-ring and composite-segment readers so both apply the
/// same unit conversion and the same 2D check.
fn polyline_points(model: &Model, id: EntityId, units: &UnitScale) -> GeometryResult<Vec<Vec2>> {
    let entity = model.get(id).ok_or(GeometryError::MissingEntity {
        referrer: id,
        missing: id,
    })?;
    let slots = Slots::new(id, entity);
    let mut points = Vec::new();
    for point_id in slots.req_ref_list(0, "Points")? {
        let point = model.get(point_id).ok_or(GeometryError::MissingEntity {
            referrer: id,
            missing: point_id,
        })?;
        let coordinates = Slots::new(point_id, point).req_f64_list(0, "Coordinates")?;
        if coordinates.len() < 2 {
            return Err(GeometryError::Degenerate {
                entity: point_id,
                type_name: point.type_name.to_string(),
                detail: "profile boundary point is not at least 2D".to_string(),
            });
        }
        points.push(Vec2::new(
            units.length(coordinates[0]),
            units.length(coordinates[1]),
        ));
    }
    Ok(points)
}

fn drop_closing_duplicate(points: &mut Vec<Vec2>) {
    if points.len() >= 2 && points[0].distance(*points.last().expect("length checked")) < 1e-12 {
        points.pop();
    }
}

fn apply_parameterized_position(
    model: &Model,
    slots: &Slots<'_>,
    units: &UnitScale,
    profile: Profile,
) -> GeometryResult<Profile> {
    let Some(position_id) = slots.opt_ref(slot::POSITION) else {
        return Ok(profile);
    };
    let position = model.get(position_id).ok_or(GeometryError::MissingEntity {
        referrer: slots.id(),
        missing: position_id,
    })?;
    let position_slots = Slots::new(position_id, position);
    let location_id = position_slots.req_ref(0, "Location")?;
    let location = model.get(location_id).ok_or(GeometryError::MissingEntity {
        referrer: position_id,
        missing: location_id,
    })?;
    let coordinates = Slots::new(location_id, location).req_f64_list(0, "Coordinates")?;
    if coordinates.len() < 2 {
        return Err(position_slots.degenerate("2D placement location is not 2D"));
    }
    let origin = Vec2::new(units.length(coordinates[0]), units.length(coordinates[1]));
    let x = if let Some(direction_id) = position_slots.opt_ref(1) {
        let direction = model
            .get(direction_id)
            .ok_or(GeometryError::MissingEntity {
                referrer: position_id,
                missing: direction_id,
            })?;
        let ratios = Slots::new(direction_id, direction).req_f64_list(0, "DirectionRatios")?;
        if ratios.len() < 2 {
            return Err(position_slots.degenerate("2D reference direction is not 2D"));
        }
        Vec2::new(ratios[0], ratios[1])
            .try_normalize()
            .ok_or_else(|| position_slots.degenerate("2D reference direction has zero length"))?
    } else {
        Vec2::X
    };
    let y = Vec2::new(-x.y, x.x);
    Ok(Profile::Derived {
        basis: Box::new(profile),
        transform: Transform2::from_cols(x, y, origin),
    })
}

/// Read an optional non-negative length, converting to kernel units.
fn opt_len(slots: &Slots<'_>, slot: usize, units: &UnitScale) -> Option<Scalar> {
    slots.opt_f64(slot).map(|v| units.length(v))
}

/// Read an optional plane angle, converting to kernel units.
///
/// Slopes are angles, not lengths: scaling one by the length factor turns a
/// 2 degree flange taper into radians-times-millimetres and silently deforms
/// the section.
fn opt_angle(slots: &Slots<'_>, slot: usize, units: &UnitScale) -> Option<Scalar> {
    slots.opt_f64(slot).map(|v| units.angle(v))
}

/// Lower a symmetric `IfcIShapeProfileDef`.
fn i_shape(slots: &Slots<'_>, units: &UnitScale) -> GeometryResult<Profile> {
    Ok(Profile::Section(SectionProfile::I {
        depth: units.length(slots.req_f64(section_slot::I_DEPTH, "OverallDepth")?),
        width: units.length(slots.req_f64(section_slot::I_WIDTH, "OverallWidth")?),
        web_thickness: units.length(slots.req_f64(section_slot::I_WEB, "WebThickness")?),
        flange_thickness: units.length(slots.req_f64(section_slot::I_FLANGE, "FlangeThickness")?),
        fillet_radius: opt_len(slots, section_slot::I_FILLET, units),
        flange_edge_radius: opt_len(slots, section_slot::I_EDGE, units),
        flange_slope: opt_angle(slots, section_slot::I_SLOPE, units),
    }))
}

/// Lower an `IfcAsymmetricIShapeProfileDef`.
///
/// Kept distinct from the symmetric variant on purpose: the top and bottom
/// flanges differ in width, thickness, fillet, edge radius and slope. Folding
/// this into `SectionProfile::I` would force a choice of one flange, and the
/// resulting section has the wrong area and the wrong second moment.
fn asymmetric_i(slots: &Slots<'_>, units: &UnitScale) -> GeometryResult<Profile> {
    let bottom_thickness =
        units.length(slots.req_f64(section_slot::AI_BOTTOM_FLANGE, "BottomFlangeThickness")?);
    Ok(Profile::Section(SectionProfile::AsymmetricI {
        depth: units.length(slots.req_f64(section_slot::AI_DEPTH, "OverallDepth")?),
        web_thickness: units.length(slots.req_f64(section_slot::AI_WEB, "WebThickness")?),
        bottom_flange_width: units
            .length(slots.req_f64(section_slot::AI_BOTTOM_WIDTH, "BottomFlangeWidth")?),
        bottom_flange_thickness: bottom_thickness,
        bottom_fillet_radius: opt_len(slots, section_slot::AI_BOTTOM_FILLET, units),
        bottom_flange_edge_radius: opt_len(slots, section_slot::AI_BOTTOM_EDGE, units),
        bottom_flange_slope: opt_angle(slots, section_slot::AI_BOTTOM_SLOPE, units),
        top_flange_width: units
            .length(slots.req_f64(section_slot::AI_TOP_WIDTH, "TopFlangeWidth")?),
        // TopFlangeThickness is optional and defaults to the bottom flange:
        // reading it as zero would produce a section with no top flange.
        top_flange_thickness: opt_len(slots, section_slot::AI_TOP_FLANGE, units),
        top_fillet_radius: opt_len(slots, section_slot::AI_TOP_FILLET, units),
        top_flange_edge_radius: opt_len(slots, section_slot::AI_TOP_EDGE, units),
        top_flange_slope: opt_angle(slots, section_slot::AI_TOP_SLOPE, units),
    }))
}

/// Lower an `IfcLShapeProfileDef`.
fn l_shape(slots: &Slots<'_>, units: &UnitScale) -> GeometryResult<Profile> {
    let depth = units.length(slots.req_f64(section_slot::L_DEPTH, "Depth")?);
    Ok(Profile::Section(SectionProfile::L {
        depth,
        // Width is optional and defaults to Depth, giving an equal-leg angle.
        width: opt_len(slots, section_slot::L_WIDTH, units),
        thickness: units.length(slots.req_f64(section_slot::L_THICKNESS, "Thickness")?),
        fillet_radius: opt_len(slots, section_slot::L_FILLET, units),
        edge_radius: opt_len(slots, section_slot::L_EDGE, units),
        leg_slope: opt_angle(slots, section_slot::L_SLOPE, units),
    }))
}

/// Lower an `IfcTShapeProfileDef`.
fn t_shape(slots: &Slots<'_>, units: &UnitScale) -> GeometryResult<Profile> {
    Ok(Profile::Section(SectionProfile::T {
        depth: units.length(slots.req_f64(section_slot::T_DEPTH, "Depth")?),
        flange_width: units.length(slots.req_f64(section_slot::T_WIDTH, "FlangeWidth")?),
        web_thickness: units.length(slots.req_f64(section_slot::T_WEB, "WebThickness")?),
        flange_thickness: units.length(slots.req_f64(section_slot::T_FLANGE, "FlangeThickness")?),
        fillet_radius: opt_len(slots, section_slot::T_FILLET, units),
        flange_edge_radius: opt_len(slots, section_slot::T_FLANGE_EDGE, units),
        web_edge_radius: opt_len(slots, section_slot::T_WEB_EDGE, units),
        web_slope: opt_angle(slots, section_slot::T_WEB_SLOPE, units),
        flange_slope: opt_angle(slots, section_slot::T_FLANGE_SLOPE, units),
    }))
}

/// Lower an `IfcUShapeProfileDef`.
fn u_shape(slots: &Slots<'_>, units: &UnitScale) -> GeometryResult<Profile> {
    Ok(Profile::Section(SectionProfile::U {
        depth: units.length(slots.req_f64(section_slot::U_DEPTH, "Depth")?),
        flange_width: units.length(slots.req_f64(section_slot::U_WIDTH, "FlangeWidth")?),
        web_thickness: units.length(slots.req_f64(section_slot::U_WEB, "WebThickness")?),
        flange_thickness: units.length(slots.req_f64(section_slot::U_FLANGE, "FlangeThickness")?),
        fillet_radius: opt_len(slots, section_slot::U_FILLET, units),
        edge_radius: opt_len(slots, section_slot::U_EDGE, units),
        flange_slope: opt_angle(slots, section_slot::U_SLOPE, units),
    }))
}

/// Lower an `IfcCShapeProfileDef`.
fn c_shape(slots: &Slots<'_>, units: &UnitScale) -> GeometryResult<Profile> {
    Ok(Profile::Section(SectionProfile::C {
        depth: units.length(slots.req_f64(section_slot::C_DEPTH, "Depth")?),
        width: units.length(slots.req_f64(section_slot::C_WIDTH, "Width")?),
        wall_thickness: units.length(slots.req_f64(section_slot::C_WALL, "WallThickness")?),
        // The returned lip. Dropping it turns a lipped channel into a plain
        // one, which is a different section with different buckling behaviour.
        girth: units.length(slots.req_f64(section_slot::C_GIRTH, "Girth")?),
        internal_fillet_radius: opt_len(slots, section_slot::C_FILLET, units),
    }))
}

/// Lower an `IfcZShapeProfileDef`.
fn z_shape(slots: &Slots<'_>, units: &UnitScale) -> GeometryResult<Profile> {
    Ok(Profile::Section(SectionProfile::Z {
        depth: units.length(slots.req_f64(section_slot::Z_DEPTH, "Depth")?),
        flange_width: units.length(slots.req_f64(section_slot::Z_FLANGE_WIDTH, "FlangeWidth")?),
        web_thickness: units.length(slots.req_f64(section_slot::Z_WEB, "WebThickness")?),
        flange_thickness: units.length(slots.req_f64(section_slot::Z_FLANGE, "FlangeThickness")?),
        fillet_radius: opt_len(slots, section_slot::Z_FILLET, units),
        edge_radius: opt_len(slots, section_slot::Z_EDGE, units),
    }))
}

/// Lower an `IfcTrapeziumProfileDef`.
fn trapezium(slots: &Slots<'_>, units: &UnitScale) -> GeometryResult<Profile> {
    Ok(Profile::Section(SectionProfile::Trapezium {
        bottom_x: units.length(slots.req_f64(section_slot::TZ_BOTTOM, "BottomXDim")?),
        top_x: units.length(slots.req_f64(section_slot::TZ_TOP, "TopXDim")?),
        y: units.length(slots.req_f64(section_slot::TZ_Y, "YDim")?),
        // TopXOffset is a plain IfcLengthMeasure and may be negative, so it
        // must not be read through a positive-length helper.
        top_offset: units.length(slots.req_f64(section_slot::TZ_OFFSET, "TopXOffset")?),
    }))
}

/// Lower an `IfcEllipseProfileDef`.
fn ellipse(slots: &Slots<'_>, units: &UnitScale) -> GeometryResult<Profile> {
    Ok(Profile::Ellipse(EllipseProfile {
        semi_axis_x: units.length(slots.req_f64(section_slot::E_SEMI1, "SemiAxis1")?),
        semi_axis_y: units.length(slots.req_f64(section_slot::E_SEMI2, "SemiAxis2")?),
    }))
}

/// Lower an `IfcCompositeProfileDef` into an ordered profile collection.
///
/// Order is preserved because it is the only identity a composite member has:
/// nothing else distinguishes two same-shaped members.
fn composite(
    model: &Model,
    slots: &Slots<'_>,
    units: &UnitScale,
    depth: usize,
) -> GeometryResult<Profile> {
    let refs = slots.req_ref_list(section_slot::COMPOSITE_PROFILES, "Profiles")?;
    let mut members = Vec::with_capacity(refs.len());
    for member in refs {
        members.push(lower_profile_depth(model, member, units, depth + 1)?);
    }
    Ok(Profile::Composite(members))
}

/// Lower an `IfcDerivedProfileDef` as a parent profile plus a 2D transform.
fn derived(
    model: &Model,
    id: EntityId,
    slots: &Slots<'_>,
    units: &UnitScale,
    depth: usize,
    mirrored: bool,
) -> GeometryResult<Profile> {
    let parent = slots.req_ref(section_slot::DERIVED_PARENT, "ParentProfile")?;
    let basis = lower_profile_depth(model, parent, units, depth + 1)?;

    let transform = (if mirrored {
        // IfcMirroredProfileDef derives its Operator in the schema, so no file
        // carries one: the mirror about the local y axis is implied by the
        // TYPE alone. Reading Operator here would find nothing and silently
        // yield an unmirrored profile, which is why this subtype cannot share
        // the parent's slot-reading path.
        Ok(Transform2::from_scale(Vec2::new(-1.0, 1.0)))
    } else {
        let operator = slots.req_ref(section_slot::DERIVED_OPERATOR, "Operator")?;
        let op_entity = model.get(operator).ok_or(GeometryError::MissingEntity {
            referrer: id,
            missing: operator,
        })?;
        // Reuse the shared operator reader rather than a second 2D-only
        // parser: it already handles the uniform and non-uniform forms.
        let full = operator_transform(model, operator, op_entity)?;
        flatten_to_2d(&full)
    })?;

    Ok(Profile::Derived {
        basis: Box::new(basis),
        transform,
    })
}

/// Reduce a 3D operator transform to the 2D transform a profile lives in.
///
/// A profile is defined in its own xy plane, and
/// `IfcCartesianTransformationOperator2D` is read through the shared 3D
/// reader. Any z component means the file used a 3D operator where the schema
/// requires a 2D one; refusing beats silently projecting geometry away.
fn flatten_to_2d(full: &Transform) -> GeometryResult<Transform2> {
    let m = full.to_geom().matrix3;
    let translation = full.to_geom().translation;
    let z_leak = m.z_axis.x.abs() + m.z_axis.y.abs() + m.x_axis.z.abs() + m.y_axis.z.abs();
    if z_leak > 1e-9 || translation.z.abs() > 1e-9 {
        return Err(GeometryError::Unsupported {
            entity: EntityId(0),
            type_name: "IFCCARTESIANTRANSFORMATIONOPERATOR2D".to_string(),
            detail: "profile operator has out-of-plane components",
        });
    }
    Ok(Transform2::from_cols(
        m.x_axis.truncate(),
        m.y_axis.truncate(),
        translation.truncate(),
    ))
}

/// Lower an `IfcCenterLineProfileDef`.
///
/// `Thickness` is the FULL width across the path, which the kernel stores
/// halved so both offset sides are symmetric by construction.
fn center_line(model: &Model, slots: &Slots<'_>, units: &UnitScale) -> GeometryResult<Profile> {
    let path = open::open_polyline_path(
        model,
        slots.req_ref(section_slot::CL_CURVE, "Curve")?,
        units,
    )?;
    let thickness = units.length(slots.req_f64(section_slot::CL_THICKNESS, "Thickness")?);
    Ok(Profile::CenterLine(CenterLineProfile::from_width(
        path, thickness,
    )))
}