Debian Codegraph @

src/Mod/BIM/importers/importIFCHelper.py

raw symbols SCIP
1 # SPDX-License-Identifier: LGPL-2.1-or-later
2
3 # ***************************************************************************
4 # * *
5 # * Copyright (c) 2019 Yorik van Havre <[email protected]> *
6 # * *
7 # * This file is part of FreeCAD. *
8 # * *
9 # * FreeCAD is free software: you can redistribute it and/or modify it *
10 # * under the terms of the GNU Lesser General Public License as *
11 # * published by the Free Software Foundation, either version 2.1 of the *
12 # * License, or (at your option) any later version. *
13 # * *
14 # * FreeCAD is distributed in the hope that it will be useful, but *
15 # * WITHOUT ANY WARRANTY; without even the implied warranty of *
16 # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
17 # * Lesser General Public License for more details. *
18 # * *
19 # * You should have received a copy of the GNU Lesser General Public *
20 # * License along with FreeCAD. If not, see *
21 # * <https://www.gnu.org/licenses/>. *
22 # * *
23 # ***************************************************************************
24
25 """Helper functions that are used by IFC importer and exporter."""
26 import math
27
28 import FreeCAD
29 import Arch
30 import ArchIFC
31
32 from draftutils import params
33 from draftutils.messages import _msg, _wrn
34
35 if FreeCAD.GuiUp:
36 import FreeCADGui as Gui
37
38
39 PREDEFINED_RGB = {
40 "black": (0, 0, 0),
41 "red": (1.0, 0, 0),
42 "green": (0, 1.0, 0),
43 "blue": (0, 0, 1.0),
44 "yellow": (1.0, 1.0, 0),
45 "magenta": (1.0, 0, 1.0),
46 "cyan": (0, 1.0, 1.0),
47 "white": (1.0, 1.0, 1.0),
48 }
49
50
51 DEBUG_prod_repr = False
52 DEBUG_prod_colors = False
53
54
55 def dd2dms(dd):
56 """Convert decimal degrees to degrees, minutes, seconds.
57
58 Used in export.
59 """
60 sign = 1 if dd >= 0 else -1
61 dd = abs(dd)
62 minutes, seconds = divmod(dd * 3600, 60)
63 degrees, minutes = divmod(minutes, 60)
64
65 if dd < 0:
66 degrees = -degrees
67
68 return (int(degrees) * sign, int(minutes) * sign, int(seconds) * sign)
69
70
71 def dms2dd(degrees, minutes, seconds, milliseconds=0):
72 """Convert degrees, minutes, seconds to decimal degrees.
73
74 Used in import.
75 """
76 dd = float(degrees) + float(minutes) / 60 + float(seconds) / 3600
77 return dd
78
79
80 def getPreferences():
81 """Retrieve the IFC preferences available in import and export.
82
83 MERGE_MODE_ARCH:
84 0 = parametric BIM objects
85 1 = non-parametric BIM objects
86 2 = Part shapes
87 3 = One compound per storey
88 """
89 preferences = {
90 "DEBUG": params.get_param_arch("ifcDebug"),
91 "PREFIX_NUMBERS": params.get_param_arch("ifcPrefixNumbers"),
92 "SKIP": params.get_param_arch("ifcSkip").split(","),
93 "SEPARATE_OPENINGS": params.get_param_arch("ifcSeparateOpenings"),
94 "ROOT_ELEMENT": params.get_param_arch("ifcRootElement"),
95 "GET_EXTRUSIONS": params.get_param_arch("ifcGetExtrusions"),
96 "MERGE_MATERIALS": params.get_param_arch("ifcMergeMaterials"),
97 "MERGE_MODE_ARCH": params.get_param_arch("ifcImportModeArch"),
98 "MERGE_MODE_STRUCT": params.get_param_arch("ifcImportModeStruct"),
99 "CREATE_CLONES": params.get_param_arch("ifcCreateClones"),
100 "IMPORT_PROPERTIES": params.get_param_arch("ifcImportProperties"),
101 "SPLIT_LAYERS": params.get_param_arch(
102 "ifcSplitLayers"
103 ), # wall layer, not layer for visual props
104 "FITVIEW_ONIMPORT": params.get_param_arch("ifcFitViewOnImport"),
105 "ALLOW_INVALID": params.get_param_arch("ifcAllowInvalid"),
106 "REPLACE_PROJECT": params.get_param_arch("ifcReplaceProject"),
107 "MULTICORE": params.get_param_arch("ifcMulticore"),
108 "IMPORT_LAYER": params.get_param_arch("ifcImportLayer"),
109 }
110
111 if preferences["MERGE_MODE_ARCH"] > 0:
112 preferences["SEPARATE_OPENINGS"] = False
113 preferences["GET_EXTRUSIONS"] = False
114 if not preferences["SEPARATE_OPENINGS"]:
115 preferences["SKIP"].append("IfcOpeningElement")
116
117 return preferences
118
119
120 class ProjectImporter:
121 """A helper class to create an Arch Project object."""
122
123 def __init__(self, file, objects):
124 self.file = file
125 self.objects = objects
126
127 def execute(self):
128 self.project = self.file.by_type("IfcProject")[0]
129 self.object = Arch.makeProject()
130 self.objects[self.project.id()] = self.object
131 self.setAttributes()
132 self.setComplexAttributes()
133
134 def setAttributes(self):
135 for prop in self.object.PropertiesList:
136 if hasattr(self.project, prop) and getattr(self.project, prop):
137 setattr(self.object, prop, getattr(self.project, prop))
138
139 def setComplexAttributes(self):
140 try:
141 mapConversion = self.project.RepresentationContexts[0].HasCoordinateOperation[0]
142
143 data = self.extractTargetCRSData(mapConversion.TargetCRS)
144 data.update(self.extractMapConversionData(mapConversion))
145 # TODO: review and refactor this piece of code.
146 # Calling a method from a class is a bit strange;
147 # this class should be derived from that class to inherit
148 # this method; otherwise a simple function (not tied to a class)
149 # should be used.
150 ArchIFC.IfcRoot.setObjIfcComplexAttributeValue(
151 self, self.object, "RepresentationContexts", data
152 )
153 except Exception:
154 # This scenario occurs validly in IFC2X3,
155 # as the mapConversion does not exist
156 return
157
158 def extractTargetCRSData(self, targetCRS):
159 mappings = {
160 "name": "Name",
161 "description": "Description",
162 "geodetic_datum": "GeodeticDatum",
163 "vertical_datum": "VerticalDatum",
164 "map_projection": "MapProjection",
165 "map_zone": "MapZone",
166 }
167 data = {}
168 for attributeName, ifcName in mappings.items():
169 data[attributeName] = str(getattr(targetCRS, ifcName))
170
171 if targetCRS.MapUnit.Prefix:
172 data["map_unit"] = targetCRS.MapUnit.Prefix.title() + targetCRS.MapUnit.Name.lower()
173 else:
174 data["map_unit"] = targetCRS.MapUnit.Name.title()
175
176 return data
177
178 def extractMapConversionData(self, mapConversion):
179 mappings = {
180 "eastings": "Eastings",
181 "northings": "Northings",
182 "orthogonal_height": "OrthogonalHeight",
183 "x_axis_abscissa": "XAxisAbscissa",
184 "x_axis_ordinate": "XAxisOrdinate",
185 "scale": "Scale",
186 }
187 data = {}
188 for attributeName, ifcName in mappings.items():
189 data[attributeName] = str(getattr(mapConversion, ifcName))
190
191 data["true_north"] = str(
192 self.calculateTrueNorthAngle(mapConversion.XAxisAbscissa, mapConversion.XAxisOrdinate)
193 )
194 return data
195
196 def calculateTrueNorthAngle(self, x, y):
197 return round(math.degrees(math.atan2(y, x)) - 90, 6)
198
199
200 def buildRelProductsAnnotations(ifcfile, root_element="IfcProduct"):
201 """Build the products and annotations relation table."""
202 products = ifcfile.by_type(root_element)
203
204 annotations = ifcfile.by_type("IfcAnnotation")
205 tp = []
206 for product in products:
207 if product.is_a("IfcGrid") and (product not in annotations):
208 annotations.append(product)
209 elif product not in annotations:
210 tp.append(product)
211
212 # remove any leftover annotations from products
213 products = sorted(tp, key=lambda prod: prod.id())
214
215 return products, annotations
216
217
218 def buildRelProductRepresentation(ifcfile):
219 """Build the product/representations relation table."""
220 if DEBUG_prod_repr:
221 _msg(32 * "-")
222 _msg("Product-representation table")
223
224 prodrepr = dict()
225
226 i = 1
227 for p in ifcfile.by_type("IfcProduct"):
228 if hasattr(p, "Representation") and p.Representation:
229 if DEBUG_prod_repr:
230 _msg("{}: {}, {}, '{}'".format(i, p.id(), p.is_a(), p.Name))
231
232 for it in p.Representation.Representations:
233 for it1 in it.Items:
234 prodrepr.setdefault(p.id(), []).append(it1.id())
235 if it1.is_a("IfcBooleanResult"):
236 prodrepr.setdefault(p.id(), []).append(it1.FirstOperand.id())
237 elif it.Items[0].is_a("IfcMappedItem"):
238 prodrepr.setdefault(p.id(), []).append(
239 it1.MappingSource.MappedRepresentation.id()
240 )
241 if it1.MappingSource.MappedRepresentation.is_a("IfcShapeRepresentation"):
242 for it2 in it1.MappingSource.MappedRepresentation.Items:
243 prodrepr.setdefault(p.id(), []).append(it2.id())
244 i += 1
245 return prodrepr
246
247
248 def buildRelAdditions(ifcfile):
249 """Build the additions relation table."""
250 additions = {} # { host:[child,...], ... }
251
252 for r in ifcfile.by_type("IfcRelContainedInSpatialStructure"):
253 additions.setdefault(r.RelatingStructure.id(), []).extend(
254 [e.id() for e in r.RelatedElements]
255 )
256 for r in ifcfile.by_type("IfcRelAggregates"):
257 additions.setdefault(r.RelatingObject.id(), []).extend([e.id() for e in r.RelatedObjects])
258
259 return additions
260
261
262 def buildRelGroups(ifcfile):
263 """Build the groups relation table."""
264 groups = {} # { host:[child,...], ... } # used in structural IFC
265
266 for r in ifcfile.by_type("IfcRelAssignsToGroup"):
267 groups.setdefault(r.RelatingGroup.id(), []).extend([e.id() for e in r.RelatedObjects])
268
269 return groups
270
271
272 def buildRelSubtractions(ifcfile):
273 """Build the subtractions relation table."""
274 subtractions = [] # [ [opening,host], ... ]
275
276 for r in ifcfile.by_type("IfcRelVoidsElement"):
277 subtractions.append([r.RelatedOpeningElement.id(), r.RelatingBuildingElement.id()])
278
279 return subtractions
280
281
282 def buildRelMattable(ifcfile):
283 """Build the mattable relation table."""
284 mattable = {} # { objid:matid }
285
286 for r in ifcfile.by_type("IfcRelAssociatesMaterial"):
287 # the related object might not exist
288 # https://forum.freecad.org/viewtopic.php?f=39&t=58607
289 if r.RelatedObjects:
290 for o in r.RelatedObjects:
291 if r.RelatingMaterial.is_a("IfcMaterial"):
292 mattable[o.id()] = r.RelatingMaterial.id()
293 elif r.RelatingMaterial.is_a("IfcMaterialLayer"):
294 mattable[o.id()] = r.RelatingMaterial.Material.id()
295 elif r.RelatingMaterial.is_a("IfcMaterialLayerSet"):
296 mattable[o.id()] = r.RelatingMaterial.MaterialLayers[0].Material.id()
297 elif r.RelatingMaterial.is_a("IfcMaterialLayerSetUsage"):
298 mattable[o.id()] = r.RelatingMaterial.ForLayerSet.MaterialLayers[
299 0
300 ].Material.id()
301
302 return mattable
303
304
305 # Color relation tables.
306 # Products can have a color, materials can have a color,
307 # and products can have a material.
308 # Colors for material assigned to a product, and color of the product itself
309 # can be different
310 def buildRelColors(ifcfile, prodrepr):
311 """Build the colors relation table.
312
313 Returns all IfcStyledItem colors, material and product colors.
314
315 Returns
316 -------
317 dict
318 A dictionary with `{id: (r,g,b), ...}` values.
319 """
320 colors = {} # { id:(r,g,b) }
321 style_material_id = {} # { style_entity_id: material_id) }
322
323 style_color_rgb = {} # { style_entity_id: (r,g,b) }
324 for r in ifcfile.by_type("IfcStyledItem"):
325 if r.Styles and r.Styles[0].is_a("IfcPresentationStyleAssignment"):
326 for style1 in r.Styles[0].Styles:
327 if style1.is_a("IfcSurfaceStyle"):
328 for style2 in style1.Styles:
329 if style2.is_a("IfcSurfaceStyleRendering"):
330 if style2.SurfaceColour:
331 c = style2.SurfaceColour
332 style_color_rgb[r.id()] = (c.Red, c.Green, c.Blue)
333
334 # Nova
335 # FIXME: style_entity_id = { style_entity_id: product_id } not material_id ???
336 # see https://forum.freecad.org/viewtopic.php?f=39&t=37940&start=10#p329491
337 # last code change in these color code https://github.com/FreeCAD/FreeCAD/commit/2d1f6ab1
338 """
339 if r.Item:
340 # print(r.id())
341 # print(r.Item) # IfcRepresentationItem or IfcShapeRepresentation
342 for p in prodrepr.keys():
343 if r.Item.id() in prodrepr[p]:
344 style_material_id[r.id()] = p
345 # print(p)
346 # print(ifcfile[p]) # product
347 """
348
349 # A much faster version for Nova style_material_id with product_ids
350 # no material colors, Nova ifc files often do not have materials at all
351 for p in prodrepr.keys():
352 # print("\n")
353 # print(ifcfile[p]) # IfcProduct
354 # print(ifcfile[p].Representation) # IfcProductDefinitionShape
355 # print(ifcfile[p].Representation.Representations[0]) # IfcShapeRepresentation
356 # print(ifcfile[p].Representation.Representations[0].Items[0]) # IfcRepresentationItem
357 # print(ifcfile[p].Representation.Representations[0].Items[0].StyledByItem[0]) # IfcStyledItem
358 # print(ifcfile[p].Representation.Representations[0].Items[0].StyledByItem[0].id())
359 # print(p)
360 representation_item = ifcfile[p].Representation.Representations[0].Items[0]
361 if hasattr(representation_item, "StyledByItem") and representation_item.StyledByItem:
362 style_material_id[representation_item.StyledByItem[0].id()] = p
363
364 # Allplan, ArchiCAD
365 for m in ifcfile.by_type("IfcMaterialDefinitionRepresentation"):
366 for it in m.Representations:
367 if it.Items:
368 style_material_id[it.Items[0].id()] = m.RepresentedMaterial.id()
369
370 # create colors out of style_color_rgb and style_material_id
371 for k in style_material_id:
372 if k in style_color_rgb:
373 colors[style_material_id[k]] = style_color_rgb[k]
374
375 return colors
376
377
378 def buildRelProductColors(ifcfile, prodrepr):
379 """Build the colors relation table from a product.
380
381 Returns
382 -------
383 dict
384 A dictionary with `{id: (r,g,b), ...}` values.
385 """
386 if DEBUG_prod_repr:
387 _msg(32 * "-")
388 _msg("Product-color table")
389
390 colors = dict()
391 i = 0
392
393 for p in prodrepr.keys():
394 # see method getColorFromProduct()
395 # it is a method for the redundant code inside this loop
396 # which can be used to get the color from a product directly
397
398 # Representation item, see `IfcRepresentationItem` documentation.
399 # All kinds of geometric or topological representation items
400 # `IfcExtrudedAreaSolid`, `IfcMappedItem`, `IfcFacetedBrep`,
401 # `IfcBooleanResult`, `IfcBooleanClippingResult`, etc.
402 _body = ifcfile[p].Representation.Representations[0]
403 repr_item = _body.Items[0]
404
405 if DEBUG_prod_colors:
406 _msg(
407 "{}: {}, {}, '{}', rep_item {}".format(
408 i, ifcfile[p].id(), ifcfile[p].is_a(), ifcfile[p].Name, repr_item
409 )
410 )
411 # Get the geometric representations which have a presentation style.
412 # All representation items have the inverse attribute `StyledByItem`
413 # for this.
414 # There will be geometric representations which do not have
415 # a presentation style so `StyledByItem` will be empty.
416 if repr_item.StyledByItem:
417 if DEBUG_prod_colors:
418 _msg(" StyledByItem -> {}".format(repr_item.StyledByItem))
419 # it has to be a `IfcStyledItem`, no check needed
420 styled_item = repr_item.StyledByItem[0]
421
422 # Write into colors table if a `IfcStyledItem` exists
423 # for this product, write `None` if something goes wrong
424 # or if the ifc file has errors and thus no valid color
425 # is returned
426 colors[p] = getColorFromStyledItem(styled_item)
427
428 i += 1
429 return colors
430
431
432 def buildRelMaterialColors(ifcfile, prodrepr):
433 # not implemented
434 pass
435
436
437 def getColorFromProduct(product):
438
439 if product.Representation:
440 for rep in product.Representation.Representations:
441 for item in rep.Items:
442 for style in item.StyledByItem:
443 color = getColorFromStyledItem(style)
444 if color:
445 return color
446
447
448 def getColorFromMaterial(material):
449
450 if material.HasRepresentation:
451 rep = material.HasRepresentation[0]
452 if hasattr(rep, "Representations") and rep.Representations:
453 rep = rep.Representations[0]
454 if rep.is_a("IfcStyledRepresentation"):
455 return getColorFromStyledItem(rep)
456 return None
457
458
459 def color2colorRGB(color_data):
460
461 if color_data is None:
462 return None
463
464 color_rgb = [
465 int(round(color_data[0] * 255, 0)),
466 int(round(color_data[1] * 255, 0)),
467 int(round(color_data[2] * 255, 0)),
468 ] # int(159.99) would return 159 not 160, thus round
469
470 return color_rgb
471
472
473 def getColorFromStyledItem(styled_item):
474 """Get color from the IfcStyledItem.
475
476 Returns
477 -------
478 float, float, float, int
479 A tuple with the red, green, blue, and transparency values.
480 If the `IfcStyledItem` is a `IfcDraughtingPreDefinedColour`
481 the transparency is set to 0.
482 The first three values range from 0 to 1.0, while the transparency
483 varies from 0 to 100.
484
485 None
486 Return `None` if `styled_item` is not of type `'IfcStyledItem'`
487 or if there is any other problem getting a color.
488 """
489
490 if styled_item.is_a("IfcStyledRepresentation"):
491 styled_item = styled_item.Items[0]
492
493 if not styled_item.is_a("IfcStyledItem"):
494 return None
495
496 rgb_color = None
497 transparency = None
498 col = None
499
500 # The `IfcStyledItem` holds presentation style information for products,
501 # either explicitly for an `IfcGeometricRepresentationItem` being part of
502 # an `IfcShapeRepresentation` assigned to a product, or by assigning
503 # presentation information to `IfcMaterial` being assigned
504 # as other representation for a product.
505
506 # In current IFC release (IFC2x3) only one presentation style
507 # assignment shall be assigned.
508 # In IFC4 `IfcPresentationStyleAssignment` is deprecated
509 # In IFC4 multiple styles are assigned to style in 'IfcStyleItem' instead
510
511 # print(ifcfile[p])
512 # print(styled_item)
513 # print(styled_item.Styles)
514 if len(styled_item.Styles) == 0:
515 # IN IFC2x3, only one element in `Styles` should be available.
516 _wrn("No 'Style' in 'IfcStyleItem', do nothing.")
517 # ca 100x in 210_King_Merged.ifc
518 # Empty styles, #4952778=IfcStyledItem(#4952779,(),$)
519 # this is an error in the IFC file in my opinion
520 else:
521 # never seen an ifc with more than one Styles in IfcStyledItem
522 # the above seems to only apply for IFC2x3, IFC4 can have them
523 # see https://forum.freecad.org/viewtopic.php?f=39&t=33560&p=437056#p437056
524
525 # Get the `IfcPresentationStyleAssignment`, there should only be one,
526 if styled_item.Styles[0].is_a("IfcPresentationStyleAssignment"):
527 assign_style = styled_item.Styles[0]
528 else:
529 # `IfcPresentationStyleAssignment` is deprecated in IFC4,
530 # in favor of `IfcStyleAssignmentSelect`
531 assign_style = styled_item
532 # print(assign_style) # IfcPresentationStyleAssignment
533
534 # `IfcPresentationStyleAssignment` can hold various kinds and counts
535 # of styles, see `IfcPresentationStyleSelect`
536 if assign_style.Styles[0].is_a("IfcSurfaceStyle"):
537 _style = assign_style.Styles[0]
538 # Schependomlaan and Nova and others
539 # `IfcSurfaceStyleRendering`
540 # print(_style.Styles[0])
541 # `IfcColourRgb`
542 rgb_color = _style.Styles[0].SurfaceColour
543 # print(rgb_color)
544 if (
545 _style.Styles[0].is_a("IfcSurfaceStyleShading")
546 and hasattr(_style.Styles[0], "Transparency")
547 and _style.Styles[0].Transparency
548 ):
549 transparency = _style.Styles[0].Transparency * 100
550 elif assign_style.Styles[0].is_a("IfcCurveStyle"):
551 if len(assign_style.Styles) == 2 and assign_style.Styles[1].is_a("IfcSurfaceStyle"):
552 # Allplan, new IFC export started in 2017
553 # `IfcDraughtingPreDefinedColour`
554 # print(assign_style.Styles[0].CurveColour)
555 # TODO: check this; on index 1, is this what we need?!
556 rgb_color = assign_style.Styles[1].Styles[0].SurfaceColour
557 # print(rgb_color)
558 else:
559 # 2x Annotations in 210_King_Merged.ifc
560 # print(ifcfile[p])
561 # print(assign_style.Styles[0])
562 # print(assign_style.Styles[0].CurveColour)
563 rgb_color = assign_style.Styles[0].CurveColour
564
565 if rgb_color:
566 if rgb_color.is_a("IfcDraughtingPreDefinedColour"):
567 if DEBUG_prod_colors:
568 _msg(" '{}'= ".format(rgb_color.Name))
569
570 col = predefined_to_rgb(rgb_color)
571
572 if col:
573 col = col + (0,)
574 else:
575 col = (
576 rgb_color.Red,
577 rgb_color.Green,
578 rgb_color.Blue,
579 int(transparency) if transparency else 0,
580 )
581 else:
582 col = None
583
584 if DEBUG_prod_colors:
585 _msg(" {}".format(col))
586
587 return col
588
589
590 def predefined_to_rgb(rgb_color):
591 """Transform a predefined color name to its [r, g, b] representation.
592
593 TODO: at the moment it doesn't handle 'by layer'.
594 See: `IfcDraughtingPreDefinedColour` and `IfcPresentationLayerWithStyle`.
595 """
596 name = rgb_color.Name.lower()
597 if name not in PREDEFINED_RGB:
598 _wrn("Color name not in 'IfcDraughtingPreDefinedColour'.")
599
600 if name == "by layer":
601 _wrn(
602 "'IfcDraughtingPreDefinedColour' set 'by layer'; "
603 "currently not handled, set to 'None'."
604 )
605 return None
606
607 return PREDEFINED_RGB[name]
608
609
610 # ************************************************************************************************
611 # property related methods
612
613
614 def buildRelProperties(ifcfile):
615 """
616 Builds and returns a dictionary of {object:[properties]} from an IFC file
617 """
618
619 # this method no longer used by the importer module
620 # but this relation table might be useful anyway for other purposes
621
622 properties = {} # { objid : { psetid : [propertyid, ... ], ... }, ... }
623 for r in ifcfile.by_type("IfcRelDefinesByProperties"):
624 for obj in r.RelatedObjects:
625 if not obj.id() in properties:
626 properties[obj.id()] = {}
627 psets = {}
628 props = []
629 if r.RelatingPropertyDefinition.is_a("IfcPropertySet"):
630 props.extend([prop.id() for prop in r.RelatingPropertyDefinition.HasProperties])
631 psets[r.RelatingPropertyDefinition.id()] = props
632 properties[obj.id()].update(psets)
633 return properties
634
635
636 def getIfcPropertySets(ifcfile, pid):
637 """Returns a dictionary of {pset_id:[prop_id, prop_id...]} for an IFC object"""
638
639 # get psets for this pid
640 psets = {}
641 for rel in ifcfile[pid].IsDefinedBy:
642 # the following if condition is needed in IFC2x3 only
643 # https://forum.freecad.org/viewtopic.php?f=39&t=37892#p322884
644 if rel.is_a("IfcRelDefinesByProperties"):
645 props = []
646 if rel.RelatingPropertyDefinition.is_a("IfcPropertySet"):
647 props.extend([prop.id() for prop in rel.RelatingPropertyDefinition.HasProperties])
648 psets[rel.RelatingPropertyDefinition.id()] = props
649 return psets
650
651
652 def getIfcProperties(ifcfile, pid, psets, d):
653 """builds valid property values for FreeCAD"""
654
655 for pset in psets.keys():
656 # print("reading pset: ",pset)
657 psetname = ifcfile[pset].Name
658 for prop in psets[pset]:
659 e = ifcfile[prop]
660 pname = e.Name
661 if e.is_a("IfcPropertySingleValue"):
662 if e.NominalValue:
663 ptype = e.NominalValue.is_a()
664 if ptype in ["IfcLabel", "IfcText", "IfcIdentifier", "IfcDescriptiveMeasure"]:
665 pvalue = e.NominalValue.wrappedValue
666 else:
667 pvalue = str(e.NominalValue.wrappedValue)
668 if hasattr(e.NominalValue, "Unit"):
669 if e.NominalValue.Unit:
670 pvalue += e.NominalValue.Unit
671 d[pname + ";;" + psetname] = ptype + ";;" + pvalue
672 # print("adding property: ",pname,ptype,pvalue," pset ",psetname)
673 return d
674
675
676 def getIfcPsetProperties(ifcfile, pid):
677 """directly build the property table from pid and ifcfile for FreeCAD"""
678
679 return getIfcProperties(ifcfile, pid, getIfcPropertySets(ifcfile, pid), {})
680
681
682 def getUnit(unit):
683 """Get the unit multiplier for different decimal prefixes.
684
685 Only for when the unit is METRE.
686 When no Prefix is provided, return 1000, that is, mm x 1000 = metre.
687 For other cases, return 1.0.
688 """
689 if unit.Name == "METRE":
690 if unit.Prefix == "KILO":
691 return 1000000.0
692 elif unit.Prefix == "HECTO":
693 return 100000.0
694 elif unit.Prefix == "DECA":
695 return 10000.0
696 elif not unit.Prefix:
697 return 1000.0
698 elif unit.Prefix == "DECI":
699 return 100.0
700 elif unit.Prefix == "CENTI":
701 return 10.0
702 return 1.0
703
704
705 def getScaling(ifcfile):
706 """Return a scaling factor from the IFC file; units to mm."""
707 ua = ifcfile.by_type("IfcUnitAssignment")
708
709 if not ua:
710 return 1.0
711
712 ua = ua[0]
713 for u in ua.Units:
714 if u.UnitType == "LENGTHUNIT":
715 if u.is_a("IfcConversionBasedUnit"):
716 f = getUnit(u.ConversionFactor.UnitComponent)
717 return f * u.ConversionFactor.ValueComponent.wrappedValue
718 elif u.is_a("IfcSIUnit") or u.is_a("IfcUnit"):
719 return getUnit(u)
720 return 1.0
721
722
723 def getRotation(entity):
724 """returns a FreeCAD rotation from an IfcProduct with a IfcMappedItem representation"""
725 try:
726 u = FreeCAD.Vector(entity.Axis1.DirectionRatios)
727 v = FreeCAD.Vector(entity.Axis2.DirectionRatios)
728 w = FreeCAD.Vector(entity.Axis3.DirectionRatios)
729 except AttributeError:
730 return FreeCAD.Rotation()
731 return FreeCAD.Rotation(u, v, w, "ZYX")
732
733
734 def getPlacement(entity, scaling=1000):
735 """returns a placement from the given entity"""
736
737 if not entity:
738 return None
739 import DraftVecUtils
740
741 pl = None
742 if entity.is_a("IfcAxis2Placement3D"):
743 x = getVector(entity.RefDirection, scaling)
744 z = getVector(entity.Axis, scaling)
745 if x and z:
746 y = z.cross(x)
747 m = DraftVecUtils.getPlaneRotation(x, y, z)
748 pl = FreeCAD.Placement(m)
749 else:
750 pl = FreeCAD.Placement()
751 loc = getVector(entity.Location, scaling)
752 if loc:
753 pl.move(loc)
754 elif entity.is_a("IfcAxis2Placement2D"):
755 _wrn("not implemented IfcAxis2Placement2D, ", end="")
756 elif entity.is_a("IfcLocalPlacement"):
757 pl = getPlacement(entity.PlacementRelTo, 1) # original placement
758 relpl = getPlacement(entity.RelativePlacement, 1) # relative transf
759 if pl and relpl:
760 pl = pl.multiply(relpl)
761 elif relpl:
762 pl = relpl
763 elif entity.is_a("IfcCartesianPoint"):
764 loc = getVector(entity, scaling)
765 pl = FreeCAD.Placement()
766 pl.move(loc)
767 if pl:
768 pl.Base = FreeCAD.Vector(pl.Base).multiply(scaling)
769 return pl
770
771
772 def getVector(entity, scaling=1000):
773 """returns a vector from the given entity"""
774
775 if not entity:
776 return None
777 v = None
778 if entity.is_a("IfcDirection"):
779 if len(entity.DirectionRatios) == 3:
780 v = FreeCAD.Vector(tuple(entity.DirectionRatios))
781 else:
782 v = FreeCAD.Vector(tuple(entity.DirectionRatios + [0]))
783 elif entity.is_a("IfcCartesianPoint"):
784 if len(entity.Coordinates) == 3:
785 v = FreeCAD.Vector(tuple(entity.Coordinates))
786 else:
787 v = FreeCAD.Vector(tuple(entity.Coordinates + [0]))
788 # if v:
789 # v.multiply(scaling)
790 return v
791
792
793 def get2DShape(representation, scaling=1000, notext=False):
794 """Returns a shape from a 2D IfcShapeRepresentation
795 if notext is True, no Draft text is created"""
796
797 import Part
798 import DraftVecUtils
799 import Draft
800
801 def getPolyline(ent):
802 pts = []
803 for p in ent.Points:
804 c = p.Coordinates
805 c = FreeCAD.Vector(c[0], c[1], c[2] if len(c) > 2 else 0)
806 c.multiply(scaling)
807 pts.append(c)
808 return Part.makePolygon(pts)
809
810 def getRectangle(ent):
811 return Part.makePlane(ent.XDim, ent.YDim)
812
813 def getLine(ent):
814 pts = []
815 p1 = getVector(ent.Pnt)
816 p1.multiply(scaling)
817 pts.append(p1)
818 p2 = getVector(ent.Dir)
819 p2.multiply(scaling)
820 p2 = p1.add(p2)
821 pts.append(p2)
822 return Part.makePolygon(pts)
823
824 def getCircle(ent):
825 c = ent.Position.Location.Coordinates
826 c = FreeCAD.Vector(c[0], c[1], c[2] if len(c) > 2 else 0)
827 c.multiply(scaling)
828 r = ent.Radius * scaling
829 return Part.makeCircle(r, c)
830
831 def getCurveSet(ent):
832 result = []
833 if ent.is_a() in ["IfcGeometricCurveSet", "IfcGeometricSet"]:
834 elts = ent.Elements
835 elif ent.is_a() in [
836 "IfcLine",
837 "IfcPolyline",
838 "IfcCircle",
839 "IfcTrimmedCurve",
840 "IfcRectangleProfileDef",
841 ]:
842 elts = [ent]
843 else:
844 print("getCurveSet: unhandled entity: ", ent)
845 return []
846
847 for el in elts:
848 if el.is_a("IfcPolyline"):
849 result.append(getPolyline(el))
850 elif el.is_a("IfcRectangleProfileDef"):
851 result.append(getRectangle(el))
852 elif el.is_a("IfcLine"):
853 result.append(getLine(el))
854 elif el.is_a("IfcCircle"):
855 result.append(getCircle(el))
856 elif el.is_a("IfcTrimmedCurve"):
857 base = el.BasisCurve
858 t1 = el.Trim1[0].wrappedValue
859 t2 = el.Trim2[0].wrappedValue
860 if not el.SenseAgreement:
861 t1, t2 = t2, t1
862 if base.is_a("IfcPolyline"):
863 bc = getPolyline(base)
864 result.append(bc)
865 elif base.is_a("IfcCircle"):
866 bc = getCircle(base)
867 e = Part.ArcOfCircle(bc.Curve, math.radians(t1), math.radians(t2)).toShape()
868 d = base.Position.RefDirection.DirectionRatios
869 v = FreeCAD.Vector(d[0], d[1], d[2] if len(d) > 2 else 0)
870 a = -DraftVecUtils.angle(v)
871 e.rotate(bc.Curve.Center, FreeCAD.Vector(0, 0, 1), math.degrees(a))
872 result.append(e)
873 elif el.is_a("IfcCompositeCurve"):
874 for base in el.Segments:
875 if base.ParentCurve.is_a("IfcPolyline"):
876 bc = getPolyline(base.ParentCurve)
877 result.append(bc)
878 elif base.ParentCurve.is_a("IfcCircle"):
879 bc = getCircle(base.ParentCurve)
880 e = Part.ArcOfCircle(bc.Curve, math.radians(t1), math.radians(t2)).toShape()
881 d = base.Position.RefDirection.DirectionRatios
882 v = FreeCAD.Vector(d[0], d[1], d[2] if len(d) > 2 else 0)
883 a = -DraftVecUtils.angle(v)
884 e.rotate(bc.Curve.Center, FreeCAD.Vector(0, 0, 1), math.degrees(a))
885 result.append(e)
886 elif el.is_a("IfcIndexedPolyCurve"):
887 coords = el.Points.CoordList
888
889 def index2points(segment):
890 pts = []
891 for i in segment.wrappedValue:
892 c = coords[i - 1]
893 c = FreeCAD.Vector(c[0], c[1], c[2] if len(c) > 2 else 0)
894 c.multiply(scaling)
895 pts.append(c)
896 return pts
897
898 if not el.Segments:
899 # use all points
900 verts = [FreeCAD.Vector(c[0], c[1], c[2] if len(c) > 2 else 0) for c in coords]
901 verts = [v.multiply(scaling) for v in verts]
902 result.append(Part.makePolygon(verts))
903 else:
904 for s in el.Segments:
905 if s.is_a("IfcLineIndex"):
906 result.append(Part.makePolygon(index2points(s)))
907 elif s.is_a("IfcArcIndex"):
908 [p1, p2, p3] = index2points(s)
909 result.append(Part.Arc(p1, p2, p3))
910 else:
911 raise RuntimeError("Illegal IfcIndexedPolyCurve segment: " + s.is_a())
912 else:
913 print("importIFCHelper.getCurveSet: unhandled element: ", el)
914
915 return result
916
917 result = []
918 if representation.is_a("IfcShapeRepresentation"):
919 for item in representation.Items:
920 if item.is_a() in ["IfcGeometricCurveSet", "IfcGeometricSet"]:
921 result = getCurveSet(item)
922 elif item.is_a("IfcMappedItem"):
923 preresult = get2DShape(item.MappingSource.MappedRepresentation, scaling)
924 pla = getPlacement(item.MappingSource.MappingOrigin, scaling)
925 rot = getRotation(item.MappingTarget)
926 if pla:
927 if rot.Angle:
928 pla.Rotation = rot
929 for r in preresult:
930 # r.Placement = pla
931 result.append(r)
932 else:
933 result = preresult
934 elif item.is_a("IfcTextLiteral"):
935 if notext:
936 continue
937 pl = getPlacement(item.Placement, scaling)
938 if pl:
939 t = Draft.make_text(item.Literal.split(";"), pl)
940 if FreeCAD.GuiUp:
941 if item.Path == "RIGHT":
942 t.ViewObject.Justification = "Right"
943 # do not return because there might be more than one representation
944 # return [] # TODO dirty hack... Object creation should not be done here
945 elif representation.is_a() in [
946 "IfcPolyline",
947 "IfcCircle",
948 "IfcTrimmedCurve",
949 "IfcRectangleProfileDef",
950 ]:
951 result = getCurveSet(representation)
952 return result
953
954
955 def getProfileCenterPoint(sweptsolid):
956 """returns the center point of the profile of an extrusion"""
957 v = FreeCAD.Vector(0, 0, 0)
958 if hasattr(sweptsolid, "SweptArea"):
959 profile = get2DShape(sweptsolid.SweptArea)
960 if profile:
961 profile = profile[0]
962 if hasattr(profile, "CenterOfMass"):
963 v = profile.CenterOfMass
964 elif hasattr(profile, "BoundBox"):
965 v = profile.BoundBox.Center
966 if hasattr(sweptsolid, "Position"):
967 pos = getPlacement(sweptsolid.Position)
968 v = pos.multVec(v)
969 return v
970
971
972 def isRectangle(verts):
973 """returns True if the given 4 vertices form a rectangle"""
974 if len(verts) != 4:
975 return False
976 v1 = verts[1].sub(verts[0])
977 v2 = verts[2].sub(verts[1])
978 v3 = verts[3].sub(verts[2])
979 v4 = verts[0].sub(verts[3])
980 if abs(v2.getAngle(v1) - math.pi / 2) > 0.01:
981 return False
982 if abs(v3.getAngle(v2) - math.pi / 2) > 0.01:
983 return False
984 if abs(v4.getAngle(v3) - math.pi / 2) > 0.01:
985 return False
986 return True
987
988
989 def createFromProperties(propsets, ifcfile, parametrics):
990 """
991 Creates a FreeCAD parametric object from a set of properties.
992 """
993
994 obj = None
995 sets = []
996 appset = None
997 guiset = None
998 for pset in propsets.keys():
999 if ifcfile[pset].Name == "FreeCADPropertySet":
1000 appset = {}
1001 for pid in propsets[pset]:
1002 p = ifcfile[pid]
1003 appset[p.Name] = p.NominalValue.wrappedValue
1004 elif ifcfile[pset].Name == "FreeCADGuiPropertySet":
1005 guiset = {}
1006 for pid in propsets[pset]:
1007 p = ifcfile[pid]
1008 guiset[p.Name] = p.NominalValue.wrappedValue
1009 if appset:
1010 oname = None
1011 otype = None
1012 if "FreeCADType" in appset:
1013 if "FreeCADName" in appset:
1014 obj = FreeCAD.ActiveDocument.addObject(appset["FreeCADType"], appset["FreeCADName"])
1015 if "FreeCADAppObject" in appset:
1016 mod, cla = appset["FreeCADAppObject"].split(".")
1017 if "'" in mod:
1018 mod = mod.split("'")[-1]
1019 if "'" in cla:
1020 cla = cla.split("'")[0]
1021 import importlib
1022
1023 mod = importlib.import_module(mod)
1024 getattr(mod, cla)(obj)
1025 sets.append(("App", appset))
1026 if FreeCAD.GuiUp:
1027 if guiset:
1028 if "FreeCADGuiObject" in guiset:
1029 mod, cla = guiset["FreeCADGuiObject"].split(".")
1030 if "'" in mod:
1031 mod = mod.split("'")[-1]
1032 if "'" in cla:
1033 cla = cla.split("'")[0]
1034 import importlib
1035
1036 mod = importlib.import_module(mod)
1037 getattr(mod, cla)(obj.ViewObject)
1038 sets.append(("Gui", guiset))
1039 if obj and sets:
1040 for realm, pset in sets:
1041 if realm == "App":
1042 target = obj
1043 else:
1044 target = obj.ViewObject
1045 for key, val in pset.items():
1046 if key.startswith("FreeCAD_") or key.startswith("FreeCADGui_"):
1047 name = key.split("_")[1]
1048 if name in target.PropertiesList:
1049 if not target.getEditorMode(name):
1050 ptype = target.getTypeIdOfProperty(name)
1051 if ptype in [
1052 "App::PropertyString",
1053 "App::PropertyEnumeration",
1054 "App::PropertyInteger",
1055 "App::PropertyFloat",
1056 ]:
1057 setattr(target, name, val)
1058 elif ptype in ["App::PropertyLength", "App::PropertyDistance"]:
1059 setattr(target, name, val * 1000)
1060 elif ptype == "App::PropertyBool":
1061 if val in [".T.", True]:
1062 setattr(target, name, True)
1063 else:
1064 setattr(target, name, False)
1065 elif ptype == "App::PropertyVector":
1066 setattr(
1067 target,
1068 name,
1069 FreeCAD.Vector(
1070 [float(s) for s in val.split("(")[1].strip(")").split(",")]
1071 ),
1072 )
1073 elif ptype == "App::PropertyArea":
1074 setattr(target, name, val * 1000000)
1075 elif ptype == "App::PropertyPlacement":
1076 data = val.split("[")[1].strip("]").split("(")
1077 data = [data[1].split(")")[0], data[2].strip(")")]
1078 v = FreeCAD.Vector([float(s) for s in data[0].split(",")])
1079 r = FreeCAD.Rotation(*[float(s) for s in data[1].split(",")])
1080 setattr(target, name, FreeCAD.Placement(v, r))
1081 elif ptype == "App::PropertyLink":
1082 link = val.split("_")[1]
1083 parametrics.append([target, name, link])
1084 else:
1085 print("Unhandled FreeCAD property:", name, " of type:", ptype)
1086 return obj, parametrics
1087
1088
1089 def applyColorDict(doc, colordict=None):
1090 """applies the contents of a color dict to the objects in the given doc.
1091 If no colordict is given, the doc Meta property is searched for a "colordict" entry."""
1092
1093 if not colordict:
1094 if "colordict" in doc.Meta:
1095 import json
1096
1097 colordict = json.loads(doc.Meta["colordict"])
1098 if colordict:
1099 for obj in doc.Objects:
1100 if obj.Name in colordict:
1101 color = colordict[obj.Name]
1102 if hasattr(obj.ViewObject, "ShapeColor"):
1103 obj.ViewObject.ShapeColor = tuple(color[0:3])
1104 if hasattr(obj.ViewObject, "Transparency") and (len(color) >= 4):
1105 obj.ViewObject.Transparency = 1.0 - color[3]
1106 else:
1107 print("No valid color dict to apply")
1108
1109
1110 def getParents(ifcobj):
1111 """finds the parent entities of an IFC entity"""
1112
1113 parentlist = []
1114 if hasattr(ifcobj, "ContainedInStructure"):
1115 for rel in ifcobj.ContainedInStructure:
1116 parentlist.append(rel.RelatingStructure)
1117 elif hasattr(ifcobj, "Decomposes"):
1118 for rel in ifcobj.Decomposes:
1119 if rel.is_a("IfcRelAggregates"):
1120 parentlist.append(rel.RelatingObject)
1121 return parentlist
1122
1123
1124 def createAnnotation(annotation, doc, ifcscale, preferences):
1125 """creates an annotation object"""
1126
1127 anno = None
1128 aid = annotation.id()
1129 if annotation.is_a("IfcGrid"):
1130 axes = []
1131 uvwaxes = ()
1132 if annotation.UAxes:
1133 uvwaxes = annotation.UAxes
1134 if annotation.VAxes:
1135 uvwaxes = uvwaxes + annotation.VAxes
1136 if annotation.WAxes:
1137 uvwaxes = uvwaxes + annotation.WAxes
1138 for axis in uvwaxes:
1139 if axis.AxisCurve:
1140 sh = get2DShape(axis.AxisCurve, ifcscale)
1141 if sh and (len(sh[0].Vertexes) == 2): # currently only straight axes are supported
1142 sh = sh[0]
1143 l = sh.Length
1144 pl = FreeCAD.Placement()
1145 pl.Base = sh.Vertexes[0].Point
1146 pl.Rotation = FreeCAD.Rotation(
1147 FreeCAD.Vector(0, 1, 0), sh.Vertexes[-1].Point.sub(sh.Vertexes[0].Point)
1148 )
1149 o = Arch.makeAxis(1, l)
1150 o.Length = l
1151 o.Placement = pl
1152 o.CustomNumber = axis.AxisTag
1153 axes.append(o)
1154 if axes:
1155 name = "Grid"
1156 grid_placement = None
1157 if annotation.Name:
1158 name = annotation.Name
1159 if annotation.ObjectPlacement:
1160 # https://forum.freecad.org/viewtopic.php?f=39&t=40027
1161 grid_placement = getPlacement(annotation.ObjectPlacement, scaling=1)
1162 if preferences["PREFIX_NUMBERS"]:
1163 name = "ID" + str(aid) + " " + name
1164 anno = Arch.makeAxisSystem(axes, name)
1165 if grid_placement:
1166 anno.Placement = grid_placement
1167 print(" axis")
1168 else:
1169 name = "Annotation"
1170 if annotation.Name:
1171 name = annotation.Name
1172 if "annotation" not in name.lower():
1173 name = "Annotation " + name
1174 if preferences["PREFIX_NUMBERS"]:
1175 name = "ID" + str(aid) + " " + name
1176 shapes2d = []
1177 for rep in annotation.Representation.Representations:
1178 if rep.RepresentationIdentifier in ["Annotation", "FootPrint", "Axis"]:
1179 sh = get2DShape(rep, ifcscale)
1180 if sh in doc.Objects:
1181 # dirty hack: get2DShape might return an object directly if non-shape based (texts for ex)
1182 anno = sh
1183 else:
1184 shapes2d.extend(sh)
1185 if shapes2d:
1186 import Part
1187
1188 sh = Part.makeCompound(shapes2d)
1189 # if preferences['DEBUG']: print(" shape")
1190 anno = doc.addObject("Part::Feature", name)
1191 anno.Shape = sh
1192 p = getPlacement(annotation.ObjectPlacement, ifcscale)
1193 if p: # and annotation.is_a("IfcAnnotation"):
1194 anno.Placement = p
1195 # else:
1196 # if preferences['DEBUG']: print(" no shape")
1197
1198 return anno