1use crate::record::{Field, Record, ToRecord};
40use crate::value::Tagged;
41use crate::{BindingError, IfcModel};
42
43#[derive(Debug, Clone, PartialEq)]
46pub struct PropertySet {
47 pub id: u64,
49 pub global_id: Option<String>,
51 pub name: String,
54 pub type_name: String,
58 pub source: String,
61 pub source_id: Option<u64>,
63 pub properties: Vec<Property>,
66}
67
68#[derive(Debug, Clone, PartialEq)]
70pub struct Property {
71 pub id: u64,
74 pub name: String,
76 pub type_name: String,
79 pub kind: String,
82 pub value_type: Option<String>,
84 pub unit: Option<u64>,
88 pub value: Tagged,
93 pub enumeration: Option<Enumeration>,
95 pub bounds: Option<Bounds>,
97 pub table: Option<Table>,
99 pub usage: Option<String>,
101 pub discrimination: Option<String>,
103 pub quality: Option<String>,
105 pub members: Vec<Property>,
107}
108
109#[derive(Debug, Clone, PartialEq)]
112pub struct ObjectPropertySets {
113 pub object: u64,
115 pub sets: Vec<PropertySet>,
118 pub refusal: Option<PropertyRefusal>,
120}
121
122#[derive(Debug, Clone, PartialEq, Eq)]
125pub struct PropertyRefusal {
126 pub code: String,
130 pub message: String,
132}
133
134impl From<&BindingError> for PropertyRefusal {
135 fn from(error: &BindingError) -> Self {
136 Self {
137 code: error.code().to_owned(),
138 message: error.to_string(),
139 }
140 }
141}
142
143#[derive(Debug, Clone, PartialEq)]
145pub struct Enumeration {
146 pub id: u64,
148 pub name: String,
150 pub values: Vec<Tagged>,
152}
153
154#[derive(Debug, Clone, PartialEq)]
156pub struct Bounds {
157 pub lower: Tagged,
159 pub upper: Tagged,
161 pub set_point: Tagged,
163}
164
165#[derive(Debug, Clone, PartialEq)]
167pub struct Table {
168 pub rows: Vec<(Tagged, Tagged)>,
170 pub expression: Option<String>,
172 pub defining_unit: Option<u64>,
174 pub defined_unit: Option<u64>,
176 pub interpolation: Option<String>,
178}
179
180#[derive(Debug, Clone, PartialEq)]
183pub struct ResolvedUnit {
184 pub unit: Option<u64>,
186 pub from_project: bool,
188 pub dimensions: [i32; 7],
190 pub scale: f64,
192 pub offset: f64,
194}
195
196impl IfcModel {
197 pub fn property_sets(&self, object: u64) -> Result<Vec<PropertySet>, BindingError> {
209 #[cfg(feature = "properties")]
210 {
211 read::property_sets(self, object)
212 }
213 #[cfg(not(feature = "properties"))]
214 {
215 let _ = object;
216 Err(BindingError::FeatureDisabled("properties"))
217 }
218 }
219
220 pub fn property_sets_many(
234 &self,
235 objects: Option<&[u64]>,
236 ) -> Result<Vec<ObjectPropertySets>, BindingError> {
237 #[cfg(feature = "properties")]
238 {
239 read::property_sets_many(self, objects)
240 }
241 #[cfg(not(feature = "properties"))]
242 {
243 let _ = objects;
244 Err(BindingError::FeatureDisabled("properties"))
245 }
246 }
247
248 pub fn resolve_unit(
258 &self,
259 measure_type: &str,
260 unit: Option<u64>,
261 ) -> Result<ResolvedUnit, BindingError> {
262 #[cfg(feature = "properties")]
263 {
264 read::resolve_unit(self, measure_type, unit)
265 }
266 #[cfg(not(feature = "properties"))]
267 {
268 let _ = (measure_type, unit);
269 Err(BindingError::FeatureDisabled("properties"))
270 }
271 }
272}
273
274impl ToRecord for PropertySet {
275 fn to_record(&self) -> Record {
276 Record::new(
277 "PropertySet",
278 vec![
279 ("id", Field::Id(self.id)),
280 ("global_id", Field::text(self.global_id.clone())),
281 ("name", Field::Text(self.name.clone())),
282 ("type_name", Field::Text(self.type_name.clone())),
283 ("source", Field::Text(self.source.clone())),
284 ("source_id", Field::id(self.source_id)),
285 ("properties", Field::records(&self.properties)),
286 ],
287 )
288 }
289}
290
291impl ToRecord for ObjectPropertySets {
292 fn to_record(&self) -> Record {
293 Record::new(
294 "ObjectPropertySets",
295 vec![
296 ("object", Field::Id(self.object)),
297 ("sets", Field::records(&self.sets)),
298 ("refusal", Field::record(self.refusal.as_ref())),
299 ],
300 )
301 }
302}
303
304impl ToRecord for PropertyRefusal {
305 fn to_record(&self) -> Record {
306 Record::new(
307 "PropertyRefusal",
308 vec![
309 ("code", Field::Text(self.code.clone())),
310 ("message", Field::Text(self.message.clone())),
311 ],
312 )
313 }
314}
315
316impl ToRecord for Property {
317 fn to_record(&self) -> Record {
318 Record::new(
319 "Property",
320 vec![
321 ("id", Field::Id(self.id)),
322 ("name", Field::Text(self.name.clone())),
323 ("type_name", Field::Text(self.type_name.clone())),
324 ("kind", Field::Text(self.kind.clone())),
325 ("value_type", Field::text(self.value_type.clone())),
326 ("unit", Field::id(self.unit)),
327 ("value", Field::Value(self.value.clone())),
328 ("enumeration", Field::record(self.enumeration.as_ref())),
329 ("bounds", Field::record(self.bounds.as_ref())),
330 ("table", Field::record(self.table.as_ref())),
331 ("usage", Field::text(self.usage.clone())),
332 ("discrimination", Field::text(self.discrimination.clone())),
333 ("quality", Field::text(self.quality.clone())),
334 ("members", Field::records(&self.members)),
335 ],
336 )
337 }
338}
339
340impl ToRecord for Enumeration {
341 fn to_record(&self) -> Record {
342 Record::new(
343 "PropertyEnumeration",
344 vec![
345 ("id", Field::Id(self.id)),
346 ("name", Field::Text(self.name.clone())),
347 (
348 "values",
349 Field::List(self.values.iter().cloned().map(Field::Value).collect()),
350 ),
351 ],
352 )
353 }
354}
355
356impl ToRecord for Bounds {
357 fn to_record(&self) -> Record {
358 Record::new(
359 "PropertyBounds",
360 vec![
361 ("lower", Field::Value(self.lower.clone())),
362 ("upper", Field::Value(self.upper.clone())),
363 ("set_point", Field::Value(self.set_point.clone())),
364 ],
365 )
366 }
367}
368
369impl ToRecord for Table {
370 fn to_record(&self) -> Record {
371 let rows = self
372 .rows
373 .iter()
374 .map(|(defining, defined)| {
375 Field::Record(Record::new(
376 "PropertyTableRow",
377 vec![
378 ("defining", Field::Value(defining.clone())),
379 ("defined", Field::Value(defined.clone())),
380 ],
381 ))
382 })
383 .collect();
384 Record::new(
385 "PropertyTable",
386 vec![
387 ("rows", Field::List(rows)),
388 ("expression", Field::text(self.expression.clone())),
389 ("defining_unit", Field::id(self.defining_unit)),
390 ("defined_unit", Field::id(self.defined_unit)),
391 ("interpolation", Field::text(self.interpolation.clone())),
392 ],
393 )
394 }
395}
396
397impl ToRecord for ResolvedUnit {
398 fn to_record(&self) -> Record {
399 Record::new(
400 "ResolvedUnit",
401 vec![
402 ("unit", Field::id(self.unit)),
403 ("from_project", Field::Bool(self.from_project)),
404 (
405 "dimensions",
406 Field::List(
407 self.dimensions
408 .iter()
409 .map(|exponent| Field::Int(i64::from(*exponent)))
410 .collect(),
411 ),
412 ),
413 ("scale", Field::Real(self.scale)),
414 ("offset", Field::Real(self.offset)),
415 ],
416 )
417 }
418}
419
420#[cfg(feature = "properties")]
421pub(crate) mod read {
422 use ifc::properties::{
423 exact_properties, exact_unit, ExactComplexMember, ExactLogical, ExactProperty,
424 ExactPropertyEntry, ExactPropertyError, ExactSource, ExactTypedValue, ExactUnitError,
425 ExactValue, PropertyIndex,
426 };
427 use ifc::EntityId;
428
429 use super::{
430 Bounds, Enumeration, ObjectPropertySets, Property, PropertyRefusal, PropertySet,
431 ResolvedUnit, Table,
432 };
433 use crate::value::Tagged;
434 use crate::{BindingError, IfcModel};
435
436 pub(super) fn property_sets(
437 model: &IfcModel,
438 object: u64,
439 ) -> Result<Vec<PropertySet>, BindingError> {
440 sets_of(model, object, |id| exact_properties(&model.inner, id))
441 }
442
443 pub(super) fn property_sets_many(
444 model: &IfcModel,
445 objects: Option<&[u64]>,
446 ) -> Result<Vec<ObjectPropertySets>, BindingError> {
447 let index = PropertyIndex::build(&model.inner);
448 index.schema().map_err(property_error)?;
451 let every;
452 let objects = match objects {
453 Some(objects) => objects,
454 None => {
455 every = model.ids_of_type_including_subtypes("IfcObjectDefinition")?;
456 &every
457 }
458 };
459 Ok(objects
460 .iter()
461 .map(
462 |&object| match sets_of(model, object, |id| index.exact_properties(id)) {
463 Ok(sets) => ObjectPropertySets {
464 object,
465 sets,
466 refusal: None,
467 },
468 Err(error) => ObjectPropertySets {
469 object,
470 sets: Vec::new(),
471 refusal: Some(PropertyRefusal::from(&error)),
472 },
473 },
474 )
475 .collect())
476 }
477
478 fn sets_of(
481 model: &IfcModel,
482 object: u64,
483 resolve: impl FnOnce(EntityId) -> Result<Vec<ExactPropertyEntry>, ExactPropertyError>,
484 ) -> Result<Vec<PropertySet>, BindingError> {
485 if !model.inner.contains(EntityId(object)) {
486 return Err(BindingError::MissingEntity(object));
487 }
488 let entries = resolve(EntityId(object)).map_err(property_error)?;
489 let mut sets: Vec<PropertySet> = Vec::new();
490 for entry in entries {
491 let property = &entry.property;
492 let (source, source_id) = source(property.source);
493 let set_id = property.set_id.0;
494 let record = convert(model, &entry.name, property.property_id.0, property)?;
495 match sets
496 .iter_mut()
497 .find(|set| set.id == set_id && set.source_id == source_id)
498 {
499 Some(set) => set.properties.push(record),
500 None => {
501 let identity = model.identity(set_id)?;
502 sets.push(PropertySet {
503 id: set_id,
504 global_id: identity.global_id,
505 name: property.property_set.to_string(),
506 type_name: model.type_of(set_id)?.to_owned(),
507 source: source.to_owned(),
508 source_id,
509 properties: vec![record],
510 });
511 }
512 }
513 }
514 Ok(sets)
515 }
516
517 pub(super) fn resolve_unit(
518 model: &IfcModel,
519 measure_type: &str,
520 unit: Option<u64>,
521 ) -> Result<ResolvedUnit, BindingError> {
522 let resolved =
523 exact_unit(&model.inner, measure_type, unit.map(EntityId)).map_err(unit_error)?;
524 Ok(ResolvedUnit {
525 unit: resolved.unit.map(|EntityId(id)| id),
526 from_project: resolved.from_project,
527 dimensions: resolved.dimensions,
528 scale: resolved.scale,
529 offset: resolved.offset,
530 })
531 }
532
533 fn source(source: ExactSource) -> (&'static str, Option<u64>) {
534 match source {
535 ExactSource::Occurrence => ("occurrence", None),
536 ExactSource::Type(id) => ("type", Some(id.0)),
537 ExactSource::Material(id) => ("material", Some(id.0)),
538 _ => ("other", None),
541 }
542 }
543
544 fn convert(
545 model: &IfcModel,
546 name: &str,
547 id: u64,
548 property: &ExactProperty,
549 ) -> Result<Property, BindingError> {
550 member(
551 model,
552 name,
553 id,
554 property.value_type.as_deref(),
555 property.unit_id.map(|EntityId(id)| id),
556 &property.value,
557 )
558 }
559
560 fn member(
561 model: &IfcModel,
562 name: &str,
563 id: u64,
564 value_type: Option<&str>,
565 unit: Option<u64>,
566 value: &ExactValue,
567 ) -> Result<Property, BindingError> {
568 let mut property = Property {
569 id,
570 name: name.to_owned(),
571 type_name: model.type_of(id)?.to_owned(),
572 kind: "value".to_owned(),
573 value_type: value_type.map(str::to_owned),
574 unit,
575 value: Tagged::Null,
576 enumeration: None,
577 bounds: None,
578 table: None,
579 usage: None,
580 discrimination: None,
581 quality: None,
582 members: Vec::new(),
583 };
584 match value {
585 ExactValue::Enumerated(enumerated) => {
586 property.kind = "enumerated".to_owned();
587 property.value = Tagged::List(typed_all(&enumerated.values)?);
588 property.enumeration = enumerated
589 .enumeration
590 .as_ref()
591 .map(|e| -> Result<_, BindingError> {
592 Ok(Enumeration {
593 id: e.id.0,
594 name: e.name.to_string(),
595 values: typed_all(&e.values)?,
596 })
597 })
598 .transpose()?;
599 }
600 ExactValue::List(values) => {
601 property.kind = "list".to_owned();
602 property.value = Tagged::List(typed_all(values)?);
603 }
604 ExactValue::Bounded(bounded) => {
605 property.kind = "bounded".to_owned();
606 let bound = |value: &Option<ExactTypedValue>| {
607 value.as_ref().map_or(Ok(Tagged::Null), typed)
608 };
609 property.bounds = Some(Bounds {
610 lower: bound(&bounded.lower)?,
611 upper: bound(&bounded.upper)?,
612 set_point: bound(&bounded.set_point)?,
613 });
614 }
615 ExactValue::Table(table) => {
616 property.kind = "table".to_owned();
617 property.table = Some(Table {
618 rows: table
619 .rows
620 .iter()
621 .map(|row| Ok((typed(&row.defining)?, typed(&row.defined)?)))
622 .collect::<Result<_, BindingError>>()?,
623 expression: table.expression.as_deref().map(str::to_owned),
624 defining_unit: table.defining_unit.map(|EntityId(id)| id),
625 defined_unit: table.defined_unit.map(|EntityId(id)| id),
626 interpolation: table.interpolation.as_deref().map(str::to_owned),
627 });
628 }
629 ExactValue::Reference(reference) => {
630 property.kind = "reference".to_owned();
631 property.usage = reference.usage_name.as_deref().map(str::to_owned);
632 property.value = reference
633 .target
634 .as_ref()
635 .map_or(Tagged::Null, |target| Tagged::Ref(target.id.0));
636 }
637 ExactValue::Complex(complex) => {
638 property.kind = "complex".to_owned();
639 property.usage = complex.usage.as_deref().map(str::to_owned);
640 property.discrimination = complex.discrimination.as_deref().map(str::to_owned);
641 property.quality = complex.quality.as_deref().map(str::to_owned);
642 property.members = complex
643 .members
644 .iter()
645 .map(|m: &ExactComplexMember| {
646 member(
647 model,
648 &m.name,
649 m.id.0,
650 m.value_type.as_deref(),
651 m.unit_id.map(|EntityId(id)| id),
652 &m.value,
653 )
654 })
655 .collect::<Result<_, _>>()?;
656 }
657 scalar => {
658 let payload = scalar_value(scalar)?;
659 property.value = match (value_type, payload) {
660 (_, payload @ (Tagged::Null | Tagged::Enum(_) | Tagged::Ref(_))) => payload,
664 (Some(value_type), payload) => Tagged::Typed {
665 type_name: value_type.to_owned(),
666 value: Box::new(payload),
667 },
668 (None, payload) => payload,
669 };
670 }
671 }
672 Ok(property)
673 }
674
675 fn typed(value: &ExactTypedValue) -> Result<Tagged, BindingError> {
679 Ok(Tagged::Typed {
680 type_name: value.value_type.to_string(),
681 value: Box::new(scalar_value(&value.value)?),
682 })
683 }
684
685 fn typed_all(values: &[ExactTypedValue]) -> Result<Vec<Tagged>, BindingError> {
686 values.iter().map(typed).collect()
687 }
688
689 fn scalar_value(value: &ExactValue) -> Result<Tagged, BindingError> {
691 Ok(match value {
692 ExactValue::Null => Tagged::Null,
693 ExactValue::Bool(value) => Tagged::Bool(*value),
694 ExactValue::Logical(ExactLogical::True) => Tagged::Bool(true),
695 ExactValue::Logical(ExactLogical::False) => Tagged::Bool(false),
696 ExactValue::Logical(ExactLogical::Unknown) => Tagged::Unknown,
697 ExactValue::Binary(digits) => Tagged::Binary(digits.to_string()),
698 ExactValue::Integer(value) => Tagged::Integer(*value),
699 ExactValue::Real(value) => Tagged::Real(*value),
700 ExactValue::Text(text) => Tagged::Text(text.to_string()),
701 ExactValue::Enum(token) => Tagged::Enum(token.to_string()),
702 ExactValue::Entity(entity) => Tagged::Ref(entity.id.0),
703 other => {
704 return Err(BindingError::Unsupported(format!(
705 "a property value form this binding does not carry: {other:?}"
706 )))
707 }
708 })
709 }
710
711 pub(crate) fn property_error(error: ExactPropertyError) -> BindingError {
712 use ExactPropertyError as E;
713 let detail = error.to_string();
714 match error {
715 E::MissingSchema => BindingError::UnsupportedSchema(String::new()),
716 E::UnsupportedSchema { schema } => BindingError::UnsupportedSchema(schema),
717 E::MultipleSchemas { .. } => BindingError::UnsupportedSchema(detail),
718 E::MissingReference { .. } => BindingError::MissingReference(detail),
719 E::InvalidQueryObject { .. } => BindingError::WrongEntityType(detail),
720 E::ComplexCycle { .. } | E::ComplexTooDeep { .. } | E::ComplexBudgetExceeded { .. } => {
721 BindingError::BudgetExceeded(detail)
722 }
723 E::UnsupportedDefinition { .. }
724 | E::UnsupportedProperty { .. }
725 | E::UnsupportedRelationship { .. }
726 | E::UnsupportedUnit { .. } => BindingError::Unsupported(detail),
727 _ => BindingError::InvalidModel(detail),
728 }
729 }
730
731 pub(crate) fn unit_error(error: ExactUnitError) -> BindingError {
732 use ExactUnitError as E;
733 let detail = error.to_string();
734 match error {
735 E::Structure(error) => property_error(error),
736 E::MeasureNotInSchema { .. } | E::NotAMeasure { .. } => {
737 BindingError::InvalidValue(detail)
738 }
739 E::UnmappedMeasureType { .. }
740 | E::UnsupportedUnit { .. }
741 | E::UnsupportedOffset { .. } => BindingError::Unsupported(detail),
742 E::CyclicConversion { .. } | E::ConversionChainTooDeep { .. } => {
743 BindingError::BudgetExceeded(detail)
744 }
745 _ => BindingError::InvalidModel(detail),
746 }
747 }
748}