1use super::step_parser::{StepParser, StepValue};
12use anyhow::{anyhow, Result};
13
14#[derive(Debug, Clone, Default, PartialEq)]
16pub struct ImportedLuminaire {
17 pub name: String,
19 pub description: Option<String>,
21 pub manufacturer: Option<String>,
23 pub model_reference: Option<String>,
25 pub variants: Vec<ImportedVariant>,
27 pub descriptive_attributes: ProductDescriptiveAttributes,
29 pub embedded_files: Vec<EmbeddedFile>,
31}
32
33#[derive(Debug, Clone, Default, PartialEq)]
35pub struct ProductDescriptiveAttributes {
36 pub electrical_safety_class: Option<String>,
38 pub ip_code: Option<String>,
40 pub median_useful_life: Option<String>,
42 pub power_factor: Option<f64>,
44 pub constant_light_output: Option<bool>,
46 pub weight: Option<f64>,
48 pub ik_rating: Option<String>,
50 pub product_form: Option<String>,
52 pub overall_width_mm: Option<i32>,
54 pub overall_height_mm: Option<i32>,
55 pub overall_length_mm: Option<i32>,
56 pub dedicated_emergency_lighting_type: Option<String>,
58}
59
60#[derive(Debug, Clone, PartialEq)]
62pub struct EmbeddedFile {
63 pub file_type: String,
65 pub filename: String,
67 pub content_type: String,
69 pub content: Vec<u8>,
71}
72
73#[derive(Debug, Clone, Default, PartialEq)]
75pub struct ImportedVariant {
76 pub name: String,
78 pub description: Option<String>,
80 pub gldf_variant_id: Option<String>,
82 pub fixture_type: Option<String>,
84 pub light_sources: Vec<ImportedLightSource>,
86 pub photometry: Option<ImportedPhotometry>,
88 pub geometry: Option<ImportedGeometry>,
90 pub properties: ImportedProperties,
92}
93
94#[derive(Debug, Clone, Default, PartialEq)]
96pub struct ImportedLightSource {
97 pub name: String,
99 pub color_temperature: Option<f64>,
101 pub luminous_flux: Option<f64>,
103 pub emission_source: Option<String>,
105 pub distribution: Option<ImportedDistribution>,
107 pub photometry_filename: Option<String>,
109 pub ldt_metadata: Option<LdtMetadata>,
111}
112
113#[derive(Debug, Clone, Default, PartialEq)]
115pub struct LdtMetadata {
116 pub symmetry: i32,
118 pub num_c_planes: i32,
120 pub num_g_angles: i32,
122 pub dc: f64,
124 pub dg: f64,
126 pub total_flux: Option<f64>,
128 pub dr: Option<[f64; 10]>,
130 pub luminaire_name: Option<String>,
132 pub manufacturer: Option<String>,
134 pub raw_content: Option<String>,
136}
137
138#[derive(Debug, Clone, Default, PartialEq)]
140pub struct ImportedDistribution {
141 pub distribution_type: String,
143 pub data: Vec<DistributionPlane>,
145}
146
147#[derive(Debug, Clone, Default, PartialEq)]
149pub struct DistributionPlane {
150 pub main_angle: f64,
152 pub intensities: Vec<(f64, f64)>, }
155
156#[derive(Debug, Clone, Default, PartialEq)]
158pub struct ImportedPhotometry {
159 pub name: String,
161 pub luminous_flux: f64,
163 pub num_c_planes: usize,
165 pub num_gamma_angles: usize,
167 pub c_angles: Vec<f64>,
169 pub gamma_angles: Vec<f64>,
171 pub intensities: Vec<Vec<f64>>,
173}
174
175#[derive(Debug, Clone, Default, PartialEq)]
177pub struct ImportedGeometry {
178 pub vertices: Vec<(f64, f64, f64)>,
180 pub triangles: Vec<(u32, u32, u32)>,
182}
183
184#[derive(Debug, Clone, Default, PartialEq)]
186pub struct ImportedProperties {
187 pub number_of_sources: Option<i32>,
189 pub total_wattage: Option<f64>,
191 pub mounting_type: Option<String>,
193 pub color_temperature: Option<f64>,
195 pub luminous_flux: Option<f64>,
197 pub power: Option<f64>,
199 pub efficacy: Option<f64>,
201 pub cri: Option<i32>,
203 pub weight: Option<f64>,
205 pub ip_code: Option<String>,
207 pub ik_code: Option<String>,
209 pub rated_voltage: Option<f64>,
211 pub rated_voltage_max: Option<f64>,
213 pub rated_current: Option<f64>,
215 pub power_factor: Option<f64>,
217 pub nominal_frequency_min: Option<f64>,
219 pub nominal_frequency_max: Option<f64>,
221 pub number_of_poles: Option<i32>,
223 pub has_protective_earth: Option<bool>,
225 pub insulation_standard_class: Option<String>,
227 pub heat_dissipation: Option<f64>,
229 pub nominal_power_consumption: Option<f64>,
231 pub number_of_power_supply_ports: Option<i32>,
233 pub electrical_safety_class: Option<String>,
235 pub median_useful_life: Option<String>,
237 pub gldf_mounting_type: Option<String>,
239 pub recessed_depth: Option<f64>,
241 pub maintenance_factor: Option<f64>,
243}
244
245pub struct IfcImporter {
247 parser: StepParser,
248}
249
250impl IfcImporter {
251 #[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 pub fn import(&self) -> Result<ImportedLuminaire> {
260 let mut luminaire = ImportedLuminaire::default();
261
262 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 if let Some(first_type) = fixture_types.first() {
271 let params = first_type.get_params();
272
273 if let Some(name) = params.get(2).and_then(|v| v.as_string()) {
275 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 if let Some(desc) = params.get(3).and_then(|v| v.as_string()) {
285 luminaire.description = Some(desc.to_string());
286 }
287
288 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 for fixture_type in &fixture_types {
303 let variant = self.extract_variant(fixture_type)?;
304 luminaire.variants.push(variant);
305 }
306
307 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 if let Some(first_type) = fixture_types.first() {
324 self.scan_bim_properties(first_type.id, &mut luminaire.descriptive_attributes);
325 }
326
327 luminaire.embedded_files = self.extract_embedded_files();
329
330 Ok(luminaire)
331 }
332
333 fn extract_embedded_files(&self) -> Vec<EmbeddedFile> {
335 use base64::{engine::general_purpose::STANDARD, Engine};
336
337 let mut files = Vec::new();
338
339 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 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 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 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 if let Some(name) = params.get(2).and_then(|v| v.as_string()) {
408 variant.name = name.to_string();
409 }
410
411 if let Some(desc) = params.get(3).and_then(|v| v.as_string()) {
413 variant.description = Some(desc.to_string());
414 }
415
416 if let Some(ptype) = params.get(9).and_then(|v| v.as_enum()) {
418 variant.fixture_type = Some(ptype.to_string());
419 }
420
421 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 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 if let Some(pset) = self.find_property_set(fixture_type.id, "Pset_ElectricalDeviceCommon") {
461 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 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 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 if let Some(v) = self.get_property_value(&pset, "RatedVoltage") {
477 variant.properties.rated_voltage = v.as_real();
478 }
480 if let Some(v) = self.get_property_value(&pset, "RatedCurrent") {
482 variant.properties.rated_current = v.as_real();
483 }
484 if let Some(v) = self.get_property_value(&pset, "PowerFactor") {
486 variant.properties.power_factor = v.as_real();
487 }
488 if let Some(v) = self.get_property_value(&pset, "NominalFrequencyRange") {
490 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 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 if let Some(v) = self.get_property_value(&pset, "HasProtectiveEarth") {
502 variant.properties.has_protective_earth = v.as_boolean();
503 }
504 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 if let Some(v) = self.get_property_value(&pset, "HeatDissipation") {
513 variant.properties.heat_dissipation = v.as_real();
514 }
515 if let Some(v) = self.get_property_value(&pset, "Power") {
517 if variant.properties.power.is_none() {
519 variant.properties.power = v.as_real();
520 }
521 }
522 if let Some(v) = self.get_property_value(&pset, "NominalPowerConsumption") {
524 variant.properties.nominal_power_consumption = v.as_real();
525 }
526 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 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 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 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 let photometry_filenames = self.extract_photometry_filenames(fixture_type.id);
569
570 let ldt_metadata_map = self.extract_ldt_metadata(fixture_type.id);
572
573 let ldt_raw_content_map = self.extract_ldt_raw_content(fixture_type.id);
575
576 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 if let Some(filename) = photometry_filenames.get(idx) {
582 ls.photometry_filename = Some(filename.clone());
583 }
584 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 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 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 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 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; }
627 }
628 }
629
630 filenames
631 }
632
633 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 for pset_id in self.find_all_property_sets(element_id, "Pset_GLDF_LDTMetadata") {
643 for i in 1..=100 {
646 let idx_name = format!("LDT_{}_Index", i);
647 if self.get_property_value(&pset_id, &idx_name).is_none() {
649 continue; }
651
652 let mut meta = LdtMetadata::default();
653
654 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 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 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 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 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 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 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 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 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 for pset_id in self.find_all_property_sets(element_id, "Pset_GLDF_LDTRawContent") {
728 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 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 fn find_all_property_sets(&self, element_id: u64, pset_name: &str) -> Vec<u64> {
757 let mut psets = Vec::new();
758
759 for entity in self.parser.find_by_type("IFCRELDEFINESBYPROPERTIES") {
761 let params = entity.get_params();
762
763 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 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 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 fn scan_bim_properties(&self, element_id: u64, da: &mut ProductDescriptiveAttributes) {
799 use crate::ifc::bim_properties::resolve_imported_property;
800
801 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 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 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 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 for entity in self.parser.find_by_type("IFCRELDEFINESBYPROPERTIES") {
932 let params = entity.get_params();
933
934 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 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 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 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 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 if let Some(name) = prop_params.first().and_then(|v| v.as_string()) {
974 if name == property_name {
975 return prop_params.get(2).cloned();
977 }
978 }
979 }
980 }
981 }
982 }
983 None
984 }
985
986 fn find_light_sources_for_fixture(&self, fixture_type_id: u64) -> Vec<u64> {
988 let mut sources = Vec::new();
989
990 let occurrences = self.find_occurrences_of_type(fixture_type_id);
992
993 for occ_id in occurrences {
994 for entity in self.parser.find_by_type("IFCRELASSIGNSTOGROUP") {
996 let params = entity.get_params();
997
998 if params.get(6).and_then(|v| v.as_ref()) == Some(occ_id) {
1000 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 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 fn find_occurrences_of_type(&self, type_id: u64) -> Vec<u64> {
1032 let mut occurrences = Vec::new();
1033
1034 for entity in self.parser.find_by_type("IFCRELDEFINESBYTYPE") {
1036 let params = entity.get_params();
1037
1038 if params.get(5).and_then(|v| v.as_ref()) == Some(type_id) {
1040 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 fn find_fixture_occurrence(&self, type_id: u64) -> Option<u64> {
1056 self.find_occurrences_of_type(type_id).first().copied()
1057 }
1058
1059 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 if let Some(name) = params.first().and_then(|v| v.as_string()) {
1073 source.name = name.to_string();
1074 }
1075
1076 if let Some(cct) = params.get(6).and_then(|v| v.as_real()) {
1078 source.color_temperature = Some(cct);
1079 }
1080
1081 if let Some(flux) = params.get(7).and_then(|v| v.as_real()) {
1083 source.luminous_flux = Some(flux);
1084 }
1085
1086 if let Some(emission) = params.get(8).and_then(|v| v.as_enum()) {
1088 source.emission_source = Some(emission.to_string());
1089 }
1090
1091 if let Some(dist_ref) = params.get(9).and_then(|v| v.as_ref()) {
1093 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 if let Some(location) = ext_params.first().and_then(|v| v.as_string()) {
1099 let filename = location.rsplit('/').next().unwrap_or(location);
1101 source.photometry_filename = Some(filename.to_string());
1102 }
1103 }
1104 }
1105 source.distribution = self.extract_distribution(dist_ref);
1107 }
1108
1109 Some(source)
1110 }
1111
1112 fn extract_distribution(&self, dist_id: u64) -> Option<ImportedDistribution> {
1114 let entity = self.parser.get(dist_id)?;
1115
1116 if entity.entity_type == "IFCLIGHTINTENSITYDISTRIBUTION" {
1118 let params = entity.get_params();
1119 let mut dist = ImportedDistribution::default();
1120
1121 if let Some(curve_type) = params.first().and_then(|v| v.as_enum()) {
1123 dist.distribution_type = curve_type.to_string();
1124 }
1125
1126 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 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 if let Some(main) = params.first().and_then(|v| v.as_real()) {
1155 plane.main_angle = main;
1156 }
1157
1158 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 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 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 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 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 let rep_type = params.get(2).and_then(|v| v.as_string())?;
1215
1216 let items = params.get(3)?.as_list()?;
1218
1219 match rep_type {
1221 "Tessellation" => {
1222 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 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 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 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 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 let shape_rep_ref = map_params.get(1).and_then(|v| v.as_ref())?;
1276
1277 self.extract_shape_representation(shape_rep_ref)
1279 }
1280
1281 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 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 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 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 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 let profile_ref = params.first().and_then(|v| v.as_ref())?;
1346 let profile = self.parser.get(profile_ref)?;
1347
1348 let depth = params.get(3).and_then(|v| v.as_real()).unwrap_or(0.1);
1350
1351 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 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 (-hw, -hh, 0.0),
1377 (hw, -hh, 0.0),
1378 (hw, hh, 0.0),
1379 (-hw, hh, 0.0),
1380 (-hw, -hh, depth),
1382 (hw, -hh, depth),
1383 (hw, hh, depth),
1384 (-hw, hh, depth),
1385 ];
1386
1387 let triangles = vec![
1388 (0, 2, 1),
1390 (0, 3, 2),
1391 (4, 5, 6),
1393 (4, 6, 7),
1394 (0, 1, 5),
1396 (0, 5, 4),
1397 (2, 3, 7),
1399 (2, 7, 6),
1400 (0, 4, 7),
1402 (0, 7, 3),
1403 (1, 2, 6),
1405 (1, 6, 5),
1406 ];
1407
1408 ImportedGeometry {
1409 vertices,
1410 triangles,
1411 }
1412 }
1413}
1414
1415fn 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
1425fn 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}