Skip to main content

gldf_rs/ifc/
ifc_import.rs

1//! IFC to GLDF Import
2//!
3//! Converts IFC luminaire data to GLDF format.
4//! Extracts:
5//! - IFCLIGHTFIXTURETYPE → GLDF Variants
6//! - Property sets → GLDF attributes
7//! - IFCLIGHTSOURCEGONIOMETRIC → Light sources
8//! - IFCLIGHTINTENSITYDISTRIBUTION → EULUMDAT photometry
9//! - IFCSHAPEREPRESENTATION → L3D geometry
10
11use super::step_parser::{StepParser, StepValue};
12use anyhow::{anyhow, Result};
13
14/// Extracted luminaire data from IFC
15#[derive(Debug, Clone, Default, PartialEq)]
16pub struct ImportedLuminaire {
17    /// Product name
18    pub name: String,
19    /// Description
20    pub description: Option<String>,
21    /// Manufacturer name
22    pub manufacturer: Option<String>,
23    /// Model/article number
24    pub model_reference: Option<String>,
25    /// Variants (one per IFCLIGHTFIXTURETYPE)
26    pub variants: Vec<ImportedVariant>,
27    /// Product-level descriptive attributes (IP code, safety class, etc.)
28    pub descriptive_attributes: ProductDescriptiveAttributes,
29    /// Embedded files (images, sensors, etc.) for roundtrip preservation
30    pub embedded_files: Vec<EmbeddedFile>,
31}
32
33/// Product-level descriptive attributes (shared across all variants)
34#[derive(Debug, Clone, Default, PartialEq)]
35pub struct ProductDescriptiveAttributes {
36    /// Electrical safety class (I, II, III)
37    pub electrical_safety_class: Option<String>,
38    /// IP code (e.g., IP20, IP65)
39    pub ip_code: Option<String>,
40    /// Median useful life (e.g., "L80B50 70000h 25°C")
41    pub median_useful_life: Option<String>,
42    /// Power factor (cos φ), Electrical.
43    pub power_factor: Option<f64>,
44    /// Constant light output flag, Electrical.
45    pub constant_light_output: Option<bool>,
46    /// Weight in kg, Mechanical.
47    pub weight: Option<f64>,
48    /// IK impact rating (e.g. IK08), Mechanical.
49    pub ik_rating: Option<String>,
50    /// Product form / housing shape, Mechanical.
51    pub product_form: Option<String>,
52    /// Overall dimensions in mm (width, height, length), Mechanical.
53    pub overall_width_mm: Option<i32>,
54    pub overall_height_mm: Option<i32>,
55    pub overall_length_mm: Option<i32>,
56    /// Dedicated emergency lighting type, Emergency.
57    pub dedicated_emergency_lighting_type: Option<String>,
58}
59
60/// Embedded file from GLDF (image, sensor, etc.)
61#[derive(Debug, Clone, PartialEq)]
62pub struct EmbeddedFile {
63    /// File type ("image", "sensor", etc.)
64    pub file_type: String,
65    /// Original filename
66    pub filename: String,
67    /// Content type (MIME type, e.g., "image/png", "sensor/sensldt")
68    pub content_type: String,
69    /// File content as bytes
70    pub content: Vec<u8>,
71}
72
73/// Extracted variant data
74#[derive(Debug, Clone, Default, PartialEq)]
75pub struct ImportedVariant {
76    /// Variant name (from type name)
77    pub name: String,
78    /// Description
79    pub description: Option<String>,
80    /// GLDF variant ID (if present from Pset_LuminaireVariant)
81    pub gldf_variant_id: Option<String>,
82    /// Light fixture type enum
83    pub fixture_type: Option<String>,
84    /// Light sources in this variant
85    pub light_sources: Vec<ImportedLightSource>,
86    /// Photometry data (if embedded)
87    pub photometry: Option<ImportedPhotometry>,
88    /// Geometry mesh data
89    pub geometry: Option<ImportedGeometry>,
90    /// Properties
91    pub properties: ImportedProperties,
92}
93
94/// Extracted light source data
95#[derive(Debug, Clone, Default, PartialEq)]
96pub struct ImportedLightSource {
97    /// Source name
98    pub name: String,
99    /// Correlated color temperature (K)
100    pub color_temperature: Option<f64>,
101    /// Luminous flux (lm)
102    pub luminous_flux: Option<f64>,
103    /// Emission source type (LED, FLUORESCENT, etc.)
104    pub emission_source: Option<String>,
105    /// Light intensity distribution reference
106    pub distribution: Option<ImportedDistribution>,
107    /// Original photometry filename (e.g., "narrow.ldt") - preserved through IFC roundtrip
108    pub photometry_filename: Option<String>,
109    /// Original LDT metadata preserved through IFC roundtrip
110    pub ldt_metadata: Option<LdtMetadata>,
111}
112
113/// LDT file metadata for roundtrip preservation
114#[derive(Debug, Clone, Default, PartialEq)]
115pub struct LdtMetadata {
116    /// Symmetry type (0=none, 1=vertical axis, 2=C0-C180, 3=C90-C270, 4=both planes)
117    pub symmetry: i32,
118    /// Number of C-planes in original file
119    pub num_c_planes: i32,
120    /// Number of gamma angles in original file
121    pub num_g_angles: i32,
122    /// C-plane step (Dc)
123    pub dc: f64,
124    /// Gamma step (Dg)
125    pub dg: f64,
126    /// Total luminous flux from LDT header
127    pub total_flux: Option<f64>,
128    /// Direct ratios (DR) values
129    pub dr: Option<[f64; 10]>,
130    /// Luminaire name from LDT
131    pub luminaire_name: Option<String>,
132    /// Manufacturer from LDT
133    pub manufacturer: Option<String>,
134    /// Complete raw LDT content (for exact roundtrip)
135    pub raw_content: Option<String>,
136}
137
138/// Light intensity distribution data
139#[derive(Debug, Clone, Default, PartialEq)]
140pub struct ImportedDistribution {
141    /// Distribution type (TYPE_A, TYPE_B, TYPE_C)
142    pub distribution_type: String,
143    /// Distribution data: (main_angle, secondary_angles, intensities)
144    pub data: Vec<DistributionPlane>,
145}
146
147/// Single plane of distribution data (C-plane for Type C)
148#[derive(Debug, Clone, Default, PartialEq)]
149pub struct DistributionPlane {
150    /// Main plane angle (C-angle for Type C)
151    pub main_angle: f64,
152    /// Intensities at secondary angles (gamma angles)
153    pub intensities: Vec<(f64, f64)>, // (angle, intensity)
154}
155
156/// Extracted photometry in EULUMDAT-compatible format
157#[derive(Debug, Clone, Default, PartialEq)]
158pub struct ImportedPhotometry {
159    /// Luminaire name
160    pub name: String,
161    /// Total luminous flux
162    pub luminous_flux: f64,
163    /// Number of C-planes
164    pub num_c_planes: usize,
165    /// Number of gamma angles per plane
166    pub num_gamma_angles: usize,
167    /// C-plane angles
168    pub c_angles: Vec<f64>,
169    /// Gamma angles
170    pub gamma_angles: Vec<f64>,
171    /// Intensity values \[c_plane\]\[gamma\]
172    pub intensities: Vec<Vec<f64>>,
173}
174
175/// Extracted mesh geometry
176#[derive(Debug, Clone, Default, PartialEq)]
177pub struct ImportedGeometry {
178    /// Vertex positions (x, y, z) in meters
179    pub vertices: Vec<(f64, f64, f64)>,
180    /// Triangle indices (0-based)
181    pub triangles: Vec<(u32, u32, u32)>,
182}
183
184/// Extracted properties from property sets
185#[derive(Debug, Clone, Default, PartialEq)]
186pub struct ImportedProperties {
187    /// Number of light sources
188    pub number_of_sources: Option<i32>,
189    /// Total wattage (W)
190    pub total_wattage: Option<f64>,
191    /// Mounting type (CEILING, WALL, etc.)
192    pub mounting_type: Option<String>,
193    /// Color temperature (K)
194    pub color_temperature: Option<f64>,
195    /// Luminous flux (lm)
196    pub luminous_flux: Option<f64>,
197    /// Power (W)
198    pub power: Option<f64>,
199    /// Efficacy (lm/W)
200    pub efficacy: Option<f64>,
201    /// Color rendering index
202    pub cri: Option<i32>,
203    /// Weight (kg)
204    pub weight: Option<f64>,
205    /// IP code (IEC 60529)
206    pub ip_code: Option<String>,
207    /// IK code (IEC 62262) - mechanical impact protection
208    pub ik_code: Option<String>,
209    /// Rated voltage (V)
210    pub rated_voltage: Option<f64>,
211    /// Maximum rated voltage (V) - for voltage range
212    pub rated_voltage_max: Option<f64>,
213    /// Rated current (A)
214    pub rated_current: Option<f64>,
215    /// Power factor (cos φ)
216    pub power_factor: Option<f64>,
217    /// Nominal frequency min (Hz)
218    pub nominal_frequency_min: Option<f64>,
219    /// Nominal frequency max (Hz)
220    pub nominal_frequency_max: Option<f64>,
221    /// Number of electrical poles
222    pub number_of_poles: Option<i32>,
223    /// Has protective earth connection
224    pub has_protective_earth: Option<bool>,
225    /// Insulation standard class (CLASS0, CLASSI, CLASSII, CLASSIII)
226    pub insulation_standard_class: Option<String>,
227    /// Heat dissipation (W)
228    pub heat_dissipation: Option<f64>,
229    /// Nominal power consumption (W)
230    pub nominal_power_consumption: Option<f64>,
231    /// Number of power supply ports
232    pub number_of_power_supply_ports: Option<i32>,
233    /// Electrical safety class (I, II, III) - legacy/GLDF format
234    pub electrical_safety_class: Option<String>,
235    /// Median useful life (e.g., "L80B50 70000h 25°C")
236    pub median_useful_life: Option<String>,
237    /// GLDF mounting type (Ceiling, Wall, Ground, etc.)
238    pub gldf_mounting_type: Option<String>,
239    /// Recessed depth (mm)
240    pub recessed_depth: Option<f64>,
241    /// Maintenance factor (0.0-1.0)
242    pub maintenance_factor: Option<f64>,
243}
244
245/// IFC to GLDF importer
246pub struct IfcImporter {
247    parser: StepParser,
248}
249
250impl IfcImporter {
251    /// Create importer from IFC file content
252    #[allow(clippy::should_implement_trait)]
253    pub fn from_str(content: &str) -> Result<Self> {
254        let parser = StepParser::parse(content)?;
255        Ok(Self { parser })
256    }
257
258    /// Import all luminaires from the IFC file
259    pub fn import(&self) -> Result<ImportedLuminaire> {
260        let mut luminaire = ImportedLuminaire::default();
261
262        // Find all light fixture types
263        let fixture_types = self.parser.find_by_type("IFCLIGHTFIXTURETYPE");
264
265        if fixture_types.is_empty() {
266            return Err(anyhow!("No IFCLIGHTFIXTURETYPE found in IFC file"));
267        }
268
269        // Extract manufacturer info from first type
270        if let Some(first_type) = fixture_types.first() {
271            let params = first_type.get_params();
272
273            // Name is param[2]
274            if let Some(name) = params.get(2).and_then(|v| v.as_string()) {
275                // Split variant suffix if present (e.g., "Product - Variant")
276                if let Some(pos) = name.find(" - ") {
277                    luminaire.name = name[..pos].to_string();
278                } else {
279                    luminaire.name = name.to_string();
280                }
281            }
282
283            // Description is param[3]
284            if let Some(desc) = params.get(3).and_then(|v| v.as_string()) {
285                luminaire.description = Some(desc.to_string());
286            }
287
288            // Get manufacturer from property set
289            if let Some(pset) =
290                self.find_property_set(first_type.id, "Pset_ManufacturerTypeInformation")
291            {
292                if let Some(mfr) = self.get_property_value(&pset, "Manufacturer") {
293                    luminaire.manufacturer = mfr.as_string().map(|s| s.to_string());
294                }
295                if let Some(model) = self.get_property_value(&pset, "ModelReference") {
296                    luminaire.model_reference = model.as_string().map(|s| s.to_string());
297                }
298            }
299        }
300
301        // Extract each fixture type as a variant
302        for fixture_type in &fixture_types {
303            let variant = self.extract_variant(fixture_type)?;
304            luminaire.variants.push(variant);
305        }
306
307        // Extract product-level descriptive attributes from first variant
308        // (IP code, safety class, etc. are product-level in GLDF, not per-variant)
309        if let Some(first_variant) = luminaire.variants.first() {
310            luminaire.descriptive_attributes.electrical_safety_class =
311                first_variant.properties.electrical_safety_class.clone();
312            luminaire.descriptive_attributes.ip_code = first_variant.properties.ip_code.clone();
313            luminaire.descriptive_attributes.median_useful_life =
314                first_variant.properties.median_useful_life.clone();
315        }
316
317        // Scan the Pset_GLDF_* buckets (written by our exporter, keyed
318        // by buildingSMART bSDD GlobalIds) and populate the full
319        // product-level attribute set. This is the import side of the
320        // BIM-properties spec round-trip — it recognises properties by
321        // their stable dictionary id, so it works regardless of which
322        // Pset they landed in or how the name was localised.
323        if let Some(first_type) = fixture_types.first() {
324            self.scan_bim_properties(first_type.id, &mut luminaire.descriptive_attributes);
325        }
326
327        // Extract embedded files (images, sensors) from Pset_GLDF_EmbeddedFile
328        luminaire.embedded_files = self.extract_embedded_files();
329
330        Ok(luminaire)
331    }
332
333    /// Extract embedded GLDF files (images, sensors) from IFC property sets
334    fn extract_embedded_files(&self) -> Vec<EmbeddedFile> {
335        use base64::{engine::general_purpose::STANDARD, Engine};
336
337        let mut files = Vec::new();
338
339        // Find all Pset_GLDF_EmbeddedFile property sets
340        for entity in self.parser.find_by_type("IFCPROPERTYSET") {
341            let params = entity.get_params();
342            if let Some(name) = params.get(2).and_then(|v| v.as_string()) {
343                if name == "Pset_GLDF_EmbeddedFile" {
344                    // Extract properties from this pset
345                    let mut file_type = None;
346                    let mut filename = None;
347                    let mut content_type = None;
348                    let mut content_b64 = None;
349
350                    if let Some(StepValue::List(props)) = params.get(4) {
351                        for prop_ref in props {
352                            if let StepValue::Ref(prop_id) = prop_ref {
353                                if let Some(prop_entity) = self.parser.get(*prop_id) {
354                                    let prop_params = prop_entity.get_params();
355                                    if let Some(prop_name) =
356                                        prop_params.first().and_then(|v: &StepValue| v.as_string())
357                                    {
358                                        let value = prop_params
359                                            .get(2)
360                                            .and_then(|v: &StepValue| v.as_string());
361                                        match prop_name {
362                                            "GLDF_FileType" => file_type = value.map(String::from),
363                                            "GLDF_Filename" => filename = value.map(String::from),
364                                            "GLDF_ContentType" => {
365                                                content_type = value.map(String::from)
366                                            }
367                                            "GLDF_FileContent" => {
368                                                content_b64 = value.map(String::from)
369                                            }
370                                            _ => {}
371                                        }
372                                    }
373                                }
374                            }
375                        }
376                    }
377
378                    // If we have all required fields, decode and add the file
379                    if let (Some(ft), Some(fn_), Some(ct), Some(b64)) =
380                        (file_type, filename, content_type, content_b64)
381                    {
382                        if let Ok(content) = STANDARD.decode(&b64) {
383                            files.push(EmbeddedFile {
384                                file_type: ft,
385                                filename: fn_,
386                                content_type: ct,
387                                content,
388                            });
389                        }
390                    }
391                }
392            }
393        }
394
395        files
396    }
397
398    /// Extract variant data from IFCLIGHTFIXTURETYPE
399    fn extract_variant(
400        &self,
401        fixture_type: &super::step_parser::StepEntity,
402    ) -> Result<ImportedVariant> {
403        let mut variant = ImportedVariant::default();
404        let params = fixture_type.get_params();
405
406        // Name (param[2])
407        if let Some(name) = params.get(2).and_then(|v| v.as_string()) {
408            variant.name = name.to_string();
409        }
410
411        // Description (param[3])
412        if let Some(desc) = params.get(3).and_then(|v| v.as_string()) {
413            variant.description = Some(desc.to_string());
414        }
415
416        // Predefined type (param[9])
417        if let Some(ptype) = params.get(9).and_then(|v| v.as_enum()) {
418            variant.fixture_type = Some(ptype.to_string());
419        }
420
421        // Extract properties from Pset_LightFixtureTypeCommon
422        if let Some(pset) = self.find_property_set(fixture_type.id, "Pset_LightFixtureTypeCommon") {
423            if let Some(v) = self.get_property_value(&pset, "NumberOfSources") {
424                variant.properties.number_of_sources = v.as_integer().map(|i| i as i32);
425            }
426            if let Some(v) = self.get_property_value(&pset, "TotalWattage") {
427                variant.properties.total_wattage = v.as_real();
428            }
429            if let Some(v) = self.get_property_value(&pset, "LightFixtureMountingType") {
430                variant.properties.mounting_type = v.as_string().map(|s| s.to_string());
431            }
432        }
433
434        // Extract variant-specific properties from Pset_LuminaireVariant
435        if let Some(pset) = self.find_property_set(fixture_type.id, "Pset_LuminaireVariant") {
436            if let Some(v) = self.get_property_value(&pset, "GLDF_VariantId") {
437                variant.gldf_variant_id = v.as_string().map(|s| s.to_string());
438            }
439            if let Some(v) = self.get_property_value(&pset, "ColorTemperature") {
440                variant.properties.color_temperature = v.as_real();
441            }
442            if let Some(v) = self.get_property_value(&pset, "LuminousFlux") {
443                variant.properties.luminous_flux = v.as_real();
444            }
445            if let Some(v) = self.get_property_value(&pset, "Power") {
446                variant.properties.power = v.as_real();
447            }
448            if let Some(v) = self.get_property_value(&pset, "Efficacy") {
449                variant.properties.efficacy = v.as_real();
450            }
451            if let Some(v) = self.get_property_value(&pset, "ColorRenderingIndex") {
452                variant.properties.cri = v.as_integer().map(|i| i as i32);
453            }
454            if let Some(v) = self.get_property_value(&pset, "Weight") {
455                variant.properties.weight = v.as_real();
456            }
457        }
458
459        // Extract electrical properties from Pset_ElectricalDeviceCommon (Electrical MVD)
460        if let Some(pset) = self.find_property_set(fixture_type.id, "Pset_ElectricalDeviceCommon") {
461            // IP_Code (IEC 60529)
462            if let Some(v) = self.get_property_value(&pset, "IP_Code") {
463                variant.properties.ip_code = v.as_string().map(|s| s.to_string());
464            }
465            // Legacy IPCode support
466            if variant.properties.ip_code.is_none() {
467                if let Some(v) = self.get_property_value(&pset, "IPCode") {
468                    variant.properties.ip_code = v.as_string().map(|s| s.to_string());
469                }
470            }
471            // IK_Code (IEC 62262)
472            if let Some(v) = self.get_property_value(&pset, "IK_Code") {
473                variant.properties.ik_code = v.as_string().map(|s| s.to_string());
474            }
475            // RatedVoltage
476            if let Some(v) = self.get_property_value(&pset, "RatedVoltage") {
477                variant.properties.rated_voltage = v.as_real();
478                // TODO: Handle bounded values for voltage range
479            }
480            // RatedCurrent
481            if let Some(v) = self.get_property_value(&pset, "RatedCurrent") {
482                variant.properties.rated_current = v.as_real();
483            }
484            // PowerFactor
485            if let Some(v) = self.get_property_value(&pset, "PowerFactor") {
486                variant.properties.power_factor = v.as_real();
487            }
488            // NominalFrequencyRange - bounded value
489            if let Some(v) = self.get_property_value(&pset, "NominalFrequencyRange") {
490                // For bounded values, try to extract both min and max
491                if let Some(freq) = v.as_real() {
492                    variant.properties.nominal_frequency_min = Some(freq);
493                    variant.properties.nominal_frequency_max = Some(freq);
494                }
495            }
496            // NumberOfPoles
497            if let Some(v) = self.get_property_value(&pset, "NumberOfPoles") {
498                variant.properties.number_of_poles = v.as_integer().map(|i| i as i32);
499            }
500            // HasProtectiveEarth
501            if let Some(v) = self.get_property_value(&pset, "HasProtectiveEarth") {
502                variant.properties.has_protective_earth = v.as_boolean();
503            }
504            // InsulationStandardClass - can be enum or string
505            if let Some(v) = self.get_property_value(&pset, "InsulationStandardClass") {
506                variant.properties.insulation_standard_class = v
507                    .as_enum()
508                    .map(|s| s.to_string())
509                    .or_else(|| v.as_string().map(|s| s.to_string()));
510            }
511            // HeatDissipation
512            if let Some(v) = self.get_property_value(&pset, "HeatDissipation") {
513                variant.properties.heat_dissipation = v.as_real();
514            }
515            // Power
516            if let Some(v) = self.get_property_value(&pset, "Power") {
517                // Don't overwrite power from variant pset
518                if variant.properties.power.is_none() {
519                    variant.properties.power = v.as_real();
520                }
521            }
522            // NominalPowerConsumption
523            if let Some(v) = self.get_property_value(&pset, "NominalPowerConsumption") {
524                variant.properties.nominal_power_consumption = v.as_real();
525            }
526            // NumberOfPowerSupplyPorts
527            if let Some(v) = self.get_property_value(&pset, "NumberOfPowerSupplyPorts") {
528                variant.properties.number_of_power_supply_ports = v.as_integer().map(|i| i as i32);
529            }
530        }
531
532        // Extract from Pset_LightFixtureTypeCommon
533        if let Some(pset) = self.find_property_set(fixture_type.id, "Pset_LightFixtureTypeCommon") {
534            if let Some(v) = self.get_property_value(&pset, "MaintenanceFactor") {
535                variant.properties.maintenance_factor = v.as_real();
536            }
537            // These might override values from basic pset
538            if variant.properties.number_of_sources.is_none() {
539                if let Some(v) = self.get_property_value(&pset, "NumberOfSources") {
540                    variant.properties.number_of_sources = v.as_integer().map(|i| i as i32);
541                }
542            }
543            if variant.properties.total_wattage.is_none() {
544                if let Some(v) = self.get_property_value(&pset, "TotalWattage") {
545                    variant.properties.total_wattage = v.as_real();
546                }
547            }
548        }
549
550        // Extract GLDF descriptive attributes from ALL Pset_GLDF_DescriptiveAttributes property sets
551        for pset in self.find_all_property_sets(fixture_type.id, "Pset_GLDF_DescriptiveAttributes")
552        {
553            if let Some(v) = self.get_property_value(&pset, "ElectricalSafetyClass") {
554                variant.properties.electrical_safety_class = v.as_string().map(|s| s.to_string());
555            }
556            if let Some(v) = self.get_property_value(&pset, "MedianUsefulLife") {
557                variant.properties.median_useful_life = v.as_string().map(|s| s.to_string());
558            }
559            if let Some(v) = self.get_property_value(&pset, "GLDF_MountingType") {
560                variant.properties.gldf_mounting_type = v.as_string().map(|s| s.to_string());
561            }
562            if let Some(v) = self.get_property_value(&pset, "GLDF_RecessedDepth") {
563                variant.properties.recessed_depth = v.as_real();
564            }
565        }
566
567        // Extract photometry filenames from Pset_GLDF_PhotometryFiles (for roundtrip preservation)
568        let photometry_filenames = self.extract_photometry_filenames(fixture_type.id);
569
570        // Extract LDT metadata from Pset_GLDF_LDTMetadata (for roundtrip preservation)
571        let ldt_metadata_map = self.extract_ldt_metadata(fixture_type.id);
572
573        // Extract raw LDT content from Pset_GLDF_LDTRawContent (for exact roundtrip)
574        let ldt_raw_content_map = self.extract_ldt_raw_content(fixture_type.id);
575
576        // Find associated light sources via IFCRELASSIGNSTOGROUP
577        let light_sources = self.find_light_sources_for_fixture(fixture_type.id);
578        for (idx, ls_id) in light_sources.iter().enumerate() {
579            if let Some(mut ls) = self.extract_light_source(*ls_id) {
580                // Associate preserved photometry filename with this light source
581                if let Some(filename) = photometry_filenames.get(idx) {
582                    ls.photometry_filename = Some(filename.clone());
583                }
584                // Associate preserved LDT metadata with this light source
585                // First try raw content, then fall back to metadata
586                if let Some((filename, content)) = ldt_raw_content_map.get(&(idx + 1)) {
587                    let mut meta = ldt_metadata_map
588                        .get(&(idx + 1))
589                        .cloned()
590                        .unwrap_or_default();
591                    meta.raw_content = Some(content.clone());
592                    // Override filename if we have it from raw content
593                    ls.photometry_filename = Some(filename.clone());
594                    ls.ldt_metadata = Some(meta);
595                } else if let Some(meta) = ldt_metadata_map.get(&(idx + 1)) {
596                    ls.ldt_metadata = Some(meta.clone());
597                }
598                variant.light_sources.push(ls);
599            }
600        }
601
602        // Find geometry from fixture occurrence
603        if let Some(occurrence_id) = self.find_fixture_occurrence(fixture_type.id) {
604            if let Some(geom) = self.extract_geometry(occurrence_id) {
605                variant.geometry = Some(geom);
606            }
607        }
608
609        Ok(variant)
610    }
611
612    /// Extract photometry filenames from Pset_GLDF_PhotometryFiles
613    fn extract_photometry_filenames(&self, element_id: u64) -> Vec<String> {
614        let mut filenames = Vec::new();
615
616        if let Some(pset_id) = self.find_property_set(element_id, "Pset_GLDF_PhotometryFiles") {
617            // Get all PhotometryFile_N properties (1, 2, 3, etc.)
618            for i in 1..=100 {
619                let prop_name = format!("PhotometryFile_{}", i);
620                if let Some(value) = self.get_property_value(&pset_id, &prop_name) {
621                    if let Some(filename) = value.as_string() {
622                        filenames.push(filename.to_string());
623                    }
624                } else {
625                    break; // No more properties
626                }
627            }
628        }
629
630        filenames
631    }
632
633    /// Extract LDT metadata from all Pset_GLDF_LDTMetadata property sets
634    fn extract_ldt_metadata(
635        &self,
636        element_id: u64,
637    ) -> std::collections::HashMap<usize, LdtMetadata> {
638        use std::collections::HashMap;
639        let mut metadata_map: HashMap<usize, LdtMetadata> = HashMap::new();
640
641        // Find ALL Pset_GLDF_LDTMetadata property sets for this element
642        for pset_id in self.find_all_property_sets(element_id, "Pset_GLDF_LDTMetadata") {
643            // Each property set contains metadata for one LDT file
644            // Try to find the index from properties like LDT_1_Index, LDT_2_Index, etc.
645            for i in 1..=100 {
646                let idx_name = format!("LDT_{}_Index", i);
647                // Check if this index exists in this pset
648                if self.get_property_value(&pset_id, &idx_name).is_none() {
649                    continue; // Try next index
650                }
651
652                let mut meta = LdtMetadata::default();
653
654                // Symmetry
655                if let Some(v) = self.get_property_value(&pset_id, &format!("LDT_{}_Symmetry", i)) {
656                    meta.symmetry = v.as_integer().unwrap_or(0) as i32;
657                }
658
659                // Number of C-planes
660                if let Some(v) = self.get_property_value(&pset_id, &format!("LDT_{}_NumCPlanes", i))
661                {
662                    meta.num_c_planes = v.as_integer().unwrap_or(1) as i32;
663                }
664
665                // Number of gamma angles
666                if let Some(v) = self.get_property_value(&pset_id, &format!("LDT_{}_NumGAngles", i))
667                {
668                    meta.num_g_angles = v.as_integer().unwrap_or(19) as i32;
669                }
670
671                // C-plane distance (Dc)
672                if let Some(v) = self.get_property_value(&pset_id, &format!("LDT_{}_Dc", i)) {
673                    meta.dc = v.as_real().unwrap_or(0.0);
674                }
675
676                // Gamma distance (Dg)
677                if let Some(v) = self.get_property_value(&pset_id, &format!("LDT_{}_Dg", i)) {
678                    meta.dg = v.as_real().unwrap_or(0.0);
679                }
680
681                // Total flux
682                if let Some(v) = self.get_property_value(&pset_id, &format!("LDT_{}_TotalFlux", i))
683                {
684                    meta.total_flux = Some(v.as_real().unwrap_or(1000.0));
685                }
686
687                // DR values (stored as comma-separated string)
688                if let Some(v) = self.get_property_value(&pset_id, &format!("LDT_{}_DR", i)) {
689                    if let Some(dr_str) = v.as_string() {
690                        let dr_vals: Vec<f64> = dr_str
691                            .split(',')
692                            .filter_map(|s| s.trim().parse().ok())
693                            .collect();
694                        if dr_vals.len() == 10 {
695                            let mut dr_arr = [1.0; 10];
696                            for (j, val) in dr_vals.iter().enumerate() {
697                                dr_arr[j] = *val;
698                            }
699                            meta.dr = Some(dr_arr);
700                        }
701                    }
702                }
703
704                // Luminaire name
705                if let Some(v) =
706                    self.get_property_value(&pset_id, &format!("LDT_{}_LuminaireName", i))
707                {
708                    meta.luminaire_name = v.as_string().map(|s| s.to_string());
709                }
710
711                metadata_map.insert(i, meta);
712            }
713        }
714
715        metadata_map
716    }
717
718    /// Extract raw LDT content from Pset_GLDF_LDTRawContent
719    fn extract_ldt_raw_content(
720        &self,
721        element_id: u64,
722    ) -> std::collections::HashMap<usize, (String, String)> {
723        use std::collections::HashMap;
724        let mut content_map: HashMap<usize, (String, String)> = HashMap::new();
725
726        // Find ALL Pset_GLDF_LDTRawContent property sets for this element
727        for pset_id in self.find_all_property_sets(element_id, "Pset_GLDF_LDTRawContent") {
728            // Each property set contains LDT_N_Filename and LDT_N_Content
729            for i in 1..=100 {
730                let filename_prop = format!("LDT_{}_Filename", i);
731                let content_prop = format!("LDT_{}_Content", i);
732
733                let filename = self
734                    .get_property_value(&pset_id, &filename_prop)
735                    .and_then(|v| v.as_string().map(|s| s.to_string()));
736                let content_b64 = self
737                    .get_property_value(&pset_id, &content_prop)
738                    .and_then(|v| v.as_string().map(|s| s.to_string()));
739
740                if let (Some(f), Some(c)) = (filename, content_b64) {
741                    // Decode base64 content
742                    use base64::{engine::general_purpose::STANDARD, Engine};
743                    if let Ok(decoded) = STANDARD.decode(&c) {
744                        if let Ok(content) = String::from_utf8(decoded) {
745                            content_map.insert(i, (f, content));
746                        }
747                    }
748                }
749            }
750        }
751
752        content_map
753    }
754
755    /// Find ALL property sets with a given name for an element
756    fn find_all_property_sets(&self, element_id: u64, pset_name: &str) -> Vec<u64> {
757        let mut psets = Vec::new();
758
759        // Look for IFCRELDEFINESBYPROPERTIES that references our element
760        for entity in self.parser.find_by_type("IFCRELDEFINESBYPROPERTIES") {
761            let params = entity.get_params();
762
763            // RelatedObjects is param[4] (list)
764            let related_to_element = params
765                .get(4)
766                .and_then(|v| v.as_list())
767                .is_some_and(|list| list.iter().any(|item| item.as_ref() == Some(element_id)));
768
769            if !related_to_element {
770                continue;
771            }
772
773            // RelatingPropertyDefinition is param[5] (ref)
774            if let Some(pset_ref) = params.get(5).and_then(|v| v.as_ref()) {
775                if let Some(pset) = self.parser.get(pset_ref) {
776                    if pset.entity_type == "IFCPROPERTYSET" {
777                        let pset_params = pset.get_params();
778                        // Name is param[2]
779                        if let Some(name) = pset_params.get(2).and_then(|v| v.as_string()) {
780                            if name == pset_name {
781                                psets.push(pset_ref);
782                            }
783                        }
784                    }
785                }
786            }
787        }
788
789        psets
790    }
791
792    /// Find property set for an element
793    /// Scan every property set attached to `element_id` for properties
794    /// that carry a buildingSMART bSDD GlobalId (in their Description as
795    /// `bSDD:<id>`) and populate `da` accordingly. The import-side of
796    /// the BIM-properties spec round-trip — see
797    /// [`crate::ifc::bim_properties`].
798    fn scan_bim_properties(&self, element_id: u64, da: &mut ProductDescriptiveAttributes) {
799        use crate::ifc::bim_properties::resolve_imported_property;
800
801        // Collect every IFCPROPERTYSET attached to the element.
802        let mut pset_ids: Vec<u64> = Vec::new();
803        for rel in self.parser.find_by_type("IFCRELDEFINESBYPROPERTIES") {
804            let params = rel.get_params();
805            let attached = params
806                .get(4)
807                .and_then(|v| v.as_list())
808                .map(|l| l.iter().any(|v| v.as_ref() == Some(element_id)))
809                .unwrap_or(false);
810            if !attached {
811                continue;
812            }
813            if let Some(pset_ref) = params.get(5).and_then(|v| v.as_ref()) {
814                pset_ids.push(pset_ref);
815            }
816        }
817
818        for pset_id in pset_ids {
819            let Some(pset) = self.parser.get(pset_id) else {
820                continue;
821            };
822            if pset.entity_type != "IFCPROPERTYSET" {
823                continue;
824            }
825            let pset_params = pset.get_params();
826            let Some(props) = pset_params.get(4).and_then(|v| v.as_list()) else {
827                continue;
828            };
829            for prop_ref in props {
830                let Some(prop_id) = prop_ref.as_ref() else {
831                    continue;
832                };
833                let Some(prop) = self.parser.get(prop_id) else {
834                    continue;
835                };
836                if prop.entity_type != "IFCPROPERTYSINGLEVALUE" {
837                    continue;
838                }
839                let pp = prop.get_params();
840                let name = pp.first().and_then(|v| v.as_string()).unwrap_or("");
841                // Description (param[1]) may carry `bSDD:<id>`.
842                let bsdd = pp
843                    .get(1)
844                    .and_then(|v| v.as_string())
845                    .and_then(|d| d.strip_prefix("bSDD:"))
846                    .unwrap_or("");
847                // NominalValue (param[2]) — unwrap the measure/label
848                // text. `as_string` handles IFCLABEL/IFCTEXT/IFCIDENTIFIER;
849                // `as_real` handles the numeric measures (and unwraps
850                // the Typed wrapper); booleans round-trip via as_boolean.
851                let nominal = pp.get(2);
852                let value = nominal
853                    .and_then(|v| v.as_string().map(|s| s.to_string()))
854                    .or_else(|| nominal.and_then(|v| v.as_boolean()).map(|b| b.to_string()))
855                    .or_else(|| nominal.and_then(|v| v.as_real()).map(|f| f.to_string()))
856                    .unwrap_or_default();
857                if value.is_empty() {
858                    continue;
859                }
860
861                if let Some(resolved) = resolve_imported_property(name, bsdd, value) {
862                    Self::apply_bim_property(da, resolved.name, &resolved.value);
863                }
864            }
865        }
866    }
867
868    /// Write one resolved BIM property into the descriptive-attributes
869    /// struct. Only fills empty fields — earlier extraction (from
870    /// Pset_ElectricalDeviceCommon etc.) wins, since those are the
871    /// canonical IFC Psets.
872    fn apply_bim_property(da: &mut ProductDescriptiveAttributes, name: &str, value: &str) {
873        match name {
874            "ElectricalSafetyClass" => {
875                da.electrical_safety_class
876                    .get_or_insert_with(|| value.to_string());
877            }
878            "IngressProtectionIPCode" => {
879                da.ip_code.get_or_insert_with(|| value.to_string());
880            }
881            "MedianUsefulLife" => {
882                da.median_useful_life
883                    .get_or_insert_with(|| value.to_string());
884            }
885            "PowerFactor" => {
886                if da.power_factor.is_none() {
887                    da.power_factor = value.parse().ok();
888                }
889            }
890            "ConstantLightOutput" => {
891                if da.constant_light_output.is_none() {
892                    da.constant_light_output = parse_ifc_bool(value);
893                }
894            }
895            "Weight" => {
896                if da.weight.is_none() {
897                    da.weight = value.parse().ok();
898                }
899            }
900            "IKRating" => {
901                da.ik_rating.get_or_insert_with(|| value.to_string());
902            }
903            "ProductForm" => {
904                da.product_form.get_or_insert_with(|| value.to_string());
905            }
906            "OverallWidth" => {
907                if da.overall_width_mm.is_none() {
908                    da.overall_width_mm = parse_length_mm(value);
909                }
910            }
911            "OverallHeight" => {
912                if da.overall_height_mm.is_none() {
913                    da.overall_height_mm = parse_length_mm(value);
914                }
915            }
916            "OverallLength" => {
917                if da.overall_length_mm.is_none() {
918                    da.overall_length_mm = parse_length_mm(value);
919                }
920            }
921            "DedicatedEmergencyLightingType" => {
922                da.dedicated_emergency_lighting_type
923                    .get_or_insert_with(|| value.to_string());
924            }
925            _ => {}
926        }
927    }
928
929    fn find_property_set(&self, element_id: u64, pset_name: &str) -> Option<u64> {
930        // Look for IFCRELDEFINESBYPROPERTIES that references our element
931        for entity in self.parser.find_by_type("IFCRELDEFINESBYPROPERTIES") {
932            let params = entity.get_params();
933
934            // RelatedObjects is param[4] (list of element refs)
935            if let Some(related) = params.get(4).and_then(|v| v.as_list()) {
936                let has_element = related.iter().any(|v| v.as_ref() == Some(element_id));
937
938                if has_element {
939                    // RelatingPropertyDefinition is param[5]
940                    if let Some(pset_ref) = params.get(5).and_then(|v| v.as_ref()) {
941                        if let Some(pset) = self.parser.get(pset_ref) {
942                            if pset.entity_type == "IFCPROPERTYSET" {
943                                let pset_params = pset.get_params();
944                                // Name is param[2]
945                                if let Some(name) = pset_params.get(2).and_then(|v| v.as_string()) {
946                                    if name == pset_name {
947                                        return Some(pset_ref);
948                                    }
949                                }
950                            }
951                        }
952                    }
953                }
954            }
955        }
956        None
957    }
958
959    /// Get property value from property set
960    fn get_property_value(&self, pset_id: &u64, property_name: &str) -> Option<StepValue> {
961        let pset = self.parser.get(*pset_id)?;
962        let params = pset.get_params();
963
964        // HasProperties is param[4] (list of property refs)
965        let properties = params.get(4)?.as_list()?;
966
967        for prop_ref in properties {
968            if let Some(prop_id) = prop_ref.as_ref() {
969                if let Some(prop) = self.parser.get(prop_id) {
970                    if prop.entity_type == "IFCPROPERTYSINGLEVALUE" {
971                        let prop_params = prop.get_params();
972                        // Name is param[0]
973                        if let Some(name) = prop_params.first().and_then(|v| v.as_string()) {
974                            if name == property_name {
975                                // NominalValue is param[2]
976                                return prop_params.get(2).cloned();
977                            }
978                        }
979                    }
980                }
981            }
982        }
983        None
984    }
985
986    /// Find light sources associated with a fixture type via IFCRELASSIGNSTOGROUP
987    fn find_light_sources_for_fixture(&self, fixture_type_id: u64) -> Vec<u64> {
988        let mut sources = Vec::new();
989
990        // First find fixture occurrences of this type
991        let occurrences = self.find_occurrences_of_type(fixture_type_id);
992
993        for occ_id in occurrences {
994            // Find IFCRELASSIGNSTOGROUP that has this occurrence as RelatingGroup
995            for entity in self.parser.find_by_type("IFCRELASSIGNSTOGROUP") {
996                let params = entity.get_params();
997
998                // RelatingGroup is param[6]
999                if params.get(6).and_then(|v| v.as_ref()) == Some(occ_id) {
1000                    // RelatedObjects is param[5] (list)
1001                    if let Some(related) = params.get(5).and_then(|v| v.as_list()) {
1002                        for item in related {
1003                            if let Some(id) = item.as_ref() {
1004                                if let Some(e) = self.parser.get(id) {
1005                                    if e.entity_type == "IFCLIGHTSOURCEGONIOMETRIC"
1006                                        || e.entity_type == "IFCLIGHTSOURCESPOT"
1007                                        || e.entity_type == "IFCLIGHTSOURCEPOSITIONAL"
1008                                    {
1009                                        sources.push(id);
1010                                    }
1011                                }
1012                            }
1013                        }
1014                    }
1015                }
1016            }
1017        }
1018
1019        // Only fall back to finding ALL light sources if no grouped sources were found
1020        // This handles legacy IFC files without proper grouping
1021        if sources.is_empty() {
1022            for entity in self.parser.find_by_type("IFCLIGHTSOURCEGONIOMETRIC") {
1023                sources.push(entity.id);
1024            }
1025        }
1026
1027        sources
1028    }
1029
1030    /// Find fixture occurrences (IFCLIGHTFIXTURE) of a given type
1031    fn find_occurrences_of_type(&self, type_id: u64) -> Vec<u64> {
1032        let mut occurrences = Vec::new();
1033
1034        // Find IFCRELDEFINESBYTYPE
1035        for entity in self.parser.find_by_type("IFCRELDEFINESBYTYPE") {
1036            let params = entity.get_params();
1037
1038            // RelatingType is param[5]
1039            if params.get(5).and_then(|v| v.as_ref()) == Some(type_id) {
1040                // RelatedObjects is param[4] (list)
1041                if let Some(related) = params.get(4).and_then(|v| v.as_list()) {
1042                    for item in related {
1043                        if let Some(id) = item.as_ref() {
1044                            occurrences.push(id);
1045                        }
1046                    }
1047                }
1048            }
1049        }
1050
1051        occurrences
1052    }
1053
1054    /// Find a fixture occurrence for a type
1055    fn find_fixture_occurrence(&self, type_id: u64) -> Option<u64> {
1056        self.find_occurrences_of_type(type_id).first().copied()
1057    }
1058
1059    /// Extract light source data
1060    fn extract_light_source(&self, light_source_id: u64) -> Option<ImportedLightSource> {
1061        let entity = self.parser.get(light_source_id)?;
1062        let params = entity.get_params();
1063
1064        let mut source = ImportedLightSource::default();
1065
1066        // IFCLIGHTSOURCEGONIOMETRIC params:
1067        // 0: Name, 1: Description, 2: LightColour, 3: AmbientIntensity,
1068        // 4: Position, 5: ColourAppearance, 6: ColourTemperature, 7: LuminousFlux,
1069        // 8: LightEmissionSource, 9: LightDistributionDataSource
1070
1071        // Name (param[0])
1072        if let Some(name) = params.first().and_then(|v| v.as_string()) {
1073            source.name = name.to_string();
1074        }
1075
1076        // ColorTemperature (param[6])
1077        if let Some(cct) = params.get(6).and_then(|v| v.as_real()) {
1078            source.color_temperature = Some(cct);
1079        }
1080
1081        // LuminousFlux (param[7])
1082        if let Some(flux) = params.get(7).and_then(|v| v.as_real()) {
1083            source.luminous_flux = Some(flux);
1084        }
1085
1086        // LightEmissionSource (param[8])
1087        if let Some(emission) = params.get(8).and_then(|v| v.as_enum()) {
1088            source.emission_source = Some(emission.to_string());
1089        }
1090
1091        // LightDistributionDataSource (param[9])
1092        if let Some(dist_ref) = params.get(9).and_then(|v| v.as_ref()) {
1093            // First check if it's an IFCEXTERNALREFERENCE (contains filename)
1094            if let Some(ext_ref) = self.parser.get(dist_ref) {
1095                if ext_ref.entity_type == "IFCEXTERNALREFERENCE" {
1096                    let ext_params = ext_ref.get_params();
1097                    // Location is param[0] - contains the file path
1098                    if let Some(location) = ext_params.first().and_then(|v| v.as_string()) {
1099                        // Extract just the filename from the path
1100                        let filename = location.rsplit('/').next().unwrap_or(location);
1101                        source.photometry_filename = Some(filename.to_string());
1102                    }
1103                }
1104            }
1105            // Then try to extract distribution data
1106            source.distribution = self.extract_distribution(dist_ref);
1107        }
1108
1109        Some(source)
1110    }
1111
1112    /// Extract light distribution data
1113    fn extract_distribution(&self, dist_id: u64) -> Option<ImportedDistribution> {
1114        let entity = self.parser.get(dist_id)?;
1115
1116        // Could be IFCLIGHTINTENSITYDISTRIBUTION or IFCEXTERNALREFERENCE
1117        if entity.entity_type == "IFCLIGHTINTENSITYDISTRIBUTION" {
1118            let params = entity.get_params();
1119            let mut dist = ImportedDistribution::default();
1120
1121            // LightDistributionCurve (param[0]) - enum
1122            if let Some(curve_type) = params.first().and_then(|v| v.as_enum()) {
1123                dist.distribution_type = curve_type.to_string();
1124            }
1125
1126            // DistributionData (param[1]) - list of IFCLIGHTDISTRIBUTIONDATA refs
1127            if let Some(data_list) = params.get(1).and_then(|v| v.as_list()) {
1128                for data_ref in data_list {
1129                    if let Some(data_id) = data_ref.as_ref() {
1130                        if let Some(plane) = self.extract_distribution_plane(data_id) {
1131                            dist.data.push(plane);
1132                        }
1133                    }
1134                }
1135            }
1136
1137            return Some(dist);
1138        }
1139
1140        None
1141    }
1142
1143    /// Extract a single distribution plane
1144    fn extract_distribution_plane(&self, data_id: u64) -> Option<DistributionPlane> {
1145        let entity = self.parser.get(data_id)?;
1146        if entity.entity_type != "IFCLIGHTDISTRIBUTIONDATA" {
1147            return None;
1148        }
1149
1150        let params = entity.get_params();
1151        let mut plane = DistributionPlane::default();
1152
1153        // MainPlaneAngle (param[0])
1154        if let Some(main) = params.first().and_then(|v| v.as_real()) {
1155            plane.main_angle = main;
1156        }
1157
1158        // SecondaryPlaneAngle (param[1]) - list
1159        // LuminousIntensity (param[2]) - list
1160        if let Some(secondary_list) = params.get(1).and_then(|v| v.as_list()) {
1161            let intensity_list = params.get(2).and_then(|v| v.as_list());
1162
1163            for (i, angle_val) in secondary_list.iter().enumerate() {
1164                if let Some(angle) = angle_val.as_real() {
1165                    let intensity = intensity_list
1166                        .and_then(|l| l.get(i))
1167                        .and_then(|v| v.as_real())
1168                        .unwrap_or(0.0);
1169                    plane.intensities.push((angle, intensity));
1170                }
1171            }
1172        }
1173
1174        Some(plane)
1175    }
1176
1177    /// Extract geometry from fixture occurrence
1178    fn extract_geometry(&self, occurrence_id: u64) -> Option<ImportedGeometry> {
1179        let entity = self.parser.get(occurrence_id)?;
1180        let params = entity.get_params();
1181
1182        // Representation is param[6] for IFCLIGHTFIXTURE
1183        let rep_ref = params.get(6).and_then(|v| v.as_ref())?;
1184        let rep = self.parser.get(rep_ref)?;
1185
1186        if rep.entity_type != "IFCPRODUCTDEFINITIONSHAPE" {
1187            return None;
1188        }
1189
1190        let rep_params = rep.get_params();
1191        // Representations is param[2] (list)
1192        let reps = rep_params.get(2)?.as_list()?;
1193
1194        for rep_item in reps {
1195            if let Some(shape_rep_id) = rep_item.as_ref() {
1196                if let Some(geom) = self.extract_shape_representation(shape_rep_id) {
1197                    return Some(geom);
1198                }
1199            }
1200        }
1201
1202        None
1203    }
1204
1205    /// Extract geometry from IFCSHAPEREPRESENTATION
1206    fn extract_shape_representation(&self, rep_id: u64) -> Option<ImportedGeometry> {
1207        let rep = self.parser.get(rep_id)?;
1208        if rep.entity_type != "IFCSHAPEREPRESENTATION" {
1209            return None;
1210        }
1211
1212        let params = rep.get_params();
1213        // RepresentationType is param[2]
1214        let rep_type = params.get(2).and_then(|v| v.as_string())?;
1215
1216        // Items is param[3] (list)
1217        let items = params.get(3)?.as_list()?;
1218
1219        // Handle different representation types
1220        match rep_type {
1221            "Tessellation" => {
1222                // Look for IFCTRIANGULATEDFACESET
1223                for item in items {
1224                    if let Some(item_id) = item.as_ref() {
1225                        if let Some(geom) = self.extract_triangulated_faceset(item_id) {
1226                            return Some(geom);
1227                        }
1228                    }
1229                }
1230            }
1231            "MappedRepresentation" => {
1232                // Look for IFCMAPPEDITEM and follow to the actual geometry
1233                for item in items {
1234                    if let Some(item_id) = item.as_ref() {
1235                        if let Some(geom) = self.extract_mapped_item(item_id) {
1236                            return Some(geom);
1237                        }
1238                    }
1239                }
1240            }
1241            "SweptSolid" => {
1242                // IFCEXTRUDEDAREASOLID - create simple box mesh
1243                for item in items {
1244                    if let Some(item_id) = item.as_ref() {
1245                        if let Some(geom) = self.extract_extruded_solid(item_id) {
1246                            return Some(geom);
1247                        }
1248                    }
1249                }
1250            }
1251            _ => {}
1252        }
1253
1254        None
1255    }
1256
1257    /// Extract geometry from IFCMAPPEDITEM
1258    fn extract_mapped_item(&self, item_id: u64) -> Option<ImportedGeometry> {
1259        let entity = self.parser.get(item_id)?;
1260        if entity.entity_type != "IFCMAPPEDITEM" {
1261            return None;
1262        }
1263
1264        let params = entity.get_params();
1265        // MappingSource is param[0] - ref to IFCREPRESENTATIONMAP
1266        let map_ref = params.first().and_then(|v| v.as_ref())?;
1267        let rep_map = self.parser.get(map_ref)?;
1268
1269        if rep_map.entity_type != "IFCREPRESENTATIONMAP" {
1270            return None;
1271        }
1272
1273        let map_params = rep_map.get_params();
1274        // MappedRepresentation is param[1] - ref to IFCSHAPEREPRESENTATION
1275        let shape_rep_ref = map_params.get(1).and_then(|v| v.as_ref())?;
1276
1277        // Recursively extract from the mapped shape representation
1278        self.extract_shape_representation(shape_rep_ref)
1279    }
1280
1281    /// Extract mesh from IFCTRIANGULATEDFACESET
1282    fn extract_triangulated_faceset(&self, faceset_id: u64) -> Option<ImportedGeometry> {
1283        let entity = self.parser.get(faceset_id)?;
1284        if entity.entity_type != "IFCTRIANGULATEDFACESET" {
1285            return None;
1286        }
1287
1288        let params = entity.get_params();
1289        let mut geom = ImportedGeometry::default();
1290
1291        // Coordinates is param[0] - ref to IFCCARTESIANPOINTLIST3D
1292        if let Some(coords_ref) = params.first().and_then(|v| v.as_ref()) {
1293            if let Some(coords) = self.parser.get(coords_ref) {
1294                if coords.entity_type == "IFCCARTESIANPOINTLIST3D" {
1295                    let coords_params = coords.get_params();
1296                    // CoordList is param[0] - nested list of coordinates
1297                    if let Some(coord_list) = coords_params.first().and_then(|v| v.as_list()) {
1298                        for point in coord_list {
1299                            if let Some(point_coords) = point.as_list() {
1300                                let x = point_coords
1301                                    .first()
1302                                    .and_then(|v| v.as_real())
1303                                    .unwrap_or(0.0);
1304                                let y =
1305                                    point_coords.get(1).and_then(|v| v.as_real()).unwrap_or(0.0);
1306                                let z =
1307                                    point_coords.get(2).and_then(|v| v.as_real()).unwrap_or(0.0);
1308                                geom.vertices.push((x, y, z));
1309                            }
1310                        }
1311                    }
1312                }
1313            }
1314        }
1315
1316        // CoordIndex is param[3] - list of triangle indices (1-based in IFC)
1317        if let Some(index_list) = params.get(3).and_then(|v| v.as_list()) {
1318            for tri in index_list {
1319                if let Some(indices) = tri.as_list() {
1320                    let i0 = indices.first().and_then(|v| v.as_integer()).unwrap_or(1) as u32 - 1;
1321                    let i1 = indices.get(1).and_then(|v| v.as_integer()).unwrap_or(1) as u32 - 1;
1322                    let i2 = indices.get(2).and_then(|v| v.as_integer()).unwrap_or(1) as u32 - 1;
1323                    geom.triangles.push((i0, i1, i2));
1324                }
1325            }
1326        }
1327
1328        if geom.vertices.is_empty() || geom.triangles.is_empty() {
1329            return None;
1330        }
1331
1332        Some(geom)
1333    }
1334
1335    /// Extract mesh from IFCEXTRUDEDAREASOLID (create simple box)
1336    fn extract_extruded_solid(&self, solid_id: u64) -> Option<ImportedGeometry> {
1337        let entity = self.parser.get(solid_id)?;
1338        if entity.entity_type != "IFCEXTRUDEDAREASOLID" {
1339            return None;
1340        }
1341
1342        let params = entity.get_params();
1343
1344        // SweptArea is param[0] - ref to profile
1345        let profile_ref = params.first().and_then(|v| v.as_ref())?;
1346        let profile = self.parser.get(profile_ref)?;
1347
1348        // Depth is param[3]
1349        let depth = params.get(3).and_then(|v| v.as_real()).unwrap_or(0.1);
1350
1351        // Handle IFCRECTANGLEPROFILEDEF
1352        if profile.entity_type == "IFCRECTANGLEPROFILEDEF" {
1353            let profile_params = profile.get_params();
1354            let width = profile_params
1355                .get(3)
1356                .and_then(|v| v.as_real())
1357                .unwrap_or(0.3);
1358            let height = profile_params
1359                .get(4)
1360                .and_then(|v| v.as_real())
1361                .unwrap_or(0.3);
1362
1363            return Some(self.create_box_mesh(width, height, depth));
1364        }
1365
1366        None
1367    }
1368
1369    /// Create a simple box mesh
1370    fn create_box_mesh(&self, width: f64, height: f64, depth: f64) -> ImportedGeometry {
1371        let hw = width / 2.0;
1372        let hh = height / 2.0;
1373
1374        let vertices = vec![
1375            // Bottom face
1376            (-hw, -hh, 0.0),
1377            (hw, -hh, 0.0),
1378            (hw, hh, 0.0),
1379            (-hw, hh, 0.0),
1380            // Top face
1381            (-hw, -hh, depth),
1382            (hw, -hh, depth),
1383            (hw, hh, depth),
1384            (-hw, hh, depth),
1385        ];
1386
1387        let triangles = vec![
1388            // Bottom
1389            (0, 2, 1),
1390            (0, 3, 2),
1391            // Top
1392            (4, 5, 6),
1393            (4, 6, 7),
1394            // Front
1395            (0, 1, 5),
1396            (0, 5, 4),
1397            // Back
1398            (2, 3, 7),
1399            (2, 7, 6),
1400            // Left
1401            (0, 4, 7),
1402            (0, 7, 3),
1403            // Right
1404            (1, 2, 6),
1405            (1, 6, 5),
1406        ];
1407
1408        ImportedGeometry {
1409            vertices,
1410            triangles,
1411        }
1412    }
1413}
1414
1415/// Parse an IFC boolean value (already stringified to "true"/"false"
1416/// by the scan, or a raw `.T.`/`.F.` enum text).
1417fn parse_ifc_bool(value: &str) -> Option<bool> {
1418    match value.trim().to_ascii_lowercase().as_str() {
1419        "true" | "t" | ".t." | "1" => Some(true),
1420        "false" | "f" | ".f." | "0" => Some(false),
1421        _ => None,
1422    }
1423}
1424
1425/// Parse an IFCPOSITIVELENGTHMEASURE (metres, as written by the
1426/// exporter) back to GLDF's native millimetres. The exporter divided
1427/// mm by 1000; we multiply back and round to the nearest mm.
1428fn parse_length_mm(value: &str) -> Option<i32> {
1429    value
1430        .trim()
1431        .parse::<f64>()
1432        .ok()
1433        .map(|m| (m * 1000.0).round() as i32)
1434}
1435
1436#[cfg(test)]
1437mod tests {
1438    use super::*;
1439
1440    #[test]
1441    fn test_import_basic() {
1442        let content = r#"
1443ISO-10303-21;
1444HEADER;
1445FILE_DESCRIPTION(('GLDF to IFC Export'),'2;1');
1446FILE_NAME('test.ifc','2024-01-01',(''),(''),'gldf-rs','gldf-rs','');
1447FILE_SCHEMA(('IFC4'));
1448ENDSEC;
1449
1450DATA;
1451#1=IFCPERSON($,$,'',$,$,$,$,$);
1452#2=IFCORGANIZATION($,'Test Corp','GLDF Export',$,$);
1453#3=IFCPERSONANDORGANIZATION(#1,#2,$);
1454#4=IFCAPPLICATION(#2,'1.0','Test','Test');
1455#5=IFCOWNERHISTORY(#3,#4,.READWRITE.,.ADDED.,$,$,$,0);
1456#6=IFCLIGHTFIXTURETYPE('guid1',#5,'LED Panel - 4000K','Test fixture',$,$,$,$,$,.POINTSOURCE.);
1457#7=IFCPROPERTYSINGLEVALUE('Manufacturer',$,IFCLABEL('Test Corp'),$);
1458#8=IFCPROPERTYSINGLEVALUE('ModelReference',$,IFCLABEL('LED-001'),$);
1459#9=IFCPROPERTYSET('guid2',#5,'Pset_ManufacturerTypeInformation',$,(#7,#8));
1460#10=IFCRELDEFINESBYPROPERTIES('guid3',#5,$,$,(#6),#9);
1461ENDSEC;
1462
1463END-ISO-10303-21;
1464"#;
1465
1466        let importer = IfcImporter::from_str(content).unwrap();
1467        let luminaire = importer.import().unwrap();
1468
1469        assert_eq!(luminaire.name, "LED Panel");
1470        assert_eq!(luminaire.manufacturer, Some("Test Corp".to_string()));
1471        assert_eq!(luminaire.model_reference, Some("LED-001".to_string()));
1472        assert_eq!(luminaire.variants.len(), 1);
1473        assert_eq!(luminaire.variants[0].name, "LED Panel - 4000K");
1474    }
1475}