Skip to main content

ifc_lite_geometry/
profiles.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Profile Processors - Handle all IFC profile types
6//!
7//! Dynamic profile processing for parametric, arbitrary, and composite profiles.
8
9use crate::profile::Profile2D;
10use crate::{Error, Point2, Point3, Result, Vector3};
11use ifc_lite_core::{AttributeValue, DecodedEntity, EntityDecoder, IfcSchema, IfcType, ProfileCategory};
12use std::f64::consts::PI;
13
14/// Maximum recursion depth for nested curve processing.
15/// Prevents stack overflow from deeply nested CompositeCurve → TrimmedCurve → CompositeCurve chains.
16const MAX_CURVE_DEPTH: u32 = 50;
17
18/// Profile processor - processes IFC profiles into 2D contours
19pub struct ProfileProcessor {
20    schema: IfcSchema,
21}
22
23impl ProfileProcessor {
24    /// Create new profile processor
25    pub fn new(schema: IfcSchema) -> Self {
26        Self { schema }
27    }
28
29    /// Process any IFC profile definition
30    #[inline]
31    pub fn process(
32        &self,
33        profile: &DecodedEntity,
34        decoder: &mut EntityDecoder,
35    ) -> Result<Profile2D> {
36        match self.schema.profile_category(&profile.ifc_type) {
37            Some(ProfileCategory::Parametric) => self.process_parametric(profile, decoder),
38            Some(ProfileCategory::Arbitrary) => self.process_arbitrary(profile, decoder),
39            Some(ProfileCategory::Composite) => self.process_composite(profile, decoder),
40            _ => Err(Error::geometry(format!(
41                "Unsupported profile type: {}",
42                profile.ifc_type
43            ))),
44        }
45    }
46
47    /// Process parametric profiles (rectangle, circle, I-shape, etc.)
48    #[inline]
49    fn process_parametric(
50        &self,
51        profile: &DecodedEntity,
52        decoder: &mut EntityDecoder,
53    ) -> Result<Profile2D> {
54        // First create the base profile shape
55        let mut base_profile = match profile.ifc_type {
56            IfcType::IfcRectangleProfileDef => self.process_rectangle(profile),
57            IfcType::IfcCircleProfileDef => self.process_circle(profile),
58            IfcType::IfcCircleHollowProfileDef => self.process_circle_hollow(profile),
59            IfcType::IfcRectangleHollowProfileDef => self.process_rectangle_hollow(profile),
60            IfcType::IfcIShapeProfileDef => self.process_i_shape(profile),
61            IfcType::IfcLShapeProfileDef => self.process_l_shape(profile),
62            IfcType::IfcUShapeProfileDef => self.process_u_shape(profile),
63            IfcType::IfcTShapeProfileDef => self.process_t_shape(profile),
64            IfcType::IfcCShapeProfileDef => self.process_c_shape(profile),
65            IfcType::IfcZShapeProfileDef => self.process_z_shape(profile),
66            _ => Err(Error::geometry(format!(
67                "Unsupported parametric profile: {}",
68                profile.ifc_type
69            ))),
70        }?;
71
72        // Apply Profile Position transform (attribute 2: IfcAxis2Placement2D)
73        if let Some(pos_attr) = profile.get(2) {
74            if !pos_attr.is_null() {
75                if let Some(pos_entity) = decoder.resolve_ref(pos_attr)? {
76                    if pos_entity.ifc_type == IfcType::IfcAxis2Placement2D {
77                        self.apply_profile_position(&mut base_profile, &pos_entity, decoder)?;
78                    }
79                }
80            }
81        }
82
83        Ok(base_profile)
84    }
85
86    /// Apply IfcAxis2Placement2D transform to profile points
87    /// IfcAxis2Placement2D: Location, RefDirection
88    fn apply_profile_position(
89        &self,
90        profile: &mut Profile2D,
91        placement: &DecodedEntity,
92        decoder: &mut EntityDecoder,
93    ) -> Result<()> {
94        // Get Location (attribute 0) - IfcCartesianPoint
95        let (loc_x, loc_y) = if let Some(loc_attr) = placement.get(0) {
96            if !loc_attr.is_null() {
97                if let Some(loc_entity) = decoder.resolve_ref(loc_attr)? {
98                    let coords = loc_entity
99                        .get(0)
100                        .and_then(|v| v.as_list())
101                        .ok_or_else(|| Error::geometry("Missing point coordinates".to_string()))?;
102                    let x = coords.first().and_then(|v| v.as_float()).unwrap_or(0.0);
103                    let y = coords.get(1).and_then(|v| v.as_float()).unwrap_or(0.0);
104                    (x, y)
105                } else {
106                    (0.0, 0.0)
107                }
108            } else {
109                (0.0, 0.0)
110            }
111        } else {
112            (0.0, 0.0)
113        };
114
115        // Get RefDirection (attribute 1) - IfcDirection (optional, default is (1,0))
116        let (dir_x, dir_y) = if let Some(dir_attr) = placement.get(1) {
117            if !dir_attr.is_null() {
118                if let Some(dir_entity) = decoder.resolve_ref(dir_attr)? {
119                    let ratios = dir_entity
120                        .get(0)
121                        .and_then(|v| v.as_list())
122                        .ok_or_else(|| Error::geometry("Missing direction ratios".to_string()))?;
123                    let x = ratios.first().and_then(|v| v.as_float()).unwrap_or(1.0);
124                    let y = ratios.get(1).and_then(|v| v.as_float()).unwrap_or(0.0);
125                    // Normalize
126                    let len = (x * x + y * y).sqrt();
127                    if len > 1e-10 {
128                        (x / len, y / len)
129                    } else {
130                        (1.0, 0.0)
131                    }
132                } else {
133                    (1.0, 0.0)
134                }
135            } else {
136                (1.0, 0.0)
137            }
138        } else {
139            (1.0, 0.0)
140        };
141
142        // Skip transform if it's identity (location at origin, direction is (1,0))
143        if loc_x.abs() < 1e-10
144            && loc_y.abs() < 1e-10
145            && (dir_x - 1.0).abs() < 1e-10
146            && dir_y.abs() < 1e-10
147        {
148            return Ok(());
149        }
150
151        // RefDirection is the local X axis direction
152        // Local Y axis is perpendicular: (-dir_y, dir_x)
153        let x_axis = (dir_x, dir_y);
154        let y_axis = (-dir_y, dir_x);
155
156        // Transform all outer points
157        for point in &mut profile.outer {
158            let old_x = point.x;
159            let old_y = point.y;
160            // Rotation then translation: p' = R * p + t
161            point.x = old_x * x_axis.0 + old_y * y_axis.0 + loc_x;
162            point.y = old_x * x_axis.1 + old_y * y_axis.1 + loc_y;
163        }
164
165        // Transform all hole points
166        for hole in &mut profile.holes {
167            for point in hole {
168                let old_x = point.x;
169                let old_y = point.y;
170                point.x = old_x * x_axis.0 + old_y * y_axis.0 + loc_x;
171                point.y = old_x * x_axis.1 + old_y * y_axis.1 + loc_y;
172            }
173        }
174
175        Ok(())
176    }
177
178    /// Process rectangle profile
179    /// IfcRectangleProfileDef: ProfileType, ProfileName, Position, XDim, YDim
180    #[inline]
181    fn process_rectangle(&self, profile: &DecodedEntity) -> Result<Profile2D> {
182        // Get dimensions (attributes 3 and 4)
183        let x_dim = profile
184            .get_float(3)
185            .ok_or_else(|| Error::geometry("Rectangle missing XDim".to_string()))?;
186        let y_dim = profile
187            .get_float(4)
188            .ok_or_else(|| Error::geometry("Rectangle missing YDim".to_string()))?;
189
190        // Create rectangle centered at origin
191        let half_x = x_dim / 2.0;
192        let half_y = y_dim / 2.0;
193
194        let points = vec![
195            Point2::new(-half_x, -half_y),
196            Point2::new(half_x, -half_y),
197            Point2::new(half_x, half_y),
198            Point2::new(-half_x, half_y),
199        ];
200
201        Ok(Profile2D::new(points))
202    }
203
204    /// Process circle profile
205    /// IfcCircleProfileDef: ProfileType, ProfileName, Position, Radius
206    #[inline]
207    fn process_circle(&self, profile: &DecodedEntity) -> Result<Profile2D> {
208        // Get radius (attribute 3)
209        let radius = profile
210            .get_float(3)
211            .ok_or_else(|| Error::geometry("Circle missing Radius".to_string()))?;
212
213        // Generate circle with 24 segments (matches web-ifc typical quality)
214        let segments = 24;
215        let mut points = Vec::with_capacity(segments);
216
217        for i in 0..segments {
218            let angle = (i as f64) * 2.0 * PI / (segments as f64);
219            let x = radius * angle.cos();
220            let y = radius * angle.sin();
221            points.push(Point2::new(x, y));
222        }
223
224        Ok(Profile2D::new(points))
225    }
226
227    /// Process I-shape profile (simplified - basic I-beam)
228    /// IfcIShapeProfileDef: ProfileType, ProfileName, Position, OverallWidth, OverallDepth, WebThickness, FlangeThickness, ...
229    fn process_i_shape(&self, profile: &DecodedEntity) -> Result<Profile2D> {
230        // Get dimensions
231        let overall_width = profile
232            .get_float(3)
233            .ok_or_else(|| Error::geometry("I-Shape missing OverallWidth".to_string()))?;
234        let overall_depth = profile
235            .get_float(4)
236            .ok_or_else(|| Error::geometry("I-Shape missing OverallDepth".to_string()))?;
237        let web_thickness = profile
238            .get_float(5)
239            .ok_or_else(|| Error::geometry("I-Shape missing WebThickness".to_string()))?;
240        let flange_thickness = profile
241            .get_float(6)
242            .ok_or_else(|| Error::geometry("I-Shape missing FlangeThickness".to_string()))?;
243
244        let half_width = overall_width / 2.0;
245        let half_depth = overall_depth / 2.0;
246        let half_web = web_thickness / 2.0;
247
248        // Create I-shape profile (counter-clockwise from bottom-left)
249        let points = vec![
250            // Bottom flange
251            Point2::new(-half_width, -half_depth),
252            Point2::new(half_width, -half_depth),
253            Point2::new(half_width, -half_depth + flange_thickness),
254            // Right side of web
255            Point2::new(half_web, -half_depth + flange_thickness),
256            Point2::new(half_web, half_depth - flange_thickness),
257            // Top flange
258            Point2::new(half_width, half_depth - flange_thickness),
259            Point2::new(half_width, half_depth),
260            Point2::new(-half_width, half_depth),
261            Point2::new(-half_width, half_depth - flange_thickness),
262            // Left side of web
263            Point2::new(-half_web, half_depth - flange_thickness),
264            Point2::new(-half_web, -half_depth + flange_thickness),
265            Point2::new(-half_width, -half_depth + flange_thickness),
266        ];
267
268        Ok(Profile2D::new(points))
269    }
270
271    /// Process circle hollow profile (tube/pipe)
272    /// IfcCircleHollowProfileDef: ProfileType, ProfileName, Position, Radius, WallThickness
273    fn process_circle_hollow(&self, profile: &DecodedEntity) -> Result<Profile2D> {
274        let radius = profile
275            .get_float(3)
276            .ok_or_else(|| Error::geometry("CircleHollow missing Radius".to_string()))?;
277        let wall_thickness = profile
278            .get_float(4)
279            .ok_or_else(|| Error::geometry("CircleHollow missing WallThickness".to_string()))?;
280
281        let inner_radius = radius - wall_thickness;
282        let segments = 24;
283
284        // Outer circle
285        let mut outer_points = Vec::with_capacity(segments);
286        for i in 0..segments {
287            let angle = (i as f64) * 2.0 * PI / (segments as f64);
288            outer_points.push(Point2::new(radius * angle.cos(), radius * angle.sin()));
289        }
290
291        // Inner circle (reversed for hole)
292        let mut inner_points = Vec::with_capacity(segments);
293        for i in (0..segments).rev() {
294            let angle = (i as f64) * 2.0 * PI / (segments as f64);
295            inner_points.push(Point2::new(
296                inner_radius * angle.cos(),
297                inner_radius * angle.sin(),
298            ));
299        }
300
301        let mut result = Profile2D::new(outer_points);
302        result.add_hole(inner_points);
303        Ok(result)
304    }
305
306    /// Process rectangle hollow profile (rectangular tube)
307    /// IfcRectangleHollowProfileDef: ProfileType, ProfileName, Position, XDim, YDim, WallThickness, InnerFilletRadius, OuterFilletRadius
308    fn process_rectangle_hollow(&self, profile: &DecodedEntity) -> Result<Profile2D> {
309        let x_dim = profile
310            .get_float(3)
311            .ok_or_else(|| Error::geometry("RectangleHollow missing XDim".to_string()))?;
312        let y_dim = profile
313            .get_float(4)
314            .ok_or_else(|| Error::geometry("RectangleHollow missing YDim".to_string()))?;
315        let wall_thickness = profile
316            .get_float(5)
317            .ok_or_else(|| Error::geometry("RectangleHollow missing WallThickness".to_string()))?;
318
319        let half_x = x_dim / 2.0;
320        let half_y = y_dim / 2.0;
321
322        // Validate wall thickness
323        if wall_thickness >= half_x || wall_thickness >= half_y {
324            return Err(Error::geometry(format!(
325                "RectangleHollow WallThickness {} exceeds half dimensions ({}, {})",
326                wall_thickness, half_x, half_y
327            )));
328        }
329
330        let inner_half_x = half_x - wall_thickness;
331        let inner_half_y = half_y - wall_thickness;
332
333        // Outer rectangle (counter-clockwise)
334        let outer_points = vec![
335            Point2::new(-half_x, -half_y),
336            Point2::new(half_x, -half_y),
337            Point2::new(half_x, half_y),
338            Point2::new(-half_x, half_y),
339        ];
340
341        // Inner rectangle (clockwise for hole - reversed order)
342        let inner_points = vec![
343            Point2::new(-inner_half_x, -inner_half_y),
344            Point2::new(-inner_half_x, inner_half_y),
345            Point2::new(inner_half_x, inner_half_y),
346            Point2::new(inner_half_x, -inner_half_y),
347        ];
348
349        let mut result = Profile2D::new(outer_points);
350        result.add_hole(inner_points);
351        Ok(result)
352    }
353
354    /// Process L-shape profile (angle)
355    /// IfcLShapeProfileDef: ProfileType, ProfileName, Position, Depth, Width, Thickness, ...
356    fn process_l_shape(&self, profile: &DecodedEntity) -> Result<Profile2D> {
357        let depth = profile
358            .get_float(3)
359            .ok_or_else(|| Error::geometry("L-Shape missing Depth".to_string()))?;
360        let width = profile
361            .get_float(4)
362            .ok_or_else(|| Error::geometry("L-Shape missing Width".to_string()))?;
363        let thickness = profile
364            .get_float(5)
365            .ok_or_else(|| Error::geometry("L-Shape missing Thickness".to_string()))?;
366
367        // L-shape profile (counter-clockwise from origin)
368        let points = vec![
369            Point2::new(0.0, 0.0),
370            Point2::new(width, 0.0),
371            Point2::new(width, thickness),
372            Point2::new(thickness, thickness),
373            Point2::new(thickness, depth),
374            Point2::new(0.0, depth),
375        ];
376
377        Ok(Profile2D::new(points))
378    }
379
380    /// Process U-shape profile (channel)
381    /// IfcUShapeProfileDef: ProfileType, ProfileName, Position, Depth, FlangeWidth, WebThickness, FlangeThickness, ...
382    fn process_u_shape(&self, profile: &DecodedEntity) -> Result<Profile2D> {
383        let depth = profile
384            .get_float(3)
385            .ok_or_else(|| Error::geometry("U-Shape missing Depth".to_string()))?;
386        let flange_width = profile
387            .get_float(4)
388            .ok_or_else(|| Error::geometry("U-Shape missing FlangeWidth".to_string()))?;
389        let web_thickness = profile
390            .get_float(5)
391            .ok_or_else(|| Error::geometry("U-Shape missing WebThickness".to_string()))?;
392        let flange_thickness = profile
393            .get_float(6)
394            .ok_or_else(|| Error::geometry("U-Shape missing FlangeThickness".to_string()))?;
395
396        let half_depth = depth / 2.0;
397
398        // U-shape profile (counter-clockwise)
399        let points = vec![
400            Point2::new(0.0, -half_depth),
401            Point2::new(flange_width, -half_depth),
402            Point2::new(flange_width, -half_depth + flange_thickness),
403            Point2::new(web_thickness, -half_depth + flange_thickness),
404            Point2::new(web_thickness, half_depth - flange_thickness),
405            Point2::new(flange_width, half_depth - flange_thickness),
406            Point2::new(flange_width, half_depth),
407            Point2::new(0.0, half_depth),
408        ];
409
410        Ok(Profile2D::new(points))
411    }
412
413    /// Process T-shape profile
414    /// IfcTShapeProfileDef: ProfileType, ProfileName, Position, Depth, FlangeWidth, WebThickness, FlangeThickness, ...
415    fn process_t_shape(&self, profile: &DecodedEntity) -> Result<Profile2D> {
416        let depth = profile
417            .get_float(3)
418            .ok_or_else(|| Error::geometry("T-Shape missing Depth".to_string()))?;
419        let flange_width = profile
420            .get_float(4)
421            .ok_or_else(|| Error::geometry("T-Shape missing FlangeWidth".to_string()))?;
422        let web_thickness = profile
423            .get_float(5)
424            .ok_or_else(|| Error::geometry("T-Shape missing WebThickness".to_string()))?;
425        let flange_thickness = profile
426            .get_float(6)
427            .ok_or_else(|| Error::geometry("T-Shape missing FlangeThickness".to_string()))?;
428
429        let half_flange = flange_width / 2.0;
430        let half_web = web_thickness / 2.0;
431
432        // T-shape profile (counter-clockwise)
433        let points = vec![
434            Point2::new(-half_web, 0.0),
435            Point2::new(-half_web, depth - flange_thickness),
436            Point2::new(-half_flange, depth - flange_thickness),
437            Point2::new(-half_flange, depth),
438            Point2::new(half_flange, depth),
439            Point2::new(half_flange, depth - flange_thickness),
440            Point2::new(half_web, depth - flange_thickness),
441            Point2::new(half_web, 0.0),
442        ];
443
444        Ok(Profile2D::new(points))
445    }
446
447    /// Process C-shape profile (channel with lips)
448    /// IfcCShapeProfileDef: ProfileType, ProfileName, Position, Depth, Width, WallThickness, Girth, ...
449    fn process_c_shape(&self, profile: &DecodedEntity) -> Result<Profile2D> {
450        let depth = profile
451            .get_float(3)
452            .ok_or_else(|| Error::geometry("C-Shape missing Depth".to_string()))?;
453        let _width = profile
454            .get_float(4)
455            .ok_or_else(|| Error::geometry("C-Shape missing Width".to_string()))?;
456        let wall_thickness = profile
457            .get_float(5)
458            .ok_or_else(|| Error::geometry("C-Shape missing WallThickness".to_string()))?;
459        let girth = profile.get_float(6).unwrap_or(wall_thickness * 2.0); // Lip length
460
461        let half_depth = depth / 2.0;
462
463        // C-shape profile (counter-clockwise)
464        let points = vec![
465            Point2::new(girth, -half_depth),
466            Point2::new(0.0, -half_depth),
467            Point2::new(0.0, half_depth),
468            Point2::new(girth, half_depth),
469            Point2::new(girth, half_depth - wall_thickness),
470            Point2::new(wall_thickness, half_depth - wall_thickness),
471            Point2::new(wall_thickness, -half_depth + wall_thickness),
472            Point2::new(girth, -half_depth + wall_thickness),
473        ];
474
475        Ok(Profile2D::new(points))
476    }
477
478    /// Process Z-shape profile
479    /// IfcZShapeProfileDef: ProfileType, ProfileName, Position, Depth, FlangeWidth, WebThickness, FlangeThickness, ...
480    fn process_z_shape(&self, profile: &DecodedEntity) -> Result<Profile2D> {
481        let depth = profile
482            .get_float(3)
483            .ok_or_else(|| Error::geometry("Z-Shape missing Depth".to_string()))?;
484        let flange_width = profile
485            .get_float(4)
486            .ok_or_else(|| Error::geometry("Z-Shape missing FlangeWidth".to_string()))?;
487        let web_thickness = profile
488            .get_float(5)
489            .ok_or_else(|| Error::geometry("Z-Shape missing WebThickness".to_string()))?;
490        let flange_thickness = profile
491            .get_float(6)
492            .ok_or_else(|| Error::geometry("Z-Shape missing FlangeThickness".to_string()))?;
493
494        let half_depth = depth / 2.0;
495        let half_web = web_thickness / 2.0;
496
497        // Z-shape profile (counter-clockwise)
498        let points = vec![
499            Point2::new(-half_web, -half_depth),
500            Point2::new(-half_web - flange_width, -half_depth),
501            Point2::new(-half_web - flange_width, -half_depth + flange_thickness),
502            Point2::new(-half_web, -half_depth + flange_thickness),
503            Point2::new(-half_web, half_depth - flange_thickness),
504            Point2::new(half_web, half_depth - flange_thickness),
505            Point2::new(half_web, half_depth),
506            Point2::new(half_web + flange_width, half_depth),
507            Point2::new(half_web + flange_width, half_depth - flange_thickness),
508            Point2::new(half_web, half_depth - flange_thickness),
509            Point2::new(half_web, -half_depth + flange_thickness),
510            Point2::new(-half_web, -half_depth + flange_thickness),
511        ];
512
513        Ok(Profile2D::new(points))
514    }
515
516    /// Process arbitrary closed profile (polyline-based)
517    /// IfcArbitraryClosedProfileDef: ProfileType, ProfileName, OuterCurve
518    /// IfcArbitraryProfileDefWithVoids: ProfileType, ProfileName, OuterCurve, InnerCurves
519    fn process_arbitrary(
520        &self,
521        profile: &DecodedEntity,
522        decoder: &mut EntityDecoder,
523    ) -> Result<Profile2D> {
524        // Get outer curve (attribute 2)
525        let curve_attr = profile
526            .get(2)
527            .ok_or_else(|| Error::geometry("Arbitrary profile missing OuterCurve".to_string()))?;
528
529        let curve = decoder
530            .resolve_ref(curve_attr)?
531            .ok_or_else(|| Error::geometry("Failed to resolve OuterCurve".to_string()))?;
532
533        // Process outer curve
534        let outer_points = self.process_curve(&curve, decoder)?;
535        let mut result = Profile2D::new(outer_points);
536
537        // Check if this is IfcArbitraryProfileDefWithVoids (has inner curves)
538        if profile.ifc_type == IfcType::IfcArbitraryProfileDefWithVoids {
539            // Get inner curves list (attribute 3)
540            if let Some(inner_curves_attr) = profile.get(3) {
541                let inner_curves = decoder.resolve_ref_list(inner_curves_attr)?;
542                for inner_curve in inner_curves {
543                    let hole_points = self.process_curve(&inner_curve, decoder)?;
544                    result.add_hole(hole_points);
545                }
546            }
547        }
548
549        Ok(result)
550    }
551
552    /// Process any supported curve type into 2D points
553    #[inline]
554    fn process_curve(
555        &self,
556        curve: &DecodedEntity,
557        decoder: &mut EntityDecoder,
558    ) -> Result<Vec<Point2<f64>>> {
559        self.process_curve_with_depth(curve, decoder, 0)
560    }
561
562    /// Process curve with depth tracking to prevent stack overflow
563    fn process_curve_with_depth(
564        &self,
565        curve: &DecodedEntity,
566        decoder: &mut EntityDecoder,
567        depth: u32,
568    ) -> Result<Vec<Point2<f64>>> {
569        if depth > MAX_CURVE_DEPTH {
570            return Err(Error::geometry(format!(
571                "Curve nesting depth {} exceeds limit {}",
572                depth, MAX_CURVE_DEPTH
573            )));
574        }
575        match curve.ifc_type {
576            IfcType::IfcPolyline => self.process_polyline(curve, decoder),
577            IfcType::IfcIndexedPolyCurve => self.process_indexed_polycurve(curve, decoder),
578            IfcType::IfcCompositeCurve => self.process_composite_curve_with_depth(curve, decoder, depth),
579            IfcType::IfcTrimmedCurve => self.process_trimmed_curve_with_depth(curve, decoder, depth),
580            IfcType::IfcCircle => self.process_circle_curve(curve, decoder),
581            IfcType::IfcEllipse => self.process_ellipse_curve(curve, decoder),
582            _ => Err(Error::geometry(format!(
583                "Unsupported curve type: {}",
584                curve.ifc_type
585            ))),
586        }
587    }
588
589    /// Get 3D points from a curve (for swept disk solid, etc.)
590    #[inline]
591    pub fn get_curve_points(
592        &self,
593        curve: &DecodedEntity,
594        decoder: &mut EntityDecoder,
595    ) -> Result<Vec<Point3<f64>>> {
596        self.get_curve_points_with_depth(curve, decoder, 0)
597    }
598
599    /// Get 3D curve points with depth tracking to prevent stack overflow
600    fn get_curve_points_with_depth(
601        &self,
602        curve: &DecodedEntity,
603        decoder: &mut EntityDecoder,
604        depth: u32,
605    ) -> Result<Vec<Point3<f64>>> {
606        if depth > MAX_CURVE_DEPTH {
607            return Err(Error::geometry(format!(
608                "Curve nesting depth {} exceeds limit {}",
609                depth, MAX_CURVE_DEPTH
610            )));
611        }
612        match curve.ifc_type {
613            IfcType::IfcPolyline => self.process_polyline_3d(curve, decoder),
614            IfcType::IfcCompositeCurve => self.process_composite_curve_3d_with_depth(curve, decoder, depth),
615            IfcType::IfcCircle => self.process_circle_3d(curve, decoder),
616            IfcType::IfcTrimmedCurve => {
617                // For trimmed curve, get 2D points and convert to 3D
618                let points_2d = self.process_trimmed_curve_with_depth(curve, decoder, depth)?;
619                Ok(points_2d
620                    .into_iter()
621                    .map(|p| Point3::new(p.x, p.y, 0.0))
622                    .collect())
623            }
624            _ => {
625                // Fallback: try 2D curve and convert to 3D
626                let points_2d = self.process_curve_with_depth(curve, decoder, depth)?;
627                Ok(points_2d
628                    .into_iter()
629                    .map(|p| Point3::new(p.x, p.y, 0.0))
630                    .collect())
631            }
632        }
633    }
634
635    /// Process circle curve in 3D space (for swept disk solid, etc.)
636    fn process_circle_3d(
637        &self,
638        curve: &DecodedEntity,
639        decoder: &mut EntityDecoder,
640    ) -> Result<Vec<Point3<f64>>> {
641        // IfcCircle: Position (IfcAxis2Placement2D or 3D), Radius
642        let position_attr = curve
643            .get(0)
644            .ok_or_else(|| Error::geometry("Circle missing Position".to_string()))?;
645
646        let radius = curve
647            .get_float(1)
648            .ok_or_else(|| Error::geometry("Circle missing Radius".to_string()))?;
649
650        let position = decoder
651            .resolve_ref(position_attr)?
652            .ok_or_else(|| Error::geometry("Failed to resolve circle position".to_string()))?;
653
654        // Get center and orientation from Axis2Placement3D
655        let (center, x_axis, y_axis) = if position.ifc_type == IfcType::IfcAxis2Placement3D {
656            // IfcAxis2Placement3D: Location, Axis (Z), RefDirection (X)
657            let loc_attr = position
658                .get(0)
659                .ok_or_else(|| Error::geometry("Axis2Placement3D missing Location".to_string()))?;
660            let loc = decoder
661                .resolve_ref(loc_attr)?
662                .ok_or_else(|| Error::geometry("Failed to resolve location".to_string()))?;
663            let coords = loc
664                .get(0)
665                .and_then(|v| v.as_list())
666                .ok_or_else(|| Error::geometry("Location missing coordinates".to_string()))?;
667            let center = Point3::new(
668                coords.first().and_then(|v| v.as_float()).unwrap_or(0.0),
669                coords.get(1).and_then(|v| v.as_float()).unwrap_or(0.0),
670                coords.get(2).and_then(|v| v.as_float()).unwrap_or(0.0),
671            );
672
673            // Get Z axis (Axis attribute)
674            let z_axis = if let Some(axis_attr) = position.get(1) {
675                if !axis_attr.is_null() {
676                    let axis = decoder.resolve_ref(axis_attr)?;
677                    if let Some(axis) = axis {
678                        let coords = axis.get(0).and_then(|v| v.as_list());
679                        if let Some(coords) = coords {
680                            Vector3::new(
681                                coords.first().and_then(|v| v.as_float()).unwrap_or(0.0),
682                                coords.get(1).and_then(|v| v.as_float()).unwrap_or(0.0),
683                                coords.get(2).and_then(|v| v.as_float()).unwrap_or(1.0),
684                            )
685                            .normalize()
686                        } else {
687                            Vector3::new(0.0, 0.0, 1.0)
688                        }
689                    } else {
690                        Vector3::new(0.0, 0.0, 1.0)
691                    }
692                } else {
693                    Vector3::new(0.0, 0.0, 1.0)
694                }
695            } else {
696                Vector3::new(0.0, 0.0, 1.0)
697            };
698
699            // Get X axis (RefDirection attribute)
700            let x_axis = if let Some(ref_attr) = position.get(2) {
701                if !ref_attr.is_null() {
702                    let ref_dir = decoder.resolve_ref(ref_attr)?;
703                    if let Some(ref_dir) = ref_dir {
704                        let coords = ref_dir.get(0).and_then(|v| v.as_list());
705                        if let Some(coords) = coords {
706                            Vector3::new(
707                                coords.first().and_then(|v| v.as_float()).unwrap_or(1.0),
708                                coords.get(1).and_then(|v| v.as_float()).unwrap_or(0.0),
709                                coords.get(2).and_then(|v| v.as_float()).unwrap_or(0.0),
710                            )
711                            .normalize()
712                        } else {
713                            Vector3::new(1.0, 0.0, 0.0)
714                        }
715                    } else {
716                        Vector3::new(1.0, 0.0, 0.0)
717                    }
718                } else {
719                    Vector3::new(1.0, 0.0, 0.0)
720                }
721            } else {
722                Vector3::new(1.0, 0.0, 0.0)
723            };
724
725            // Y axis = Z cross X
726            let y_axis = z_axis.cross(&x_axis).normalize();
727
728            (center, x_axis, y_axis)
729        } else {
730            // 2D placement - use XY plane
731            let loc_attr = position.get(0);
732            let (cx, cy) = if let Some(attr) = loc_attr {
733                let loc = decoder.resolve_ref(attr)?;
734                if let Some(loc) = loc {
735                    let coords = loc.get(0).and_then(|v| v.as_list());
736                    if let Some(coords) = coords {
737                        (
738                            coords.first().and_then(|v| v.as_float()).unwrap_or(0.0),
739                            coords.get(1).and_then(|v| v.as_float()).unwrap_or(0.0),
740                        )
741                    } else {
742                        (0.0, 0.0)
743                    }
744                } else {
745                    (0.0, 0.0)
746                }
747            } else {
748                (0.0, 0.0)
749            };
750            (
751                Point3::new(cx, cy, 0.0),
752                Vector3::new(1.0, 0.0, 0.0),
753                Vector3::new(0.0, 1.0, 0.0),
754            )
755        };
756
757        // Generate circle points in 3D (16 segments for full circle)
758        let segments = 16usize;
759        let mut points = Vec::with_capacity(segments + 1);
760
761        for i in 0..=segments {
762            let angle = 2.0 * std::f64::consts::PI * i as f64 / segments as f64;
763            let p = center + x_axis * (radius * angle.cos()) + y_axis * (radius * angle.sin());
764            points.push(p);
765        }
766
767        Ok(points)
768    }
769
770    /// Process polyline into 3D points
771    fn process_polyline_3d(
772        &self,
773        curve: &DecodedEntity,
774        decoder: &mut EntityDecoder,
775    ) -> Result<Vec<Point3<f64>>> {
776        // IfcPolyline: Points
777        let points_attr = curve
778            .get(0)
779            .ok_or_else(|| Error::geometry("Polyline missing Points".to_string()))?;
780
781        let points = decoder.resolve_ref_list(points_attr)?;
782        let mut result = Vec::with_capacity(points.len());
783
784        for point in points {
785            // IfcCartesianPoint: Coordinates
786            let coords_attr = point
787                .get(0)
788                .ok_or_else(|| Error::geometry("CartesianPoint missing Coordinates".to_string()))?;
789
790            let coords = coords_attr
791                .as_list()
792                .ok_or_else(|| Error::geometry("Coordinates is not a list".to_string()))?;
793
794            let x = coords.first().and_then(|v| v.as_float()).unwrap_or(0.0);
795            let y = coords.get(1).and_then(|v| v.as_float()).unwrap_or(0.0);
796            let z = coords.get(2).and_then(|v| v.as_float()).unwrap_or(0.0);
797
798            result.push(Point3::new(x, y, z));
799        }
800
801        Ok(result)
802    }
803
804    /// Process composite curve into 3D points
805    fn process_composite_curve_3d_with_depth(
806        &self,
807        curve: &DecodedEntity,
808        decoder: &mut EntityDecoder,
809        depth: u32,
810    ) -> Result<Vec<Point3<f64>>> {
811        // IfcCompositeCurve: Segments, SelfIntersect
812        let segments_attr = curve
813            .get(0)
814            .ok_or_else(|| Error::geometry("CompositeCurve missing Segments".to_string()))?;
815
816        let segments = decoder.resolve_ref_list(segments_attr)?;
817        let mut result = Vec::new();
818
819        for segment in segments {
820            // IfcCompositeCurveSegment: Transition, SameSense, ParentCurve
821            let parent_curve_attr = segment.get(2).ok_or_else(|| {
822                Error::geometry("CompositeCurveSegment missing ParentCurve".to_string())
823            })?;
824
825            let parent_curve = decoder
826                .resolve_ref(parent_curve_attr)?
827                .ok_or_else(|| Error::geometry("Failed to resolve ParentCurve".to_string()))?;
828
829            // Get same_sense for direction
830            let same_sense = segment
831                .get(1)
832                .and_then(|v| match v {
833                    ifc_lite_core::AttributeValue::Enum(e) => Some(e.as_str()),
834                    _ => None,
835                })
836                .map(|e| e == "T" || e == "TRUE")
837                .unwrap_or(true);
838
839            let mut segment_points = self.get_curve_points_with_depth(&parent_curve, decoder, depth + 1)?;
840
841            if !same_sense {
842                segment_points.reverse();
843            }
844
845            // Skip first point if we already have points (avoid duplicates)
846            if !result.is_empty() && !segment_points.is_empty() {
847                result.extend(segment_points.into_iter().skip(1));
848            } else {
849                result.extend(segment_points);
850            }
851        }
852
853        Ok(result)
854    }
855
856    /// Process trimmed curve
857    /// IfcTrimmedCurve: BasisCurve, Trim1, Trim2, SenseAgreement, MasterRepresentation
858    fn process_trimmed_curve_with_depth(
859        &self,
860        curve: &DecodedEntity,
861        decoder: &mut EntityDecoder,
862        depth: u32,
863    ) -> Result<Vec<Point2<f64>>> {
864        // Get basis curve (attribute 0)
865        let basis_attr = curve
866            .get(0)
867            .ok_or_else(|| Error::geometry("TrimmedCurve missing BasisCurve".to_string()))?;
868
869        let basis_curve = decoder
870            .resolve_ref(basis_attr)?
871            .ok_or_else(|| Error::geometry("Failed to resolve BasisCurve".to_string()))?;
872
873        // Get trim parameters
874        let trim1 = curve.get(1).and_then(|v| self.extract_trim_param(v));
875        let trim2 = curve.get(2).and_then(|v| self.extract_trim_param(v));
876
877        // Get sense agreement (attribute 3) - default true
878        let sense = curve
879            .get(3)
880            .and_then(|v| match v {
881                ifc_lite_core::AttributeValue::Enum(s) => Some(s == "T"),
882                _ => None,
883            })
884            .unwrap_or(true);
885
886        // Process basis curve based on type
887        match basis_curve.ifc_type {
888            IfcType::IfcCircle | IfcType::IfcEllipse => {
889                self.process_trimmed_conic(&basis_curve, trim1, trim2, sense, decoder)
890            }
891            _ => {
892                // Fallback: try to process as a regular curve (with depth tracking)
893                self.process_curve_with_depth(&basis_curve, decoder, depth + 1)
894            }
895        }
896    }
897
898    /// Extract trim parameter (can be IFCPARAMETERVALUE or IFCCARTESIANPOINT)
899    fn extract_trim_param(&self, attr: &ifc_lite_core::AttributeValue) -> Option<f64> {
900        if let Some(list) = attr.as_list() {
901            for item in list {
902                // Check for IFCPARAMETERVALUE (stored as ["IFCPARAMETERVALUE", value])
903                if let Some(inner_list) = item.as_list() {
904                    if inner_list.len() >= 2 {
905                        if let Some(type_name) = inner_list.first().and_then(|v| v.as_string()) {
906                            if type_name == "IFCPARAMETERVALUE" {
907                                return inner_list.get(1).and_then(|v| v.as_float());
908                            }
909                        }
910                    }
911                }
912                if let Some(f) = item.as_float() {
913                    return Some(f);
914                }
915            }
916        }
917        None
918    }
919
920    /// Process trimmed conic (circle or ellipse arc)
921    fn process_trimmed_conic(
922        &self,
923        basis: &DecodedEntity,
924        trim1: Option<f64>,
925        trim2: Option<f64>,
926        sense: bool,
927        decoder: &mut EntityDecoder,
928    ) -> Result<Vec<Point2<f64>>> {
929        let radius = basis.get_float(1).unwrap_or(1.0);
930        let radius2 = if basis.ifc_type == IfcType::IfcEllipse {
931            basis.get_float(2).unwrap_or(radius)
932        } else {
933            radius
934        };
935
936        let (center, rotation) = self.get_placement_2d(basis, decoder)?;
937
938        // Convert trim parameters to angles (in degrees usually)
939        let start_angle = trim1.unwrap_or(0.0).to_radians();
940        let end_angle = trim2.unwrap_or(360.0).to_radians();
941
942        // Calculate arc angle and adaptive segment count
943        // Use ~8 segments per 90° (quarter circle), minimum 2
944        let arc_angle = (end_angle - start_angle).abs();
945        let num_segments = ((arc_angle / std::f64::consts::FRAC_PI_2 * 8.0).ceil() as usize).max(2);
946        let mut points = Vec::with_capacity(num_segments + 1);
947
948        let angle_range = if sense {
949            end_angle - start_angle
950        } else {
951            start_angle - end_angle
952        };
953
954        for i in 0..=num_segments {
955            let t = i as f64 / num_segments as f64;
956            let angle = if sense {
957                start_angle + t * angle_range
958            } else {
959                start_angle - t * angle_range.abs()
960            };
961
962            let x = radius * angle.cos();
963            let y = radius2 * angle.sin();
964
965            let rx = x * rotation.cos() - y * rotation.sin() + center.x;
966            let ry = x * rotation.sin() + y * rotation.cos() + center.y;
967
968            points.push(Point2::new(rx, ry));
969        }
970
971        Ok(points)
972    }
973
974    /// Get 2D placement from entity
975    fn get_placement_2d(
976        &self,
977        entity: &DecodedEntity,
978        decoder: &mut EntityDecoder,
979    ) -> Result<(Point2<f64>, f64)> {
980        let placement_attr = match entity.get(0) {
981            Some(attr) if !attr.is_null() => attr,
982            _ => return Ok((Point2::new(0.0, 0.0), 0.0)),
983        };
984
985        let placement = match decoder.resolve_ref(placement_attr)? {
986            Some(p) => p,
987            None => return Ok((Point2::new(0.0, 0.0), 0.0)),
988        };
989
990        let location_attr = placement.get(0);
991        let center = if let Some(loc_attr) = location_attr {
992            if let Some(loc) = decoder.resolve_ref(loc_attr)? {
993                let coords = loc.get(0).and_then(|v| v.as_list());
994                if let Some(coords) = coords {
995                    let x = coords.first().and_then(|v| v.as_float()).unwrap_or(0.0);
996                    let y = coords.get(1).and_then(|v| v.as_float()).unwrap_or(0.0);
997                    Point2::new(x, y)
998                } else {
999                    Point2::new(0.0, 0.0)
1000                }
1001            } else {
1002                Point2::new(0.0, 0.0)
1003            }
1004        } else {
1005            Point2::new(0.0, 0.0)
1006        };
1007
1008        let rotation = if let Some(dir_attr) = placement.get(1) {
1009            if let Some(dir) = decoder.resolve_ref(dir_attr)? {
1010                let ratios = dir.get(0).and_then(|v| v.as_list());
1011                if let Some(ratios) = ratios {
1012                    let x = ratios.first().and_then(|v| v.as_float()).unwrap_or(1.0);
1013                    let y = ratios.get(1).and_then(|v| v.as_float()).unwrap_or(0.0);
1014                    y.atan2(x)
1015                } else {
1016                    0.0
1017                }
1018            } else {
1019                0.0
1020            }
1021        } else {
1022            0.0
1023        };
1024
1025        Ok((center, rotation))
1026    }
1027
1028    /// Process circle curve (full circle)
1029    fn process_circle_curve(
1030        &self,
1031        curve: &DecodedEntity,
1032        decoder: &mut EntityDecoder,
1033    ) -> Result<Vec<Point2<f64>>> {
1034        let radius = curve.get_float(1).unwrap_or(1.0);
1035        let (center, rotation) = self.get_placement_2d(curve, decoder)?;
1036
1037        let segments = 24;
1038        let mut points = Vec::with_capacity(segments);
1039
1040        for i in 0..segments {
1041            let angle = (i as f64) * 2.0 * PI / (segments as f64);
1042            let x = radius * angle.cos();
1043            let y = radius * angle.sin();
1044
1045            let rx = x * rotation.cos() - y * rotation.sin() + center.x;
1046            let ry = x * rotation.sin() + y * rotation.cos() + center.y;
1047
1048            points.push(Point2::new(rx, ry));
1049        }
1050
1051        Ok(points)
1052    }
1053
1054    /// Process ellipse curve (full ellipse)
1055    fn process_ellipse_curve(
1056        &self,
1057        curve: &DecodedEntity,
1058        decoder: &mut EntityDecoder,
1059    ) -> Result<Vec<Point2<f64>>> {
1060        let semi_axis1 = curve.get_float(1).unwrap_or(1.0);
1061        let semi_axis2 = curve.get_float(2).unwrap_or(1.0);
1062        let (center, rotation) = self.get_placement_2d(curve, decoder)?;
1063
1064        let segments = 24;
1065        let mut points = Vec::with_capacity(segments);
1066
1067        for i in 0..segments {
1068            let angle = (i as f64) * 2.0 * PI / (segments as f64);
1069            let x = semi_axis1 * angle.cos();
1070            let y = semi_axis2 * angle.sin();
1071
1072            let rx = x * rotation.cos() - y * rotation.sin() + center.x;
1073            let ry = x * rotation.sin() + y * rotation.cos() + center.y;
1074
1075            points.push(Point2::new(rx, ry));
1076        }
1077
1078        Ok(points)
1079    }
1080
1081    /// Process polyline into 2D points
1082    /// IfcPolyline: Points (list of IfcCartesianPoint)
1083    #[inline]
1084    fn process_polyline(
1085        &self,
1086        polyline: &DecodedEntity,
1087        decoder: &mut EntityDecoder,
1088    ) -> Result<Vec<Point2<f64>>> {
1089        // Get points list (attribute 0)
1090        let points_attr = polyline
1091            .get(0)
1092            .ok_or_else(|| Error::geometry("Polyline missing Points".to_string()))?;
1093
1094        let point_entities = decoder.resolve_ref_list(points_attr)?;
1095
1096        let mut points = Vec::with_capacity(point_entities.len());
1097        for point_entity in point_entities {
1098            if point_entity.ifc_type != IfcType::IfcCartesianPoint {
1099                continue;
1100            }
1101
1102            // Get coordinates (attribute 0)
1103            let coords_attr = point_entity
1104                .get(0)
1105                .ok_or_else(|| Error::geometry("CartesianPoint missing coordinates".to_string()))?;
1106
1107            let coords = coords_attr
1108                .as_list()
1109                .ok_or_else(|| Error::geometry("Expected coordinate list".to_string()))?;
1110
1111            let x = coords.first().and_then(|v| v.as_float()).unwrap_or(0.0);
1112            let y = coords.get(1).and_then(|v| v.as_float()).unwrap_or(0.0);
1113
1114            points.push(Point2::new(x, y));
1115        }
1116
1117        Ok(points)
1118    }
1119
1120    /// Process indexed polycurve into 2D points
1121    /// IfcIndexedPolyCurve: Points (IfcCartesianPointList2D), Segments (optional), SelfIntersect
1122    fn process_indexed_polycurve(
1123        &self,
1124        curve: &DecodedEntity,
1125        decoder: &mut EntityDecoder,
1126    ) -> Result<Vec<Point2<f64>>> {
1127        // Get points list (attribute 0) - references IfcCartesianPointList2D
1128        let points_attr = curve
1129            .get(0)
1130            .ok_or_else(|| Error::geometry("IndexedPolyCurve missing Points".to_string()))?;
1131
1132        let points_list = decoder
1133            .resolve_ref(points_attr)?
1134            .ok_or_else(|| Error::geometry("Failed to resolve Points list".to_string()))?;
1135
1136        // IfcCartesianPointList2D: CoordList (list of 2D coordinates)
1137        let coord_list_attr = points_list
1138            .get(0)
1139            .ok_or_else(|| Error::geometry("CartesianPointList2D missing CoordList".to_string()))?;
1140
1141        let coord_list = coord_list_attr
1142            .as_list()
1143            .ok_or_else(|| Error::geometry("Expected coordinate list".to_string()))?;
1144
1145        // Parse all 2D points from the coordinate list
1146        let all_points: Vec<Point2<f64>> = coord_list
1147            .iter()
1148            .filter_map(|coord| {
1149                coord.as_list().and_then(|coords| {
1150                    let x = coords.first()?.as_float()?;
1151                    let y = coords.get(1)?.as_float()?;
1152                    Some(Point2::new(x, y))
1153                })
1154            })
1155            .collect();
1156
1157        // Get segments (attribute 1) - optional, if not present use all points in order
1158        let segments_attr = curve.get(1);
1159
1160        if segments_attr.is_none() || segments_attr.map(|a| a.is_null()).unwrap_or(true) {
1161            // No segments specified - use all points in order
1162            return Ok(all_points);
1163        }
1164
1165        // Process segments (IfcLineIndex or IfcArcIndex)
1166        let segments = segments_attr
1167            .unwrap()
1168            .as_list()
1169            .ok_or_else(|| Error::geometry("Expected segments list".to_string()))?;
1170
1171        let mut result_points = Vec::new();
1172
1173        for segment in segments {
1174            // Each segment is either IFCLINEINDEX((i1,i2,...)) or IFCARCINDEX((i1,i2,i3))
1175            // Typed values are stored as List([String("IFCLINEINDEX"), List([indices...])])
1176            // So we need to extract the inner list AND check the type name
1177            let (is_arc, indices) = if let Some(segment_list) = segment.as_list() {
1178                // Check if this is a typed value: List([String(type_name), List([indices...])])
1179                // Typed values like IFCLINEINDEX((1,2)) are stored as:
1180                // List([String("IFCLINEINDEX"), List([Integer(1), Integer(2)])])
1181                if segment_list.len() >= 2 {
1182                    // First element is type name (String), second is the actual indices list
1183                    let type_name = segment_list.first()
1184                        .and_then(|v| v.as_string())
1185                        .unwrap_or("");
1186                    let is_arc_type = type_name.to_uppercase().contains("ARC");
1187                    
1188                    if let Some(AttributeValue::List(indices_list)) = segment_list.get(1) {
1189                        (is_arc_type, Some(indices_list.as_slice()))
1190                    } else {
1191                        // Fallback: maybe it's a direct list of indices (not typed)
1192                        (false, Some(segment_list))
1193                    }
1194                } else {
1195                    // Single element or empty - treat as direct list (line)
1196                    (false, Some(segment_list))
1197                }
1198            } else {
1199                (false, None)
1200            };
1201
1202            if let Some(indices) = indices {
1203                let idx_values: Vec<usize> = indices
1204                    .iter()
1205                    .filter_map(|v| v.as_float().map(|f| f as usize - 1)) // 1-indexed to 0-indexed
1206                    .collect();
1207
1208                if is_arc && idx_values.len() == 3 {
1209                    // Arc segment - 3 points define an arc (ONLY if type is IFCARCINDEX)
1210                    let p1 = all_points.get(idx_values[0]).copied();
1211                    let p2 = all_points.get(idx_values[1]).copied(); // Mid-point
1212                    let p3 = all_points.get(idx_values[2]).copied();
1213
1214                    if let (Some(start), Some(mid), Some(end)) = (p1, p2, p3) {
1215                        // Approximate arc with adaptive segment count based on arc size
1216                        // Calculate approximate arc angle from chord length vs radius
1217                        let chord_len =
1218                            ((end.x - start.x).powi(2) + (end.y - start.y).powi(2)).sqrt();
1219                        let mid_chord = ((mid.x - (start.x + end.x) / 2.0).powi(2)
1220                            + (mid.y - (start.y + end.y) / 2.0).powi(2))
1221                        .sqrt();
1222                        // Estimate arc angle: larger mid deviation = larger arc
1223                        let arc_estimate = if chord_len > 1e-10 {
1224                            (mid_chord / chord_len).abs().min(1.0).acos() * 2.0
1225                        } else {
1226                            0.5
1227                        };
1228                        let num_segments = ((arc_estimate / std::f64::consts::FRAC_PI_2 * 8.0)
1229                            .ceil() as usize)
1230                            .clamp(4, 16);
1231                        let arc_points = self.approximate_arc_3pt(start, mid, end, num_segments);
1232                        for pt in arc_points {
1233                            if result_points.last() != Some(&pt) {
1234                                result_points.push(pt);
1235                            }
1236                        }
1237                    }
1238                } else {
1239                    // Line segment - add all points (includes IFCLINEINDEX with any number of points)
1240                    for &idx in &idx_values {
1241                        if let Some(&pt) = all_points.get(idx) {
1242                            if result_points.last() != Some(&pt) {
1243                                result_points.push(pt);
1244                            }
1245                        }
1246                    }
1247                }
1248            }
1249            // else: segment is not a list, skip it
1250        }
1251
1252        Ok(result_points)
1253    }
1254
1255    /// Approximate a 3-point arc with line segments
1256    fn approximate_arc_3pt(
1257        &self,
1258        p1: Point2<f64>,
1259        p2: Point2<f64>,
1260        p3: Point2<f64>,
1261        num_segments: usize,
1262    ) -> Vec<Point2<f64>> {
1263        // Find circle center from 3 points
1264        let ax = p1.x;
1265        let ay = p1.y;
1266        let bx = p2.x;
1267        let by = p2.y;
1268        let cx = p3.x;
1269        let cy = p3.y;
1270
1271        let d = 2.0 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));
1272
1273        // Check for collinearity using a RELATIVE tolerance based on the arc span
1274        // The determinant d scales with the square of the point distances
1275        let arc_span = ((p3.x - p1.x).powi(2) + (p3.y - p1.y).powi(2)).sqrt();
1276        let collinear_tolerance = 1e-6 * arc_span.powi(2).max(1e-10);
1277        
1278        if d.abs() < collinear_tolerance {
1279            // Points are collinear - return as line
1280            return vec![p1, p2, p3];
1281        }
1282        
1283        // Calculate center
1284        let ux_num = (ax * ax + ay * ay) * (by - cy)
1285            + (bx * bx + by * by) * (cy - ay)
1286            + (cx * cx + cy * cy) * (ay - by);
1287        let uy_num = (ax * ax + ay * ay) * (cx - bx)
1288            + (bx * bx + by * by) * (ax - cx)
1289            + (cx * cx + cy * cy) * (bx - ax);
1290        let ux = ux_num / d;
1291        let uy = uy_num / d;
1292        let center = Point2::new(ux, uy);
1293        let radius = ((p1.x - center.x).powi(2) + (p1.y - center.y).powi(2)).sqrt();
1294        
1295        // If radius is more than 100x the arc span, the points are essentially collinear
1296        if radius > arc_span * 100.0 {
1297            return vec![p1, p2, p3];
1298        }
1299
1300        // Calculate angles
1301        let angle1 = (p1.y - center.y).atan2(p1.x - center.x);
1302        let angle3 = (p3.y - center.y).atan2(p3.x - center.x);
1303        let angle2 = (p2.y - center.y).atan2(p2.x - center.x);
1304
1305        // Normalize angle difference to [-PI, PI]
1306        fn normalize_angle(a: f64) -> f64 {
1307            let mut a = a % (2.0 * PI);
1308            if a > PI {
1309                a -= 2.0 * PI;
1310            } else if a < -PI {
1311                a += 2.0 * PI;
1312            }
1313            a
1314        }
1315
1316        // Determine if we should go clockwise or counterclockwise from angle1 to angle3
1317        // The correct direction is the one that passes through angle2
1318        let diff_direct = normalize_angle(angle3 - angle1);
1319        let diff_to_mid = normalize_angle(angle2 - angle1);
1320        
1321        let go_direct = if diff_direct > 0.0 {
1322            // Direct path is counterclockwise (positive angles)
1323            diff_to_mid > 0.0 && diff_to_mid < diff_direct
1324        } else {
1325            // Direct path is clockwise (negative angles)
1326            diff_to_mid < 0.0 && diff_to_mid > diff_direct
1327        };
1328
1329        let start_angle = angle1;
1330        let end_angle = if go_direct {
1331            angle1 + diff_direct
1332        } else {
1333            // Go the other way around
1334            if diff_direct > 0.0 {
1335                angle1 + diff_direct - 2.0 * PI
1336            } else {
1337                angle1 + diff_direct + 2.0 * PI
1338            }
1339        };
1340
1341        // Generate arc points
1342        let mut points = Vec::with_capacity(num_segments + 1);
1343        for i in 0..=num_segments {
1344            let t = i as f64 / num_segments as f64;
1345            let angle = start_angle + t * (end_angle - start_angle);
1346            points.push(Point2::new(
1347                center.x + radius * angle.cos(),
1348                center.y + radius * angle.sin(),
1349            ));
1350        }
1351
1352        points
1353    }
1354
1355    /// Process composite curve into 2D points
1356    /// IfcCompositeCurve: Segments (list of IfcCompositeCurveSegment), SelfIntersect
1357    fn process_composite_curve_with_depth(
1358        &self,
1359        curve: &DecodedEntity,
1360        decoder: &mut EntityDecoder,
1361        depth: u32,
1362    ) -> Result<Vec<Point2<f64>>> {
1363        // Get segments list (attribute 0)
1364        let segments_attr = curve
1365            .get(0)
1366            .ok_or_else(|| Error::geometry("CompositeCurve missing Segments".to_string()))?;
1367
1368        let segments = decoder.resolve_ref_list(segments_attr)?;
1369
1370        let mut all_points = Vec::new();
1371
1372        for segment in segments {
1373            // IfcCompositeCurveSegment: Transition, SameSense, ParentCurve
1374            if segment.ifc_type != IfcType::IfcCompositeCurveSegment {
1375                continue;
1376            }
1377
1378            // Get ParentCurve (attribute 2)
1379            let parent_curve_attr = segment.get(2).ok_or_else(|| {
1380                Error::geometry("CompositeCurveSegment missing ParentCurve".to_string())
1381            })?;
1382
1383            let parent_curve = decoder
1384                .resolve_ref(parent_curve_attr)?
1385                .ok_or_else(|| Error::geometry("Failed to resolve ParentCurve".to_string()))?;
1386
1387            // Get SameSense (attribute 1) - whether to reverse the curve
1388            // Note: IFC enum values like ".T." are parsed/stored as "T" without dots
1389            let same_sense = segment
1390                .get(1)
1391                .and_then(|v| match v {
1392                    ifc_lite_core::AttributeValue::Enum(s) => Some(s == "T" || s == "TRUE"),
1393                    _ => None,
1394                })
1395                .unwrap_or(true);
1396
1397            // Process the parent curve (with depth tracking)
1398            let mut segment_points = self.process_curve_with_depth(&parent_curve, decoder, depth + 1)?;
1399
1400            if !same_sense {
1401                segment_points.reverse();
1402            }
1403
1404            // Append to result, avoiding duplicates at connection points
1405            for pt in segment_points {
1406                if all_points.last() != Some(&pt) {
1407                    all_points.push(pt);
1408                }
1409            }
1410        }
1411
1412        Ok(all_points)
1413    }
1414
1415    /// Process composite profile (combination of profiles)
1416    /// IfcCompositeProfileDef: ProfileType, ProfileName, Profiles, Label
1417    fn process_composite(
1418        &self,
1419        profile: &DecodedEntity,
1420        decoder: &mut EntityDecoder,
1421    ) -> Result<Profile2D> {
1422        // Get profiles list (attribute 2)
1423        let profiles_attr = profile
1424            .get(2)
1425            .ok_or_else(|| Error::geometry("Composite profile missing Profiles".to_string()))?;
1426
1427        let sub_profiles = decoder.resolve_ref_list(profiles_attr)?;
1428
1429        if sub_profiles.is_empty() {
1430            return Err(Error::geometry(
1431                "Composite profile has no sub-profiles".to_string(),
1432            ));
1433        }
1434
1435        // Process first profile as base
1436        let mut result = self.process(&sub_profiles[0], decoder)?;
1437
1438        // Add remaining profiles as holes (simplified - assumes they're holes)
1439        for sub_profile in &sub_profiles[1..] {
1440            let hole = self.process(sub_profile, decoder)?;
1441            result.add_hole(hole.outer);
1442        }
1443
1444        Ok(result)
1445    }
1446}
1447
1448#[cfg(test)]
1449mod tests {
1450    use super::*;
1451
1452    #[test]
1453    fn test_rectangle_profile() {
1454        let content = r#"
1455#1=IFCRECTANGLEPROFILEDEF(.AREA.,$,$,100.0,200.0);
1456"#;
1457
1458        let mut decoder = EntityDecoder::new(content);
1459        let schema = IfcSchema::new();
1460        let processor = ProfileProcessor::new(schema);
1461
1462        let profile_entity = decoder.decode_by_id(1).unwrap();
1463        let profile = processor.process(&profile_entity, &mut decoder).unwrap();
1464
1465        assert_eq!(profile.outer.len(), 4);
1466        assert!(!profile.outer.is_empty());
1467    }
1468
1469    #[test]
1470    fn test_circle_profile() {
1471        let content = r#"
1472#1=IFCCIRCLEPROFILEDEF(.AREA.,$,$,50.0);
1473"#;
1474
1475        let mut decoder = EntityDecoder::new(content);
1476        let schema = IfcSchema::new();
1477        let processor = ProfileProcessor::new(schema);
1478
1479        let profile_entity = decoder.decode_by_id(1).unwrap();
1480        let profile = processor.process(&profile_entity, &mut decoder).unwrap();
1481
1482        assert_eq!(profile.outer.len(), 24); // Circle with 24 segments
1483        assert!(!profile.outer.is_empty());
1484    }
1485
1486    #[test]
1487    fn test_i_shape_profile() {
1488        let content = r#"
1489#1=IFCISHAPEPROFILEDEF(.AREA.,$,$,200.0,300.0,10.0,15.0,$,$,$,$);
1490"#;
1491
1492        let mut decoder = EntityDecoder::new(content);
1493        let schema = IfcSchema::new();
1494        let processor = ProfileProcessor::new(schema);
1495
1496        let profile_entity = decoder.decode_by_id(1).unwrap();
1497        let profile = processor.process(&profile_entity, &mut decoder).unwrap();
1498
1499        assert_eq!(profile.outer.len(), 12); // I-shape has 12 vertices
1500        assert!(!profile.outer.is_empty());
1501    }
1502
1503    #[test]
1504    fn test_arbitrary_profile() {
1505        let content = r#"
1506#1=IFCCARTESIANPOINT((0.0,0.0));
1507#2=IFCCARTESIANPOINT((100.0,0.0));
1508#3=IFCCARTESIANPOINT((100.0,100.0));
1509#4=IFCCARTESIANPOINT((0.0,100.0));
1510#5=IFCPOLYLINE((#1,#2,#3,#4,#1));
1511#6=IFCARBITRARYCLOSEDPROFILEDEF(.AREA.,$,#5);
1512"#;
1513
1514        let mut decoder = EntityDecoder::new(content);
1515        let schema = IfcSchema::new();
1516        let processor = ProfileProcessor::new(schema);
1517
1518        let profile_entity = decoder.decode_by_id(6).unwrap();
1519        let profile = processor.process(&profile_entity, &mut decoder).unwrap();
1520
1521        assert_eq!(profile.outer.len(), 5); // 4 corners + closing point
1522        assert!(!profile.outer.is_empty());
1523    }
1524}