1use crate::record::{Field, Record, ToRecord};
41use crate::{BindingError, IfcModel};
42
43pub mod curves;
44pub mod graph;
45
46#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct GeometryRefusal {
49 pub code: String,
55 pub entity: Option<u64>,
57 pub message: String,
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct SelectedRepresentation {
65 pub id: u64,
67 pub identifier: Option<String>,
69 pub representation_type: Option<String>,
71 pub context: Option<u64>,
73 pub context_type: Option<String>,
76 pub context_identifier: Option<String>,
78 pub target_view: Option<String>,
80}
81
82#[derive(Debug, Clone, PartialEq)]
84pub struct ProductPlacement {
85 pub id: u64,
87 pub global_id: Option<String>,
89 pub type_name: String,
91 pub transform: Option<[f64; 16]>,
93 pub representation: Option<SelectedRepresentation>,
96 pub refusal: Option<GeometryRefusal>,
99}
100
101#[derive(Debug, Clone, PartialEq)]
103pub struct SurfaceColour {
104 pub red: f64,
106 pub green: f64,
108 pub blue: f64,
110 pub transparency: Option<f64>,
113 pub source: String,
120 pub source_entity: u64,
126 pub surface_style: u64,
128 pub source_materials: Vec<u64>,
133}
134
135#[derive(Debug, Clone, PartialEq)]
137pub struct ProductMesh {
138 pub id: u64,
140 pub global_id: Option<String>,
142 pub type_name: String,
144 pub transform: Option<[f64; 16]>,
147 pub positions: Vec<f32>,
149 pub indices: Vec<u32>,
151 pub refusal: Option<GeometryRefusal>,
154 pub colour: Option<SurfaceColour>,
157 pub colour_refusal: Option<GeometryRefusal>,
164 pub closure: String,
168}
169
170impl IfcModel {
171 pub fn product_placements(
179 &self,
180 products: Option<&[u64]>,
181 ) -> Result<Vec<ProductPlacement>, BindingError> {
182 #[cfg(feature = "placements")]
183 {
184 placements(self, products)
185 }
186 #[cfg(not(feature = "placements"))]
187 {
188 let _ = products;
189 Err(BindingError::FeatureDisabled("placements"))
190 }
191 }
192
193 pub fn product_meshes(
199 &self,
200 products: Option<&[u64]>,
201 ) -> Result<Vec<ProductMesh>, BindingError> {
202 self.product_meshes_for(products, "Body")
203 }
204
205 pub fn product_meshes_for(
215 &self,
216 products: Option<&[u64]>,
217 representation: &str,
218 ) -> Result<Vec<ProductMesh>, BindingError> {
219 #[cfg(feature = "mesh")]
220 {
221 meshes(self, products, purpose(representation)?)
222 }
223 #[cfg(not(feature = "mesh"))]
224 {
225 let _ = (products, representation);
226 Err(BindingError::FeatureDisabled("mesh"))
227 }
228 }
229}
230
231#[cfg(feature = "mesh")]
233fn purpose(name: &str) -> Result<ifc::RepresentationPurpose, BindingError> {
234 ifc::RepresentationPurpose::from_name(name).ok_or_else(|| {
235 BindingError::InvalidValue(format!(
236 "representation must be Body, Plan, Axis, FootPrint, Annotation, Surface or Reference, \
237 not {name:?}"
238 ))
239 })
240}
241
242#[cfg(feature = "placements")]
243fn ids(products: Option<&[u64]>) -> Option<Vec<ifc::EntityId>> {
244 products.map(|ids| ids.iter().copied().map(ifc::EntityId).collect())
245}
246
247#[cfg(feature = "placements")]
249fn product_identity(model: &IfcModel, id: u64) -> Result<(Option<String>, String), BindingError> {
250 let identity = model.identity(id)?;
251 let type_name = model
252 .inner
253 .get(ifc::EntityId(id))
254 .map_or_else(String::new, |entity| entity.type_name.to_string());
255 Ok((identity.global_id, type_name))
256}
257
258#[cfg(feature = "placements")]
259fn placements(
260 model: &IfcModel,
261 products: Option<&[u64]>,
262) -> Result<Vec<ProductPlacement>, BindingError> {
263 let products = ids(products);
264 let mut out = Vec::new();
265 for placement in ifc::product_placements(&model.inner, products.as_deref()) {
266 let id = placement.product.0;
267 let (global_id, type_name) = product_identity(model, id)?;
268 let refusal = placement
269 .world
270 .as_ref()
271 .err()
272 .or(placement.body.as_ref().err())
273 .map(refusal);
274 let representation = placement.body.ok().flatten().map(|body| {
275 let context = body.context.as_ref();
276 SelectedRepresentation {
277 id: body.id.0,
278 identifier: body.identifier.clone(),
279 representation_type: body.representation_type.clone(),
280 context: context.map(|c| c.id.0),
281 context_type: context.and_then(|c| c.context_type.clone()),
282 context_identifier: context.and_then(|c| c.identifier.clone()),
283 target_view: context.and_then(|c| c.target_view.clone()),
284 }
285 });
286 out.push(ProductPlacement {
287 id,
288 global_id,
289 type_name,
290 transform: placement.world.ok().map(|world| ifc::column_major(&world)),
291 representation,
292 refusal,
293 });
294 }
295 Ok(out)
296}
297
298#[cfg(feature = "mesh")]
299fn meshes(
300 model: &IfcModel,
301 products: Option<&[u64]>,
302 purpose: ifc::RepresentationPurpose,
303) -> Result<Vec<ProductMesh>, BindingError> {
304 let products = ids(products);
305 let mut out = Vec::new();
306 for (product, mesh) in ifc::product_meshes_for(&model.inner, products.as_deref(), purpose) {
307 let (global_id, type_name) = product_identity(model, product.0)?;
308 let mut record = ProductMesh {
309 id: product.0,
310 global_id,
311 type_name,
312 transform: None,
313 positions: Vec::new(),
314 indices: Vec::new(),
315 refusal: None,
316 colour: None,
317 colour_refusal: None,
318 closure: "unknown".to_owned(),
319 };
320 match mesh {
321 Ok(mesh) => {
322 record.transform = Some(ifc::column_major(&mesh.world));
323 record.positions = mesh.positions;
324 record.indices = mesh.indices;
325 record.closure = closure(mesh.closure).to_owned();
326 match mesh.colour {
327 Ok(colour) => record.colour = colour.as_ref().map(surface_colour),
328 Err(error) => record.colour_refusal = Some(colour_refusal(&error)),
329 }
330 }
331 Err(error) => record.refusal = Some(refusal(&error)),
332 }
333 out.push(record);
334 }
335 Ok(out)
336}
337
338#[cfg(feature = "placements")]
340fn refusal(error: &ifc::geometry::GeometryError) -> GeometryRefusal {
341 use ifc::geometry::GeometryError as E;
342 let code = match error {
343 E::MissingEntity { .. } => "missing-reference",
344 E::CyclicChain { .. } | E::ChainTooDeep { .. } | E::AggregateTooLarge { .. } => {
345 "budget-exceeded"
346 }
347 E::Unsupported { .. } => "unsupported",
348 #[cfg(feature = "mesh")]
349 E::CompilationRefused { .. } => "unsupported",
350 E::OpeningNotSubtracted { cause, .. } => return refusal(cause),
352 E::MissingAttribute { .. }
353 | E::WrongValueKind { .. }
354 | E::WrongEntityType { .. }
355 | E::Degenerate { .. }
356 | E::Units(_)
357 | E::LengthUnitUndeclared { .. }
358 | E::AngleUnitUndeclared { .. }
359 | E::UnitUnreadable { .. }
360 | E::UnitsAmbiguous { .. }
361 | E::UnitRecordDamaged { .. }
362 | E::UnitsIncomplete { .. } => "invalid-model",
363 other if other.is_unsupported() => "unsupported",
366 _ => "invalid-model",
367 };
368 GeometryRefusal {
369 code: code.to_owned(),
370 entity: error.entity().map(|id| id.0),
371 message: error.to_string(),
372 }
373}
374
375#[cfg(feature = "mesh")]
377fn closure(closure: ifc::geometry::compile::MeshClosure) -> &'static str {
378 use ifc::geometry::compile::MeshClosure as C;
379 match closure {
380 C::Solid => "solid",
381 C::Surface => "surface",
382 _ => "unknown",
384 }
385}
386
387#[cfg(feature = "mesh")]
389fn surface_colour(colour: &ifc::SurfaceColour) -> SurfaceColour {
390 use ifc::ColourSource as S;
391 let mut materials = Vec::new();
392 let (source, entity) = match &colour.source {
393 S::StyledItem(id) => ("item", *id),
394 S::PresentationLayer(id) => ("layer", *id),
395 S::Material { material, .. } => ("material", *material),
396 S::MaterialSet {
397 definition,
398 materials: set,
399 } => {
400 materials = set.iter().map(|id| id.0).collect();
401 ("materialSet", *definition)
402 }
403 _ => ("other", colour.surface_style),
405 };
406 let [red, green, blue] = colour.rgb;
407 SurfaceColour {
408 red,
409 green,
410 blue,
411 transparency: colour.transparency,
412 source: source.to_owned(),
413 source_entity: entity.0,
414 source_materials: materials,
415 surface_style: colour.surface_style.0,
416 }
417}
418
419#[cfg(feature = "mesh")]
421fn colour_refusal(error: &ifc::ColourError) -> GeometryRefusal {
422 use ifc::material::MaterialError as M;
423 use ifc::style::StyleError as S;
424 use ifc::ColourError as E;
425 let (code, entity) = match error {
426 E::Geometry(error) => return refusal(error),
427 E::AmbiguousMaterial { item, .. } => ("ambiguous", Some(*item)),
428 E::ItemsDiffer { product, .. } => ("ambiguous", Some(*product)),
429 E::DecidersDiffer { product, .. } => ("ambiguous", Some(*product)),
430 E::UnsupportedSchema { .. } => ("unsupported", None),
431 E::Style(S::AmbiguousStyleAssignment { item, .. }) => ("ambiguous", Some(*item)),
432 E::Style(S::AmbiguousSurfaceColour { owner, .. }) => ("ambiguous", Some(*owner)),
433 E::Style(S::UnknownEntity { id }) => ("missing-reference", Some(*id)),
434 E::Style(S::DanglingReference { source_id, .. }) => ("missing-reference", Some(*source_id)),
435 E::Style(S::UnsupportedSchema { .. }) => ("unsupported", None),
436 E::Material(M::AmbiguousAssignment { object, .. } | M::AmbiguousType { object, .. }) => {
437 ("ambiguous", Some(*object))
438 }
439 E::Material(M::UnsupportedSchema { .. }) => ("unsupported", None),
440 E::Material(M::UnknownEntity { id }) => ("missing-reference", Some(*id)),
441 _ => ("invalid-model", None),
442 };
443 GeometryRefusal {
444 code: code.to_owned(),
445 entity: entity.map(|id| id.0),
446 message: error.to_string(),
447 }
448}
449
450fn matrix(transform: Option<&[f64; 16]>) -> Field {
452 Field::optional(transform, |m| {
453 Field::List(m.iter().copied().map(Field::Real).collect())
454 })
455}
456
457impl ToRecord for GeometryRefusal {
458 fn to_record(&self) -> Record {
459 Record::new(
460 "GeometryRefusal",
461 vec![
462 ("code", Field::Text(self.code.clone())),
463 ("entity", Field::id(self.entity)),
464 ("message", Field::Text(self.message.clone())),
465 ],
466 )
467 }
468}
469
470impl ToRecord for SelectedRepresentation {
471 fn to_record(&self) -> Record {
472 Record::new(
473 "SelectedRepresentation",
474 vec![
475 ("id", Field::Id(self.id)),
476 ("identifier", Field::text(self.identifier.clone())),
477 (
478 "representation_type",
479 Field::text(self.representation_type.clone()),
480 ),
481 ("context", Field::id(self.context)),
482 ("context_type", Field::text(self.context_type.clone())),
483 (
484 "context_identifier",
485 Field::text(self.context_identifier.clone()),
486 ),
487 ("target_view", Field::text(self.target_view.clone())),
488 ],
489 )
490 }
491}
492
493impl ToRecord for ProductPlacement {
494 fn to_record(&self) -> Record {
495 Record::new(
496 "ProductPlacement",
497 vec![
498 ("id", Field::Id(self.id)),
499 ("global_id", Field::text(self.global_id.clone())),
500 ("type_name", Field::Text(self.type_name.clone())),
501 ("transform", matrix(self.transform.as_ref())),
502 (
503 "representation",
504 Field::record(self.representation.as_ref()),
505 ),
506 ("refusal", Field::record(self.refusal.as_ref())),
507 ],
508 )
509 }
510}
511
512impl ToRecord for ProductMesh {
516 fn to_record(&self) -> Record {
517 Record::new(
518 "ProductMesh",
519 vec![
520 ("id", Field::Id(self.id)),
521 ("global_id", Field::text(self.global_id.clone())),
522 ("type_name", Field::Text(self.type_name.clone())),
523 ("transform", matrix(self.transform.as_ref())),
524 ("vertex_count", Field::Count(self.positions.len() / 3)),
525 ("triangle_count", Field::Count(self.indices.len() / 3)),
526 ("refusal", Field::record(self.refusal.as_ref())),
527 ("colour", Field::record(self.colour.as_ref())),
528 (
529 "colour_refusal",
530 Field::record(self.colour_refusal.as_ref()),
531 ),
532 ("closure", Field::Text(self.closure.clone())),
533 ],
534 )
535 }
536}
537
538impl ToRecord for SurfaceColour {
539 fn to_record(&self) -> Record {
540 Record::new(
541 "SurfaceColour",
542 vec![
543 ("red", Field::Real(self.red)),
544 ("green", Field::Real(self.green)),
545 ("blue", Field::Real(self.blue)),
546 (
547 "transparency",
548 Field::optional(self.transparency.as_ref(), |t| Field::Real(*t)),
549 ),
550 ("source", Field::Text(self.source.clone())),
551 ("source_entity", Field::Id(self.source_entity)),
552 ("surface_style", Field::Id(self.surface_style)),
553 (
554 "source_materials",
555 Field::List(
556 self.source_materials
557 .iter()
558 .map(|&id| Field::Id(id))
559 .collect(),
560 ),
561 ),
562 ],
563 )
564 }
565}