Compare commits

...

105 Commits

Author SHA1 Message Date
Andrej730 8f34752141 ifccsv - support importing enum properties 2024-05-06 18:56:26 +05:00
Andrej730 28d205b4a3 show info message on saving/loading csv from bbim 2024-05-06 18:56:20 +05:00
Andrej730 dcc52fc4e4 pset.edit_pset not to fail silently on invalid enum values #4608 2024-05-06 18:22:52 +05:00
Andrej730 a9d785c28f typing 2024-05-06 18:22:52 +05:00
Bruno Postle 54a3730c20 fix d11ec67 mathutils dependency regression
mathutils is a blender module, wrap imports in try/except
2024-05-06 13:55:20 +01:00
Andrej730 31d322a28c descriptions for operators removing classifications/contexts #4614 2024-05-06 17:29:30 +05:00
Andrej730 3b90086109 Fix loading search queries with exclusion #4609
It was failing to load queries like "!IfcWall" or "!2Mg7PHubX0xxOfF0DdA9Wd"
2024-05-06 17:06:10 +05:00
Gorgious56 30b870b98d Fix #4617 : Switching representation in edit mode is no longer possible 2024-05-06 13:20:33 +02:00
Thomas Krijnen b3e7975b83 Consider material profile set in single material determination 2024-05-06 13:18:05 +02:00
Andrej730 8f7f6223de unlink pasted blender objects if there is no active ifc file #4619 2024-05-06 15:03:27 +05:00
Dion Moult 6c313dd25c Fix for static analysis of ifcopenshell.api submodules. See #2693. 2024-05-06 18:39:13 +10:00
Bruno Postle b718bd19bd fix TypeError
File "/usr/lib64/python3.12/site-packages/ifcopenshell/api/project/assign_declaration.py", line 126, in execute
    related_definitions = set(has_context.RelatedDefinitions) - objects_with_contexts
                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for -: 'set' and 'list'
2024-05-06 09:05:56 +01:00
Dion Moult ab5ea4c853 Implement listener wrapper for new API functions. See #2693. 2024-05-06 14:43:43 +10:00
Dion Moult d11ec67129 Generate functions for all API usecases for better static code features. See #2693. 2024-05-06 14:43:43 +10:00
Ryan Schultz 10f894e2ea Find the "Types" Collection regardless of the IfcProject.Name 2024-05-05 20:46:07 -05:00
Ryan Schultz 34bbc8f1ea for 'Add Fitting' changed the hot key from Shift+F to Shift+Y. per https://community.osarch.org/discussion/2124/ui-discussion-around-add-fitting-and-add-bend
Also added Shift+F (bim.flip_object) to all profile-based objects
2024-05-05 19:20:13 -05:00
Dion Moult a213ab6760 Fix docstrings to reference datatype as it would be used for users 2024-05-06 08:39:48 +10:00
Ryan Schultz d694d8fcc2 fix #4610: bim.select_type() from type launcher throws error 2024-05-05 13:16:30 -05:00
ppaawweeuu 5f2d451c5e Update selector_syntax.rst (#4618)
info about 'Must contain..' and 'Must not contain..' comparisons added
2024-05-05 23:40:32 +10:00
Dion Moult ab696b980a See #2693. Expose static functions of IfcOpenShell API. 2024-05-05 16:26:41 +10:00
Andrej730 9f2df7fb9d preview external shading style as material is selected from other .blend file
previously it required to save external style attributes to preview the changes, now it's couple clicks saved if you want to preview different blender materials for your styles
2024-05-03 17:55:30 +05:00
Andrej730 9e5c3ff675 fix bug appending blender material when style.Location isn't .blend
it wasn't considering that .Location could be either None or not a .blend file and was failing in those cases
2024-05-03 17:38:04 +05:00
Andrej730 a67108e6c1 Reload current shading style after editing it #4567
Examples:
1) active shading type = EXTERNAL, now after changing it's SHADING attributes and accepting the changes, it will reload EXTERNAL shading back since it's the one that's active.
2) active shading type = SHADING, after adding EXTERNAL shader will reload SHADING style to the material.
2024-05-03 17:36:14 +05:00
Andrej730 b1706f2eac fix error launching type manager in empty project 2024-05-03 16:28:10 +05:00
Andrej730 ac29e152bb project.unassign_declaration - support batching #4474 2024-05-03 16:28:10 +05:00
Andrej730 de690a385c project.assign_declaration - support batching #4474 2024-05-03 16:28:10 +05:00
Andrej730 a973b62918 small comment fix 2024-05-03 16:28:10 +05:00
Andrej730 92426a640a bim.active_model not to unhide all types and drawings elements 2024-05-03 16:23:55 +05:00
Andrej730 93f8638a94 Use active camera drawing id for bim.create_drawing #4581
There was inconsistency between .poll and .execute on what use as active drawing.
2024-05-03 16:23:55 +05:00
Andrej730 16b0b1c3a5 Fix UI error #4575 2024-05-03 15:43:42 +05:00
Dion Moult 25fff3fdd0 Consolidate duplicate operators "Convert to Blender file" and "Purge IFC Links" 2024-05-03 17:02:05 +10:00
dependabot[bot] 0384de46a4 Bump pydantic from 1.10.7 to 1.10.13 in /src/opencdeserver/api/app (#4585)
Bumps [pydantic](https://github.com/pydantic/pydantic) from 1.10.7 to 1.10.13.
- [Release notes](https://github.com/pydantic/pydantic/releases)
- [Changelog](https://github.com/pydantic/pydantic/blob/main/HISTORY.md)
- [Commits](https://github.com/pydantic/pydantic/compare/v1.10.7...v1.10.13)

---
updated-dependencies:
- dependency-name: pydantic
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-03 16:21:08 +10:00
Ryan Schultz 080f325557 extends bim.select_type by selecting multiple types from a selection of objects.
Also when the type is selected and turned on, all other types are automatically turned off.
https://imgur.com/a/DQUF0ai
2024-05-03 00:59:33 -05:00
Andrej730 86cc2bf39a fix bug using "trace outlines" for reprsentation in ifc2x3
Mentioned in #4593

The error message was (it was trying to access curves from the original mesh instead of dummy curve object):
```
Error: Python: Traceback (most recent call last):
  File "\blenderbim\bim\module\geometry\operator.py", line 46, in execute
    IfcStore.execute_ifc_operator(self, context)
  File "\blenderbim\bim\ifc.py", line 349, in execute_ifc_operator
    result = getattr(operator, "_execute")(context)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "\blenderbim\bim\module\geometry\operator.py", line 169, in _execute
    core.add_representation(
  File "\blenderbim\core\geometry.py", line 52, in add_representation
    representation = ifc.run(
                     ^^^^^^^^
  File "\blenderbim\tool\ifc.py", line 34, in run
    return ifcopenshell.api.run(command, IfcStore.get_file(), **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "\blenderbim\libs\site\packages\ifcopenshell\api\__init__.py", line 172, in run
    result = usecase_class(ifc_file, **settings).execute()
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "\blenderbim\libs\site\packages\ifcopenshell\api\geometry\add_representation.py", line 73, in execute
    return self.create_plan_representation()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "\blenderbim\libs\site\packages\ifcopenshell\api\geometry\add_representation.py", line 170, in create_plan_representation
    return self.create_annotation2d_representation()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "\blenderbim\libs\site\packages\ifcopenshell\api\geometry\add_representation.py", line 833, in create_annotation2d_representation
    items = [self.file.createIfcGeometricCurveSet(self.create_curves(is_2d=True))]
                                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "\blenderbim\libs\site\packages\ifcopenshell\api\geometry\add_representation.py", line 492, in create_curves
    curves = self.create_curves_from_curve_ifc2x3(is_2d=is_2d, curve_object_data=dummy.data)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "\blenderbim\libs\site\packages\ifcopenshell\api\geometry\add_representation.py", line 575, in create_curves_from_curve_ifc2x3
    for spline in self.settings["geometry"].splines:
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Mesh' object has no attribute 'splines'
```
2024-05-02 16:48:52 +05:00
Andrej730 c7effa3f25 More descriptive errors linking ifc files 2024-05-02 12:13:44 +05:00
Andrej730 be262eaef2 fix errors linking ifc2x3 projects
it was failing with something very verbose:

```
  File "\blenderbim\bim\module\project\operator.py", line 1239, in execute
    db = ifcpatch.execute(
         ^^^^^^^^^^^^^^^^^
  File "\blenderbim\libs\site\packages\ifcpatch\__init__.py", line 80, in execute
    patcher.patch()
  File "\blenderbim\libs\site\packages\ifcpatch\recipes\ExtractPropertiesToSQLite.py", line 137, in patch
    properties.append([i, "IFC Material", f"Layer {idx + 1} Name", item.Name])
                                                                   ^^^^^^^^^
  File "\blenderbim\libs\site\packages\ifcopenshell\entity_instance.py", line 197, in __getattr__
    raise AttributeError(
AttributeError: entity instance of type 'IFC2X3.IfcMaterialLayer' has no attribute 'Name'
Error: Python: Traceback (most recent call last):
  File "\blenderbim\bim\module\project\operator.py", line 1239, in execute
    db = ifcpatch.execute(
         ^^^^^^^^^^^^^^^^^
  File "\blenderbim\libs\site\packages\ifcpatch\__init__.py", line 80, in execute
    patcher.patch()
  File "\blenderbim\libs\site\packages\ifcpatch\recipes\ExtractPropertiesToSQLite.py", line 137, in patch
    properties.append([i, "IFC Material", f"Layer {idx + 1} Name", item.Name])
                                                                   ^^^^^^^^^
  File "\blenderbim\libs\site\packages\ifcopenshell\entity_instance.py", line 197, in __getattr__
    raise AttributeError(
AttributeError: entity inTraceback (most recent call last):
  File "\Temp\tmpdggt3syt.py", line 9, in <module>
    run()
  File "\Temp\tmpdggt3syt.py", line 5, in run
    bpy.ops.bim.load_linked_project(filepath="/Dormitory-ARC.ifc", false_origin="0,0,0")
  File "\Blender\4.1\scripts\modules\bpy\ops.py", line 109, in __call__
    ret = _op_call(self.idname_py(), kw)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Error: Python: Traceback (most recent call last):
  File "\blenderbim\bim\module\project\operator.py", line 1239, in execute
    db = ifcpatch.execute(
         ^^^^^^^^^^^^^^^^^
  File "\blenderbim\libs\site\packages\ifcpatch\__init__.py", line 80, in execute
    patcher.patch()
  File "\blenderbim\libs\site\packages\ifcpatch\recipes\ExtractPropertiesToSQLite.py", line 137, in patch
    properties.append([i, "IFC Material", f"Layer {idx + 1} Name", item.Name])
                                                                   ^^^^^^^^^
  File "\blenderbim\libs\site\packages\ifcopenshell\entity_instance.py", line 197, in __getattr__
    raise AttributeError(
AttributeError: entity instance of type 'IFC2X3.IfcMaterialLayer' has no attribute 'Name'
Location: \Blender\4.1\scripts\modules\bpy\ops.py:109

... truncatedUnregistered Snippets Library
BMAX Connector - UnRegistred!
An error occurred while processing your IFC.
Traceback (most recent call last):
  File "\blenderbim\bim\module\project\operator.py", line 949, in execute
    self.link_ifc()
  File "\blenderbim\bim\module\project\operator.py", line 991, in link_ifc
    self.link_blend(blend_filepath)
  File "\blenderbim\bim\module\project\operator.py", line 953, in link_blend
    with bpy.data.libraries.load(filepath, link=True) as (data_from, data_to):
OSError: load: \Dormitory-ARC.ifc.cache.blend failed to open blend file
Error: Python: Traceback (most recent call last):
  File "\blenderbim\bim\module\project\operator.py", line 949, in execute
    self.link_ifc()
  File "\blenderbim\bim\module\project\operator.py", line 991, in link_ifc
    self.link_blend(blend_filepath)
  File "\blenderbim\bim\module\project\operator.py", line 953, in link_blend
    with bpy.data.libraries.load(filepath, link=True) as (data_from, data_to):
OSError: load: \Dormitory-ARC.ifc.cache.blend failed to open blend file
Location: \Blender\4.1\scripts\modules\bpy\ops.py:109
Traceback (most recent call last):
  File "\blenderbim\bim\module\project\operator.py", line 870, in execute
    bpy.ops.bim.load_link(filepath=filepath, false_origin=self.false_origin)
  File "\Blender\4.1\scripts\modules\bpy\ops.py", line 109, in __call__
    ret = _op_call(self.idname_py(), kw)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Error: Python: Traceback (most recent call last):
  File "\blenderbim\bim\module\project\operator.py", line 949, in execute
    self.link_ifc()
  File "\blenderbim\bim\module\project\operator.py", line 991, in link_ifc
    self.link_blend(blend_filepath)
  File "\blenderbim\bim\module\project\operator.py", line 953, in link_blend
    with bpy.data.libraries.load(filepath, link=True) as (data_from, data_to):
OSError: load: \Dormitory-ARC.ifc.cache.blend failed to open blend file
Location: \Blender\4.1\scripts\modules\bpy\ops.py:109
```
2024-05-01 18:26:58 +05:00
Andrej730 523e51c775 use json serialization for #4599
changed my mind about 5410f14aa, probably better to use `json.dumps` to keep it consistent with how we serialize other attributes
2024-05-01 18:26:58 +05:00
Andrej730 5410f14aa1 ifc2sql - stringify psets list values #4599 2024-05-01 18:03:25 +05:00
Andrej730 45b2411c2b Fix #4598 after 229c7285c 2024-05-01 17:43:31 +05:00
Andrej730 9f12091c7f fix bug assigning materials
it was clearing all other blender materials - e.g. blender materials associated with representation items styles. Also had the same issue with affecting extra elements as with unassigning materials
2024-05-01 16:42:20 +05:00
Andrej730 bef5d3cca5 blenderbim - fix bug with unassigning material
When you would unassign material (e.g. implicitly by removing the object), it might have also removed materials slots from other occurrences of the same type.

Which may had some unexpected sideffects later on - as unassigned styles saving IFC project (BBIM unassigned styles based on a assumption that it was the user decision to remove the materials and related styles).
2024-05-01 16:42:20 +05:00
Andrej730 0f548eb93e Indicate in UI if type material was overridden by occurrence material
Example - https://i.imgur.com/T1hidJg.png

+small optimization in material_name
2024-05-01 16:42:20 +05:00
Andrej730 374348bb81 IfcImporter small optimization 2024-05-01 16:42:20 +05:00
Andrej730 b42f6b1827 ifc delete to show time it took if it was more than 10 secs 2024-05-01 16:42:20 +05:00
Andrej730 addcf531f0 owner.update_owner_history - optimization
as it may be used very often
2024-05-01 16:42:20 +05:00
Andrej730 0ef683013a RegenerateGlobalIds - more informative fixing duplicates 2024-05-01 16:42:20 +05:00
Andrej730 137a306269 typing 2024-05-01 16:42:20 +05:00
Andrej730 fc0ffd1c02 fix a typo #4596 😬 2024-05-01 15:40:45 +05:00
Bruno Perdigão 97e0c43702 Merge pull request #4440 from brunoperdigao/fix-normal-duplication-of-linked-aggregate
Fix normal duplication of linked aggregate
2024-04-30 17:01:44 -03:00
Andrej730 8dde98f543 fix #4592 (after 0da3270)
Before IFC4 Shape Aspects counldn't be part of IfcRepresentationMap
2024-04-29 15:22:26 +05:00
Ryan Schultz 9962a0c905 small fix to previous commit. Solves https://github.com/IfcOpenShell/IfcOpenShell/commit/4b56b341243d6b0eed82e8533848b124e82e1344#commitcomment-141442796 2024-04-28 18:57:42 -05:00
Ryan Schultz 4b56b34124 Tweaked UI for Linked Aggregates https://imgur.com/a/rExISKO 2024-04-28 10:34:52 -05:00
Thomas Krijnen f857c513c5 submodule 2024-04-28 10:17:57 +02:00
Kaare Hansen 41df6410bd Comment std::cout causing console spam 2024-04-28 10:11:32 +02:00
Ryan Schultz dcbd6a925d small fix for #4361. remove IfcProject for class iterator. See https://github.com/IfcOpenShell/IfcOpenShell/issues/4361#issuecomment-2081223615 2024-04-27 18:13:38 -05:00
Ryan Schultz 3848a21136 fix #4361: Have the aggregate empty turn on too, if at least one object in the aggregate, is turned on as well 2024-04-27 11:31:39 -05:00
Andrej730 8af37cb4ec Fix #4586 occurred after e14d96e6e 2024-04-27 12:03:56 +05:00
Ryan Schultz 44c28e9a4c fix #4327: reorder format as well 2024-04-26 20:48:59 -05:00
Ryan Schultz 677324927c fix #4431: prompt for name, when creating aggregate 2024-04-26 20:09:20 -05:00
Massimo Fabbro d212344c54 Covering tool more user friendly UI ... 2024-04-26 17:19:28 +02:00
Massimo Fabbro 74da327803 Fix create space from cursor bug where spaces were created always in zero elevation 2024-04-26 17:19:28 +02:00
Massimo Fabbro f021041b31 Remove the (maybe) unnecessary poll functions for spatial tool and cleaner error messages 2024-04-26 17:19:28 +02:00
Massimo Fabbro c05d2df116 now spaces created with spatial tool have relative zero elevation origin point 2024-04-26 17:19:28 +02:00
Andrej730 2b926f7906 more descriptive error setting non-optional attributes with None
Example:

```
import ifcopenshell
import ifcopenshell.api.owner.settings

ifc_file = ifcopenshell.file(schema="IFC2X3")
ifc_file.createIfcOwnerHistory(OwningUser=None)

# Before:
# Traceback (most recent call last):
#   File "\test.py", line 16, in <module>
#     ifcopenshell.api.run("owner.create_owner_history", ifc_file)
#   File "\ifcopenshell\api\__init__.py", line 172, in run
#     result = usecase_class(ifc_file, **settings).execute()
#              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#   File "\ifcopenshell\api\owner\create_owner_history.py", line 111, in execute
#     return self.file.create_entity(
#            ^^^^^^^^^^^^^^^^^^^^^^^^
#   File "\ifcopenshell\file.py", line 350, in create_entity
#     e[idx] = arg
#     ~^^^^^
#   File "\ifcopenshell\entity_instance.py", line 305, in __setitem__
#     self.wrapped_data.setArgumentAsNull(idx)
#   File "\ifcopenshell\ifcopenshell_wrapper.py", line 5285, in setArgumentAsNull
#     return _ifcopenshell_wrapper.entity_instance_setArgumentAsNull(self, i)
#            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# RuntimeError: Attribute not set

# After:
# Traceback (most recent call last):
#   File "\test.py", line 16, in <module>
#     ifcopenshell.api.run("owner.create_owner_history", ifc_file)
#   File "\ifcopenshell\api\__init__.py", line 172, in run
#     result = usecase_class(ifc_file, **settings).execute()
#              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#   File "\ifcopenshell\api\owner\create_owner_history.py", line 111, in execute
#     return self.file.create_entity(
#            ^^^^^^^^^^^^^^^^^^^^^^^^
#   File "\ifcopenshell\file.py", line 350, in create_entity
#     e[idx] = arg
#     ~^^^^^
#   File "\ifcopenshell\entity_instance.py", line 316, in __setitem__
#     raise ValueError(
# ValueError: attribute 'OwningUser' is not optional for entity instance of type 'IFC2X3.IfcOwnerHistory'
```
2024-04-26 18:23:19 +05:00
Andrej730 3ac69043d6 bbim to provide default user and organisation in ifc2x3 #4574
previously every operation that would try to create owner history would fail with the error below if there wasn't IfcPersonAndOrganisation in the project.
2024-04-26 18:23:19 +05:00
Andrej730 f726708815 edit_object_placement - small optimizations 2024-04-26 18:23:19 +05:00
Andrej730 21e153087a edit_object_placement - adherence support
Update edit_object_placement.py
2024-04-26 18:23:18 +05:00
Andrej730 31d85b715a typing 2024-04-26 18:23:18 +05:00
Andrej730 344cc1fb7d file.by_type docs note 2024-04-26 11:49:44 +05:00
Andrej730 1cea3d21e8 BBIM support importing IfcRelAdheresToElement #4565 2024-04-26 11:44:32 +05:00
Andrej730 640320f70d shape_builder - create non-optional position for profiles in ifc2x3 2024-04-25 18:05:47 +05:00
Andrej730 29352092aa fix issue creating 3d location for 2d placement in ifc2x3 2024-04-25 18:05:47 +05:00
Andrej730 5b877b549a fix numpy typing #4579
On older numpy versions, np.ndarray was less forgiving and wasn't allowing passing 1 argument instead of required 2.

And turned out numpy doesn't yet have typing for shapes (https://github.com/numpy/numpy/issues/16544), so all matrices and other shapes specified as `npt.NDArray[np.float64]`.

Fixed type discrepancies for `get_edges` and `get_faces` and also had to fix `import_ifc` as Blender apparently has problems with storing np.int32 in custom attributes (https://projects.blender.org/blender/blender/issues/121072), tested that Blender is okay with np.int32 in other cases we had (addressing BMesh.verts[i] where `i` is np.int32).
2024-04-25 18:05:47 +05:00
Andrej730 721466c429 typing 2024-04-25 18:05:47 +05:00
Andrej730 cce2fee1fa More descriptive error setting non-present attributes
Example:

```
import ifcopenshell

ifc_file = ifcopenshell.file(schema="IFC2X3")
# ifc_file.begin_transaction()

wall = ifc_file.createIfcWall()
wall.Identification = "25"

# Before:
# Traceback (most recent call last):
#   File "test.py", line 4, in <module>
#     wall.Identification = "25"
#     ^^^^^^^^^^^^^^^^^^^
#   File "\ifcopenshell\entity_instance.py", line 279, in __setattr__
#     self[index] = value
#     ~~~~^^^^^^^
#   File "\ifcopenshell\entity_instance.py", line 293, in __setitem__
#     method = self.method_list[idx]
#              ~~~~~~~~~~~~~~~~^^^^^
# IndexError: list index out of range

# or this (if file had a transaction going)
#   File "\ifcopenshell\entity_instance.py", line 279, in __setattr__
#     self[index] = value
#     ~~~~^^^^^^^
#   File "\ifcopenshell\entity_instance.py", line 288, in __setitem__
#     self.wrapped_data.file.transaction.store_edit(self, idx, value)
#   File "\ifcopenshell\file.py", line 101, in store_edit
#     "old": self.serialise_value(element, element[index]),
#                                          ~~~~~~~^^^^^^^
#   File "\ifcopenshell\entity_instance.py", line 283, in __getitem__
#     raise IndexError("Attribute index {} out of range for instance of type {}".format(key, self.is_a()))
# IndexError: Attribute index 4294967295 out of range for instance of type IfcWall

# After:
# Traceback (most recent call last):
#   File "test.py", line 4, in <module>
#     wall.Identification = "25"
#     ^^^^^^^^^^^^^^^^^^^
#   File "ifcopenshell\entity_instance.py", line 283, in __setattr__
#     raise AttributeError(
# AttributeError: entity instance of type 'IFC2X3.IfcWall' has no attribute 'Identification'

```
2024-04-25 18:05:47 +05:00
Andrej730 087d55f02a fix editing sheets in ifc2x3 #4576 2024-04-25 18:05:47 +05:00
Andrej730 f1037de14d small fix for 60a70f523 2024-04-25 18:05:46 +05:00
Ryan Schultz 4711672170 small tweak to 3ff31b577c and cd013079f4 - duplicate material and duplicate style have '_copy' suffix. 2024-04-24 21:48:26 -05:00
Bruno Postle c0b4e099af fix sheet regeneration missing drawing Identifier
Was passing LAYOUT document reference to sheeter instead of
DRAWING document reference
2024-04-24 23:05:44 +01:00
Andrej730 f41fbf24c3 small fix for e14d96e6e 2024-04-24 18:19:20 +05:00
Andrej730 e14d96e6ee Use .Name instead of .Description if IFC2X3 for sheets #4576
As Description was added only in IFC4
2024-04-24 18:17:37 +05:00
Andrej730 716a33f347 convert_file_length_units - fix issue converting to imperial units
ifcpatch ConvertLengthUnit - change used units from plural to singular names, to make it consistent across the api

more test coverage - test converting to more units and back from them
2024-04-24 15:15:30 +05:00
Andrej730 c5f084a4af ConvertLengthUnit test 2024-04-24 14:12:13 +05:00
Andrej730 606a0b46f2 MergeProject - support merging projects with different units 2024-04-24 14:12:13 +05:00
Andrej730 1c729a74d1 util.unit to support converting aggregate of aggregates 2024-04-24 14:12:13 +05:00
Andrej730 db31574103 typing 2024-04-24 14:12:13 +05:00
stefkeB d03b47e1e6 Fix HDF5 conditional inclusion in GeomTree
IfcGeomTree uses HDF5, but this is an optional module, so we have to wrap it with #ifdef WITH_HDF5
2024-04-23 18:46:10 +02:00
Ryan Schultz ae62ac2777 small tweak to b8a9674483 - duplicate profile has '_copy' suffix. 2024-04-23 07:42:02 -05:00
Andrej730 998f9c6a1e make styles ui more similar to profiles and materials ui
before - https://i.imgur.com/bTbyt2t.png
after - https://i.imgur.com/U53h8Yh.png
2024-04-23 16:39:49 +05:00
Andrej730 3ff31b577c bim.duplicate_style 2024-04-23 16:39:49 +05:00
Andrej730 cd013079f4 bim.duplicate_material 2024-04-23 16:39:49 +05:00
Andrej730 b8a9674483 bim.duplicate_profile
simple operator for profile duplication
example - https://imgur.com/a/dsP78iV
2024-04-23 16:39:49 +05:00
Andrej730 8beb1bef98 preserve selected profile index removing profiles 2024-04-23 16:39:38 +05:00
Andrej730 377676f881 dev environment - add libs/desktop and bsdd 2024-04-23 15:23:16 +05:00
Andrej730 4efe284338 use IFC4X3_ADD2 for ifcopenshell.schema_by_name
as it is the main IFC4X3 schema
2024-04-22 17:30:25 +05:00
Andrej730 34a4e3f37a util.doc - use release schema version for IFC4X3
As it will be more like to be available in the ifcopenshell package. Related to #4565
2024-04-22 17:30:25 +05:00
Andrej730 889c9a9e9f typing 2024-04-22 17:30:25 +05:00
Andrej730 9e79499532 small optimization 2024-04-22 17:30:24 +05:00
Kristof Semjen 589b98053e Fixes #4261
SWIG_Python_str_AsChar and SWIG_Python_str_DelForPy3 are no longer available in swig 4.2 (see : https://github.com/swig/swig/commit/f89dd59d4b82ece899087682fdb86e94d2611513 ),
this commit fixes the build for swig versions > 4.2.
2024-04-21 16:22:56 +02:00
Bruno Postle fc5bb230a9 Abandon SVG layout generation on missing drawings
Drawings need to be generated before layout can be generated, so
remove a partial failed layout caused by missing drawings.
2024-04-21 11:12:24 +01:00
Bruno Perdigão 01361cc8f2 Merge branch 'v0.7.0' into fix-normal-duplication-of-linked-aggregate 2024-04-18 21:00:39 -03:00
Bruno Perdigão e6bef16c45 small deletions 2024-03-18 23:39:06 -03:00
Bruno Perdigão 4829c4c02b fix: when subaggregate that is a linked aggregate is unassinged from the main aggregate, it remains a linked aggregate. 2024-03-16 15:27:04 -03:00
Bruno Perdigão 3bf4a8ef52 small refactor 2024-03-16 12:44:26 -03:00
Bruno Perdigão c95a47ca97 fix #4430. Shift+D whem selecting all the objects of a linked aggregate creates a normal copy that is not linked 2024-03-15 21:34:27 -03:00
424 changed files with 15322 additions and 14397 deletions
+9 -5
View File
@@ -16,6 +16,7 @@
# You should have received a copy of the GNU General Public License
# along with BlenderBIM Add-on. If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations
import os
import bpy
import json
@@ -36,6 +37,7 @@ import blenderbim.core.style
from blenderbim.bim.ifc import IfcStore
from mathutils import Vector
from typing import Union
from logging import Logger
class IfcExporter:
@@ -163,10 +165,10 @@ class IfcExporter:
bpy.ops.bim.update_representation(obj=obj.name)
tool.Geometry.record_object_position(obj)
def get_application_name(self):
def get_application_name(self) -> str:
return "BlenderBIM"
def get_application_version(self):
def get_application_version(self) -> str:
version = ".".join(
[
str(x)
@@ -184,11 +186,13 @@ class IfcExporter:
class IfcExportSettings:
def __init__(self):
self.logger = None
self.output_file = None
self.logger: Logger = None
self.output_file: str = None
self.json_version: str = None
self.json_compact: bool = None
@staticmethod
def factory(context, output_file, logger):
def factory(context: bpy.types.Context, output_file: str, logger: Logger) -> IfcExportSettings:
settings = IfcExportSettings()
settings.output_file = output_file
settings.logger = logger
+16 -3
View File
@@ -223,7 +223,7 @@ def redo_post(scene):
tool.Ifc.rebuild_element_maps()
def get_application(ifc):
def get_application(ifc: ifcopenshell.file) -> ifcopenshell.entity_instance:
# TODO: cache this for even faster application retrieval. It honestly makes a difference on long scripts.
version = get_application_version()
for element in ifc.by_type("IfcApplication"):
@@ -238,7 +238,20 @@ def get_application(ifc):
)
def get_application_version():
def get_user(ifc: ifcopenshell.file) -> Union[ifcopenshell.entity_instance, None]:
# TODO: cache this for even faster application retrieval. It honestly makes a difference on long scripts.
if pao := next(iter(ifc.by_type("IfcPersonAndOrganization")), None):
return pao
elif ifc.schema == "IFC2X3":
if (person := next(iter(ifc.by_type("IfcPerson")), None)) is None:
person = tool.Ifc.run("owner.add_person")
if (organization := next(iter(ifc.by_type("IfcOrganization")), None)) is None:
organization = tool.Ifc.run("owner.add_organisation")
pao = tool.Ifc.run("owner.add_person_and_organisation", person=person, organisation=organization)
return pao
def get_application_version() -> str:
return ".".join(
[
str(x)
@@ -279,7 +292,7 @@ def load_post(scene):
key=key, owner=global_subscription_owner, args=(area,), notify=viewport_shading_changed_callback
)
ifcopenshell.api.owner.settings.get_user = lambda ifc: core_owner.get_user(tool.Owner)
ifcopenshell.api.owner.settings.get_user = get_user
ifcopenshell.api.owner.settings.get_application = get_application
AuthoringData.type_thumbnails = {}
+49 -28
View File
@@ -34,6 +34,7 @@ import ifcopenshell.util.element
import ifcopenshell.util.geolocation
import ifcopenshell.util.placement
import ifcopenshell.util.representation
import ifcopenshell.util.shape
import blenderbim.tool as tool
import ifcopenshell.ifcopenshell_wrapper as ifcopenshell_wrapper
from itertools import chain, accumulate
@@ -199,7 +200,7 @@ class MaterialCreator:
class IfcImporter:
def __init__(self, ifc_import_settings):
def __init__(self, ifc_import_settings: IfcImportSettings):
self.ifc_import_settings = ifc_import_settings
self.diff = None
self.file: ifcopenshell.file = None
@@ -298,6 +299,7 @@ class IfcImporter:
if self.ifc_import_settings.should_setup_viewport_camera:
self.setup_viewport_camera()
self.setup_arrays()
self.profile_code("Setup arrays")
self.update_progress(100)
bpy.context.window_manager.progress_end()
@@ -430,7 +432,7 @@ class IfcImporter:
self.annotations = set([a for a in self.file.by_type("IfcAnnotation")])
self.annotations -= drawing_annotations
self.elements = [e for e in self.elements if not e.is_a("IfcFeatureElement")]
self.elements = [e for e in self.elements if not e.is_a("IfcFeatureElement") or e.is_a("IfcSurfaceFeature")]
if self.ifc_import_settings.is_coordinating:
self.elements = [e for e in self.elements if e.Representation]
@@ -601,6 +603,9 @@ class IfcImporter:
return products
def predict_dense_mesh(self):
if self.ifc_import_settings.should_use_native_meshes:
return
threshold = 10000 # Just from experience.
faces = [len(e.CfsFaces) for e in self.file.by_type("IfcClosedShell")]
@@ -725,7 +730,7 @@ class IfcImporter:
if len(subelement.Coordinates) == 3 and self.is_point_far_away(subelement, is_meters=False):
return True
def apply_blender_offset_to_matrix_world(self, obj, matrix):
def apply_blender_offset_to_matrix_world(self, obj: bpy.types.Object, matrix: np.ndarray) -> mathutils.Matrix:
props = bpy.context.scene.BIMGeoreferenceProperties
if props.has_blender_offset:
if obj.data and obj.data.get("has_cartesian_point_offset", None):
@@ -862,7 +867,6 @@ class IfcImporter:
else:
self.create_generic_elements(self.spatial_elements, unselectable=False)
def create_elements(self) -> None:
self.create_generic_elements(self.elements)
tmp = self.context_settings
@@ -953,7 +957,9 @@ class IfcImporter:
self.create_product(element, mesh=mesh)
def create_products(
self, products, settings: Optional[ifcopenshell.geom.main.settings] = None
self,
products: set[ifcopenshell.entity_instance],
settings: Optional[ifcopenshell.geom.main.settings] = None,
) -> set[ifcopenshell.entity_instance]:
results = set()
if not products:
@@ -1492,7 +1498,11 @@ class IfcImporter:
# Occurs when reloading a project
pass
project_collection = bpy.context.view_layer.layer_collection.children[self.project["blender"].name]
project_collection.children[self.type_collection.name].hide_viewport = True
types_collection = project_collection.children[self.type_collection.name]
types_collection.hide_viewport = False
for obj in types_collection.collection.objects: #turn off all objects inside Types collection.
obj.hide_set(True)
def clean_mesh(self):
obj = None
@@ -1627,30 +1637,34 @@ class IfcImporter:
if self.ifc_import_settings.has_filter:
rel_aggregates = set()
for element in self.elements:
if element.IsDecomposedBy:
rel_aggregates.add(element.IsDecomposedBy[0])
elif element.Decomposes:
rel_aggregates.add(element.Decomposes[0])
elif getattr(element, "IsNestedBy", []): # IFC2X3 does not have IsNestedBy
if [e for e in element.IsNestedBy[0].RelatedObjects if not e.is_a("IfcPort")]:
rel_aggregates.add(element.IsNestedBy[0])
elif getattr(element, "Nests", []):
rel_aggregates.add(element.Nests[0])
if decomposed_by := element.IsDecomposedBy:
rel_aggregates.add(decomposed_by[0])
elif decomposes := element.Decomposes:
rel_aggregates.add(decomposes[0])
elif nested_by := getattr(element, "IsNestedBy", []): # IFC2X3 does not have IsNestedBy
if next((e for e in nested_by[0].RelatedObjects if not e.is_a("IfcPort")), None):
rel_aggregates.add(nested_by[0])
elif nests := getattr(element, "Nests", []):
rel_aggregates.add(nests[0])
elif element.is_a("IfcSurfaceFeature") and self.file.schema == "IFC4X3":
rel_aggregates.add(element.AdheresToElement[0])
else:
rel_aggregates = [
r
for r in self.file.by_type("IfcRelAggregates")
if r.RelatingObject.is_a("IfcElement") or r.RelatingObject.is_a("IfcElementType")
if (relating_obj := r.RelatingObject).is_a("IfcElement") or relating_obj.is_a("IfcElementType")
] + [
r
for r in self.file.by_type("IfcRelNests")
if (
r.RelatingObject.is_a("IfcElement")
or r.RelatingObject.is_a("IfcElementType")
or (r.RelatingObject.is_a("IfcPositioningElement") and not r.RelatingObject.is_a("IfcGrid"))
(relating_obj := r.RelatingObject).is_a("IfcElement")
or relating_obj.is_a("IfcElementType")
or (relating_obj.is_a("IfcPositioningElement") and not relating_obj.is_a("IfcGrid"))
)
and [e for e in r.RelatedObjects if not e.is_a("IfcPort")]
]
if self.file.schema == "IFC4X3":
rel_aggregates += [r for r in self.file.by_type("IfcRelAdheresToElement")]
if len(rel_aggregates) > 10000:
# More than 10,000 collections makes Blender unhappy
@@ -1660,7 +1674,9 @@ class IfcImporter:
aggregates: dict[str, dict] = {}
for rel_aggregate in rel_aggregates:
element: ifcopenshell.entity_instance = rel_aggregate.RelatingObject
element: ifcopenshell.entity_instance = getattr(rel_aggregate, "RelatingObject", None) or getattr(
rel_aggregate, "RelatingElement"
)
collection = bpy.data.collections.new(tool.Loader.get_name(element))
aggregates[element.GlobalId] = {"element": element, "collection": collection}
self.collections[element.GlobalId] = collection
@@ -1761,6 +1777,9 @@ class IfcImporter:
elif getattr(element, "Nests", None) and not element.is_a("IfcPort"):
nest = ifcopenshell.util.element.get_nest(element)
return self.collections[nest.GlobalId].objects.link(obj)
elif element.is_a("IfcSurfaceFeature") and self.file.schema == "IFC4X3":
adherend = element.AdheresToElement[0].RelatingElement
return self.collections[adherend.GlobalId].objects.link(obj)
return self.place_object_in_spatial_decomposition_collection(element, obj)
@@ -1810,7 +1829,7 @@ class IfcImporter:
if rel.is_a("IfcRelAssignsToGroup") and rel.RelatingGroup.ObjectType == "DRAWING":
return rel.RelatingGroup
def get_element_matrix(self, element: ifcopenshell.entity_instance) -> np.array:
def get_element_matrix(self, element: ifcopenshell.entity_instance) -> np.ndarray:
if isinstance(element, ifcopenshell.sqlite_entity):
result = self.geometry_cache["shapes"][element.id()]["matrix"]
else:
@@ -1932,7 +1951,9 @@ class IfcImporter:
# See bug 3546
# ios_edges holds true edges that aren't triangulated.
mesh["ios_edges"] = list(set(tuple(e) for e in ifcopenshell.util.shape.get_edges(geometry)))
#
# we do `.tolist()` because Blender can't assign `np.int32` to it's custom attributes
mesh["ios_edges"] = list(set(tuple(e) for e in ifcopenshell.util.shape.get_edges(geometry).tolist()))
mesh.vertices.add(num_vertices)
mesh.vertices.foreach_set("co", verts)
@@ -1959,14 +1980,14 @@ class IfcImporter:
print(traceback.format_exc())
def a2p(self, o, z, x):
def a2p(self, o: mathutils.Vector, z: mathutils.Vector, x: mathutils.Vector) -> mathutils.Matrix:
y = z.cross(x)
r = mathutils.Matrix((x, y, z, o))
r.resize_4x4()
r.transpose()
return r
def get_axis2placement(self, plc):
def get_axis2placement(self, plc: ifcopenshell.entity_instance) -> mathutils.Matrix:
if plc.is_a("IfcAxis2Placement3D"):
z = mathutils.Vector(plc.Axis.DirectionRatios if plc.Axis else (0, 0, 1))
x = mathutils.Vector(plc.RefDirection.DirectionRatios if plc.RefDirection else (1, 0, 0))
@@ -1986,7 +2007,7 @@ class IfcImporter:
o = plc.LocalOrigin.Coordinates
return self.a2p(o, z, x)
def get_local_placement(self, plc):
def get_local_placement(self, plc: Optional[ifcopenshell.entity_instance] = None) -> mathutils.Matrix:
if plc is None:
return mathutils.Matrix()
if plc.PlacementRelTo is None:
@@ -2001,11 +2022,11 @@ class IfcImporter:
bpy.context.scene.BIMRootProperties.contexts = str(subcontext.id())
break
def link_element(self, element, obj):
def link_element(self, element: ifcopenshell.entity_instance, obj: IFC_CONNECTED_TYPE) -> None:
self.added_data[element.id()] = obj
tool.Ifc.link(element, obj)
def set_matrix_world(self, obj, matrix_world):
def set_matrix_world(self, obj: bpy.types.Object, matrix_world: mathutils.Matrix) -> None:
obj.matrix_world = matrix_world
tool.Geometry.record_object_position(obj)
@@ -2028,7 +2049,7 @@ class IfcImporter:
class IfcImportSettings:
def __init__(self):
self.logger = None
self.logger: logging.Logger = None
self.input_file = None
self.diff_file = None
self.should_use_cpu_multiprocessing = True
@@ -96,12 +96,13 @@ class BIM_OT_aggregate_unassign_object(bpy.types.Operator, Operator):
)
# Removes Pset related to Linked Aggregates
pset = ifcopenshell.util.element.get_pset(element, "BBIM_Linked_Aggregate")
if pset:
pset = tool.Ifc.get().by_id(pset["id"])
ifcopenshell.api.run("pset.remove_pset", tool.Ifc.get(), pset=pset)
if not element.is_a('IfcElementAssembly'):
pset = ifcopenshell.util.element.get_pset(element, 'BBIM_Linked_Aggregate')
if pset:
pset = tool.Ifc.get().by_id(pset["id"])
ifcopenshell.api.run("pset.remove_pset", tool.Ifc.get(), pset=pset)
class BIM_OT_enable_editing_aggregate(bpy.types.Operator, Operator):
"""Enable editing aggregation relationship"""
@@ -132,6 +133,7 @@ class BIM_OT_add_aggregate(bpy.types.Operator, tool.Ifc.Operator):
bl_options = {"REGISTER", "UNDO"}
obj: bpy.props.StringProperty()
ifc_class: bpy.props.StringProperty(name="IFC Class", default="IfcElementAssembly")
aggregate_name: bpy.props.StringProperty(name="Name", default="Default_Name")
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
@@ -139,13 +141,15 @@ class BIM_OT_add_aggregate(bpy.types.Operator, tool.Ifc.Operator):
def draw(self, context):
row = self.layout
row.prop(self, "ifc_class")
row = self.layout
row.prop(self, "aggregate_name")
def _execute(self, context):
try:
ifc_class = tool.Ifc.schema().declaration_by_name(self.ifc_class).name()
except:
return
aggregate = self.create_aggregate(context, ifc_class)
aggregate = self.create_aggregate(context, ifc_class, self.aggregate_name)
for obj in context.selected_objects:
element = tool.Ifc.get_entity(obj)
@@ -173,8 +177,8 @@ class BIM_OT_add_aggregate(bpy.types.Operator, tool.Ifc.Operator):
)
core.assign_object(tool.Ifc, tool.Aggregate, tool.Collector, relating_obj=aggregate, related_obj=obj)
def create_aggregate(self, context, ifc_class):
aggregate = bpy.data.objects.new("Assembly", None)
def create_aggregate(self, context, ifc_class, aggregate_name):
aggregate = bpy.data.objects.new(aggregate_name, None)
aggregate.location = context.scene.cursor.location
bpy.ops.bim.assign_class(obj=aggregate.name, ifc_class=ifc_class)
return aggregate
@@ -20,6 +20,7 @@ from bpy.types import Panel
from blenderbim.bim.module.aggregate.data import AggregateData
from blenderbim.bim.module.group.data import GroupsData, ObjectGroupsData
from blenderbim.bim.ifc import IfcStore
import blenderbim.tool as tool
class BIM_PT_aggregate(Panel):
@@ -131,22 +132,29 @@ class BIM_PT_linked_aggregate(Panel):
if not AggregateData.is_loaded:
AggregateData.load()
props = context.active_object.BIMObjectAggregateProperties
obj = context.active_object
element = tool.Ifc.get_entity(obj)
props = obj.BIMObjectAggregateProperties
row = layout.row(align=True)
row.label(text="Advanced Users Only", icon="ERROR")
row = layout.row(align=True)
if type(AggregateData.data['total_linked_aggregate']) is int:
if AggregateData.data['total_linked_aggregate'] > 0:
row.label(text=f"{AggregateData.data['total_linked_aggregate']} Linked Aggregates")
op = row.operator("bim.select_linked_aggregates", text="", icon="OUTLINER_DATA_POINTCLOUD")
op.select_parts = False
op = row.operator("bim.select_linked_aggregates", text="", icon="OUTLINER_OB_POINTCLOUD")
op.select_parts = True
row.operator("bim.refresh_linked_aggregate", text="", icon="FILE_REFRESH")
op = row.operator("bim.break_link_to_other_aggregates", text="", icon="X")
if element.Decomposes:
Number_Linked_Aggregates = AggregateData.data['total_linked_aggregate']
if not Number_Linked_Aggregates:
row.label(text="Not a Linked Aggregate")
else:
row.label(text=f"{Number_Linked_Aggregates} Linked Aggregates")
op = row.operator("bim.object_duplicate_move_linked_aggregate", text="", icon="DUPLICATE")
if type(Number_Linked_Aggregates) is int:
if Number_Linked_Aggregates > 0:
op = row.operator("bim.select_linked_aggregates", text="", icon="OUTLINER_DATA_POINTCLOUD")
op.select_parts = False
op = row.operator("bim.select_linked_aggregates", text="", icon="OUTLINER_OB_POINTCLOUD")
op.select_parts = True
row.operator("bim.refresh_linked_aggregate", text="", icon="FILE_REFRESH")
op = row.operator("bim.break_link_to_other_aggregates", text="", icon="X")
else:
row.label(text="No Linked Aggregates")
row.label(text="Not an Aggregate")
@@ -20,6 +20,7 @@ import bpy
import bmesh
import logging
import shapely
import shapely.ops
import mathutils
import numpy as np
import multiprocessing
@@ -209,6 +209,10 @@ class DisableEditingClassification(bpy.types.Operator):
class RemoveClassification(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.remove_classification"
bl_label = "Remove Classification"
bl_description = (
"The classification and all of its relationships, children references, "
"and relationships between objects and child references will be completely removed from a project"
)
bl_options = {"REGISTER", "UNDO"}
classification: bpy.props.IntProperty()
@@ -53,6 +53,10 @@ class AddContext(bpy.types.Operator, Operator):
class RemoveContext(bpy.types.Operator, Operator):
bl_idname = "bim.remove_context"
bl_label = "Remove Context"
bl_description = (
"Remove representation context. Any representation geometry that is assigned to the context is also removed. "
"If a context is removed, then any subcontexts are also removed"
)
bl_options = {"REGISTER", "UNDO"}
context: bpy.props.IntProperty()
@@ -107,59 +107,88 @@ class CoveringToolUI:
# elif element and bpy.context.selected_objects and element.is_a("IfcSpace"):
# op. = row.operator("bim.add_istance_flooring_from_spaces"):
if (type_material_usage == "IfcMaterialLayerSet" and
not bpy.context.selected_objects):
row = cls.layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="", icon="EVENT_A")
if tool.Ifc.get_entity(collection_obj):
if AuthoringData.data["predefined_type"] == "FLOORING":
op = row.operator("bim.add_instance_flooring_covering_from_cursor")
elif AuthoringData.data["predefined_type"] == "CEILING":
op = row.operator("bim.add_instance_ceiling_covering_from_cursor")
else:
op = row.operator("bim.add_constr_type_instance", text="Add")
op.from_invoke = True
if cls.props.relating_type_id.isnumeric():
op.relating_type_id = int(cls.props.relating_type_id)
else:
op = row.operator("bim.add_constr_type_instance", text="Add")
op.from_invoke = True
if cls.props.relating_type_id.isnumeric():
op.relating_type_id = int(cls.props.relating_type_id)
elif (AuthoringData.data["predefined_type"] == "FLOORING" and
type_material_usage == "IfcMaterialLayerSet" and
element and
bpy.context.selected_objects and
element.is_a("IfcWall")):
row = cls.layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="", icon="EVENT_A")
op = row.operator("bim.add_instance_flooring_coverings_from_walls")
elif (AuthoringData.data["predefined_type"] == "CEILING" and
type_material_usage == "IfcMaterialLayerSet" and
element and
bpy.context.selected_objects and
element.is_a("IfcWall")):
row = cls.layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="", icon="EVENT_A")
op = row.operator("bim.add_instance_ceiling_coverings_from_walls")
elif (element and
bpy.context.selected_objects and
element.is_a("IfcCovering") and
# AuthoringData.data["predefined_type"] == "FLOORING" and
AuthoringData.data["active_material_usage"] == "LAYER3"):
row = cls.layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="", icon="EVENT_G")
op = row.operator("bim.regen_selected_covering_object")
# if (type_material_usage == "IfcMaterialLayerSet" and
# not bpy.context.selected_objects):
# row = cls.layout.row(align=True)
# row.label(text="", icon="EVENT_SHIFT")
# row.label(text="", icon="EVENT_A")
# if tool.Ifc.get_entity(collection_obj):
# if AuthoringData.data["predefined_type"] == "FLOORING":
# op = row.operator("bim.add_instance_flooring_covering_from_cursor")
# elif AuthoringData.data["predefined_type"] == "CEILING":
# op = row.operator("bim.add_instance_ceiling_covering_from_cursor")
# else:
# op = row.operator("bim.add_constr_type_instance", text="Add")
# op.from_invoke = True
# if cls.props.relating_type_id.isnumeric():
# op.relating_type_id = int(cls.props.relating_type_id)
#
# else:
# op = row.operator("bim.add_constr_type_instance", text="Add")
# op.from_invoke = True
# if cls.props.relating_type_id.isnumeric():
# op.relating_type_id = int(cls.props.relating_type_id)
#
# elif (AuthoringData.data["predefined_type"] == "FLOORING" and
# type_material_usage == "IfcMaterialLayerSet" and
# element and
# bpy.context.selected_objects and
# element.is_a("IfcWall")):
# row = cls.layout.row(align=True)
# row.label(text="", icon="EVENT_SHIFT")
# row.label(text="", icon="EVENT_A")
# op = row.operator("bim.add_instance_flooring_coverings_from_walls")
#
# elif (AuthoringData.data["predefined_type"] == "CEILING" and
# type_material_usage == "IfcMaterialLayerSet" and
# element and
# bpy.context.selected_objects and
# element.is_a("IfcWall")):
# row = cls.layout.row(align=True)
# row.label(text="", icon="EVENT_SHIFT")
# row.label(text="", icon="EVENT_A")
# op = row.operator("bim.add_instance_ceiling_coverings_from_walls")
#
# elif (element and
# bpy.context.selected_objects and
# element.is_a("IfcCovering") and
## AuthoringData.data["predefined_type"] == "FLOORING" and
# AuthoringData.data["active_material_usage"] == "LAYER3"):
# row = cls.layout.row(align=True)
# row.label(text="", icon="EVENT_SHIFT")
# row.label(text="", icon="EVENT_G")
# op = row.operator("bim.regen_selected_covering_object")
row = cls.layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="", icon="EVENT_A")
op = row.operator("bim.add_constr_type_instance", text="Add")
row = cls.layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="", icon="EVENT_A")
op = row.operator("bim.add_instance_flooring_covering_from_cursor")
row = cls.layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="", icon="EVENT_A")
op = row.operator("bim.add_instance_ceiling_covering_from_cursor")
row = cls.layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="", icon="EVENT_A")
op = row.operator("bim.add_instance_flooring_coverings_from_walls")
row = cls.layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="", icon="EVENT_A")
op = row.operator("bim.add_instance_ceiling_coverings_from_walls")
row = cls.layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="", icon="EVENT_G")
op = row.operator("bim.regen_selected_covering_object")
# elif AuthoringData.data["predefined_type"] == "CEILING":
# row = cls.layout.row(align=True)
@@ -174,14 +203,14 @@ class CoveringToolUI:
# op.from_invoke = True
# if cls.props.relating_type_id.isnumeric():
# op.relating_type_id = int(cls.props.relating_type_id)
else:
row = cls.layout.row(align=True)
row.label(text="", icon="EVENT_SHIFT")
row.label(text="", icon="EVENT_A")
op = row.operator("bim.add_constr_type_instance", text="Add")
op.from_invoke = True
if cls.props.relating_type_id.isnumeric():
op.relating_type_id = int(cls.props.relating_type_id)
# else:
# row = cls.layout.row(align=True)
# row.label(text="", icon="EVENT_SHIFT")
# row.label(text="", icon="EVENT_A")
# op = row.operator("bim.add_constr_type_instance", text="Add")
# op.from_invoke = True
# if cls.props.relating_type_id.isnumeric():
# op.relating_type_id = int(cls.props.relating_type_id)
@classmethod
def draw_type_selection_interface(cls):
@@ -72,7 +72,7 @@ class ReorderCsvAttribute(bpy.types.Operator):
def execute(self, context):
old = context.scene.CsvProperties.csv_attributes[self.old_index]
new = context.scene.CsvProperties.csv_attributes[self.new_index]
props = ["name", "header", "sort", "group", "varies_value", "summary"]
props = ["name", "header", "sort", "group", "varies_value", "summary", "formatting"]
for prop in props:
value = getattr(new, prop)
setattr(new, prop, getattr(old, prop))
@@ -246,6 +246,7 @@ class ExportIfcCsv(bpy.types.Operator):
if props.format != "csv" and props.should_generate_svg:
schedule_creator = scheduler.Scheduler()
schedule_creator.schedule(self.filepath, tool.Drawing.get_path_with_ext(self.filepath, "svg"))
self.report({"INFO"}, f"Data is exported to {props.format.upper()}.")
return {"FINISHED"}
@@ -281,10 +282,12 @@ class ImportIfcCsv(bpy.types.Operator):
empty=props.empty_value,
bool_true=props.true_value,
bool_false=props.false_value,
concat=props.concat_value
)
if not props.should_load_from_memory:
ifc_file.write(props.csv_ifc_file)
refresh_ui_data()
self.report({"INFO"}, "Data is imported to IFC.")
return {"FINISHED"}
@@ -35,7 +35,6 @@ classes = (
operator.PrintUnusedElementStats,
operator.ProfileImportIFC,
operator.PurgeHdf5Cache,
operator.PurgeIfcLinks,
operator.PurgeUnusedElementsByClass,
operator.RewindInspector,
operator.SelectExpressFile,
@@ -104,10 +104,11 @@ class PrintIfcFile(bpy.types.Operator):
return {"FINISHED"}
class PurgeIfcLinks(bpy.types.Operator):
bl_idname = "bim.purge_ifc_links"
bl_label = "Purge IFC Links"
bl_description = "Purge all definitions and references from the file.\nWarning : Cannot be undone."
class ConvertToBlender(bpy.types.Operator):
bl_idname = "bim.convert_to_blender"
bl_label = "Convert To Blender File"
bl_description = "Removes all IFC data and revert to basic Blender objects.\nWarning : Cannot be undone."
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
for obj in bpy.data.objects:
@@ -124,26 +125,6 @@ class PurgeIfcLinks(bpy.types.Operator):
return {"FINISHED"}
class ConvertToBlender(bpy.types.Operator):
bl_idname = "bim.convert_to_blender"
bl_label = "Convert To Blender File"
bl_description = "Removes all IFC data, and converts the file to a simple Blender file."
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
for o in bpy.data.objects:
if o.type in {"MESH", "EMPTY"}:
o.BIMObjectProperties.ifc_definition_id = 0
if o.data:
o.data.BIMMeshProperties.ifc_definition_id = 0
for m in bpy.data.materials:
m.BIMMaterialProperties.ifc_style_id = False
bpy.context.scene.BIMProperties.ifc_file = ""
IfcStore.purge()
blenderbim.bim.handler.refresh_ui_data()
return {"FINISHED"}
class ValidateIfcFile(bpy.types.Operator):
bl_idname = "bim.validate_ifc_file"
bl_label = "Validate IFC File"
@@ -60,9 +60,6 @@ class BIM_PT_debug(Panel):
row = layout.row()
row.operator("bim.purge_hdf5_cache")
row = layout.row()
row.operator("bim.purge_ifc_links")
row = layout.row()
row.operator("bim.update_representation", text="Manually Save Representation")
@@ -29,6 +29,7 @@ import subprocess
import numpy as np
import multiprocessing
import ifcopenshell
import ifcopenshell.ifcopenshell_wrapper
import ifcopenshell.geom
import ifcopenshell.util.selector
import ifcopenshell.util.representation
@@ -219,11 +220,12 @@ class CreateDrawing(bpy.types.Operator):
def execute(self, context):
self.props = context.scene.DocProperties
active_drawing_id = context.scene.camera.BIMObjectProperties.ifc_definition_id
if self.print_all:
original_drawing_id = self.props.active_drawing_id
original_drawing_id = active_drawing_id
drawings_to_print = [d.ifc_definition_id for d in self.props.drawings if d.is_selected and d.is_drawing]
else:
drawings_to_print = [self.props.active_drawing_id]
drawings_to_print = [active_drawing_id]
for drawing_i, drawing_id in enumerate(drawings_to_print):
self.drawing_index = drawing_i
@@ -1241,12 +1243,14 @@ class AddDrawingToSheet(bpy.types.Operator, Operator):
return
reference = tool.Ifc.run("document.add_reference", information=sheet)
id_attr = "ItemReference" if tool.Ifc.get_schema() == "IFC2X3" else "Identification"
attributes = {
id_attr: str(len([r for r in references if r.Description in ("DRAWING", "SCHEDULE")]) + 1),
"Location": drawing_reference.Location,
"Description": "DRAWING",
}
attributes = tool.Drawing.generate_reference_attributes(
reference,
Identification=str(
len([r for r in references if tool.Drawing.get_reference_description(r) in ("DRAWING", "SCHEDULE")]) + 1
),
Location=drawing_reference.Location,
Description="DRAWING",
)
tool.Ifc.run("document.edit_reference", reference=reference, attributes=attributes)
sheet_builder = sheeter.SheetBuilder()
sheet_builder.data_dir = context.scene.BIMProperties.data_dir
@@ -1314,9 +1318,10 @@ class CreateSheets(bpy.types.Operator, Operator):
has_sheet_reference = False
for reference in tool.Drawing.get_document_references(sheet):
if reference.Description == "SHEET":
reference_description = tool.Drawing.get_reference_description(reference)
if reference_description == "SHEET":
has_sheet_reference = True
elif reference.Description == "RASTER":
elif reference_description == "RASTER":
if reference.Location in raster_references:
raster_references.remove(reference.Location)
else:
@@ -1327,7 +1332,9 @@ class CreateSheets(bpy.types.Operator, Operator):
tool.Ifc.run(
"document.edit_reference",
reference=reference,
attributes={"Location": tool.Ifc.get_relative_uri(svg), "Description": "SHEET"},
attributes=tool.Drawing.generate_reference_attributes(
reference, Location=tool.Ifc.get_relative_uri(svg), Description="SHEET"
),
)
for raster_reference in raster_references:
@@ -1335,7 +1342,9 @@ class CreateSheets(bpy.types.Operator, Operator):
tool.Ifc.run(
"document.edit_reference",
reference=reference,
attributes={"Location": tool.Ifc.get_relative_uri(raster_reference), "Description": "RASTER"},
attributes=tool.Drawing.generate_reference_attributes(
reference, Location=tool.Ifc.get_relative_uri(raster_reference), Description="RASTER"
),
)
svg2pdf_command = context.preferences.addons["blenderbim"].preferences.svg2pdf_command
@@ -1444,13 +1453,19 @@ class ActivateModel(bpy.types.Operator):
CutDecorator.uninstall()
# save current visibility statuses for Views and Types collections
visibility_status: dict[bpy.types.Object, bool] = {}
for col in bpy.data.collections["Views"].children:
for obj in col.objects:
visibility_status[obj] = obj.hide_get()
for obj in bpy.data.collections["Types"].objects:
visibility_status[obj] = obj.hide_get()
if not bpy.app.background:
with context.temp_override(**tool.Blender.get_viewport_context()):
bpy.ops.object.hide_view_clear()
bpy.ops.bim.activate_status_filters()
subcontext = ifcopenshell.util.representation.get_context(tool.Ifc.get(), "Model", "Body", "MODEL_VIEW")
for obj in context.visible_objects:
element = tool.Ifc.get_entity(obj)
if not element:
@@ -1468,6 +1483,11 @@ class ActivateModel(bpy.types.Operator):
is_global=True,
should_sync_changes_first=True,
)
# restore visibility after hide_view_clear()
for obj, hide_status in visibility_status.items():
obj.hide_set(hide_status)
tool.Blender.update_viewport()
return {"FINISHED"}
@@ -1988,12 +2008,14 @@ class AddScheduleToSheet(bpy.types.Operator, Operator):
return
reference = tool.Ifc.run("document.add_reference", information=sheet)
id_attr = "ItemReference" if tool.Ifc.get_schema() == "IFC2X3" else "Identification"
attributes = {
id_attr: str(len([r for r in references if r.Description in ("DRAWING", "SCHEDULE")]) + 1),
"Location": schedule_location,
"Description": "SCHEDULE",
}
attributes = tool.Drawing.generate_reference_attributes(
reference,
Identification=str(
len([r for r in references if tool.Drawing.get_reference_description(r) in ("DRAWING", "SCHEDULE")]) + 1
),
Location=schedule_location,
Description="SCHEDULE",
)
tool.Ifc.run("document.edit_reference", reference=reference, attributes=attributes)
sheet_builder = sheeter.SheetBuilder()
@@ -2042,12 +2064,15 @@ class AddReferenceToSheet(bpy.types.Operator, Operator):
return
reference = tool.Ifc.run("document.add_reference", information=sheet)
id_attr = "ItemReference" if tool.Ifc.get_schema() == "IFC2X3" else "Identification"
attributes = {
id_attr: str(len([r for r in references if r.Description in ("DRAWING", "REFERENCE")]) + 1),
"Location": extref_location,
"Description": "REFERENCE",
}
attributes = tool.Drawing.generate_reference_attributes(
reference,
Identification=str(
len([r for r in references if tool.Drawing.get_reference_description(r) in ("DRAWING", "REFERENCE")])
+ 1
),
Location=extref_location,
Description="REFERENCE",
)
tool.Ifc.run("document.edit_reference", reference=reference, attributes=attributes)
sheet_builder = sheeter.SheetBuilder()
@@ -2392,8 +2417,8 @@ class EditSheet(bpy.types.Operator, Operator):
if sheet.is_a("IfcDocumentInformation"):
self.document_type = "SHEET"
self.name = sheet.Name
self.identification = sheet.Identification
elif sheet.is_a("IfcDocumentReference") and sheet.Description == "TITLEBLOCK":
self.identification = sheet.DocumentId if tool.Ifc.get_schema() == "IFC2X3" else sheet.Identification
elif sheet.is_a("IfcDocumentReference") and tool.Drawing.get_reference_description(sheet) == "TITLEBLOCK":
self.document_type = "TITLEBLOCK"
else:
self.document_type = "EMBEDDED"
@@ -2419,7 +2444,7 @@ class EditSheet(bpy.types.Operator, Operator):
if self.document_type == "SHEET":
core.rename_sheet(tool.Ifc, tool.Drawing, sheet=sheet, identification=self.identification, name=self.name)
elif self.document_type == "EMBEDDED":
core.rename_reference(tool.Ifc, reference=sheet, identification=self.identification)
core.rename_reference(tool.Ifc, tool.Drawing, reference=sheet, identification=self.identification)
elif self.document_type == "TITLEBLOCK":
titleblock = self.props.titleblock
reference = sheet
@@ -41,7 +41,7 @@ class SheetBuilder:
self.data_dir = None
self.scale = "NTS"
def create(self, layout_path, titleblock_name):
def create(self, layout_path: str, titleblock_name: str) -> None:
root = ET.Element("svg")
root.attrib["xmlns"] = "http://www.w3.org/2000/svg"
root.attrib["xmlns:xlink"] = "http://www.w3.org/1999/xlink"
@@ -76,7 +76,12 @@ class SheetBuilder:
with open(layout_path, "w") as f:
f.write(minidom.parseString(ET.tostring(root)).toprettyxml(indent=" "))
def add_drawing(self, reference, drawing, sheet):
def add_drawing(
self,
reference: ifcopenshell.entity_instance,
drawing: ifcopenshell.entity_instance,
sheet: ifcopenshell.entity_instance,
) -> None:
filename = drawing.Name
layout_path = tool.Drawing.get_document_uri(sheet, "LAYOUT")
layout_dir = os.path.dirname(layout_path)
@@ -131,7 +136,7 @@ class SheetBuilder:
)
layout_tree.write(layout_path)
def update_sheet_drawing_sizes(self, sheet):
def update_sheet_drawing_sizes(self, sheet: ifcopenshell.entity_instance) -> None:
ET.register_namespace("", "http://www.w3.org/2000/svg")
layout_path = tool.Drawing.get_document_uri(sheet, "LAYOUT")
@@ -171,7 +176,7 @@ class SheetBuilder:
layout_tree.write(layout_path)
def remove_drawing(self, reference, sheet):
def remove_drawing(self, reference: ifcopenshell.entity_instance, sheet: ifcopenshell.entity_instance) -> None:
ET.register_namespace("", "http://www.w3.org/2000/svg")
layout_path = tool.Drawing.get_document_uri(sheet, "LAYOUT")
@@ -187,7 +192,12 @@ class SheetBuilder:
layout_tree.write(layout_path)
def add_document(self, reference, document, sheet):
def add_document(
self,
reference: ifcopenshell.entity_instance,
document: ifcopenshell.entity_instance,
sheet: ifcopenshell.entity_instance,
) -> None:
view_path = tool.Drawing.get_path_with_ext(tool.Drawing.get_document_uri(document), "svg")
if not os.path.exists(view_path):
tool.Drawing.create_svg_document(document)
@@ -224,7 +234,7 @@ class SheetBuilder:
)
layout_tree.write(layout_path)
def add_view_title(self, x, y, parent, layout_dir):
def add_view_title(self, x: float, y: float, parent: ET.Element, layout_dir: str) -> None:
title_path = os.path.join(layout_dir, "assets", "view-title.svg")
os.makedirs(os.path.dirname(title_path), exist_ok=True)
if not os.path.exists(title_path):
@@ -241,7 +251,7 @@ class SheetBuilder:
title.attrib["width"] = str(self.convert_to_mm(title_root.attrib.get("width")))
title.attrib["height"] = str(self.convert_to_mm(title_root.attrib.get("height")))
def build(self, sheet):
def build(self, sheet: ifcopenshell.entity_instance) -> dict:
self.references = {"SHEET": None, "RASTER": []}
layout_path = tool.Drawing.get_document_uri(sheet, "LAYOUT")
@@ -272,7 +282,7 @@ class SheetBuilder:
return self.references
def build_titleblock(self, root, sheet):
def build_titleblock(self, root: ET.Element, sheet: ifcopenshell.entity_instance) -> None:
titleblock = root.findall('{http://www.w3.org/2000/svg}g[@data-type="titleblock"]')[0]
image = titleblock.findall("{http://www.w3.org/2000/svg}image")[0]
g = self.parse_embedded_svg(image, sheet.get_info())
@@ -285,7 +295,7 @@ class SheetBuilder:
titleblock.append(g)
titleblock.remove(image)
def ensure_drawing_unique_styles(self, svg, drawing_id):
def ensure_drawing_unique_styles(self, svg: ET.Element, drawing_id: int) -> ET.Element:
"""ensures all drawing's classes and ids will be unique for the whole sheet
by adding `drawing_id` based prefix
"""
@@ -313,7 +323,7 @@ class SheetBuilder:
brackets_level -= 1
text += l
def replace_urls(text):
def replace_urls(text: str) -> str:
"""replace urls `url(#marker)` with `url(#prefix-marker)`
since `url(#marker.prefix)` doesn't seem to work
"""
@@ -343,7 +353,7 @@ class SheetBuilder:
return svg
def build_drawings(self, root, sheet):
def build_drawings(self, root: ET.Element, sheet: ifcopenshell.entity_instance):
for view in root.findall('{http://www.w3.org/2000/svg}g[@data-type="drawing"]'):
drawing_id = int(view.attrib["data-id"])
try:
@@ -390,7 +400,7 @@ class SheetBuilder:
for image in images:
view.remove(image)
def build_documents(self, root, sheet):
def build_documents(self, root: ET.Element, sheet: ifcopenshell.entity_instance) -> None:
schedules = root.findall('{http://www.w3.org/2000/svg}g[@data-type="schedule"]')
references = root.findall('{http://www.w3.org/2000/svg}g[@data-type="reference"]')
documents = schedules + references
@@ -427,10 +437,10 @@ class SheetBuilder:
for image in images:
view.remove(image)
def get_href(self, element):
return urllib.parse.unquote(element.attrib.get("{http://www.w3.org/1999/xlink}href")).replace('\\','/')
def get_href(self, element: ET.Element) -> str:
return urllib.parse.unquote(element.attrib.get("{http://www.w3.org/1999/xlink}href")).replace("\\", "/")
def parse_embedded_svg(self, image, data):
def parse_embedded_svg(self, image: ET.Element, data: dict) -> ET.Element:
group = ET.Element("g")
group.attrib["transform"] = "translate({},{})".format(
self.convert_to_mm(image.attrib.get("x")), self.convert_to_mm(image.attrib.get("y"))
@@ -466,7 +476,7 @@ class SheetBuilder:
group.append(child)
return group
def change_titleblock(self, sheet, titleblock_name):
def change_titleblock(self, sheet: ifcopenshell.entity_instance, titleblock_name: str) -> None:
ootb_titleblock_path = os.path.join(self.data_dir, "templates", "titleblocks", titleblock_name + ".svg")
titleblock_path = tool.Drawing.get_default_titleblock_path(titleblock_name)
sheet_path = tool.Drawing.get_document_uri(sheet, "LAYOUT")
@@ -499,7 +509,7 @@ class SheetBuilder:
sheet_tree.write(sheet_path)
def convert_to_mm(self, value):
def convert_to_mm(self, value: str) -> float:
# CSS is what defines these possibilities
# https://www.w3.org/TR/SVG/refs.html#ref-css-values-3
# https://www.w3.org/TR/css-values-3/#absolute-lengths
@@ -520,5 +530,5 @@ class SheetBuilder:
return float(value[0:-2]) * (1 / 96) * 2.54 * 10
return float(value)
def mm_to_px(self, value):
def mm_to_px(self, value: float) -> float:
return (value / 25.4) * 96
@@ -719,14 +719,15 @@ class SvgWriter:
self.svg.text(sheet_id, insert=(text_position[0], text_position[1] + 2.5), class_="ELEVATION", **text_style)
)
def get_reference_and_sheet_id_from_annotation(self, element):
def get_reference_and_sheet_id_from_annotation(self, element: ifcopenshell.entity_instance) -> tuple[str, str]:
reference_id = "-"
sheet_id = "-"
drawing = tool.Drawing.get_annotation_element(element)
reference = tool.Drawing.get_drawing_reference(drawing)
if reference:
for sheet_reference in tool.Ifc.get().by_type("IfcDocumentReference"):
if sheet_reference.Description != "DRAWING" or sheet_reference.Location != reference.Location:
reference_description = tool.Drawing.get_reference_description(sheet_reference)
if reference_description != "DRAWING" or sheet_reference.Location != reference.Location:
continue
sheet = tool.Drawing.get_reference_document(sheet_reference)
if sheet:
@@ -17,6 +17,7 @@
# along with BlenderBIM Add-on. If not, see <http://www.gnu.org/licenses/>.
import bpy
import ifcopenshell.util.element
import blenderbim.tool as tool
import ifcopenshell.util.placement
from mathutils import Vector
@@ -222,7 +223,7 @@ class ConnectionsData:
@classmethod
def is_connection_realization(cls):
element = tool.Ifc.get_entity(bpy.context.active_object)
connections = element.IsConnectionRealization
connections = getattr(element, "IsConnectionRealization", None)
if not connections:
return
@@ -538,7 +538,7 @@ class Helper:
)
position = None
if self.file.schema == "IFC2X3":
position = self.file.createIfcAxis2Placement2D(self.file.createIfcCartesianPoint([0.0, 0.0, 0.0]))
position = self.file.createIfcAxis2Placement2D(self.file.createIfcCartesianPoint([0.0, 0.0]))
curve = self.file.createIfcRectangleProfileDef("AREA", None, position, xdim, ydim)
return {"curve_ucs": curve_ucs, "curve": curve}
@@ -215,6 +215,13 @@ class SwitchRepresentation(bpy.types.Operator, Operator):
disable_opening_subtractions: bpy.props.BoolProperty()
should_switch_all_meshes: bpy.props.BoolProperty()
@classmethod
def poll(cls, context):
if context.active_object.mode == "OBJECT":
return True
cls.poll_message_set("Only available in OBJECT mode - Press TAB in the viewport")
return False
def _execute(self, context):
target_representation = tool.Ifc.get().by_id(self.ifc_definition_id)
target = target_representation.ContextOfItems
@@ -223,6 +230,8 @@ class SwitchRepresentation(bpy.types.Operator, Operator):
element = tool.Ifc.get_entity(obj)
if not element:
continue
if not obj.mode == "OBJECT":
continue
if obj == context.active_object:
representation = target_representation
else:
@@ -538,6 +547,8 @@ class OverrideDelete(bpy.types.Operator):
row.prop(self, "is_batch", text="Enable Faster Deletion")
def _execute(self, context):
start_time = time()
if self.is_batch:
ifcopenshell.util.element.batch_remove_deep2(tool.Ifc.get())
@@ -562,6 +573,11 @@ class OverrideDelete(bpy.types.Operator):
IfcStore.add_transaction_operation(self)
# Required otherwise gizmos are still visible
context.view_layer.objects.active = None
operator_time = time() - start_time
if operator_time > 10:
self.report({"INFO"}, "IFC Delete was finished in {:.2f} seconds".format(operator_time))
return {"FINISHED"}
def rollback(self, data):
@@ -843,7 +859,7 @@ class OverrideDuplicateMove(bpy.types.Operator):
# Recreate decompositions
tool.Root.recreate_decompositions(decomposition_relationships, old_to_new)
OverrideDuplicateMove.handle_linked_aggregates(old_to_new)
OverrideDuplicateMove.remove_linked_aggregate_data(old_to_new)
blenderbim.bim.handler.refresh_ui_data()
return old_to_new
@@ -896,25 +912,21 @@ class OverrideDuplicateMove(bpy.types.Operator):
if entity in old_to_new.keys():
core.remove_connection(tool.Geometry, connection=connection)
@staticmethod
def handle_linked_aggregates(old_to_new):
def remove_linked_aggregate_data(old_to_new):
for old, new in old_to_new.items():
pset = ifcopenshell.util.element.get_pset(new[0], "BBIM_Linked_Aggregate")
if pset:
old_aggregate = ifcopenshell.util.element.get_aggregate(old)
new_aggregate = ifcopenshell.util.element.get_aggregate(new[0])
if old_aggregate == new_aggregate:
parts = ifcopenshell.util.element.get_parts(new_aggregate)
if parts:
index = DuplicateMoveLinkedAggregate.get_max_index(parts)
index += 1
pset = tool.Ifc.get().by_id(pset["id"])
ifcopenshell.api.run(
"pset.edit_pset",
tool.Ifc.get(),
pset=pset,
properties={"Index": index},
)
pset = tool.Ifc.get().by_id(pset["id"])
ifcopenshell.api.run("pset.remove_pset", tool.Ifc.get(), pset=pset)
if new[0].is_a("IfcElementAssembly"):
linked_aggregate_group = [
r.RelatingGroup
for r in getattr(new[0], "HasAssignments", []) or []
if r.is_a("IfcRelAssignsToGroup")
if "BBIM_Linked_Aggregate" in r.RelatingGroup.Name
]
tool.Ifc.run("group.unassign_group", group=linked_aggregate_group[0], product=new[0])
class OverrideDuplicateMoveLinkedMacro(bpy.types.Macro):
@@ -940,6 +952,7 @@ class OverrideDuplicateMoveLinked(bpy.types.Operator):
class DuplicateMoveLinkedAggregateMacro(bpy.types.Macro):
bl_description = "Create a new linked aggregate"
bl_idname = "bim.object_duplicate_move_linked_aggregate_macro"
bl_label = "IFC Duplicate Linked Aggregate"
bl_options = {"REGISTER", "UNDO"}
@@ -974,15 +987,15 @@ class DuplicateMoveLinkedAggregate(bpy.types.Operator):
obj.select_set(True)
parts = ifcopenshell.util.element.get_parts(element)
if parts:
index = DuplicateMoveLinkedAggregate.get_max_index(parts)
index = get_max_index(parts)
add_linked_aggregate_pset(element, index)
index += 1
for part in parts:
if part.is_a("IfcElementAssembly"):
select_objects_and_add_data(part)
else:
add_linked_aggregate_pset(part, index)
index += 1
index = add_linked_aggregate_pset(part, index)
# index += 1
obj = tool.Ifc.get_object(part)
obj.select_set(True)
@@ -999,6 +1012,8 @@ class DuplicateMoveLinkedAggregate(bpy.types.Operator):
pset=pset,
properties={"Index": index},
)
index += 1
else:
pass
@@ -1015,9 +1030,7 @@ class DuplicateMoveLinkedAggregate(bpy.types.Operator):
return
linked_aggregate_group = ifcopenshell.api.run("group.add_group", tool.Ifc.get(), Name=self.group_name)
ifcopenshell.api.run(
"group.assign_group", tool.Ifc.get(), products=[element], group=linked_aggregate_group
)
ifcopenshell.api.run("group.assign_group", tool.Ifc.get(), products=[element], group=linked_aggregate_group)
def custom_incremental_naming_for_element_assembly(old_to_new):
for new in old_to_new.values():
@@ -1042,6 +1055,39 @@ class DuplicateMoveLinkedAggregate(bpy.types.Operator):
split_name = new_obj.name.split(".")
new_obj.name = split_name[0] + "_" + number
def get_max_index(parts):
psets = [ifcopenshell.util.element.get_pset(p, "BBIM_Linked_Aggregate") for p in parts]
index = [i["Index"] for i in psets if i]
if len(index) > 0:
index = max(index)
return index
else:
return 0
def copy_linked_aggregate_data(old_to_new):
for old, new in old_to_new.items():
pset = ifcopenshell.util.element.get_pset(old, "BBIM_Linked_Aggregate")
if pset:
new_pset = ifcopenshell.api.run(
"pset.add_pset", tool.Ifc.get(), product=new[0], name=self.pset_name
)
ifcopenshell.api.run(
"pset.edit_pset",
tool.Ifc.get(),
pset=new_pset,
properties={"Index": pset["Index"]},
)
if new[0].is_a("IfcElementAssembly"):
linked_aggregate_group = [
r.RelatingGroup
for r in getattr(old, "HasAssignments", []) or []
if r.is_a("IfcRelAssignsToGroup")
if "BBIM_Linked_Aggregate" in r.RelatingGroup.Name
]
tool.Ifc.run("group.assign_group", group=linked_aggregate_group[0], products=new)
if len(context.selected_objects) != 1:
return {"FINISHED"}
@@ -1062,27 +1108,16 @@ class DuplicateMoveLinkedAggregate(bpy.types.Operator):
old_to_new = OverrideDuplicateMove.execute_ifc_duplicate_operator(self, context, linked=True)
custom_incremental_naming_for_element_assembly(old_to_new)
tool.Root.recreate_aggregate(old_to_new)
# Recreate aggregate relationship
for old in old_to_new.keys():
if old.is_a("IfcElementAssembly"):
tool.Root.recreate_aggregate(old_to_new)
copy_linked_aggregate_data(old_to_new)
custom_incremental_naming_for_element_assembly(old_to_new)
blenderbim.bim.handler.refresh_ui_data()
return old_to_new
@staticmethod
def get_max_index(parts):
psets = [ifcopenshell.util.element.get_pset(p, "BBIM_Linked_Aggregate") for p in parts]
index = [i["Index"] for i in psets if i]
if len(index) > 0:
index = max(index)
return index
else:
return 0
class RefreshLinkedAggregate(bpy.types.Operator):
bl_idname = "bim.refresh_linked_aggregate"
@@ -1216,6 +1251,22 @@ class RefreshLinkedAggregate(bpy.types.Operator):
return list(set(linked_aggregate_groups)), selected_parents
def get_original_matrix(element, base_instance):
selected_obj = tool.Ifc.get_object(base_instance)
selected_matrix = selected_obj.matrix_world
object_duplicate = tool.Ifc.get_object(element)
duplicate_matrix = object_duplicate.matrix_world.decompose()
return selected_matrix, duplicate_matrix
def set_new_matrix(selected_matrix, duplicate_matrix, old_to_new):
for old, new in old_to_new.items():
new_obj = tool.Ifc.get_object(new[0])
new_base_matrix = Matrix.LocRotScale(*duplicate_matrix)
matrix_diff = Matrix.inverted(selected_matrix) @ new_obj.matrix_world
new_obj_matrix = new_base_matrix @ matrix_diff
new_obj.matrix_world = new_obj_matrix
active_element = tool.Ifc.get_entity(context.active_object)
if not active_element:
self.report({"INFO"}, "Object has no Ifc metadata.")
@@ -1255,10 +1306,7 @@ class RefreshLinkedAggregate(bpy.types.Operator):
element_aggregate = ifcopenshell.util.element.get_aggregate(element)
selected_obj = tool.Ifc.get_object(base_instance)
selected_matrix = selected_obj.matrix_world
object_duplicate = tool.Ifc.get_object(element)
duplicate_matrix = object_duplicate.matrix_world.decompose()
selected_matrix, duplicate_matrix = get_original_matrix(element, base_instance)
original_names = get_original_names(element)
@@ -1269,15 +1317,9 @@ class RefreshLinkedAggregate(bpy.types.Operator):
tool.Ifc.get_object(base_instance).select_set(True)
old_to_new = DuplicateMoveLinkedAggregate.execute_ifc_duplicate_linked_aggregate_operator(
self, context
)
for old, new in old_to_new.items():
new_obj = tool.Ifc.get_object(new[0])
new_base_matrix = Matrix.LocRotScale(*duplicate_matrix)
matrix_diff = Matrix.inverted(selected_matrix) @ new_obj.matrix_world
new_obj_matrix = new_base_matrix @ matrix_diff
new_obj.matrix_world = new_obj_matrix
old_to_new = DuplicateMoveLinkedAggregate.execute_ifc_duplicate_linked_aggregate_operator(self, context)
set_new_matrix(selected_matrix, duplicate_matrix, old_to_new)
for old, new in old_to_new.items():
if element_aggregate and new[0].is_a("IfcElementAssembly"):
@@ -1409,14 +1451,13 @@ class OverridePasteBuffer(bpy.types.Operator):
def execute(self, context):
bpy.ops.view3d.pastebuffer()
if IfcStore.get_file():
for obj in context.selected_objects:
# Pasted objects may come from another Blender session, or even
# from the same session where the original object has since
# been deleted. As the source element may not exist, paste will
# always unlink the element. If you want to duplicate an
# element, use the duplicate commands.
tool.Root.unlink_object(obj)
for obj in context.selected_objects:
# Pasted objects may come from another Blender session, or even
# from the same session where the original object has since
# been deleted. As the source element may not exist, paste will
# always unlink the element. If you want to duplicate an
# element, use the duplicate commands.
tool.Root.unlink_object(obj)
return {"FINISHED"}
@@ -24,6 +24,7 @@ classes = (
operator.AddLayer,
operator.AddListItem,
operator.AddMaterial,
operator.DuplicateMaterial,
operator.AddMaterialSet,
operator.AddProfile,
operator.AssignMaterial,
@@ -19,6 +19,7 @@
import os
import bpy
import ifcopenshell
import ifcopenshell.util.element
import ifcopenshell.util.doc
import ifcopenshell.util.schema
import blenderbim.tool as tool
@@ -166,6 +167,9 @@ class ObjectMaterialData:
cls.data["type_material"] = cls.type_material()
cls.data["material_type"] = cls.material_type()
cls.data["active_material_constituents"] = cls.active_material_constituents()
# after material_name and type_material
cls.data["is_type_material_overridden"] = cls.is_type_material_overridden()
cls.is_loaded = True
@classmethod
@@ -294,8 +298,7 @@ class ObjectMaterialData:
@classmethod
def material_name(cls):
element = tool.Ifc.get_entity(bpy.context.active_object)
material = ifcopenshell.util.element.get_material(element)
material = cls.material
if material:
return getattr(material, "Name", None) or "Unnamed"
@@ -339,3 +342,18 @@ class ObjectMaterialData:
if not cls.material or not material.is_a("IfcMaterialConstituentSet"):
return []
return [m.Name for m in material.MaterialConstituents if m.Name]
@classmethod
def is_type_material_overridden(cls) -> bool:
if not cls.data["type_material"]:
return False
# try to avoid accessing ifc
if cls.data["material_name"] != cls.data["type_material"]:
return True
# in theory material can be overridden by the same material
# so we check occurrence material explicitly
element = tool.Ifc.get_entity(bpy.context.active_object)
occurrence_material = ifcopenshell.util.element.get_material(element, should_inherit=False)
return bool(occurrence_material)
@@ -134,6 +134,19 @@ class AddMaterial(bpy.types.Operator, tool.Ifc.Operator):
material_prop_purge()
class DuplicateMaterial(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.duplicate_material"
bl_label = "Diplicate Material"
bl_options = {"REGISTER", "UNDO"}
material: bpy.props.IntProperty(name="Material ID")
def _execute(self, context):
ifc_file = tool.Ifc.get()
tool.Material.duplicate_material(ifc_file.by_id(self.material))
material_prop_purge()
bpy.ops.bim.load_materials()
class AddMaterialSet(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.add_material_set"
bl_label = "Add Material Set"
@@ -61,6 +61,8 @@ class BIM_PT_materials(Panel):
if self.props.materials and self.props.active_material_index < len(self.props.materials):
material = self.props.materials[self.props.active_material_index]
if material.ifc_definition_id:
op = row.operator("bim.duplicate_material", text="", icon="DUPLICATE")
op.material = material.ifc_definition_id
op = row.operator("bim.select_by_material", text="", icon="RESTRICT_SELECT_OFF")
op.material = material.ifc_definition_id
op = row.operator("bim.enable_editing_material", text="", icon="GREASEPENCIL")
@@ -175,7 +177,13 @@ class BIM_PT_object_material(Panel):
if ObjectMaterialData.data["type_material"]:
row = self.layout.row(align=True)
row.label(text="Inherited Material: " + ObjectMaterialData.data["type_material"], icon="CON_CHILDOF")
if ObjectMaterialData.data["is_type_material_overridden"]:
row.label(
text=f"Inherited Material Is Occurrence Overridden",
icon="CON_CHILDOF",
)
else:
row.label(text="Inherited Material: " + ObjectMaterialData.data["type_material"], icon="CON_CHILDOF")
if ObjectMaterialData.data["material_class"]:
return self.draw_material_ui()
@@ -32,7 +32,9 @@ class AddInstanceFlooringCoveringFromCursor(bpy.types.Operator, tool.Ifc.Operato
def poll(cls, context):
collection = context.view_layer.active_layer_collection.collection
collection_obj = collection.BIMCollectionProperties.obj
return tool.Ifc.get_entity(collection_obj)
relating_type_id = int(bpy.data.scenes["Scene"].BIMModelProperties.relating_type_id)
relating_type = ifcopenshell.util.element.get_predefined_type(tool.Ifc.get().by_id(relating_type_id))
return tool.Ifc.get_entity(collection_obj) and relating_type == "FLOORING"
def _execute(self, context):
@@ -61,7 +63,9 @@ class AddInstanceCeilingCoveringFromCursor(bpy.types.Operator, tool.Ifc.Operator
def poll(cls, context):
collection = context.view_layer.active_layer_collection.collection
collection_obj = collection.BIMCollectionProperties.obj
return tool.Ifc.get_entity(collection_obj)
relating_type_id = int(bpy.data.scenes["Scene"].BIMModelProperties.relating_type_id)
relating_type = ifcopenshell.util.element.get_predefined_type(tool.Ifc.get().by_id(relating_type_id))
return tool.Ifc.get_entity(collection_obj) and relating_type == "CEILING"
def _execute(self, context):
@@ -116,9 +120,11 @@ class AddInstanceFlooringCoveringsFromWalls(bpy.types.Operator, tool.Ifc.Operato
def poll(cls, context):
active_obj = bpy.context.active_object
element = tool.Ifc.get_entity(active_obj)
relating_type_id = int(bpy.data.scenes["Scene"].BIMModelProperties.relating_type_id)
relating_type = ifcopenshell.util.element.get_predefined_type(tool.Ifc.get().by_id(relating_type_id))
if element:
if element.is_a("IfcWall") and tool.Model.get_usage_type(element) == "LAYER2":
return context.selected_objects
return context.selected_objects and relating_type == "FLOORING"
def _execute(self, context):
# This only works based on a 2D plan only considering the standard
@@ -147,7 +153,7 @@ class AddInstanceFlooringCoveringsFromWalls(bpy.types.Operator, tool.Ifc.Operato
class AddInstanceCeilingCoveringsFromWalls(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.add_instance_ceiling_coverings_from_walls"
bl_label = "Add Ceilings From Walls"
bl_label = "Add Ceiling From Walls"
bl_options = {"REGISTER", "UNDO"}
bl_description = "Add instance ceiling coverings from selected walls. The active object must be a wall and layered vertically"
@@ -155,9 +161,11 @@ class AddInstanceCeilingCoveringsFromWalls(bpy.types.Operator, tool.Ifc.Operator
def poll(cls, context):
active_obj = bpy.context.active_object
element = tool.Ifc.get_entity(active_obj)
relating_type_id = int(bpy.data.scenes["Scene"].BIMModelProperties.relating_type_id)
relating_type = ifcopenshell.util.element.get_predefined_type(tool.Ifc.get().by_id(relating_type_id))
if element:
if element.is_a("IfcWall") and tool.Model.get_usage_type(element) == "LAYER2":
return context.selected_objects
return context.selected_objects and relating_type == "CEILING"
def _execute(self, context):
# This only works based on a 2D plan only considering the standard
@@ -39,6 +39,7 @@ from mathutils import Vector, Matrix
from bpy_extras.object_utils import AddObjectHelper
from . import prop
import json
from typing import Any, Union
class EnableAddType(bpy.types.Operator, tool.Ifc.Operator):
@@ -511,7 +512,7 @@ def regenerate_profile_usage(usecase_path, ifc_file, settings):
)
def ensure_material_assigned(usecase_path, ifc_file, settings):
def ensure_material_assigned(usecase_path: str, ifc_file: ifcopenshell.file, settings: dict[str, Any]) -> None:
if usecase_path == "material.assign_material":
if not settings.get("material", None):
return
@@ -524,53 +525,76 @@ def ensure_material_assigned(usecase_path, ifc_file, settings):
]:
elements.extend(rel.RelatedObjects)
for element in elements:
obj = IfcStore.get_element(element.GlobalId)
if not obj or not obj.data:
continue
element_material = ifcopenshell.util.element.get_material(element)
material = [m for m in ifc_file.traverse(element_material) if m.is_a("IfcMaterial")]
object_material_ids = [
om.BIMObjectProperties.ifc_definition_id
for om in obj.data.materials
if om is not None and om.BIMObjectProperties.ifc_definition_id
]
if material and material[0].id() in object_material_ids:
continue
if len(obj.data.materials) == 1:
obj.data.materials.clear()
if not material:
continue
obj.data.materials.append(IfcStore.get_element(material[0].id()))
update_blender_ifc_materials(elements)
def ensure_material_unassigned(usecase_path, ifc_file, settings):
def ensure_material_unassigned(usecase_path: str, ifc_file: ifcopenshell.file, settings: dict[str, Any]) -> None:
elements = settings["products"]
if elements[0].is_a("IfcElementType"):
elements.extend(ifcopenshell.util.element.get_types(elements[0]))
update_blender_ifc_materials(elements)
def update_blender_ifc_materials(elements: list[ifcopenshell.entity_instance]) -> None:
"""update mesh blender materials that have ifc material connected to them
by replacing them with `blender_material`"""
# since different elements can share meshes (e.g. occurrecnes without openings)
# we need to make sure not to affect them accidentally
meshes_users: dict[bpy.types.Mesh, set[bpy.types.Object]] = dict()
for obj in bpy.data.objects:
if not obj.data:
continue
meshes_users.setdefault(obj.data, set()).add(obj)
objects: set[bpy.types.Object] = set()
for element in elements:
obj = tool.Ifc.get_object(element)
obj: bpy.types.Object = tool.Ifc.get_object(element)
if not obj or not obj.data:
continue
element_material = ifcopenshell.util.element.get_material(element)
if element_material:
objects.add(obj)
meshes: set[bpy.types.Mesh] = {obj.data for obj in objects}
for mesh in meshes:
mesh_users = meshes_users[mesh]
if not mesh_users.issubset(objects):
continue
to_remove = []
for i, slot in enumerate(obj.material_slots):
if not slot.material:
# NOTE: we need `obj` as removing materials and appending them to `mesh.materials`
# will mess up mesh faces material indices
# NOTE: we make an assumption here that all mesh users
# have the same material - they either inherit it from the type
# or type doesn't have a material.
#
# If we add option to UI to add materials overriding type materials
# then this assumption won't be safe anymore
obj = next(iter(mesh_users))
element = tool.Ifc.get_entity(obj)
current_material = ifcopenshell.util.element.get_material(element)
if current_material:
current_material = tool.Ifc.get_object(current_material)
material_replaced = False
for material_slot in obj.material_slots:
material = material_slot.material
if material is None:
continue
material = tool.Ifc.get_entity(slot.material)
if material:
to_remove.append(i)
total_removed = 0
for i in to_remove:
obj.active_material_index = i - total_removed
with bpy.context.temp_override(object=obj):
bpy.ops.object.material_slot_remove()
total_removed += 1
ifc_material = tool.Ifc.get_entity(material)
# it's blender material for style, so ignore it
if not ifc_material:
continue
if ifc_material == current_material:
continue
material_slot.material = current_material
material_replaced = True
if not material_replaced and current_material:
mesh.materials.append(current_material)
# clear empty slots
for i, material in reversed(list(enumerate(mesh.materials[:]))):
if material is None:
mesh.materials.pop(index=i)
@@ -27,7 +27,7 @@ import blenderbim.core.type
class GenerateSpace(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.generate_space"
bl_label = "Generate Space"
bl_label = "Generate Space from Cursor"
bl_options = {"REGISTER"}
bl_description = (
"Create a space from the cursor position. "
@@ -35,30 +35,34 @@ class GenerateSpace(bpy.types.Operator, tool.Ifc.Operator):
"select the right space collection and run the operator"
)
@classmethod
def poll(cls, context):
collection = context.view_layer.active_layer_collection.collection
collection_obj = collection.BIMCollectionProperties.obj
active_obj = context.active_object
element = tool.Ifc.get_entity(active_obj)
return tool.Ifc.get_entity(collection_obj) and not element.is_a("IfcWall")
# @classmethod
# def poll(cls, context):
# print(context)
# collection = context.view_layer.active_layer_collection.collection
# collection_obj = collection.BIMCollectionProperties.obj
# active_obj = context.active_object
# element = tool.Ifc.get_entity(active_obj)
# return tool.Ifc.get_entity(collection_obj) and not element.is_a("IfcWall")
def _execute(self, context):
# This works as a 2.5 extruded polygon based on a cutting plane. Note
# that rooms exclude walls (i.e. not to wall midpoint or exterior /
# exterior edge.
def msg(self, context):
self.layout.label(text="NO ACTIVE STOREY")
def msg_no_collection(self, context):
self.layout.label(text="NO ACTIVE COLLECTION. PLEASE SELECT A SPATIAL COLLECTION OBJECT OR A WALL")
def msg_no_active_storey(self, context):
self.layout.label(text="NO ACTIVE STOREY. PLEASE SELECT A SPATIAL COLLECTION OBJECT")
collection = context.view_layer.active_layer_collection.collection
collection_obj = collection.BIMCollectionProperties.obj
if not collection_obj:
context.window_manager.popup_menu(msg, title="Error", icon="ERROR")
context.window_manager.popup_menu(msg_no_collection, title="Error", icon="ERROR")
return
spatial_element = tool.Ifc.get_entity(collection_obj)
if not spatial_element:
context.window_manager.popup_menu(msg, title="Error", icon="ERROR")
if not spatial_element or not spatial_element.is_a("IfcBuildingStorey"):
context.window_manager.popup_menu(msg_no_active_storey, title="Error", icon="ERROR")
return
core.generate_space(tool.Ifc, tool.Spatial, tool.Model, tool.Type)
@@ -70,12 +74,12 @@ class GenerateSpacesFromWalls(bpy.types.Operator, tool.Ifc.Operator):
bl_options = {"REGISTER", "UNDO"}
bl_description = "Generate spaces from selected walls. The active object must be a wall"
@classmethod
def poll(cls, context):
active_obj = context.active_object
element = tool.Ifc.get_entity(active_obj)
if element:
return context.selected_objects and element.is_a("IfcWall")
# @classmethod
# def poll(cls, context):
# active_obj = context.active_object
# element = tool.Ifc.get_entity(active_obj)
# if element:
# return context.selected_objects and element.is_a("IfcWall")
def _execute(self, context):
# This only works based on a 2D plan only considering the standard
@@ -87,19 +91,30 @@ class GenerateSpacesFromWalls(bpy.types.Operator, tool.Ifc.Operator):
element = tool.Ifc.get_entity(active_obj)
container = tool.Spatial.get_container(element)
def msg_no_active_object(self, context):
self.layout.label(text="No active object. Please select a wall")
def msg_no_active_wall(self, context):
self.layout.label(text="The active object is not a wall. Please select a wall.")
def msg_no_container(self, context):
self.layout.label(text="The wall is not contained. Please the selected wall in a building container")
def msg_no_selected_objects(self, context):
self.layout.label(text="No selected objects found. Please select walls.")
if not active_obj:
self.report({"ERROR"}, "No active object. Please select a wall")
context.window_manager.popup_menu(msg_no_active_object, title="Error", icon="ERROR")
return
element = tool.Ifc.get_entity(active_obj)
if element and not element.is_a("IfcWall"):
return self.report({"ERROR"}, "The active object is not a wall. Please select a wall.")
context.window_manager.popup_menu(msg_no_active_wall, title="Error", icon="ERROR")
return
if not container:
self.report({"ERROR"}, "The wall is not contained.")
context.window_manager.popup_menu(msg_no_container, title="Error", icon="ERROR")
return
if not context.selected_objects:
self.report({"ERROR"}, "No selected objects found. Please select walls.")
context.window_manager.popup_menu(msg_no_selected_objects, title="Error", icon="ERROR")
return
core.generate_spaces_from_walls(tool.Ifc, tool.Spatial, tool.Collector)
@@ -56,8 +56,11 @@ class LaunchTypeManager(bpy.types.Operator):
ifc_class = props.ifc_class or AuthoringData.data["ifc_element_type"]
else:
ifc_class = AuthoringData.data["ifc_element_type"]
props.type_class = ifc_class
bpy.ops.bim.load_type_thumbnails(ifc_class=ifc_class, offset=0, limit=9)
# will be None if project has no types
if ifc_class is not None:
props.type_class = ifc_class
bpy.ops.bim.load_type_thumbnails(ifc_class=ifc_class, offset=0, limit=9)
return context.window_manager.invoke_popup(self, width=550)
def draw(self, context):
@@ -378,6 +378,7 @@ class BimToolUI:
op.depth = cls.props.extrusion_depth
add_layout_hotkey_operator(cls.layout, "Extend", "S_E", "")
add_layout_hotkey_operator(cls.layout, "Flip", "S_F", bpy.ops.bim.flip_object.__doc__)
if AuthoringData.data["active_class"] in (
"IfcCableCarrierSegment",
@@ -385,8 +386,8 @@ class BimToolUI:
"IfcDuctSegment",
"IfcPipeSegment",
):
add_layout_hotkey_operator(cls.layout, "Add Fitting", "S_F", "")
add_layout_hotkey_operator(cls.layout, "Add Fitting", "S_Y", "")
if context.region.type != "TOOL_HEADER":
cls.layout.operator("bim.mep_add_bend")
cls.layout.operator("bim.mep_add_transition")
@@ -394,7 +395,6 @@ class BimToolUI:
else:
add_layout_hotkey_operator(cls.layout, "Edit Axis", "A_E", "")
add_layout_hotkey_operator(cls.layout, "Flip", "S_F", bpy.ops.bim.flip_object.__doc__)
add_layout_hotkey_operator(cls.layout, "Butt", "S_T", "")
add_layout_hotkey_operator(cls.layout, "Mitre", "S_Y", "")
add_layout_hotkey_operator(cls.layout, "Rotate 90", "S_R", bpy.ops.bim.rotate_90.__doc__)
@@ -719,10 +719,9 @@ class Hotkey(bpy.types.Operator, tool.Ifc.Operator):
bpy.ops.bim.flip_wall()
elif self.active_class in ("IfcWindow", "IfcWindowStandardCase", "IfcDoor", "IfcDoorStandardCase"):
bpy.ops.bim.flip_fill()
elif self.active_class in ("IfcBeam", "IfcColumn"):
elif self.active_material_usage == "PROFILE":
bpy.ops.bim.flip_object(flip_local_axes="XZ")
elif self.active_class in ("IfcDuctSegment", "IfcPipeSegment", "IfcCableCarrierSegment", "IfcCableSegment"):
bpy.ops.bim.fit_flow_segments()
def hotkey_S_G(self):
obj = bpy.context.active_object
@@ -808,9 +807,12 @@ class Hotkey(bpy.types.Operator, tool.Ifc.Operator):
return
if self.active_material_usage == "LAYER2":
bpy.ops.bim.join_wall(join_type="V")
elif self.active_class in ("IfcDuctSegment", "IfcPipeSegment", "IfcCableCarrierSegment", "IfcCableSegment"):
bpy.ops.bim.fit_flow_segments()
elif self.active_material_usage == "PROFILE":
bpy.ops.bim.extend_profile(join_type="V")
def hotkey_S_B(self):
bpy.ops.bim.add_boundary()
@@ -21,6 +21,7 @@ from . import ui, prop, operator, data
classes = (
operator.AddProfileDef,
operator.DuplicateProfileDef,
operator.DisableEditingArbitraryProfile,
operator.DisableEditingProfile,
operator.DisableProfileEditingUI,
@@ -66,9 +66,15 @@ class RemoveProfileDef(bpy.types.Operator, tool.Ifc.Operator):
profile: bpy.props.IntProperty()
def _execute(self, context):
props = context.scene.BIMProfileProperties
current_index = props.active_profile_index
ifcopenshell.api.run("profile.remove_profile", tool.Ifc.get(), profile=tool.Ifc.get().by_id(self.profile))
bpy.ops.bim.load_profiles()
# preserve selected index if possible
if props.profiles:
props.active_profile_index = min(current_index, len(props.profiles) - 1)
class EnableEditingProfile(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.enable_editing_profile"
@@ -126,6 +132,27 @@ class AddProfileDef(bpy.types.Operator, tool.Ifc.Operator):
bpy.ops.bim.load_profiles()
class DuplicateProfileDef(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.duplicate_profile_def"
bl_label = "Duplicate Profile"
bl_options = {"REGISTER", "UNDO"}
@classmethod
def poll(cls, context):
props = context.scene.BIMProfileProperties
if len(props.profiles) > props.active_profile_index:
return True
cls.poll_message_set("No profile selected to duplicate.")
return False
def _execute(self, context):
props = context.scene.BIMProfileProperties
ifc_file = tool.Ifc.get()
profile = ifc_file.by_id(props.profiles[props.active_profile_index].ifc_definition_id)
tool.Profile.duplicate_profile(profile)
bpy.ops.bim.load_profiles()
class EnableEditingArbitraryProfile(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.enable_editing_arbitrary_profile"
bl_label = "Enable Editing Arbitrary Profile"
@@ -70,6 +70,7 @@ class BIM_PT_profiles(Panel):
row = self.layout.row(align=True)
row.prop(self.props, "profile_classes", text="")
row.operator("bim.add_profile_def", text="", icon="ADD")
row.operator("bim.duplicate_profile_def", icon="DUPLICATE", text="")
self.layout.template_list(
"BIM_UL_profiles",
@@ -47,6 +47,7 @@ from mathutils import Vector, Matrix
from bpy.app.handlers import persistent
from blenderbim.bim.module.project.data import LinksData
from blenderbim.bim.module.project.decorator import ProjectDecorator, ClippingPlaneDecorator
from typing import Union
class NewProject(bpy.types.Operator):
@@ -301,7 +302,7 @@ class AssignLibraryDeclaration(bpy.types.Operator):
ifcopenshell.api.run(
"project.assign_declaration",
self.file,
definition=self.file.by_id(self.definition),
definitions=[self.file.by_id(self.definition)],
relating_context=self.file.by_type("IfcProjectLibrary")[0],
)
element_name = self.props.active_library_element
@@ -337,7 +338,7 @@ class UnassignLibraryDeclaration(bpy.types.Operator):
ifcopenshell.api.run(
"project.unassign_declaration",
self.file,
definition=self.file.by_id(self.definition),
definitions=[self.file.by_id(self.definition)],
relating_context=self.file.by_type("IfcProjectLibrary")[0],
)
element_name = self.props.active_library_element
@@ -867,7 +868,16 @@ class LinkIfc(bpy.types.Operator):
except:
pass # Perhaps on another drive or something
new.name = filepath
bpy.ops.bim.load_link(filepath=filepath, false_origin=self.false_origin)
status = bpy.ops.bim.load_link(filepath=filepath, false_origin=self.false_origin)
if status == {"CANCELLED"}:
error_msg = (
f'Error processing IFC file "{self.filepath}" '
"was critical and blend file either wasn't saved or wasn't updated. "
"See logs above in system console for details."
)
print(error_msg)
self.report({"ERROR"}, error_msg)
return {"FINISHED"}
print(f"Finished linking {len(files)} IFCs", time.time() - start)
return {"FINISHED"}
@@ -946,10 +956,12 @@ class LoadLink(bpy.types.Operator):
if self.filepath.lower().endswith(".blend"):
self.link_blend(filepath)
elif self.filepath.lower().endswith(".ifc"):
self.link_ifc()
status = self.link_ifc()
if status:
return status
return {"FINISHED"}
def link_blend(self, filepath):
def link_blend(self, filepath: str) -> None:
with bpy.data.libraries.load(filepath, link=True) as (data_from, data_to):
data_to.scenes = data_from.scenes
for scene in bpy.data.scenes:
@@ -962,7 +974,7 @@ class LoadLink(bpy.types.Operator):
link = bpy.context.scene.BIMProjectProperties.links.get(self.filepath)
link.is_loaded = True
def link_ifc(self):
def link_ifc(self) -> Union[set[str], None]:
blend_filepath = self.filepath + ".cache.blend"
h5_filepath = self.filepath + ".cache.h5"
@@ -982,11 +994,14 @@ except Exception as e:
exit(1)
"""
t = time.time()
with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as temp_file:
temp_file.write(code)
run = subprocess.run([bpy.app.binary_path, "-b", "--python", temp_file.name, "--python-exit-code", "1"])
if run.returncode == 1:
print("An error occurred while processing your IFC.")
if not os.path.exists(blend_filepath) or os.stat(blend_filepath).st_mtime < t:
return {"CANCELLED"}
self.link_blend(blend_filepath)
@@ -30,6 +30,7 @@ classes = (
operator.DisableAddingPresentationStyle,
operator.DisableEditingStyle,
operator.DisableEditingStyles,
operator.DuplicateStyle,
operator.EditStyle,
operator.EditSurfaceStyle,
operator.EnableAddingPresentationStyle,
@@ -23,6 +23,7 @@ import blenderbim.bim.handler
import blenderbim.tool as tool
import blenderbim.core.style as core
import ifcopenshell.util.representation
from blenderbim.bim.module.style.prop import switch_shading
from pathlib import Path
from mathutils import Vector
@@ -126,6 +127,10 @@ class DisableEditingStyle(bpy.types.Operator, tool.Ifc.Operator):
tool.Style.reload_material_from_ifc(material)
props.is_editing_style = 0
# restore selected style type
material = tool.Ifc.get_object(style)
material.BIMStyleProperties.active_style_type = material.BIMStyleProperties.active_style_type
class EditStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.edit_style"
@@ -246,14 +251,15 @@ class BrowseExternalStyle(bpy.types.Operator):
)
def invoke(self, context, event):
external_style = None
style_elements = None
if self.active_surface_style_id:
style = tool.Ifc.get().by_id(self.active_surface_style_id)
external_style = tool.Style.get_style_elements(style).get("IfcExternallyDefinedSurfaceStyle", None)
style_elements = tool.Style.get_style_elements(style)
# automatically select previously selected external style in file browser
# if it exists in the file
if external_style and self.filepath == "":
if style_elements and self.filepath == "" and tool.Style.has_blender_external_style(style_elements):
external_style = style_elements["IfcExternallyDefinedSurfaceStyle"]
style_path = Path(tool.Ifc.resolve_uri(external_style.Location))
self.directory = str(style_path.parent)
self.filepath = str(style_path)
@@ -310,6 +316,9 @@ class BrowseExternalStyle(bpy.types.Operator):
attributes["Location"].string_value = filepath
attributes["Identification"].string_value = f"{self.data_block_type}/{self.data_block}"
attributes["Name"].string_value = self.data_block
style = tool.Ifc.get().by_id(self.active_surface_style_id)
bpy.ops.bim.activate_external_style(material_name=tool.Ifc.get_object(style).name)
return {"FINISHED"}
@@ -325,14 +334,23 @@ class ActivateExternalStyle(bpy.types.Operator, tool.Ifc.Operator):
material = context.active_object.active_material
else:
material = bpy.data.materials[self.material_name]
external_style = tool.Style.get_style_elements(material)["IfcExternallyDefinedSurfaceStyle"]
data_block_type, data_block = external_style.Identification.split("/")
style_path = Path(tool.Ifc.resolve_uri(external_style.Location))
props = context.scene.BIMStylesProperties
if props.is_editing:
location = props.external_style_attributes["Location"].string_value
identification = props.external_style_attributes["Identification"].string_value
else:
external_style = tool.Style.get_style_elements(material)["IfcExternallyDefinedSurfaceStyle"]
location = external_style.Location
identification = external_style.Identification
data_block_type, data_block = identification.split("/")
style_path = Path(tool.Ifc.resolve_uri(location))
if style_path.suffix != ".blend":
self.report(
{"ERROR"},
f"Error loading external style for \"{material.name}\" - only Blender external styles are supported",
f'Error loading external style for "{material.name}" - only Blender external styles are supported',
)
return {"CANCELLED"}
@@ -493,6 +511,22 @@ class EnableAddingPresentationStyle(bpy.types.Operator, tool.Ifc.Operator):
props.is_adding = True
class DuplicateStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.duplicate_style"
bl_label = "Duplicate Style"
bl_options = {"REGISTER", "UNDO"}
style: bpy.props.IntProperty(name="Style ID")
def _execute(self, context):
style_type = context.scene.BIMStylesProperties.style_type
ifc_file = tool.Ifc.get()
style = ifc_file.by_id(self.style)
tool.Style.duplicate_style(style)
bpy.ops.bim.disable_editing_styles()
bpy.ops.bim.load_styles(style_type=style_type)
class DisableAddingPresentationStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.disable_adding_presentation_style"
bl_label = "Disable Add Presentation Style"
@@ -571,7 +605,8 @@ class EnableEditingSurfaceStyle(bpy.types.Operator, tool.Ifc.Operator):
props.is_editing_class = self.ifc_class
tool.Style.set_surface_style_props()
surface_style = tool.Style.get_style_elements(style).get(self.ifc_class, None)
style_elements = tool.Style.get_style_elements(style)
surface_style = style_elements.get(self.ifc_class, None)
attributes = tool.Style.get_style_ui_props_attributes(self.ifc_class)
# lighting style require special handling since Attribute doesn't support colors
@@ -591,6 +626,17 @@ class EnableEditingSurfaceStyle(bpy.types.Operator, tool.Ifc.Operator):
attributes.clear()
blenderbim.bim.helper.import_attributes2(surface_style or self.ifc_class, attributes, callback)
material = tool.Ifc.get_object(style)
active_style_type = material.BIMStyleProperties.active_style_type
if self.ifc_class == "IfcExternallyDefinedSurfaceStyle" and active_style_type != "External":
if tool.Style.has_blender_external_style(style_elements):
switch_shading(material, "External")
elif (
self.ifc_class in ("IfcSurfaceStyleShading", "IfcSurfaceStyleRendering", "IfcSurfaceStyleWithTextures")
and active_style_type != "Shading"
):
switch_shading(material, "Shading")
class EditSurfaceStyle(bpy.types.Operator, tool.Ifc.Operator):
bl_idname = "bim.edit_surface_style"
@@ -615,6 +661,10 @@ class EditSurfaceStyle(bpy.types.Operator, tool.Ifc.Operator):
self.props.is_editing_style = 0
core.load_styles(tool.Style, style_type=self.props.style_type)
# restore selected style type
material = tool.Ifc.get_object(self.style)
material.BIMStyleProperties.active_style_type = material.BIMStyleProperties.active_style_type
def edit_existing_style(self):
material = tool.Ifc.get_object(self.style)
if self.surface_style.is_a() == "IfcSurfaceStyleShading":
@@ -33,6 +33,8 @@ from bpy.props import (
)
import gettext
from typing import Literal
_ = gettext.gettext
@@ -251,19 +253,15 @@ class BIMStylesProperties(PropertyGroup):
)
def update_shading_style(self, context):
blender_material = self.id_data
style_elements = tool.Style.get_style_elements(blender_material)
if self.active_style_type == "External":
if tool.Style.has_blender_external_style(style_elements):
try:
bpy.ops.bim.activate_external_style(material_name=blender_material.name)
except RuntimeError as error:
if str(error).startswith("Error: Error loading external style for "):
return
raise error
elif self.active_style_type == "Shading":
def switch_shading(blender_material: bpy.types.Material, style_type: Literal["External", "Shading"]) -> None:
if style_type == "External":
try:
bpy.ops.bim.activate_external_style(material_name=blender_material.name)
except RuntimeError as error:
if str(error).startswith("Error: Error loading external style for "):
return
raise error
elif style_type == "Shading":
style_elements = tool.Style.get_style_elements(blender_material)
rendering_style = None
texture_style = None
@@ -279,6 +277,16 @@ def update_shading_style(self, context):
if rendering_style and texture_style:
tool.Loader.create_surface_style_with_textures(blender_material, rendering_style, texture_style)
def update_shading_style(self, context):
blender_material = self.id_data
style_elements = tool.Style.get_style_elements(blender_material)
if self.active_style_type == "External":
if tool.Style.has_blender_external_style(style_elements):
switch_shading(blender_material, self.active_style_type)
elif self.active_style_type == "Shading":
switch_shading(blender_material, self.active_style_type)
tool.Style.record_shading(blender_material)
@@ -44,19 +44,33 @@ class BIM_PT_styles(Panel):
self.props = context.scene.BIMStylesProperties
if self.props.is_editing:
row = self.layout.row(align=True)
row.label(text="{} {}s".format(len(self.props.styles), self.props.style_type), icon="SHADING_RENDERED")
if not self.props.is_adding:
row.operator("bim.enable_adding_presentation_style", text="", icon="ADD")
row.operator("bim.disable_editing_styles", text="", icon="CANCEL")
else:
if not self.props.is_editing:
row = self.layout.row(align=True)
row.label(text="{} Styles".format(StylesData.data["total_styles"]), icon="SHADING_RENDERED")
blenderbim.bim.helper.prop_with_search(row, self.props, "style_type", text="")
row.operator("bim.load_styles", text="", icon="IMPORT").style_type = self.props.style_type
return
active_style = self.props.styles and self.props.active_style_index < len(self.props.styles)
row = self.layout.row(align=True)
row.label(text="{} {}s".format(len(self.props.styles), self.props.style_type), icon="SHADING_RENDERED")
row.operator("bim.disable_editing_styles", text="", icon="CANCEL")
row = self.layout.row(align=True)
row.alignment = "RIGHT"
if not self.props.is_adding:
row.operator("bim.enable_adding_presentation_style", text="", icon="ADD")
if active_style:
style = self.props.styles[self.props.active_style_index]
material_name = StylesData.data["styles_to_blender_material_names"][self.props.active_style_index]
material = bpy.data.materials[material_name]
row.operator("bim.duplicate_style", text="", icon="DUPLICATE").style = style.ifc_definition_id
row.operator("bim.select_by_style", text="", icon="RESTRICT_SELECT_OFF").style = style.ifc_definition_id
op = row.operator("bim.enable_editing_style", text="", icon="GREASEPENCIL")
op.style = style.ifc_definition_id
row.operator("bim.remove_style", text="", icon="X").style = style.ifc_definition_id
self.layout.template_list("BIM_UL_styles", "", self.props, "styles", self.props, "active_style_index")
# adding a new IfcSurfaceStyle
@@ -77,17 +91,7 @@ class BIM_PT_styles(Panel):
row.operator("bim.disable_adding_presentation_style", text="", icon="CANCEL")
# style ui tools
if self.props.styles and self.props.active_style_index < len(self.props.styles):
row = self.layout.row(align=True)
style = self.props.styles[self.props.active_style_index]
material_name = StylesData.data["styles_to_blender_material_names"][self.props.active_style_index]
material = bpy.data.materials[material_name]
op = row.operator("bim.enable_editing_style", text="Edit Style", icon="GREASEPENCIL")
op.style = style.ifc_definition_id
row.operator("bim.select_by_style", text="", icon="RESTRICT_SELECT_OFF").style = style.ifc_definition_id
row.operator("bim.remove_style", text="", icon="X").style = style.ifc_definition_id
if active_style:
row = self.layout.row(align=True)
row.prop(material.BIMStyleProperties, "active_style_type", icon="SHADING_RENDERED", text="")
op = row.operator("bim.update_current_style", icon="FILE_REFRESH", text="")
@@ -146,23 +146,51 @@ class SelectType(bpy.types.Operator):
relating_type: bpy.props.IntProperty()
def execute(self, context):
element = tool.Ifc.get().by_id(self.relating_type)
obj = tool.Ifc.get_object(element)
if obj:
try:
tool.Blender.select_and_activate_single_object(context, obj)
except:
self.report({"INFO"}, "Type object is hidden.")
# IfcTypeProducts are only used for annotations and not part of the model interface.
if element.is_a() != "IfcTypeProduct":
try:
context.scene.BIMModelProperties.ifc_class = element.is_a()
context.scene.BIMModelProperties.relating_type_id = str(self.relating_type)
except:
# Potentially our BIM Tool is filtered to a specific element.
pass
if self.relating_type: #if operator button sends a relating_type, the iterator only selects this one type
element = tool.Ifc.get().by_id(self.relating_type)
obj = tool.Ifc.get_object(element)
selected_objs = [obj]
else: #else, the iterator selects all the types of all the selected objects
selected_objs = context.selected_objects
active_obj = context.active_object
selected_objs.append(active_obj) #update selected_objs so the active_obj is at the end of the list
last_relating_type_obj = None
types_collection_in_view_layer = self.find_collection_in_ifcproject(context, collection_name = "Types")
types_collection_in_view_layer.hide_viewport = False
types_collection = bpy.data.collections.get("Types")
for type_obj in types_collection.objects:
type_obj.hide_set(True)
for obj in selected_objs:
element = tool.Ifc.get_entity(obj)
relating_type = ifcopenshell.util.element.get_type(element)
if relating_type:
relating_type_obj = tool.Ifc.get_object(relating_type)
if relating_type_obj:
if relating_type_obj.hide_get():
relating_type_obj.hide_set(False)
relating_type_obj.select_set(True)
last_relating_type_obj = relating_type_obj
if not element.is_a("IfcTypeObject"):
obj.select_set(False)
context.view_layer.objects.active = last_relating_type_obj #makes the active_obj's type the active object
return {"FINISHED"}
def find_collection_in_ifcproject(self, context, collection_name):
ifc_project_collection = None
for child in context.view_layer.layer_collection.children:
if "IfcProject" in child.name:
ifc_project_collection = child
break
if ifc_project_collection:
collection_in_view_layer = ifc_project_collection.children.get(collection_name)
return collection_in_view_layer
class SelectSimilarType(bpy.types.Operator):
bl_idname = "bim.select_similar_type"
@@ -88,7 +88,7 @@ class BIM_PT_type(Panel):
if TypeData.data["relating_type"]:
row.label(text=TypeData.data["relating_type"]["name"])
op = row.operator("bim.select_type", icon="OBJECT_DATA", text="")
op.relating_type = TypeData.data["relating_type"]["id"]
op.relating_type = 0 #will only select the relating types of only the selected objects
row.operator("bim.select_similar_type", icon="RESTRICT_SELECT_OFF", text="")
row.operator("bim.enable_editing_type", icon="GREASEPENCIL", text="")
row.operator("bim.unassign_type", icon="X", text="")
+5 -4
View File
@@ -46,7 +46,8 @@ def add_instance_flooring_covering_from_cursor(ifc, spatial, model, Type, geomet
obj = spatial.get_named_obj_from_mesh(name, mesh)
spatial.set_obj_origin_to_cursor_position(obj)
spatial.set_obj_origin_to_cursor_position_and_zero_elevation(obj)
spatial.traslate_obj_to_z_location(obj, z)
spatial.link_obj_to_active_collection(obj)
points = spatial.get_2d_vertices_from_obj(obj)
points = spatial.get_scaled_2d_vertices(points)
@@ -74,7 +75,7 @@ def add_instance_ceiling_covering_from_cursor(ifc, spatial, model, Type, geometr
else:
x, y, z, h, mat = spatial.get_x_y_z_h_mat_from_cursor()
z = covering.get_z_from_ceiling_height()
ceiling_height = covering.get_z_from_ceiling_height()
space_polygon = spatial.get_space_polygon_from_context_visible_objects(x, y)
@@ -87,8 +88,8 @@ def add_instance_ceiling_covering_from_cursor(ifc, spatial, model, Type, geometr
obj = spatial.get_named_obj_from_mesh(name, mesh)
spatial.set_obj_origin_to_cursor_position(obj)
spatial.traslate_obj_to_z_location(obj, z)
spatial.set_obj_origin_to_cursor_position_and_zero_elevation(obj)
spatial.traslate_obj_to_z_location(obj, z+ceiling_height)
spatial.link_obj_to_active_collection(obj)
points = spatial.get_2d_vertices_from_obj(obj)
points = spatial.get_scaled_2d_vertices(points)
+26 -14
View File
@@ -17,6 +17,7 @@
# along with BlenderBIM Add-on. If not, see <http://www.gnu.org/licenses/>.
from pathlib import Path
import ifcopenshell
def enable_editing_text(drawing, obj=None):
@@ -66,7 +67,7 @@ def disable_editing_sheets(drawing):
drawing.disable_editing_sheets()
def add_sheet(ifc, drawing, titleblock=None):
def add_sheet(ifc, drawing, titleblock: ifcopenshell.entity_instance):
sheet = ifc.run("document.add_information")
layout = ifc.run("document.add_reference", information=sheet)
titleblock_reference = ifc.run("document.add_reference", information=sheet)
@@ -77,16 +78,17 @@ def add_sheet(ifc, drawing, titleblock=None):
else:
attributes = {"Identification": identification, "Name": "UNTITLED", "Scope": "SHEET"}
ifc.run("document.edit_information", information=sheet, attributes=attributes)
ifc.run(
"document.edit_reference",
reference=layout,
attributes={"Location": drawing.get_default_layout_path(identification, "UNTITLED"), "Description": "LAYOUT"},
attributes = drawing.generate_reference_attributes(
layout, Location=drawing.get_default_layout_path(identification, "UNTITLED"), Description="LAYOUT"
)
ifc.run(
"document.edit_reference",
reference=titleblock_reference,
attributes={"Location": drawing.get_default_titleblock_path(titleblock), "Description": "TITLEBLOCK"},
ifc.run("document.edit_reference", reference=layout, attributes=attributes)
attributes = drawing.generate_reference_attributes(
layout, Location=drawing.get_default_titleblock_path(titleblock), Description="TITLEBLOCK"
)
ifc.run("document.edit_reference", reference=titleblock_reference, attributes=attributes)
drawing.create_svg_sheet(sheet, titleblock)
drawing.import_sheets()
@@ -94,7 +96,12 @@ def add_sheet(ifc, drawing, titleblock=None):
def regenerate_sheet(drawing, sheet=None):
titleblock_uri = drawing.get_document_uri(sheet, "TITLEBLOCK")
drawing.create_svg_sheet(sheet, drawing.sanitise_filename(Path(titleblock_uri).stem))
drawing.add_drawings(sheet)
try:
drawing.add_drawings(sheet)
except FileNotFoundError:
path_layout = drawing.get_document_uri(sheet, "LAYOUT")
if drawing.does_file_exist(path_layout):
drawing.delete_file(path_layout)
def open_sheet(drawing, sheet=None):
@@ -111,8 +118,12 @@ def remove_sheet(ifc, drawing, sheet=None):
drawing.import_sheets()
def rename_sheet(ifc, drawing, sheet=None, identification=None, name=None):
ifc.run("document.edit_information", information=sheet, attributes={"Identification": identification, "Name": name})
def rename_sheet(ifc, drawing, sheet: ifcopenshell.entity_instance, identification: str, name: str) -> None:
if ifc.get_schema() == "IFC2X3":
attributes = {"DocumentId": identification, "Name": name}
else:
attributes = {"Identification": identification, "Name": name}
ifc.run("document.edit_information", information=sheet, attributes=attributes)
for reference in drawing.get_document_references(sheet):
description = drawing.get_reference_description(reference)
if description == "SHEET":
@@ -133,8 +144,9 @@ def rename_sheet(ifc, drawing, sheet=None, identification=None, name=None):
drawing.move_file(old_location, ifc.resolve_uri(new_location))
def rename_reference(ifc, reference=None, identification=None):
ifc.run("document.edit_reference", reference=reference, attributes={"Identification": identification})
def rename_reference(ifc, drawing, reference=None, identification=None):
attributes = drawing.generate_reference_attributes(reference, Identification=identification)
ifc.run("document.edit_reference", reference=reference, attributes=attributes)
def load_schedules(drawing):
+3 -2
View File
@@ -189,7 +189,8 @@ def generate_space(ifc, spatial, model, Type):
name = "Space"
obj = spatial.get_named_obj_from_mesh(name, mesh)
spatial.set_obj_origin_to_cursor_position(obj)
spatial.set_obj_origin_to_cursor_position_and_zero_elevation(obj)
spatial.traslate_obj_to_z_location(obj, z)
spatial.link_obj_to_active_collection(obj)
spatial.assign_ifcspace_class_to_obj(obj)
@@ -214,7 +215,7 @@ def generate_spaces_from_walls(ifc, spatial, collector):
obj = spatial.get_named_obj_from_bmesh(name, bmesh=bm)
spatial.set_obj_origin_to_bboxcenter(obj)
spatial.set_obj_origin_to_bboxcenter_and_zero_elevation(obj)
spatial.traslate_obj_to_z_location(obj, z)
spatial.link_obj_to_active_collection(obj)
+3 -1
View File
@@ -329,6 +329,7 @@ class Drawing:
def get_name(cls, element): pass
def get_path_filename(cls, uri): pass
def get_reference_description(cls, reference): pass
def generate_reference_attributes(cls, reference, **attributes): pass
def get_reference_document(cls, reference): pass
def get_reference_location(cls, reference): pass
def get_references_with_location(cls, location): pass
@@ -871,7 +872,8 @@ class Spatial:
def get_transformed_mesh_from_local_to_global(cls, mesh): pass
def edit_active_space_obj_from_mesh(cls, mesh): pass
def set_obj_origin_to_bboxcenter(cls, obj): pass
def set_obj_origin_to_cursor_position(cls, obj): pass
def set_obj_origin_to_bboxcenter_and_zero_elevation(cls, obj): pass
def set_obj_origin_to_cursor_position_and_zero_elevation(cls, obj): pass
def get_selected_objects(cls): pass
def get_active_obj(cls): pass
def get_active_obj_z(cls): pass
@@ -187,6 +187,9 @@ class Collector(blenderbim.core.tool.Collector):
if any(e for e in element.IsNestedBy[0].RelatedObjects if not e.is_a("IfcPort")):
return cls._create_own_collection(obj)
if getattr(element, "HasSurfaceFeatures", None):
return cls._create_own_collection(obj)
@classmethod
def _get_collection(cls, element: ifcopenshell.entity_instance, obj: bpy.types.Object) -> bpy.types.Collection:
"""get or create collection for the element based on it's type"""
@@ -247,6 +250,13 @@ class Collector(blenderbim.core.tool.Collector):
if collection:
return collection
if element.is_a("IfcSurfaceFeature") and element.file.schema == "IFC4X3":
adherend = element.AdheresToElement[0].RelatingElement
adherend_obj = tool.Ifc.get_object(adherend)
collection = adherend_obj.BIMObjectProperties.collection
if collection:
return collection
if element.is_a("IfcProject"):
return bpy.context.scene.collection
+51 -16
View File
@@ -240,7 +240,7 @@ class Drawing(blenderbim.core.tool.Drawing):
)
@classmethod
def create_svg_sheet(cls, document, titleblock):
def create_svg_sheet(cls, document: ifcopenshell.entity_instance, titleblock: str) -> str:
sheet_builder = sheeter.SheetBuilder()
sheet_builder.data_dir = bpy.context.scene.BIMProperties.data_dir
uri = cls.get_document_uri(document, "LAYOUT")
@@ -251,16 +251,16 @@ class Drawing(blenderbim.core.tool.Drawing):
def add_drawings(cls, sheet):
sheet_builder = sheeter.SheetBuilder()
sheet_builder.data_dir = bpy.context.scene.BIMProperties.data_dir
sheet_reference = None
drawing_references = {}
drawing_names = []
for reference in cls.get_document_references(sheet):
if reference.Description == "LAYOUT":
sheet_reference = reference
elif reference.Description == "DRAWING":
reference_description = cls.get_reference_description(reference)
if reference_description == "DRAWING":
drawing_references[Path(reference.Location).stem] = reference
drawing_names.append(Path(reference.Location).stem)
for annotation in [e for e in tool.Ifc.get().by_type("IfcAnnotation") if e.ObjectType == "DRAWING"]:
if annotation.Name in drawing_names:
sheet_builder.add_drawing(sheet_reference, annotation, sheet)
for drawing_annotation in [e for e in tool.Ifc.get().by_type("IfcAnnotation") if e.ObjectType == "DRAWING"]:
if drawing_annotation.Name in drawing_names:
sheet_builder.add_drawing(drawing_references[drawing_annotation.Name], drawing_annotation, sheet)
@classmethod
def delete_collection(cls, collection):
@@ -421,7 +421,7 @@ class Drawing(blenderbim.core.tool.Drawing):
else:
references = document.HasDocumentReferences
for reference in references:
if description and reference.Description != description:
if description and cls.get_reference_description(reference) != description:
continue
location = cls.get_document_uri(reference)
if location:
@@ -823,7 +823,8 @@ class Drawing(blenderbim.core.tool.Drawing):
continue
for reference in cls.get_document_references(sheet):
if reference.Description in ("SHEET", "LAYOUT", "RASTER"):
reference_description = cls.get_reference_description(reference)
if reference_description in ("SHEET", "LAYOUT", "RASTER"):
# These references are an internal detail and should not be visible to users
continue
new = props.sheets.add()
@@ -836,7 +837,7 @@ class Drawing(blenderbim.core.tool.Drawing):
new.identification = reference.Identification or ""
new.name = os.path.basename(reference.Location)
new.reference_type = reference.Description
new.reference_type = reference_description
@classmethod
def get_active_sheet(cls, context):
@@ -1568,9 +1569,28 @@ class Drawing(blenderbim.core.tool.Drawing):
tree.write(uri, pretty_print=True, xml_declaration=True, encoding="utf-8")
@classmethod
def get_reference_description(cls, reference):
def get_reference_description(cls, reference: ifcopenshell.entity_instance) -> Union[str, None]:
if reference.file.schema == "IFC2X3":
return reference.Name
return reference.Description
@classmethod
def generate_reference_attributes(cls, reference: ifcopenshell.entity_instance, **attributes: Any) -> dict[str, Any]:
"""will automatically convert attributes below for IFC2X3 compatibility:
- Identification -> ItemReference
- Description -> Name
"""
if reference.file.schema == "IFC2X3":
if "Description" in attributes:
attributes["Name"] = attributes["Description"]
del attributes["Description"]
if "Identification" in attributes:
attributes["ItemReference"] = attributes["Identification"]
del attributes["Identification"]
return attributes
@classmethod
def get_reference_location(cls, reference):
return reference.Location
@@ -1637,8 +1657,23 @@ class Drawing(blenderbim.core.tool.Drawing):
base_elements = set(ifc_file.by_type("IfcElement") + ifc_file.by_type("IfcSpatialElement"))
elements = {e for e in (elements & base_elements) if e.is_a() != "IfcSpace"}
# exclude annotations to avoid including annotations from other drawings
elements = {i for i in elements if not i.is_a("IfcAnnotation")}
updated_set = set()
for i in elements:
# exclude annotations to avoid including annotations from other drawings
if not i.is_a("IfcAnnotation"):
updated_set.add(i)
#add aggregate too, if element is host by one
if i.Decomposes:
aggregate = i.Decomposes[0].RelatingObject
#remove IfcProject for class iterator. See https://github.com/IfcOpenShell/IfcOpenShell/issues/4361#issuecomment-2081223615
if not aggregate.is_a("IfcProject"):
updated_set.add(aggregate)
# After the iteration is complete, update elements with updated set
elements.update(updated_set)
# add annotations from the current drawing
annotations = tool.Drawing.get_group_elements(tool.Drawing.get_drawing_group(drawing))
elements.update(annotations)
@@ -1816,8 +1851,8 @@ class Drawing(blenderbim.core.tool.Drawing):
has_context = True
break
# Don't hide IfcAnnotations as some of them might exist without representations
if has_context or element.is_a("IfcAnnotation"):
# Don't hide IfcAnnotations or Aggregates as some of them might exist without representations
if has_context or element.is_a("IfcAnnotation") or element.IsDecomposedBy:
element_obj_names.add(obj.name)
# Note that render visibility is only set on drawing generation time for speed.
+6 -1
View File
@@ -23,9 +23,14 @@ import hashlib
import logging
import numpy as np
import ifcopenshell
import ifcopenshell.api
import ifcopenshell.util.element
import ifcopenshell.util.system
import blenderbim.core.tool
import blenderbim.core.drawing
import blenderbim.core.style
import blenderbim.core.spatial
import blenderbim.core.system
import blenderbim.core.geometry
import blenderbim.tool as tool
import blenderbim.bim.import_ifc
@@ -622,7 +627,7 @@ class Geometry(blenderbim.core.tool.Geometry):
obj.data.BIMMeshProperties.material_checksum = str([s.id() for s in cls.get_styles(obj) if s])
@classmethod
def record_object_position(cls, obj):
def record_object_position(cls, obj: bpy.types.Object) -> None:
# These are recorded separately because they have different numerical tolerances
obj.BIMObjectProperties.location_checksum = repr(np.array(obj.matrix_world.translation).tobytes())
obj.BIMObjectProperties.rotation_checksum = repr(np.array(obj.matrix_world.to_3x3()).tobytes())
@@ -38,6 +38,12 @@ class Material(blenderbim.core.tool.Material):
def disable_editing_materials(cls):
bpy.context.scene.BIMMaterialProperties.is_editing = False
@classmethod
def duplicate_material(cls, material: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance:
new_material = ifcopenshell.util.element.copy_deep(tool.Ifc.get(), material)
new_material.Name = material.Name + "_copy"
return new_material
@classmethod
def enable_editing_materials(cls):
bpy.context.scene.BIMMaterialProperties.is_editing = True
+3 -1
View File
@@ -19,6 +19,8 @@
import bpy
import blenderbim.core.tool
import blenderbim.tool as tool
import ifcopenshell
from typing import Union
class Owner(blenderbim.core.tool.Owner):
@@ -27,7 +29,7 @@ class Owner(blenderbim.core.tool.Owner):
bpy.context.scene.BIMOwnerProperties.active_user_id = user.id()
@classmethod
def get_user(cls):
def get_user(cls) -> Union[ifcopenshell.entity_instance, None]:
if bpy.context.scene.BIMOwnerProperties.active_user_id:
return tool.Ifc.get().by_id(bpy.context.scene.BIMOwnerProperties.active_user_id)
elif tool.Ifc.get_schema() == "IFC2X3":
@@ -17,6 +17,7 @@
# along with BlenderBIM Add-on. If not, see <http://www.gnu.org/licenses/>.
import ifcopenshell
import ifcopenshell.util.element
import ifcopenshell.util.unit
import ifcopenshell.util.placement
import ifcopenshell.util.representation
@@ -75,3 +76,9 @@ class Profile(blenderbim.core.tool.Profile):
@classmethod
def get_model_profiles(cls):
return tool.Ifc.get().by_type("IfcProfileDef")
@classmethod
def duplicate_profile(cls, profile: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance:
new_profile = ifcopenshell.util.element.copy_deep(tool.Ifc.get(), profile)
new_profile.ProfileName = profile.ProfileName + "_copy"
return new_profile
+8 -2
View File
@@ -160,10 +160,16 @@ class ImportFilterQueryTransformer(lark.Transformer):
return args[0]
def instance(self, args):
return {"type": "instance", "value": " ".join([a.children[0].value for a in args])}
if args[0].data == "not":
return {"type": "instance", "value": "!" + args[1].children[0].value}
else:
return {"type": "instance", "value": args[0].children[0].value}
def entity(self, args):
return {"type": "entity", "value": " ".join([a.children[0].value for a in args])}
if args[0].data == "not":
return {"type": "entity", "value": "!" + args[1].children[0].value}
else:
return {"type": "entity", "value": args[0].children[0].value}
def attribute(self, args):
name, comparison, value = args
+20 -2
View File
@@ -583,14 +583,32 @@ class Spatial(blenderbim.core.tool.Spatial):
obj.location = newLoc
@classmethod
def set_obj_origin_to_cursor_position(cls, obj):
def set_obj_origin_to_bboxcenter_and_zero_elevation(cls, obj):
mat = obj.matrix_world
inverted = mat.inverted()
local_bbox_center = 0.125 * sum((Vector(b) for b in obj.bound_box), Vector())
global_bbox_center = mat @ local_bbox_center
global_obj_origin = global_bbox_center
global_obj_origin.z = 0
oldLoc = obj.location
newLoc = global_obj_origin
diff = newLoc - oldLoc
for vert in obj.data.vertices:
aux_vector = mat @ vert.co
aux_vector = aux_vector - diff
vert.co = inverted @ aux_vector
obj.location = newLoc
@classmethod
def set_obj_origin_to_cursor_position_and_zero_elevation(cls, obj):
mat = obj.matrix_world
inverted = mat.inverted()
collection = bpy.context.view_layer.active_layer_collection.collection
collection_obj = collection.BIMCollectionProperties.obj
x, y = bpy.context.scene.cursor.location.xy
z = collection_obj.matrix_world.translation.z
z = 0
oldLoc = obj.location
newLoc = Vector((x, y, z))
+7
View File
@@ -19,6 +19,7 @@
import bpy
import numpy as np
import ifcopenshell
import ifcopenshell.util.element
import blenderbim.core.tool
import blenderbim.tool as tool
import blenderbim.bim.helper
@@ -59,6 +60,12 @@ class Style(blenderbim.core.tool.Style):
def disable_editing_styles(cls):
bpy.context.scene.BIMStylesProperties.is_editing = False
@classmethod
def duplicate_style(cls, style: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance:
new_style = ifcopenshell.util.element.copy_deep(tool.Ifc.get(), style)
new_style.Name = style.Name + "_copy"
return new_style
@classmethod
def enable_editing(cls, obj):
obj.BIMStyleProperties.is_editing = True
+8 -1
View File
@@ -17,6 +17,7 @@
# along with BlenderBIM Add-on. If not, see <http://www.gnu.org/licenses/>.
import bpy
import ifcopenshell.util.element
import ifcopenshell.util.system
import blenderbim.core.tool
import blenderbim.tool as tool
@@ -145,7 +146,7 @@ class System(blenderbim.core.tool.System):
new.ifc_class = system.is_a()
@classmethod
def load_ports(cls, element, ports):
def load_ports(cls, element: ifcopenshell.entity_instance, ports: list[ifcopenshell.entity_instance]) -> None:
if not ports:
return
obj = tool.Ifc.get_object(element)
@@ -155,7 +156,13 @@ class System(blenderbim.core.tool.System):
ifc_importer.calculate_unit_scale()
ifc_importer.process_context_filter()
ifc_importer.create_generic_elements(set(ports))
container = ifcopenshell.util.element.get_container(element)
if container:
collection = tool.Ifc.get_object(container).BIMObjectProperties.collection
ifc_importer.collections[container.GlobalId] = collection
ifc_importer.place_objects_in_collections()
for port_obj in ifc_importer.added_data.values():
port_obj.parent = obj
port_obj.matrix_parent_inverse = obj.matrix_world.inverted()
@@ -103,6 +103,7 @@ For Linux or Mac:
# Remove and link other IfcOpenShell utilities
$ rm -r $BLENDER_ADDON_PATH/libs/site/packages/ifccsv.py
$ rm -r $BLENDER_ADDON_PATH/libs/site/packages/ifcdiff.py
$ rm -r $BLENDER_ADDON_PATH/libs/site/packages/bsdd.py
$ rm -r $BLENDER_ADDON_PATH/libs/site/packages/ifc4d
$ rm -r $BLENDER_ADDON_PATH/libs/site/packages/ifc5d
$ rm -r $BLENDER_ADDON_PATH/libs/site/packages/ifccityjson
@@ -110,9 +111,11 @@ For Linux or Mac:
$ rm -r $BLENDER_ADDON_PATH/libs/site/packages/ifcpatch
$ rm -r $BLENDER_ADDON_PATH/libs/site/packages/ifctester
$ rm -r $BLENDER_ADDON_PATH/libs/site/packages/ifcfm
$ rm -r $BLENDER_ADDON_PATH/libs/Desktop
$ ln -s $PWD/src/ifccsv/ifccsv.py $BLENDER_ADDON_PATH/libs/site/packages/ifccsv.py
$ ln -s $PWD/src/ifcdiff/ifcdiff.py $BLENDER_ADDON_PATH/libs/site/packages/ifcdiff.py
$ ln -s $PWD/src/bsdd/bsdd.py $BLENDER_ADDON_PATH/libs/site/packages/bsdd.py
$ ln -s $PWD/src/ifc4d/ifc4d $BLENDER_ADDON_PATH/libs/site/packages/ifc4d
$ ln -s $PWD/src/ifc5d/ifc5d $BLENDER_ADDON_PATH/libs/site/packages/ifc5d
$ ln -s $PWD/src/ifccityjson/ifccityjson $BLENDER_ADDON_PATH/libs/site/packages/ifccityjson
@@ -120,6 +123,7 @@ For Linux or Mac:
$ ln -s $PWD/src/ifcpatch/ifcpatch $BLENDER_ADDON_PATH/libs/site/packages/ifcpatch
$ ln -s $PWD/src/ifctester/ifctester $BLENDER_ADDON_PATH/libs/site/packages/ifctester
$ ln -s $PWD/src/ifcfm/ifcfm $BLENDER_ADDON_PATH/libs/site/packages/ifcfm
$ ln -s $PWD/src/blenderbim/blenderbim/libs/desktop $BLENDER_ADDON_PATH/libs/Desktop
# Manually download some third party dependencies
$ cd $BLENDER_ADDON_PATH/bim/data/gantt
@@ -168,6 +172,7 @@ Before running it follow the instructions descibed after `rem` tags.
echo Remove and link other IfcOpenShell utilities...
del "%blenderbim%\libs\site\packages\ifccsv.py"
del "%blenderbim%\libs\site\packages\ifcdiff.py"
del "%blenderbim%\libs\site\packages\bsdd.py"
rd /S /Q "%blenderbim%\libs\site\packages\ifc4d"
rd /S /Q "%blenderbim%\libs\site\packages\ifc5d"
rd /S /Q "%blenderbim%\libs\site\packages\ifccityjson"
@@ -175,9 +180,11 @@ Before running it follow the instructions descibed after `rem` tags.
rd /S /Q "%blenderbim%\libs\site\packages\ifcpatch"
rd /S /Q "%blenderbim%\libs\site\packages\ifctester"
rd /S /Q "%blenderbim%\libs\site\packages\ifcfm"
rd /S /Q "%blenderbim%\libs\desktop"
mklink "%blenderbim%\libs\site\packages\ifccsv.py" "%cd%\src\ifccsv\ifccsv.py"
mklink "%blenderbim%\libs\site\packages\ifcdiff.py" "%cd%\src\ifcdiff\ifcdiff.py"
mklink "%blenderbim%\libs\site\packages\bsdd.py" "%cd%\src\bsdd\bsdd.py"
mklink /D "%blenderbim%\libs\site\packages\ifc4d" "%cd%\src\ifc4d\ifc4d"
mklink /D "%blenderbim%\libs\site\packages\ifc5d" "%cd%\src\ifc5d\ifc5d"
mklink /D "%blenderbim%\libs\site\packages\ifccityjson" "%cd%\src\ifccityjson\ifccityjson"
@@ -185,6 +192,7 @@ Before running it follow the instructions descibed after `rem` tags.
mklink /D "%blenderbim%\libs\site\packages\ifcpatch" "%cd%\src\ifcpatch\ifcpatch"
mklink /D "%blenderbim%\libs\site\packages\ifctester" "%cd%\src\ifctester\ifctester"
mklink /D "%blenderbim%\libs\site\packages\ifcfm" "%cd%\src\ifcfm\ifcfm"
mklink /D "%blenderbim%\libs\desktop" "%cd%\src\blenderbim\blenderbim\libs\desktop"
echo Manually downloading some third party dependencies...
curl https://raw.githubusercontent.com/jsGanttImproved/jsgantt-improved/master/dist/jsgantt.js -o "%blenderbim%\bim\data\gantt\jsgantt.js"
@@ -40,7 +40,7 @@ class LibraryGenerator:
"root.create_entity", self.file, ifc_class="IfcProjectLibrary", name="Australian Library"
)
ifcopenshell.api.run(
"project.assign_declaration", self.file, definition=self.library, relating_context=self.project
"project.assign_declaration", self.file, definitions=[self.library], relating_context=self.project
)
unit = ifcopenshell.api.run("unit.add_si_unit", self.file, unit_type="LENGTHUNIT", prefix="MILLI")
ifcopenshell.api.run("unit.assign_unit", self.file, units=[unit])
@@ -196,7 +196,7 @@ class LibraryGenerator:
)
layer.Name = layer_data[0]
layer.LayerThickness = layer_data[2]
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
return element
def create_layer_type(self, ifc_class, name, thickness):
@@ -205,7 +205,7 @@ class LibraryGenerator:
layer_set = rel.RelatingMaterial
layer = ifcopenshell.api.run("material.add_layer", self.file, layer_set=layer_set, material=self.materials["TBD"]["ifc"])
layer.LayerThickness = thickness
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
return element
def create_profile_type(self, ifc_class, name, profile):
@@ -216,7 +216,7 @@ class LibraryGenerator:
"material.add_profile", self.file, profile_set=profile_set, material=self.materials["TBD"]["ifc"]
)
ifcopenshell.api.run("material.assign_profile", self.file, material_profile=material_profile, profile=profile)
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
def create_type(self, ifc_class, name, representations):
element = ifcopenshell.api.run("root.create_entity", self.file, ifc_class=ifc_class, name=name)
@@ -248,7 +248,7 @@ class LibraryGenerator:
ifcopenshell.api.run(
"geometry.assign_representation", self.file, product=element, representation=representation
)
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
LibraryGenerator().generate()
@@ -35,7 +35,7 @@ class LibraryGenerator:
"root.create_entity", self.file, ifc_class="IfcProjectLibrary", name="BlenderBIM Demo Library"
)
ifcopenshell.api.run(
"project.assign_declaration", self.file, definition=self.library, relating_context=self.project
"project.assign_declaration", self.file, definitions=[self.library], relating_context=self.project
)
ifcopenshell.api.run("unit.assign_unit", self.file, length={"is_metric": True, "raw": "METERS"})
model = ifcopenshell.api.run("context.add_context", self.file, context_type="Model")
@@ -209,7 +209,7 @@ class LibraryGenerator:
layer_set = rel.RelatingMaterial
layer = ifcopenshell.api.run("material.add_layer", self.file, layer_set=layer_set, material=self.material)
layer.LayerThickness = thickness
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
return element
def create_profile_type(self, ifc_class, name, profile):
@@ -220,7 +220,7 @@ class LibraryGenerator:
"material.add_profile", self.file, profile_set=profile_set, material=self.material
)
ifcopenshell.api.run("material.assign_profile", self.file, material_profile=material_profile, profile=profile)
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
def create_type(self, ifc_class, name, representations):
element = ifcopenshell.api.run("root.create_entity", self.file, ifc_class=ifc_class, name=name)
@@ -252,7 +252,7 @@ class LibraryGenerator:
ifcopenshell.api.run(
"geometry.assign_representation", self.file, product=element, representation=representation
)
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
LibraryGenerator().generate()
@@ -42,7 +42,7 @@ class LibraryGenerator:
"root.create_entity", self.file, ifc_class="IfcProjectLibrary", name=library_name
)
ifcopenshell.api.run(
"project.assign_declaration", self.file, definition=self.library, relating_context=self.project
"project.assign_declaration", self.file, definitions=[self.library], relating_context=self.project
)
unit = ifcopenshell.api.run("unit.add_si_unit", self.file, unit_type="LENGTHUNIT", prefix="MILLI")
ifcopenshell.api.run("unit.assign_unit", self.file, units=[unit])
@@ -131,7 +131,7 @@ class LibraryGenerator:
ifcopenshell.api.run(
"geometry.assign_representation", self.file, product=element, representation=representation
)
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
if __name__ == "__main__":
@@ -37,7 +37,7 @@ class LibraryGenerator:
"root.create_entity", self.file, ifc_class="IfcProjectLibrary", name=library_name
)
ifcopenshell.api.run(
"project.assign_declaration", self.file, definition=self.library, relating_context=self.project
"project.assign_declaration", self.file, definitions=[self.library], relating_context=self.project
)
unit = ifcopenshell.api.run("unit.add_si_unit", self.file, unit_type="LENGTHUNIT", prefix="MILLI")
ifcopenshell.api.run("unit.assign_unit", self.file, units=[unit])
@@ -1797,7 +1797,7 @@ class LibraryGenerator:
ifcopenshell.api.run(
"geometry.assign_representation", self.file, product=element, representation=representation_2d
)
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
return element
def create_layer_set_type(self, name, data):
@@ -1811,7 +1811,7 @@ class LibraryGenerator:
)
layer.Name = layer_data[0]
layer.LayerThickness = layer_data[2]
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
return element
def create_layer_type(self, ifc_class, name, thickness):
@@ -1822,7 +1822,7 @@ class LibraryGenerator:
"material.add_layer", self.file, layer_set=layer_set, material=self.materials["TBD"]["ifc"]
)
layer.LayerThickness = thickness
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
return element
def create_profile_type(self, ifc_class, name, profile):
@@ -1837,7 +1837,7 @@ class LibraryGenerator:
# material=self.materials["TBD"]["ifc"]
)
ifcopenshell.api.run("material.assign_profile", self.file, material_profile=material_profile, profile=profile)
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
def create_type(self, ifc_class, name, representations):
element = ifcopenshell.api.run("root.create_entity", self.file, ifc_class=ifc_class, name=name)
@@ -1869,7 +1869,7 @@ class LibraryGenerator:
ifcopenshell.api.run(
"geometry.assign_representation", self.file, product=element, representation=representation
)
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
if __name__ == "__main__":
@@ -319,7 +319,7 @@ class LibraryGenerator:
"root.create_entity", self.file, ifc_class="IfcProjectLibrary", name=library_name
)
ifcopenshell.api.run(
"project.assign_declaration", self.file, definition=self.library, relating_context=self.project
"project.assign_declaration", self.file, definitions=[self.library], relating_context=self.project
)
unit = ifcopenshell.api.run("unit.add_si_unit", self.file, unit_type="LENGTHUNIT", prefix="MILLI")
ifcopenshell.api.run("unit.assign_unit", self.file, units=[unit])
@@ -447,7 +447,7 @@ class LibraryGenerator:
ifcopenshell.api.run(
"geometry.assign_representation", self.file, product=element, representation=representation_2d
)
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
return element
def create_type(self, ifc_class, name, representations):
@@ -480,7 +480,7 @@ class LibraryGenerator:
ifcopenshell.api.run(
"geometry.assign_representation", self.file, product=element, representation=representation
)
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
@@ -35,7 +35,7 @@ class LibraryGenerator:
"root.create_entity", self.file, ifc_class="IfcProjectLibrary", name="BlenderBIM Demo Library"
)
ifcopenshell.api.run(
"project.assign_declaration", self.file, definition=self.library, relating_context=self.library
"project.assign_declaration", self.file, definitions=[self.library], relating_context=self.library
)
ifcopenshell.api.run("unit.assign_unit", self.file, length={"is_metric": True, "raw": "METERS"})
model = ifcopenshell.api.run("context.add_context", self.file, context_type="Model")
@@ -98,7 +98,7 @@ class LibraryGenerator:
ifcopenshell.api.run(
"geometry.assign_representation", self.file, product=element, representation=representation
)
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
LibraryGenerator().generate()
@@ -43,7 +43,7 @@ class LibraryGenerator:
"root.create_entity", self.file, ifc_class="IfcProjectLibrary", name=f"{parse_profiles_type} Steel Profiles Library"
)
ifcopenshell.api.run(
"project.assign_declaration", self.file, definition=self.library, relating_context=self.project
"project.assign_declaration", self.file, definitions=[self.library], relating_context=self.project
)
dim_exponents = self.file.createIfcDimensionalExponents(0, 0, 0, 0, 0, 0, 0)
length_unit = ifcopenshell.api.run("unit.add_si_unit", self.file, unit_type="LENGTHUNIT", prefix="MILLI")
@@ -182,7 +182,7 @@ class LibraryGenerator:
# material=self.materials["TBD"]["ifc"]
)
ifcopenshell.api.run("material.assign_profile", self.file, material_profile=material_profile, profile=profile)
ifcopenshell.api.run("project.assign_declaration", self.file, definition=element, relating_context=self.library)
ifcopenshell.api.run("project.assign_declaration", self.file, definitions=[element], relating_context=self.library)
def create_double_l_profile(self, profile, resulting_profile_name=None, profiles_gap=0, mode = "LLBB"):
def create_derived_profile(profile, mirrored=False):
@@ -91,7 +91,7 @@ def mirror_placement_test():
library = ifcopenshell.api.run(
"root.create_entity", ifc_file, ifc_class="IfcProjectLibrary", name=f"Non-structural assets library"
)
ifcopenshell.api.run("project.assign_declaration", ifc_file, definition=library, relating_context=project)
ifcopenshell.api.run("project.assign_declaration", ifc_file, definitions=[library], relating_context=project)
unit = ifcopenshell.api.run("unit.add_si_unit", ifc_file, unit_type="LENGTHUNIT", prefix="MILLI")
ifcopenshell.api.run("unit.assign_unit", ifc_file, units=[unit])
model = ifcopenshell.api.run("context.add_context", ifc_file, context_type="Model")
@@ -152,7 +152,7 @@ def mirror_placement_test():
element = ifcopenshell.api.run("root.create_entity", ifc_file, ifc_class="IfcFurnitureType", name="test")
ifcopenshell.api.run("geometry.assign_representation", ifc_file, product=element, representation=representation_3d)
ifcopenshell.api.run("project.assign_declaration", ifc_file, definition=element, relating_context=library)
ifcopenshell.api.run("project.assign_declaration", ifc_file, definitions=[element], relating_context=library)
ifc_file.write("tmp.ifc")
@@ -165,7 +165,7 @@ def curve_between_two_points_test():
library = ifcopenshell.api.run(
"root.create_entity", ifc_file, ifc_class="IfcProjectLibrary", name=f"Non-structural assets library"
)
ifcopenshell.api.run("project.assign_declaration", ifc_file, definition=library, relating_context=project)
ifcopenshell.api.run("project.assign_declaration", ifc_file, definitions=[library], relating_context=project)
unit = ifcopenshell.api.run("unit.add_si_unit", ifc_file, unit_type="LENGTHUNIT", prefix="MILLI")
ifcopenshell.api.run("unit.assign_unit", ifc_file, units=[unit])
model = ifcopenshell.api.run("context.add_context", ifc_file, context_type="Model")
@@ -217,7 +217,7 @@ def curve_between_two_points_test():
print(representation_2d)
element = ifcopenshell.api.run("root.create_entity", ifc_file, ifc_class="IfcFurnitureType", name="test")
ifcopenshell.api.run("geometry.assign_representation", ifc_file, product=element, representation=representation_2d)
ifcopenshell.api.run("project.assign_declaration", ifc_file, definition=element, relating_context=library)
ifcopenshell.api.run("project.assign_declaration", ifc_file, definitions=[element], relating_context=library)
ifc_file.write("tmp.ifc")
+9 -8
View File
@@ -19,6 +19,7 @@
import json
import pytest
import blenderbim.core.tool
from typing import Any, Self, Optional
@pytest.fixture
@@ -241,12 +242,12 @@ def voider():
class Prophecy:
def __init__(self, cls):
self.subject = cls
self.predictions = []
self.calls = []
self.return_values = {}
self.should_call = None
self.predictions: list[dict] = []
self.calls: list[dict] = []
self.return_values: dict[str, Any] = {}
self.should_call: Optional[dict] = None
def __getattr__(self, attr):
def __getattr__(self, attr: str):
if not hasattr(self.subject, attr):
raise AttributeError(f"Prophecy {self.subject} has no attribute {attr}")
@@ -270,12 +271,12 @@ class Prophecy:
self.predictions.append({"type": "SHOULD_BE_CALLED", "number": number, "call": self.should_call})
return self
def will_return(self, value):
def will_return(self, value: Any) -> Self:
key = json.dumps(self.should_call, sort_keys=True)
self.return_values[key] = value
return self
def verify(self):
def verify(self) -> None:
predicted_calls = []
for prediction in self.predictions:
predicted_calls.append(prediction["call"])
@@ -285,7 +286,7 @@ class Prophecy:
if call not in predicted_calls:
raise Exception(f"Unpredicted call: {call}")
def verify_should_be_called(self, prediction):
def verify_should_be_called(self, prediction: dict) -> None:
if prediction["number"]:
count = self.calls.count(prediction["call"])
if count != prediction["number"]:
+19 -5
View File
@@ -95,15 +95,21 @@ class TestAddSheet:
information="sheet",
attributes={"Identification": "u_identification", "Name": "UNTITLED", "Scope": "SHEET"},
).should_be_called()
drawing.generate_reference_attributes(
"reference", Location="layout_path", Description="LAYOUT"
).should_be_called().will_return("attributes")
ifc.run(
"document.edit_reference",
reference="reference",
attributes={"Location": "layout_path", "Description": "LAYOUT"},
attributes="attributes",
).should_be_called()
drawing.generate_reference_attributes(
"reference", Location="titleblock_path", Description="TITLEBLOCK"
).should_be_called().will_return("attributes2")
ifc.run(
"document.edit_reference",
reference="reference",
attributes={"Location": "titleblock_path", "Description": "TITLEBLOCK"},
attributes="attributes2",
).should_be_called()
drawing.create_svg_sheet("sheet", "titleblock").should_be_called()
drawing.import_sheets().should_be_called()
@@ -122,15 +128,21 @@ class TestAddSheet:
information="sheet",
attributes={"DocumentId": "u_identification", "Name": "UNTITLED", "Scope": "SHEET"},
).should_be_called()
drawing.generate_reference_attributes(
"reference", Location="layout_path", Description="LAYOUT"
).should_be_called().will_return("attributes")
ifc.run(
"document.edit_reference",
reference="reference",
attributes={"Location": "layout_path", "Description": "LAYOUT"},
attributes="attributes",
).should_be_called()
drawing.generate_reference_attributes(
"reference", Location="titleblock_path", Description="TITLEBLOCK"
).should_be_called().will_return("attributes2")
ifc.run(
"document.edit_reference",
reference="reference",
attributes={"Location": "titleblock_path", "Description": "TITLEBLOCK"},
attributes="attributes2",
).should_be_called()
drawing.create_svg_sheet("sheet", "titleblock").should_be_called()
drawing.import_sheets().should_be_called()
@@ -490,7 +502,9 @@ class TestUpdateDrawingName:
)
ifc.resolve_uri("relative_layout_uri").should_be_called().will_return("absolute_layout_uri")
drawing.does_file_exist("absolute_layout_uri").should_be_called().will_return(True)
drawing.update_embedded_svg_location("absolute_layout_uri", "reference_with_old_location", "new_uri").should_be_called()
drawing.update_embedded_svg_location(
"absolute_layout_uri", "reference_with_old_location", "new_uri"
).should_be_called()
drawing.is_editing_sheets().should_be_called().will_return(True)
drawing.import_sheets().should_be_called()
+42 -23
View File
@@ -61,20 +61,20 @@ class IfcCsv:
def export(
self,
ifc_file,
elements,
ifc_file: ifcopenshell.file,
elements: ifcopenshell.entity_instance,
attributes,
headers=None,
output=None,
format=None,
should_preserve_existing=False,
include_global_id=True,
delimiter=",",
null="-",
empty="",
bool_true="YES",
bool_false="NO",
concat=", ",
should_preserve_existing: bool = False,
include_global_id: bool = True,
delimiter: str = ",",
null: str = "-",
empty: str = "",
bool_true: str = "YES",
bool_false: str = "NO",
concat: str = ", ",
sort=None,
groups=None,
summaries=None,
@@ -382,16 +382,25 @@ class IfcCsv:
return ["{}.{}".format(pset_qto_name, n) for n in results]
def Import(
self, ifc_file, table, attributes=None, delimiter=",", null="-", empty="", bool_true="YES", bool_false="NO"
):
self,
ifc_file: ifcopenshell.file,
table: str,
attributes: Optional[list[Union[str, None]]] = None,
delimiter: str = ",",
null: str = "-",
empty: str = "",
bool_true: str = "YES",
bool_false: str = "NO",
concat: str = ", ",
) -> None:
ext = table.split(".")[-1].lower()
if ext == "csv":
self.import_csv(ifc_file, table, attributes, delimiter, null, empty, bool_true, bool_false)
self.import_csv(ifc_file, table, attributes, delimiter, null, empty, bool_true, bool_false, concat)
elif ext == "ods":
self.import_ods(ifc_file, table, attributes, null, empty, bool_true, bool_false)
self.import_ods(ifc_file, table, attributes, null, empty, bool_true, bool_false, concat)
elif ext == "xlsx":
self.import_xlsx(ifc_file, table, attributes, null, empty, bool_true, bool_false)
self.import_xlsx(ifc_file, table, attributes, null, empty, bool_true, bool_false, concat)
def import_csv(
self,
@@ -403,6 +412,7 @@ class IfcCsv:
empty: str = "",
bool_true: str = "YES",
bool_false: str = "NO",
concat: str = ", ",
) -> None:
with open(table, newline="", encoding="utf-8") as f:
reader = csv.reader(f, delimiter=delimiter)
@@ -415,17 +425,17 @@ class IfcCsv:
elif len(attributes) == len(headers) - 1:
attributes.insert(0, "") # The GlobalId column
continue
self.process_row(ifc_file, row, headers, attributes, null, empty, bool_true, bool_false)
self.process_row(ifc_file, row, headers, attributes, null, empty, bool_true, bool_false, concat)
def import_xlsx(self, ifc_file, table, attributes, null, empty, bool_true, bool_false):
def import_xlsx(self, ifc_file, table, attributes, null, empty, bool_true, bool_false, concat):
df = pd.read_excel(table)
self.import_pd(ifc_file, df, attributes, null, empty, bool_true, bool_false)
self.import_pd(ifc_file, df, attributes, null, empty, bool_true, bool_false, concat)
def import_ods(self, ifc_file, table, attributes, null, empty, bool_true, bool_false):
def import_ods(self, ifc_file, table, attributes, null, empty, bool_true, bool_false, concat):
df = pd.read_excel(table, engine="odf")
self.import_pd(ifc_file, df, attributes, null, empty, bool_true, bool_false)
self.import_pd(ifc_file, df, attributes, null, empty, bool_true, bool_false, concat)
def import_pd(self, ifc_file, df, attributes=None, null="-", empty="", bool_true="YES", bool_false="NO"):
def import_pd(self, ifc_file, df, attributes=None, null="-", empty="", bool_true="YES", bool_false="NO", concat=", "):
headers = df.columns.tolist()
if not attributes:
@@ -434,7 +444,7 @@ class IfcCsv:
attributes.insert(0, "") # The GlobalId column
for _, row in df.iterrows():
self.process_row(ifc_file, row.tolist(), headers, attributes, null, empty, bool_true, bool_false)
self.process_row(ifc_file, row.tolist(), headers, attributes, null, empty, bool_true, bool_false, concat)
def process_row(
self,
@@ -446,6 +456,7 @@ class IfcCsv:
empty: str,
bool_true: str,
bool_false: str,
concat: str
) -> None:
try:
element = ifc_file.by_guid(row[0])
@@ -464,7 +475,14 @@ class IfcCsv:
elif value == bool_false:
value = False
key = attributes[i] or headers[i]
ifcopenshell.util.selector.set_element_value(ifc_file, element, key, value)
try:
ifcopenshell.util.selector.set_element_value(ifc_file, element, key, value)
except ValueError as e:
if "enum property" in e.args[0]:
value = value.split(concat)
ifcopenshell.util.selector.set_element_value(ifc_file, element, key, value)
else:
raise e
if __name__ == "__main__":
@@ -526,5 +544,6 @@ if __name__ == "__main__":
delimiter=args.delimiter,
null=args.null,
empty=args.empty,
concat=args.concat
)
ifc_file.write(args.ifc)
+42 -7
View File
@@ -549,6 +549,36 @@ IfcSchema::IfcRelVoidsElement::list::ptr IfcGeom::Kernel::find_openings(IfcSchem
return openings;
}
namespace {
template <typename T>
IfcSchema::IfcMaterial* get_single_from_aggregate(bool take_first_regardless_of_size, const T& agg) {
if (take_first_regardless_of_size ? agg->size() >= 1 : agg->size() == 1) {
auto* layer_or_profile = *agg->begin();
if (layer_or_profile->Material()) {
return layer_or_profile->Material();
}
}
return nullptr;
}
#ifdef SCHEMA_HAS_IfcMaterialProfileSet
IfcSchema::IfcMaterial* get_single_from_set(bool take_first_regardless_of_size, IfcSchema::IfcMaterialProfileSet* profileset) {
return get_single_from_aggregate(take_first_regardless_of_size, profileset->MaterialProfiles());
}
#endif
IfcSchema::IfcMaterial* get_single_from_set(bool take_first_regardless_of_size, IfcSchema::IfcMaterialLayerSet* profileset) {
return get_single_from_aggregate(take_first_regardless_of_size, profileset->MaterialLayers());
}
IfcSchema::IfcMaterial* get_single_from_usage(bool take_first_regardless_of_size, IfcSchema::IfcMaterialLayerSetUsage* usage) {
return get_single_from_set(take_first_regardless_of_size, usage->ForLayerSet());
}
#ifdef SCHEMA_HAS_IfcMaterialProfileSet
IfcSchema::IfcMaterial* get_single_from_usage(bool take_first_regardless_of_size, IfcSchema::IfcMaterialProfileSetUsage* usage) {
return get_single_from_set(take_first_regardless_of_size, usage->ForProfileSet());
}
#endif
}
const IfcSchema::IfcMaterial* IfcGeom::Kernel::get_single_material_association(const IfcSchema::IfcProduct* product) {
IfcSchema::IfcMaterial* single_material = 0;
IfcSchema::IfcRelAssociatesMaterial::list::ptr associated_materials = product->HasAssociations()->as<IfcSchema::IfcRelAssociatesMaterial>();
@@ -566,14 +596,19 @@ const IfcSchema::IfcMaterial* IfcGeom::Kernel::get_single_material_association(c
single_material = associated_material->as<IfcSchema::IfcMaterial>();
// NB: IfcMaterialLayerSets are also considered, regardless of --enable-layerset-slicing. Picking
// the first material (in accordance with other viewers) when layerset-slicing is disabled.
if (!single_material && associated_material->as<IfcSchema::IfcMaterialLayerSetUsage>()) {
IfcSchema::IfcMaterialLayerSet* layerset = associated_material->as<IfcSchema::IfcMaterialLayerSetUsage>()->ForLayerSet();
if (getValue(GV_LAYERSET_FIRST) > 0.0 ? layerset->MaterialLayers()->size() >= 1 : layerset->MaterialLayers()->size() == 1) {
IfcSchema::IfcMaterialLayer* layer = (*layerset->MaterialLayers()->begin());
if (layer->Material()) {
single_material = layer->Material();
}
if (!single_material) {
if (auto* m = associated_material->as<IfcSchema::IfcMaterialLayerSetUsage>()) {
single_material = get_single_from_usage(getValue(GV_LAYERSET_FIRST) > 0.0, m);
} else if (auto* m = associated_material->as<IfcSchema::IfcMaterialLayerSet>()) {
single_material = get_single_from_set(getValue(GV_LAYERSET_FIRST) > 0.0, m);
}
#ifdef SCHEMA_HAS_IfcMaterialProfileSet
else if (auto* m = associated_material->as<IfcSchema::IfcMaterialProfileSetUsage>()) {
single_material = get_single_from_usage(getValue(GV_LAYERSET_FIRST) > 0.0, m);
} else if (auto* m = associated_material->as<IfcSchema::IfcMaterialProfileSet>()) {
single_material = get_single_from_set(getValue(GV_LAYERSET_FIRST) > 0.0, m);
}
#endif
}
}
}
@@ -62,7 +62,9 @@
#include <STEPConstruct_PointHasher.hxx>
#include "clash_utils.h"
#ifdef WITH_HDF5
#include "H5Cpp.h"
#endif
namespace IfcGeom {
@@ -1504,6 +1506,7 @@ namespace IfcGeom {
}
}
#ifdef WITH_HDF5
void write_h5() {
H5::H5File file("filename.h5", H5F_ACC_TRUNC);
H5::Group shapes = file.createGroup("/shapes");
@@ -1714,6 +1717,7 @@ namespace IfcGeom {
colours_dataset.write(flat_colours.data(), H5::PredType::NATIVE_FLOAT);
}
}
#endif
template <typename T>
void apply_matrix_to_flat_verts(const std::vector<T>& flat_list, const std::vector<T>& matrix, std::vector<T>& result) {
@@ -1776,9 +1780,11 @@ namespace IfcGeom {
aabb.Add(vs_transformed.back());
}
/*
std::cout << "aabb: ";
aabb.DumpJson(std::cout);
std::cout << std::endl;
*/
std::unordered_map<std::tuple<int, int, int>, std::vector<size_t>, boost::hash<std::tuple<int, int, int>>> quantized_normal_counts;
@@ -1863,9 +1869,11 @@ namespace IfcGeom {
obb.SetZComponent(ax3.Direction(), halfsize.Z());
obb.SetCenter(cent.Transformed(trsf2.Inverted()));
/*
std::cout << "obb: ";
obb.DumpJson(std::cout);
std::cout << std::endl;
*/
}
const auto& t = elem->product();
@@ -116,6 +116,8 @@ the following comparison checks:
"``>=``", "Must be greater than or equal to the value."
"``<``", "Must be less than the value."
"``<=``", "Must be less than or equal to the value."
"``*=``", "Must contain the value."
"``!*=``", "Must not contain the value."
When you specify a ``{{pset}}``, ``{{prop}}``, or ``{{value}}``, there are
three ways you can do so:
@@ -39,6 +39,7 @@ import sys
import tempfile
import zipfile
from pathlib import Path
from typing import Optional
import ifcopenshell.util.file
@@ -197,12 +198,14 @@ def register_schema(schema):
register_schema_attributes(schema.schema)
def schema_by_name(schema=None, schema_version=None):
def schema_by_name(
schema: Optional[str] = None, schema_version: Optional[tuple[int, ...]] = None
) -> ifcopenshell_wrapper.schema_definition:
"""Returns an object allowing you to query the IFC schema itself
:param schema: Which IFC schema to use, chosen from "IFC2X3", "IFC4",
or "IFC4X3". These refer to the ISO approved versions of IFC.
:type schema: string
:type schema: string, optional
:param schema_version: If you want to specify an exact version of IFC
that may not be an ISO approved version, use this argument instead
of ``schema``. IFC versions on technical.buildingsmart.org are
@@ -211,13 +214,15 @@ def schema_by_name(schema=None, schema_version=None):
ADD2 TC1, which is the official version approved by ISO when people
refer to "IFC4". Generally you should not use this argument unless
you are testing non-ISO IFC releases.
:type schema_version: tuple[int]
:type schema_version: tuple[int, ...], optional
:return: Schema definition object.
:rtype: ifocpenshell_wrapper.schema_definition
"""
if schema_version:
prefixes = ("IFC", "X", "_ADD", "_TC")
schema = "".join("".join(map(str, t)) if t[1] else "" for t in zip(prefixes, schema_version))
else:
schema = {"IFC4X3": "IFC4X3_ADD1"}.get(schema, schema)
schema = {"IFC4X3": "IFC4X3_ADD2"}.get(schema, schema)
return ifcopenshell_wrapper.schema_by_name(schema)
@@ -20,6 +20,8 @@
import json
import numpy
import pkgutil
import inspect
import importlib
import ifcopenshell
import ifcopenshell.api
@@ -117,18 +119,35 @@ ARGUMENTS_DEPRECATION = {
"constraint.unassign_constraint": partial(
batching_argument_deprecation, prev_argument="product", new_argument="products"
),
"project.assign_declaration": partial(
batching_argument_deprecation, prev_argument="definition", new_argument="definitions"
),
"project.unassign_declaration": partial(
batching_argument_deprecation, prev_argument="definition", new_argument="definitions"
),
}
CACHED_USECASE_CLASSES = dict()
CACHED_USECASE_CLASSES = {}
CACHED_USECASES = {}
def run(
usecase_path: str,
ifc_file: Optional[ifcopenshell.file] = None,
should_run_listeners=True,
should_run_listeners: bool = True,
**settings: Any,
) -> Any:
usecase_function = CACHED_USECASES.get(usecase_path)
if not usecase_function:
importlib.import_module(f"ifcopenshell.api.{usecase_path}")
module, usecase = usecase_path.split(".")
usecase_function = getattr(getattr(ifcopenshell.api, module), usecase)
CACHED_USECASES[usecase_path] = usecase_function
if ifc_file:
return usecase_function(ifc_file, should_run_listeners=should_run_listeners, **settings)
return usecase_function(should_run_listeners=should_run_listeners, **settings)
if should_run_listeners:
for listener in pre_listeners.get(usecase_path, {}).values():
listener(usecase_path, ifc_file, settings)
@@ -229,7 +248,6 @@ def remove_all_listeners():
def extract_docs(module, usecase):
import typing
import inspect
import collections
results = []
@@ -275,3 +293,79 @@ def extract_docs(module, usecase):
node_data["description"] = description.strip()
node_data["inputs"] = inputs
return node_data
def wrap_usecase(usecase_path, usecase):
"""Wraps an API function in pre/post listeners."""
def wrapper(*args, should_run_listeners: bool = True, **settings):
ifc_file = args[0] if args else None
if should_run_listeners:
for listener in pre_listeners.get(usecase_path, {}).values():
listener(usecase_path, ifc_file, settings)
try:
result = usecase(*args, **settings)
except TypeError as e:
msg = f"Incorrect function arguments provided for {usecase_path}\n{str(e)}. You specified args {args} and settings {settings}\n\nCorrect signature is {inspect.signature(Usecase.__init__)}\nSee help(ifcopenshell.api.{usecase_path}) for documentation."
raise TypeError(msg) from e
if should_run_listeners:
for listener in post_listeners.get(usecase_path, {}).values():
listener(usecase_path, ifc_file, settings)
return result
wrapper.__signature__ = inspect.signature(usecase)
wrapper.__doc__ = usecase.__doc__
wrapper.__name__ = usecase_path
return wrapper
# Expose all submodules. This means that the user can just type `import ifcopenshell.api`.
import ifcopenshell.api.aggregate as aggregate
import ifcopenshell.api.attribute as attribute
import ifcopenshell.api.boundary as boundary
import ifcopenshell.api.classification as classification
import ifcopenshell.api.constraint as constraint
import ifcopenshell.api.context as context
import ifcopenshell.api.control as control
import ifcopenshell.api.cost as cost
import ifcopenshell.api.document as document
import ifcopenshell.api.drawing as drawing
import ifcopenshell.api.geometry as geometry
import ifcopenshell.api.georeference as georeference
import ifcopenshell.api.grid as grid
import ifcopenshell.api.group as group
import ifcopenshell.api.layer as layer
import ifcopenshell.api.library as library
import ifcopenshell.api.material as material
import ifcopenshell.api.nest as nest
import ifcopenshell.api.owner as owner
import ifcopenshell.api.profile as profile
import ifcopenshell.api.project as project
import ifcopenshell.api.pset as pset
import ifcopenshell.api.pset_template as pset_template
import ifcopenshell.api.resource as resource
import ifcopenshell.api.root as root
import ifcopenshell.api.sequence as sequence
import ifcopenshell.api.spatial as spatial
import ifcopenshell.api.structural as structural
import ifcopenshell.api.style as style
import ifcopenshell.api.system as system
import ifcopenshell.api.type as type # Whoohoo!
import ifcopenshell.api.unit as unit
import ifcopenshell.api.void as void
# Wrap all submodule usecases with listeners.
# This for loop also conveniently ensures that the above imports are comprehensive.
for loader, module_name, is_pkg in pkgutil.iter_modules(__path__, __name__ + "."):
# Check if it's a direct child (only one level deep)
if module_name.count(".") == __name__.count(".") + 1:
module_name = module_name.split(".")[-1]
module = globals()[module_name]
for usecase_name in vars(module):
usecase = getattr(module, usecase_name)
if callable(usecase):
usecase_path = f"{module_name}.{usecase_name}"
setattr(module, usecase_name, wrap_usecase(usecase_path, usecase))
@@ -22,3 +22,6 @@ One common use is spatial elements, such as how a site has multiple buildings,
and a building has multiple storeys. Another is for regular elements, such as
how a wall is made out of members and coverings.
"""
from .assign_object import assign_object
from .unassign_object import unassign_object
@@ -23,148 +23,144 @@ import ifcopenshell.util.placement
from typing import Union
class Usecase:
def __init__(
self,
file: ifcopenshell.file,
products: list[ifcopenshell.entity_instance],
relating_object: ifcopenshell.entity_instance,
):
"""Assigns object as an aggregate to the products
def assign_object(
file: ifcopenshell.file,
products: list[ifcopenshell.entity_instance],
relating_object: ifcopenshell.entity_instance,
) -> Union[ifcopenshell.entity_instance, None]:
"""Assigns object as an aggregate to the products
All physical IFC model elements must be part of a hierarchical tree
called the "spatial decomposition", where large things are made up of
smaller things. This tree always begins at an "IfcProject" and is then
broken down using "decomposition" relationships, of which aggregation is
the first relationship you will use.
All physical IFC model elements must be part of a hierarchical tree
called the "spatial decomposition", where large things are made up of
smaller things. This tree always begins at an "IfcProject" and is then
broken down using "decomposition" relationships, of which aggregation is
the first relationship you will use.
Typically used when you want to describe how large spaces are made up of
smaller spaces. For example large spatial elements (e.g. sites,
buidings) can be made out of smaller spatial elements (e.g. storeys,
spaces).
Typically used when you want to describe how large spaces are made up of
smaller spaces. For example large spatial elements (e.g. sites,
buidings) can be made out of smaller spatial elements (e.g. storeys,
spaces).
The largest space (typically the IfcSite) can then be aggregated in a
project. It is requirement for all spatial structures to be directly or
indirectly aggregated back to the IfcProject to create a hierarchy of
spaces.
The largest space (typically the IfcSite) can then be aggregated in a
project. It is requirement for all spatial structures to be directly or
indirectly aggregated back to the IfcProject to create a hierarchy of
spaces.
The other common usecase is when larger physical products are made up of
smaller physical products. For example, a stair might be made out of a
flight, a landing, a railing and so on. Or a wall might be made out of
stud members, and coverings.
The other common usecase is when larger physical products are made up of
smaller physical products. For example, a stair might be made out of a
flight, a landing, a railing and so on. Or a wall might be made out of
stud members, and coverings.
As a product may only have a single location in the "spatial
decomposition" tree, assigning an aggregate relationship will remove any
previous aggregation, containment, or nesting relationships it may have.
As a product may only have a single location in the "spatial
decomposition" tree, assigning an aggregate relationship will remove any
previous aggregation, containment, or nesting relationships it may have.
IFC placements follow a convention where the placement is relative to
its parent in the spatial hierarchy. If your product has a placement,
its placement will be recalculated to follow this convention.
IFC placements follow a convention where the placement is relative to
its parent in the spatial hierarchy. If your product has a placement,
its placement will be recalculated to follow this convention.
:param products: The list of parts of the aggregate, typically of IfcElement or
IfcSpatialStructureElement subclass
:type product: list[ifcopenshell.entity_instance.entity_instance]
:param relating_object: The whole of the aggregate, typically an
IfcElement or IfcSpatialStructureElement subclass
:type relating_object: ifcopenshell.entity_instance.entity_instance
:return: The IfcRelAggregate relationship instance
or `None` if `products` was empty list.
:rtype: Union[ifcopenshell.entity_instance.entity_instance, None]
:param products: The list of parts of the aggregate, typically of IfcElement or
IfcSpatialStructureElement subclass
:type product: list[ifcopenshell.entity_instance]
:param relating_object: The whole of the aggregate, typically an
IfcElement or IfcSpatialStructureElement subclass
:type relating_object: ifcopenshell.entity_instance
:return: The IfcRelAggregate relationship instance
or `None` if `products` was empty list.
:rtype: Union[ifcopenshell.entity_instance, None]
Example:
Example:
.. code:: python
.. code:: python
project = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcProject")
element = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcSite")
subelement = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcBuilding")
project = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcProject")
element = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcSite")
subelement = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcBuilding")
# The project contains a site (note that project aggregation is a special case in IFC)
ifcopenshell.api.run("aggregate.assign_object", model, products=[element], relating_object=project)
# The project contains a site (note that project aggregation is a special case in IFC)
ifcopenshell.api.run("aggregate.assign_object", model, products=[element], relating_object=project)
# The site has a building
ifcopenshell.api.run("aggregate.assign_object", model, products=[subelement], relating_object=element)
"""
self.file = file
self.settings = {
"products": products,
"relating_object": relating_object,
}
# The site has a building
ifcopenshell.api.run("aggregate.assign_object", model, products=[subelement], relating_object=element)
"""
settings = {
"products": products,
"relating_object": relating_object,
}
def execute(self) -> Union[ifcopenshell.entity_instance, None]:
if not self.settings["products"]:
return
if not settings["products"]:
return
products = set(self.settings["products"])
relating_object = self.settings["relating_object"]
is_decomposed_by = next((i for i in relating_object.IsDecomposedBy if i.is_a("IfcRelAggregates")), None)
products = set(settings["products"])
relating_object = settings["relating_object"]
is_decomposed_by = next((i for i in relating_object.IsDecomposedBy if i.is_a("IfcRelAggregates")), None)
previous_aggregates_rels: set[ifcopenshell.entity_instance] = set()
products_without_aggregates: list[ifcopenshell.entity_instance] = []
products_with_aggregates: list[ifcopenshell.entity_instance] = []
previous_aggregates_rels: set[ifcopenshell.entity_instance] = set()
products_without_aggregates: list[ifcopenshell.entity_instance] = []
products_with_aggregates: list[ifcopenshell.entity_instance] = []
# check if there is anything to change
for product in products:
product_rel = next(iter(product.Decomposes), None)
# check if there is anything to change
for product in products:
product_rel = next(iter(product.Decomposes), None)
if product_rel is None:
products_without_aggregates.append(product)
continue
if product_rel is None:
products_without_aggregates.append(product)
continue
# either is_decomposed_by is None or product is part of different rel
if product_rel != is_decomposed_by:
previous_aggregates_rels.add(product_rel)
products_with_aggregates.append(product)
# either is_decomposed_by is None or product is part of different rel
if product_rel != is_decomposed_by:
previous_aggregates_rels.add(product_rel)
products_with_aggregates.append(product)
# products with already assigned aggregates will be skipped
# products with already assigned aggregates will be skipped
products_to_change = products_without_aggregates + products_with_aggregates
# nothing to change
if not products_to_change:
return is_decomposed_by
products_to_change = products_without_aggregates + products_with_aggregates
# nothing to change
if not products_to_change:
return is_decomposed_by
# can be either only aggregated or only contained at the same time
# some product might not be able to have a container
possibly_contained_products = [p for p in products_without_aggregates if hasattr(p, "ContainedInStructure")]
ifcopenshell.api.run("spatial.unassign_container", self.file, products=possibly_contained_products)
# can be either only aggregated or only contained at the same time
# some product might not be able to have a container
possibly_contained_products = [p for p in products_without_aggregates if hasattr(p, "ContainedInStructure")]
ifcopenshell.api.run("spatial.unassign_container", file, products=possibly_contained_products)
# unassign elements from previous aggregates
for decomposes in previous_aggregates_rels:
related_objects = set(decomposes.RelatedObjects) - products
if related_objects:
decomposes.RelatedObjects = list(related_objects)
ifcopenshell.api.run("owner.update_owner_history", self.file, **{"element": decomposes})
else:
history = decomposes.OwnerHistory
self.file.remove(decomposes)
if history:
ifcopenshell.util.element.remove_deep2(self.file, history)
# assign elements to a new aggregate
if is_decomposed_by:
is_decomposed_by.RelatedObjects = list(set(is_decomposed_by.RelatedObjects) | products)
ifcopenshell.api.run("owner.update_owner_history", self.file, **{"element": is_decomposed_by})
# unassign elements from previous aggregates
for decomposes in previous_aggregates_rels:
related_objects = set(decomposes.RelatedObjects) - products
if related_objects:
decomposes.RelatedObjects = list(related_objects)
ifcopenshell.api.run("owner.update_owner_history", file, **{"element": decomposes})
else:
is_decomposed_by = self.file.create_entity(
"IfcRelAggregates",
**{
"GlobalId": ifcopenshell.guid.new(),
"OwnerHistory": ifcopenshell.api.run("owner.create_owner_history", self.file),
"RelatedObjects": list(products),
"RelatingObject": relating_object,
}
history = decomposes.OwnerHistory
file.remove(decomposes)
if history:
ifcopenshell.util.element.remove_deep2(file, history)
# assign elements to a new aggregate
if is_decomposed_by:
is_decomposed_by.RelatedObjects = list(set(is_decomposed_by.RelatedObjects) | products)
ifcopenshell.api.run("owner.update_owner_history", file, **{"element": is_decomposed_by})
else:
is_decomposed_by = file.create_entity(
"IfcRelAggregates",
**{
"GlobalId": ifcopenshell.guid.new(),
"OwnerHistory": ifcopenshell.api.run("owner.create_owner_history", file),
"RelatedObjects": list(products),
"RelatingObject": relating_object,
}
)
# localize placement relative to a new aggregate for affected products
for product in products_to_change:
placement = getattr(product, "ObjectPlacement", None)
if placement and placement.is_a("IfcLocalPlacement"):
ifcopenshell.api.run(
"geometry.edit_object_placement",
file,
product=product,
matrix=ifcopenshell.util.placement.get_local_placement(product.ObjectPlacement),
is_si=False,
)
# localize placement relative to a new aggregate for affected products
for product in products_to_change:
placement = getattr(product, "ObjectPlacement", None)
if placement and placement.is_a("IfcLocalPlacement"):
ifcopenshell.api.run(
"geometry.edit_object_placement",
self.file,
product=product,
matrix=ifcopenshell.util.placement.get_local_placement(product.ObjectPlacement),
is_si=False,
)
return is_decomposed_by
return is_decomposed_by
@@ -21,60 +21,57 @@ import ifcopenshell.api
import ifcopenshell.util.element
class Usecase:
def __init__(self, file: ifcopenshell.file, products: list[ifcopenshell.entity_instance]):
"""Unassigns products from their aggregate
def unassign_object(file: ifcopenshell.file, products: list[ifcopenshell.entity_instance]) -> None:
"""Unassigns products from their aggregate
A product (i.e. a smaller part of a whole) may be aggregated into zero
or one larger space or element. This function will remove that
aggregation relationship.
A product (i.e. a smaller part of a whole) may be aggregated into zero
or one larger space or element. This function will remove that
aggregation relationship.
As all physical IFC model elements must be part of a hierarchical tree
called the "spatial decomposition", using this function will remove the
product from that tree. This is a dangerous operation and may result in
the product no longer being visible in IFC applications.
As all physical IFC model elements must be part of a hierarchical tree
called the "spatial decomposition", using this function will remove the
product from that tree. This is a dangerous operation and may result in
the product no longer being visible in IFC applications.
If the product is not part of an aggregation relationship, nothing will
happen.
If the product is not part of an aggregation relationship, nothing will
happen.
:param products: The list of parts of the aggregate, typically of IfcElements or
IfcSpatialStructureElement subclass
:type product: list[ifcopenshell.entity_instance.entity_instance]
:return: None
:rtype: None
:param products: The list of parts of the aggregate, typically of IfcElements or
IfcSpatialStructureElement subclass
:type product: list[ifcopenshell.entity_instance]
:return: None
:rtype: None
Example:
Example:
.. code:: python
.. code:: python
element = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcSite")
subelement1 = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcBuilding")
subelement2 = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcBuilding")
ifcopenshell.api.run("aggregate.assign_object", model, products=[subelement1], relating_object=element)
ifcopenshell.api.run("aggregate.assign_object", model, products=[subelement2], relating_object=element)
# nothing is returned
ifcopenshell.api.run("aggregate.unassign_object", model, products=[subelement1])
# nothing is returned, relationship is removed
ifcopenshell.api.run("aggregate.unassign_object", model, products=[subelement2])
"""
self.file = file
self.settings = {"products": products}
element = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcSite")
subelement1 = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcBuilding")
subelement2 = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcBuilding")
ifcopenshell.api.run("aggregate.assign_object", model, products=[subelement1], relating_object=element)
ifcopenshell.api.run("aggregate.assign_object", model, products=[subelement2], relating_object=element)
# nothing is returned
ifcopenshell.api.run("aggregate.unassign_object", model, products=[subelement1])
# nothing is returned, relationship is removed
ifcopenshell.api.run("aggregate.unassign_object", model, products=[subelement2])
"""
settings = {"products": products}
def execute(self) -> None:
products = set(self.settings["products"])
rels = set(
rel
for product in products
if (rel := next((rel for rel in product.Decomposes if rel.is_a("IfcRelAggregates")), None))
)
products = set(settings["products"])
rels = set(
rel
for product in products
if (rel := next((rel for rel in product.Decomposes if rel.is_a("IfcRelAggregates")), None))
)
for rel in rels:
related_objects = set(rel.RelatedObjects) - products
if related_objects:
rel.RelatedObjects = list(related_objects)
ifcopenshell.api.run("owner.update_owner_history", self.file, **{"element": rel})
else:
history = rel.OwnerHistory
self.file.remove(rel)
if history:
ifcopenshell.util.element.remove_deep2(self.file, history)
for rel in rels:
related_objects = set(rel.RelatedObjects) - products
if related_objects:
rel.RelatedObjects = list(related_objects)
ifcopenshell.api.run("owner.update_owner_history", file, **{"element": rel})
else:
history = rel.OwnerHistory
file.remove(rel)
if history:
ifcopenshell.util.element.remove_deep2(file, history)
@@ -15,3 +15,5 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
from .edit_attributes import edit_attributes
@@ -19,64 +19,49 @@
import ifcopenshell.api
class Usecase:
def __init__(self, file, product=None, attributes=None):
"""Edit the attributes of a product
def edit_attributes(file, product=None, attributes=None) -> None:
"""Edit the attributes of a product
All IFC entities have attributes. Normally they can be edited directly,
by simply assigning a new value to them. In some scenarios, you may wish
to also ensure that ownership history is updated. This function provides
that convenience.
All IFC entities have attributes. Normally they can be edited directly,
by simply assigning a new value to them. In some scenarios, you may wish
to also ensure that ownership history is updated. This function provides
that convenience.
:param product: The product you want to edit. This may be any rooted IFC
entity.
:type product: ifcopenshell.entity_instance.entity_instance
:param attributes: a dictionary of attribute names and values.
:type attributes: dict, optional
:return: None
:rtype: None
:param product: The product you want to edit. This may be any rooted IFC
entity.
:type product: ifcopenshell.entity_instance
:param attributes: a dictionary of attribute names and values.
:type attributes: dict, optional
:return: None
:rtype: None
Example:
Example:
.. code:: python
.. code:: python
element = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcWall")
ifcopenshell.api.run("attribute.edit_attributes", model,
product=element, attributes={"Name": "Waldo"})
"""
self.file = file
self.settings = {"product": product, "attributes": attributes or {}}
element = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcWall")
ifcopenshell.api.run("attribute.edit_attributes", model,
product=element, attributes={"Name": "Waldo"})
"""
settings = {"product": product, "attributes": attributes or {}}
def execute(self):
for name, value in self.settings["attributes"].items():
setattr(self.settings["product"], name, value)
if hasattr(self.settings["product"], "PredefinedType"):
if hasattr(self.settings["product"], "ElementType"):
if (
self.settings["product"].ElementType is None
and self.settings["product"].PredefinedType == "USERDEFINED"
):
self.settings["product"].PredefinedType = "NOTDEFINED"
elif (
self.settings["product"].ElementType
and self.settings["product"].PredefinedType != "USERDEFINED"
):
self.settings["product"].PredefinedType = "USERDEFINED"
elif hasattr(self.settings["product"], "ObjectType"):
relating_type = ifcopenshell.util.element.get_type(self.settings["product"])
# Allow for None due to https://github.com/buildingSMART/IFC4.3.x-development/issues/818
if relating_type and relating_type.PredefinedType not in ("NOTDEFINED", None):
self.settings["product"].ObjectType = None
self.settings["product"].PredefinedType = None
elif (
self.settings["product"].ObjectType is None
and self.settings["product"].PredefinedType == "USERDEFINED"
):
self.settings["product"].PredefinedType = "NOTDEFINED"
elif (
self.settings["product"].ObjectType
and self.settings["product"].PredefinedType != "USERDEFINED"
):
self.settings["product"].PredefinedType = "USERDEFINED"
if hasattr(self.settings["product"], "OwnerHistory"):
ifcopenshell.api.run("owner.update_owner_history", self.file, **{"element": self.settings["product"]})
for name, value in settings["attributes"].items():
setattr(settings["product"], name, value)
if hasattr(settings["product"], "PredefinedType"):
if hasattr(settings["product"], "ElementType"):
if settings["product"].ElementType is None and settings["product"].PredefinedType == "USERDEFINED":
settings["product"].PredefinedType = "NOTDEFINED"
elif settings["product"].ElementType and settings["product"].PredefinedType != "USERDEFINED":
settings["product"].PredefinedType = "USERDEFINED"
elif hasattr(settings["product"], "ObjectType"):
relating_type = ifcopenshell.util.element.get_type(settings["product"])
# Allow for None due to https://github.com/buildingSMART/IFC4.3.x-development/issues/818
if relating_type and relating_type.PredefinedType not in ("NOTDEFINED", None):
settings["product"].ObjectType = None
settings["product"].PredefinedType = None
elif settings["product"].ObjectType is None and settings["product"].PredefinedType == "USERDEFINED":
settings["product"].PredefinedType = "NOTDEFINED"
elif settings["product"].ObjectType and settings["product"].PredefinedType != "USERDEFINED":
settings["product"].PredefinedType = "USERDEFINED"
if hasattr(settings["product"], "OwnerHistory"):
ifcopenshell.api.run("owner.update_owner_history", file, **{"element": settings["product"]})
@@ -19,3 +19,8 @@
"""Boundaries are primarily used for representing virtual interfaces between
spaces for energy analysis.
"""
from .assign_connection_geometry import assign_connection_geometry
from .copy_boundary import copy_boundary
from .edit_attributes import edit_attributes
from .remove_boundary import remove_boundary
@@ -19,68 +19,80 @@
import ifcopenshell.util.unit
def assign_connection_geometry(
file,
rel_space_boundary=None,
outer_boundary=None,
inner_boundaries=None,
location=None,
axis=None,
ref_direction=None,
unit_scale=None,
) -> None:
"""Create and assign a connection geometry to a space boundary relationship
A space boundary may optionally have a plane that represents how that
space is adjacent to another space, known as the connection geometry.
You may specify this plane in terms of an outer boundary polyline, zero
or more inner boundaries (such as for windows), and a positional matrix
for the orientation of the plane.
:param rel_space_boundary: The space boundary relationship to assign the
connection geometry to.
:type rel_space_boundary: ifcopenshell.entity_instance
:param outer_boundary: A list of 2D points representing an open
polyline. The last point will connect to the first point. Each
point is represented by an interable of 2 floats. The coordinates of
the points are relative to the positional matrix arguments.
:type outer_boundary: list[list[float]]
:param inner_boundaries: A list of zero or more inner boundaries to use
for the plane. Each boundary is represented by an open polyline, as
defined by the outer_boundary argument.
:type inner_boundaries: list[list[list[float]]], optional
:param location: The local origin of the connection geometry, defined as
an XYZ coordinate relative to the placement of the space that is
being bounded.
:type location: list[float]
:param axis: The local X axis of the connection geometry, defined as an
XYZ vector relative to the placement of the space that is being
bounded.
:type axis: list[float]
:param ref_direction: The local Z axis of the connection geometry,
defined as an XYZ vector relative to the placement of the space that
is being bounded. The Y vector is automatically derived using the
right hand rule.
:type ref_direction: list[float]
:param unit_scale: The unit scale as calculated by
ifcopenshell.util.unit.calculate_unit_scale. If not provided, it
will be automatically calculated for you.
:type unit_scale: float, optional
:return: None
:rtype: None
Example:
.. code:: python
ifcopenshell.api.run("boundary.assign_connection_geometry", model,
rel_space_boundary=element,
outer_boundary=[(0., 0.), (1., 0.), (1., 1.), (0., 1.)],
location=[0., 0., 0.], axis=[1., 0., 0.], ref_direction=[0., 0., 1.],
)
"""
usecase = Usecase()
usecase.file = file
usecase.rel_space_boundary = rel_space_boundary
usecase.outer_boundary = outer_boundary
usecase.inner_boundaries = inner_boundaries or ()
usecase.location = location
usecase.axis = axis
usecase.ref_direction = ref_direction
usecase.unit_scale = unit_scale
usecase.ifc_vertices = []
return usecase.execute()
class Usecase:
def __init__(self, file, rel_space_boundary=None, outer_boundary=None, inner_boundaries=None, location=None, axis=None, ref_direction=None, unit_scale=None):
"""Create and assign a connection geometry to a space boundary relationship
A space boundary may optionally have a plane that represents how that
space is adjacent to another space, known as the connection geometry.
You may specify this plane in terms of an outer boundary polyline, zero
or more inner boundaries (such as for windows), and a positional matrix
for the orientation of the plane.
:param rel_space_boundary: The space boundary relationship to assign the
connection geometry to.
:type rel_space_boundary: ifcopenshell.entity_instance.entity_instance
:param outer_boundary: A list of 2D points representing an open
polyline. The last point will connect to the first point. Each
point is represented by an interable of 2 floats. The coordinates of
the points are relative to the positional matrix arguments.
:type outer_boundary: list[list[float]]
:param inner_boundaries: A list of zero or more inner boundaries to use
for the plane. Each boundary is represented by an open polyline, as
defined by the outer_boundary argument.
:type inner_boundaries: list[list[list[float]]], optional
:param location: The local origin of the connection geometry, defined as
an XYZ coordinate relative to the placement of the space that is
being bounded.
:type location: list[float]
:param axis: The local X axis of the connection geometry, defined as an
XYZ vector relative to the placement of the space that is being
bounded.
:type axis: list[float]
:param ref_direction: The local Z axis of the connection geometry,
defined as an XYZ vector relative to the placement of the space that
is being bounded. The Y vector is automatically derived using the
right hand rule.
:type ref_direction: list[float]
:param unit_scale: The unit scale as calculated by
ifcopenshell.util.unit.calculate_unit_scale. If not provided, it
will be automatically calculated for you.
:type unit_scale: float, optional
:return: None
:rtype: None
Example:
.. code:: python
ifcopenshell.api.run("boundary.assign_connection_geometry", model,
rel_space_boundary=element,
outer_boundary=[(0., 0.), (1., 0.), (1., 1.), (0., 1.)],
location=[0., 0., 0.], axis=[1., 0., 0.], ref_direction=[0., 0., 1.],
)
"""
self.file = file
self.rel_space_boundary = rel_space_boundary
self.outer_boundary = outer_boundary
self.inner_boundaries = inner_boundaries or ()
self.location = location
self.axis = axis
self.ref_direction = ref_direction
self.unit_scale = unit_scale
self.ifc_vertices = []
def execute(self):
if self.unit_scale is None:
self.unit_scale = ifcopenshell.util.unit.calculate_unit_scale(self.file)
@@ -19,29 +19,26 @@
import ifcopenshell.util.element
class Usecase:
def __init__(self, file, boundary=None):
"""Copies a space boundary
def copy_boundary(file, boundary=None) -> None:
"""Copies a space boundary
:param boundary: The IfcRelSpaceBoundary you want to copy.
:type boundary: ifcopenshell.entity_instance.entity_instance
:return: None
:rtype: None
:param boundary: The IfcRelSpaceBoundary you want to copy.
:type boundary: ifcopenshell.entity_instance
:return: None
:rtype: None
Example:
Example:
# A boring boundary with no geometry. Note that this boundary is
# invalid and does not relate to any space or building element.
boundary = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcRelSpaceBoundary")
# A boring boundary with no geometry. Note that this boundary is
# invalid and does not relate to any space or building element.
boundary = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcRelSpaceBoundary")
# And now we have two
boundary_copy = ifcopenshell.api.run("boundary.copy_boundary", model, boundary=boundary)
"""
self.file = file
self.settings = {"boundary": boundary}
# And now we have two
boundary_copy = ifcopenshell.api.run("boundary.copy_boundary", model, boundary=boundary)
"""
settings = {"boundary": boundary}
def execute(self):
result = ifcopenshell.util.element.copy(self.file, self.settings["boundary"])
if result.ConnectionGeometry:
result.ConnectionGeometry = ifcopenshell.util.element.copy_deep(self.file, result.ConnectionGeometry)
return result
result = ifcopenshell.util.element.copy(file, settings["boundary"])
if result.ConnectionGeometry:
result.ConnectionGeometry = ifcopenshell.util.element.copy_deep(file, result.ConnectionGeometry)
return result
@@ -17,45 +17,49 @@
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
class Usecase:
def __init__(self, file, entity=None, relating_space=None, related_building_element=None, parent_boundary=None, corresponding_boundary=None):
"""Modify the relationships of a space boundary relationship
def edit_attributes(
file,
entity=None,
relating_space=None,
related_building_element=None,
parent_boundary=None,
corresponding_boundary=None,
) -> None:
"""Modify the relationships of a space boundary relationship
Currently this function is quite minimal and offers no advantage to
manual assignment of the space boundary attributes.
Currently this function is quite minimal and offers no advantage to
manual assignment of the space boundary attributes.
:param entity: The IfcRelSpaceBoundary to modify
:type entity: ifcopenshell.entity_instance.entity_instance
:param relating_space: The IfcSpace or IfcExternalSpatialElement that
the space boundary is related to.
:type relating_space: ifcopenshell.entity_instance.entity_instance
:param related_building_element: The IfcElement that defines the
boundary, typically an IfcWall.
:type relating_space: ifcopenshell.entity_instance.entity_instance
:param parent_boundary: A parent IfcRelSpaceBoundary, only provided if
this is an inner boundary. This can apply to 1st and 2nd level
boundaries.
:type parent_boundary: ifcopenshell.entity_instance.entity_instance,
optional
:param corresponding_boundary: The other IfcRelSpaceBoundary on the
other side of the related element. The pair together represents a
thermal boundary. This only applies to 2nd level boundaries.
:type corresponding_boundary: ifcopenshell.entity_instance.entity_instance,
optional
:return: None
:rtype: None
"""
self.file = file
self.entity = entity
self.relating_space = relating_space
self.related_building_element = related_building_element
self.parent_boundary = parent_boundary
self.corresponding_boundary = corresponding_boundary
:param entity: The IfcRelSpaceBoundary to modify
:type entity: ifcopenshell.entity_instance
:param relating_space: The IfcSpace or IfcExternalSpatialElement that
the space boundary is related to.
:type relating_space: ifcopenshell.entity_instance
:param related_building_element: The IfcElement that defines the
boundary, typically an IfcWall.
:type relating_space: ifcopenshell.entity_instance
:param parent_boundary: A parent IfcRelSpaceBoundary, only provided if
this is an inner boundary. This can apply to 1st and 2nd level
boundaries.
:type parent_boundary: ifcopenshell.entity_instance,
optional
:param corresponding_boundary: The other IfcRelSpaceBoundary on the
other side of the related element. The pair together represents a
thermal boundary. This only applies to 2nd level boundaries.
:type corresponding_boundary: ifcopenshell.entity_instance,
optional
:return: None
:rtype: None
"""
entity = entity
relating_space = relating_space
related_building_element = related_building_element
parent_boundary = parent_boundary
corresponding_boundary = corresponding_boundary
def execute(self):
self.entity.RelatingSpace = self.relating_space
self.entity.RelatedBuildingElement = self.related_building_element
if hasattr(self.entity, "ParentBoundary"):
self.entity.ParentBoundary = self.parent_boundary
if hasattr(self.entity, "CorrespondingBoundary"):
self.entity.CorrespondingBoundary = self.corresponding_boundary
entity.RelatingSpace = relating_space
entity.RelatedBuildingElement = related_building_element
if hasattr(entity, "ParentBoundary"):
entity.ParentBoundary = parent_boundary
if hasattr(entity, "CorrespondingBoundary"):
entity.CorrespondingBoundary = corresponding_boundary
@@ -20,36 +20,33 @@ import ifcopenshell
import ifcopenshell.util.element
class Usecase:
def __init__(self, file, boundary=None):
"""Removes a space boundary
def remove_boundary(file, boundary=None) -> None:
"""Removes a space boundary
The relating space or related building element is untouched. Only the
boundary and its connection geometry is removed.
The relating space or related building element is untouched. Only the
boundary and its connection geometry is removed.
:param boundary: The IfcRelSpaceBoundary you want to remove.
:type boundary: ifcopenshell.entity_instance.entity_instance
:return: None
:rtype: None
:param boundary: The IfcRelSpaceBoundary you want to remove.
:type boundary: ifcopenshell.entity_instance
:return: None
:rtype: None
Example:
Example:
# A boring boundary with no geometry. Note that this boundary is
# invalid and does not relate to any space or building element.
boundary = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcRelSpaceBoundary")
# A boring boundary with no geometry. Note that this boundary is
# invalid and does not relate to any space or building element.
boundary = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcRelSpaceBoundary")
# Let's remove it!
ifcopenshell.api.run("boundary.remove_boundary", model, boundary=boundary)
"""
self.file = file
self.settings = {"boundary": boundary}
# Let's remove it!
ifcopenshell.api.run("boundary.remove_boundary", model, boundary=boundary)
"""
settings = {"boundary": boundary}
def execute(self):
geometry = self.settings["boundary"].ConnectionGeometry
if geometry:
self.settings["boundary"].ConnectionGeometry = None
ifcopenshell.util.element.remove_deep2(self.file, geometry)
history = self.settings["boundary"].OwnerHistory
self.file.remove(self.settings["boundary"])
if history:
ifcopenshell.util.element.remove_deep2(self.file, history)
geometry = settings["boundary"].ConnectionGeometry
if geometry:
settings["boundary"].ConnectionGeometry = None
ifcopenshell.util.element.remove_deep2(file, geometry)
history = settings["boundary"].OwnerHistory
file.remove(settings["boundary"])
if history:
ifcopenshell.util.element.remove_deep2(file, history)
@@ -15,3 +15,10 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
from .add_classification import add_classification
from .add_reference import add_reference
from .edit_classification import edit_classification
from .edit_reference import edit_reference
from .remove_classification import remove_classification
from .remove_reference import remove_reference
@@ -22,67 +22,72 @@ import ifcopenshell.util.date
from typing import Union
def add_classification(
file: ifcopenshell.file, classification: Union[str, ifcopenshell.entity_instance]
) -> ifcopenshell.entity_instance:
"""Adds a new classification system to the project
External classification systems such as Uniclass or Omniclass are
ways of categorising elements in the AEC industry, typically
standardised or nominated by governments or companies. A system
typically contains a series of hierarchical reference codes and labels
like Pr_12_23_34.
Classifications may be applied to many things, not just physical
elements, such as doors and windows, spatial elements, tasks, cost
items, or even resources.
Prior to assigning classificaion references, you need to add the name
and metadata of the classification system that you will use in your
project. Classification systems may be revised over time, so this
metadata includes the edition date.
Common classification systems are provided as an IFC library which may
be downloaded from https://github.com/Moult/IfcClassification for your
convenience. It is advised to use these to ensure that the
classification metadata is standardised.
Adding a classification system will not add the entire hierarchy of
references available in the classification. References need to be added
separately. Typically, you'd only add the references that you use in
your project, see ifcopenshell.api.classification.add_reference for more
information.
:param classification: If a string is provided, it is assumed to be the
name of your classification system. This is necessary if you are
creating your own custom classification system. Alternatively, you
may provide an entity_instance of an IfcClassification from an IFC
classification library. The latter approach is preferred if you are
using a commonly known system such as Uniclass, as this will ensure
all metadata is added correctly.
:type classification: str,ifcopenshell.entity_instance
:return: The added IfcClassification element
:rtype: ifcopenshell.entity_instance
Example:
.. code:: python
# Option 1: adding a custom clasification from scratch
ifcopenshell.api.run("classification.add_classification", model,
classification="MyCustomClassification")
# Option 2: adding a popular classification from a library
library = ifcopenshell.open("/path/to/Uniclass.ifc")
classification = library.by_type("IfcClassification")[0]
ifcopenshell.api.run("classification.add_classification", model,
classification=classification)
"""
usecase = Usecase()
usecase.file = file
usecase.settings = {
"classification": classification,
}
return usecase.execute()
class Usecase:
def __init__(self, file: ifcopenshell.file, classification: Union[str, ifcopenshell.entity_instance]):
"""Adds a new classification system to the project
External classification systems such as Uniclass or Omniclass are
ways of categorising elements in the AEC industry, typically
standardised or nominated by governments or companies. A system
typically contains a series of hierarchical reference codes and labels
like Pr_12_23_34.
Classifications may be applied to many things, not just physical
elements, such as doors and windows, spatial elements, tasks, cost
items, or even resources.
Prior to assigning classificaion references, you need to add the name
and metadata of the classification system that you will use in your
project. Classification systems may be revised over time, so this
metadata includes the edition date.
Common classification systems are provided as an IFC library which may
be downloaded from https://github.com/Moult/IfcClassification for your
convenience. It is advised to use these to ensure that the
classification metadata is standardised.
Adding a classification system will not add the entire hierarchy of
references available in the classification. References need to be added
separately. Typically, you'd only add the references that you use in
your project, see ifcopenshell.api.classification.add_reference for more
information.
:param classification: If a string is provided, it is assumed to be the
name of your classification system. This is necessary if you are
creating your own custom classification system. Alternatively, you
may provide an entity_instance of an IfcClassification from an IFC
classification library. The latter approach is preferred if you are
using a commonly known system such as Uniclass, as this will ensure
all metadata is added correctly.
:type classification: str,ifcopenshell.entity_instance.entity_instance
:return: The added IfcClassification element
:rtype: ifcopenshell.entity_instance.entity_instance
Example:
.. code:: python
# Option 1: adding a custom clasification from scratch
ifcopenshell.api.run("classification.add_classification", model,
classification="MyCustomClassification")
# Option 2: adding a popular classification from a library
library = ifcopenshell.open("/path/to/Uniclass.ifc")
classification = library.by_type("IfcClassification")[0]
ifcopenshell.api.run("classification.add_classification", model,
classification=classification)
"""
self.file = file
self.settings = {
"classification": classification,
}
def execute(self) -> ifcopenshell.entity_instance:
def execute(self):
if isinstance(self.settings["classification"], str):
classification = self.file.createIfcClassification(Name=self.settings["classification"])
self.relate_to_project(classification)
@@ -23,117 +23,119 @@ import ifcopenshell.util.schema
from typing import Optional, Union
def add_reference(
file: ifcopenshell.file,
products: list[ifcopenshell.entity_instance],
reference: Optional[ifcopenshell.entity_instance] = None,
identification: Optional[str] = None,
name: Optional[str] = None,
classification: Optional[ifcopenshell.entity_instance] = None,
is_lightweight=True,
) -> Union[ifcopenshell.entity_instance, None]:
"""Adds a new classification reference and assigns it to the list of products
A classification reference is a single entry such as "Pr_12_23_34" that
is part of an external classification system (such as Uniclass or
Omniclass).
References can be added to almost any object in IFC, including physical
objects, object types, properties, tasks, costs, resources, or even
resources such as profiles, documents, libraries, and so on.
Classification references can be added in two ways. Option 1) specify a
custom arbitrary reference, where you have to manually specify the
identification (e.g. "Pr_12_23_45") and name (e.g. "Door Products").
Option 2) add a reference from an IFC classification library. The latter
is preferred if you are using a common classification system such as
Uniclass, as the library will be prepopulated with all the valid
classifications already.
Objects are allowed to have multiple classification references from
multiple classification systems. This means that adding a new reference
will not remove existing references.
References can be inherited from types. This means that if an
IfcWallType has a classification reference of Pr_12_23_34, then all
IfcWall occurrences of that type automatically get the same
classification of Pr_12_23_34. This means that it is more efficient to
assign to types where possible. If a classification reference is
assigned to both the type and an occurrence, then the assignment at the
occurrence will override the type classification.
:param product: The list of IFC objects, properties, or resources you want to
associate the classification reference to.
:type product: list[ifcopenshell.entity_instance]
:param reference: The classification reference entity taken from an
IFC classification library. If you supply this parameter, you will
use option 2.
:type reference: ifcopenshell.entity_instance, optional
:param identification: If you choose option 1 and do not specify a
reference, you may manually specify an identification code. The code
is typically a short identifier and may have punctuation to separate
the levels of hierarchy in the classificaion (e.g. Pr_12_23_34).
:type identification: str, optional
:param name: If you choose option 1 and do not specify a reference, you
may manually specify a name. The name is typically human readable.
:type name: str, optional
:param classification: The IfcClassification entity in your IFC model
(not the library, if you are doing option 2) that the reference is
part of.
:type classification: ifcopenshell.entity_instance
:param is_lightweight: If you are doing option 2, choose whether or not
to only add that particular reference (lighweight) or also add all
of its parent references in the classification hierarchy (not
lighweight). For example, adding a lightweight reference to
Pr_12_23_34 will only add Pr_12_23_34, but adding a heavy reference
to Pr_12_23_34 will also add Pr_12_23 and Pr_12. These parent
references merely help describe the "tree" of classifications, but
is generally unnecessary. Using lightweight classifications are
recommended and is the default.
:type is_lightweight: bool, optional
:raises TypeError: If file is IFC2X3 and `products` has non-IfcRoot elements.
:return: The newly added IfcClassificationReference
or `None` if `products` was empty list.
:rtype: Union[ifcopenshell.entity_instance, None]
Example:
.. code:: python
# Option 1: adding and assigning a new reference from scratch
wall_type = model.by_type("IfcWallType")[0]
classification = ifcopenshell.api.run("classification.add_classification",
model, classification="MyCustomClassification")
ifcopenshell.api.run("classification.add_reference", model,
products=[wall_type], classification=classification,
identification="W_01", name="Interior Walls")
# Option 2: adding a popular classification from a library
library = ifcopenshell.open("/path/to/Uniclass.ifc")
lib_classification = library.by_type("IfcClassification")[0]
classification = ifcopenshell.api.run("classification.add_classification",
model, classification=lib_classification)
reference = [r for r in library.by_type("IfcClassificationReference")
if r.Identification == "XYZ"][0]
ifcopenshell.api.run("classification.add_reference", model,
products=[wall_type], classification=classification,
reference=reference)
"""
usecase = Usecase()
usecase.file = file
usecase.settings = {
"products": products,
"reference": reference,
"identification": identification,
"name": name,
"classification": classification,
"is_lightweight": is_lightweight,
}
return usecase.execute()
class Usecase:
def __init__(
self,
file: ifcopenshell.file,
products: list[ifcopenshell.entity_instance],
reference: Optional[ifcopenshell.entity_instance] = None,
identification: Optional[str] = None,
name: Optional[str] = None,
classification: Optional[ifcopenshell.entity_instance] = None,
is_lightweight=True,
):
"""Adds a new classification reference and assigns it to the list of products
A classification reference is a single entry such as "Pr_12_23_34" that
is part of an external classification system (such as Uniclass or
Omniclass).
References can be added to almost any object in IFC, including physical
objects, object types, properties, tasks, costs, resources, or even
resources such as profiles, documents, libraries, and so on.
Classification references can be added in two ways. Option 1) specify a
custom arbitrary reference, where you have to manually specify the
identification (e.g. "Pr_12_23_45") and name (e.g. "Door Products").
Option 2) add a reference from an IFC classification library. The latter
is preferred if you are using a common classification system such as
Uniclass, as the library will be prepopulated with all the valid
classifications already.
Objects are allowed to have multiple classification references from
multiple classification systems. This means that adding a new reference
will not remove existing references.
References can be inherited from types. This means that if an
IfcWallType has a classification reference of Pr_12_23_34, then all
IfcWall occurrences of that type automatically get the same
classification of Pr_12_23_34. This means that it is more efficient to
assign to types where possible. If a classification reference is
assigned to both the type and an occurrence, then the assignment at the
occurrence will override the type classification.
:param product: The list of IFC objects, properties, or resources you want to
associate the classification reference to.
:type product: list[ifcopenshell.entity_instance.entity_instance]
:param reference: The classification reference entity taken from an
IFC classification library. If you supply this parameter, you will
use option 2.
:type reference: ifcopenshell.entity_instance.entity_instance, optional
:param identification: If you choose option 1 and do not specify a
reference, you may manually specify an identification code. The code
is typically a short identifier and may have punctuation to separate
the levels of hierarchy in the classificaion (e.g. Pr_12_23_34).
:type identification: str, optional
:param name: If you choose option 1 and do not specify a reference, you
may manually specify a name. The name is typically human readable.
:type name: str, optional
:param classification: The IfcClassification entity in your IFC model
(not the library, if you are doing option 2) that the reference is
part of.
:type classification: ifcopenshell.entity_instance.entity_instance
:param is_lightweight: If you are doing option 2, choose whether or not
to only add that particular reference (lighweight) or also add all
of its parent references in the classification hierarchy (not
lighweight). For example, adding a lightweight reference to
Pr_12_23_34 will only add Pr_12_23_34, but adding a heavy reference
to Pr_12_23_34 will also add Pr_12_23 and Pr_12. These parent
references merely help describe the "tree" of classifications, but
is generally unnecessary. Using lightweight classifications are
recommended and is the default.
:type is_lightweight: bool, optional
:raises TypeError: If file is IFC2X3 and `products` has non-IfcRoot elements.
:return: The newly added IfcClassificationReference
or `None` if `products` was empty list.
:rtype: Union[ifcopenshell.entity_instance.entity_instance, None]
Example:
.. code:: python
# Option 1: adding and assigning a new reference from scratch
wall_type = model.by_type("IfcWallType")[0]
classification = ifcopenshell.api.run("classification.add_classification",
model, classification="MyCustomClassification")
ifcopenshell.api.run("classification.add_reference", model,
products=[wall_type], classification=classification,
identification="W_01", name="Interior Walls")
# Option 2: adding a popular classification from a library
library = ifcopenshell.open("/path/to/Uniclass.ifc")
lib_classification = library.by_type("IfcClassification")[0]
classification = ifcopenshell.api.run("classification.add_classification",
model, classification=lib_classification)
reference = [r for r in library.by_type("IfcClassificationReference")
if r.Identification == "XYZ"][0]
ifcopenshell.api.run("classification.add_reference", model,
products=[wall_type], classification=classification,
reference=reference)
"""
self.file = file
self.settings = {
"products": products,
"reference": reference,
"identification": identification,
"name": name,
"classification": classification,
"is_lightweight": is_lightweight,
}
def execute(self) -> Union[ifcopenshell.entity_instance, None]:
def execute(self):
if not self.settings["products"]:
return
@@ -17,32 +17,29 @@
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
class Usecase:
def __init__(self, file, classification=None, attributes=None):
"""Edits the attributes of an IfcClassification
def edit_classification(file, classification=None, attributes=None) -> None:
"""Edits the attributes of an IfcClassification
For more information about the attributes and data types of an
IfcClassification, consult the IFC documentation.
For more information about the attributes and data types of an
IfcClassification, consult the IFC documentation.
:param classification: The IfcClassification entity you want to edit
:type classification: ifcopenshell.entity_instance.entity_instance
:param attributes: a dictionary of attribute names and values.
:type attributes: dict, optional
:return: None
:rtype: None
:param classification: The IfcClassification entity you want to edit
:type classification: ifcopenshell.entity_instance
:param attributes: a dictionary of attribute names and values.
:type attributes: dict, optional
:return: None
:rtype: None
Example:
Example:
.. code:: python
.. code:: python
classification = model.by_type("IfcClassification")[0]
# Change the name of the classification system to "Foo"
ifcopenshell.api.run("classification.edit_classification", model,
classification=classification, attributes={"Name": "Foo"})
"""
self.file = file
self.settings = {"classification": classification, "attributes": attributes or {}}
classification = model.by_type("IfcClassification")[0]
# Change the name of the classification system to "Foo"
ifcopenshell.api.run("classification.edit_classification", model,
classification=classification, attributes={"Name": "Foo"})
"""
settings = {"classification": classification, "attributes": attributes or {}}
def execute(self):
for name, value in self.settings["attributes"].items():
setattr(self.settings["classification"], name, value)
for name, value in settings["attributes"].items():
setattr(settings["classification"], name, value)
@@ -17,32 +17,29 @@
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
class Usecase:
def __init__(self, file, reference=None, attributes=None):
"""Edits the attributes of an IfcClassificationReference
def edit_reference(file, reference=None, attributes=None) -> None:
"""Edits the attributes of an IfcClassificationReference
For more information about the attributes and data types of an
IfcClassificationReference, consult the IFC documentation.
For more information about the attributes and data types of an
IfcClassificationReference, consult the IFC documentation.
:param reference: The IfcClassificationReference entity you want to edit
:type reference: ifcopenshell.entity_instance.entity_instance
:param attributes: a dictionary of attribute names and values.
:type attributes: dict, optional
:return: None
:rtype: None
:param reference: The IfcClassificationReference entity you want to edit
:type reference: ifcopenshell.entity_instance
:param attributes: a dictionary of attribute names and values.
:type attributes: dict, optional
:return: None
:rtype: None
Example:
Example:
.. code:: python
.. code:: python
reference = model.by_type("IfcClassification")[0]
# Change the name of the reference to "Foo"
ifcopenshell.api.run("classification.edit_reference", model,
reference=reference, attributes={"Name": "Foo"})
"""
self.file = file
self.settings = {"reference": reference, "attributes": attributes or {}}
reference = model.by_type("IfcClassification")[0]
# Change the name of the reference to "Foo"
ifcopenshell.api.run("classification.edit_reference", model,
reference=reference, attributes={"Name": "Foo"})
"""
settings = {"reference": reference, "attributes": attributes or {}}
def execute(self):
for name, value in self.settings["attributes"].items():
setattr(self.settings["reference"], name, value)
for name, value in settings["attributes"].items():
setattr(settings["reference"], name, value)
@@ -20,30 +20,33 @@ import ifcopenshell
import ifcopenshell.util.element
def remove_classification(file: ifcopenshell.entity_instance, classification: ifcopenshell.entity_instance) -> None:
"""Removes an IfcClassification from the project and all references
The classification and all of its relationships, children references,
and relationships between objects and child references are completely
removed from a project.
:param classification: The IfcClassification entity you want to remove
:type classification: ifcopenshell.entity_instance
:return: None
:rtype: None
Example:
.. code:: python
classification = model.by_type("IfcClassification")[0]
ifcopenshell.api.run("classification.remove_classification", model,
classification=classification)
"""
usecase = Usecase()
usecase.file = file
usecase.settings = {"classification": classification}
return usecase.execute()
class Usecase:
def __init__(self, file, classification=None):
"""Removes an IfcClassification from the project and all references
The classification and all of its relationships, children references,
and relationships between objectse and child references are completely
removed from a project.
:param classification: The IfcClassification entity you want to remove
:type classification: ifcopenshell.entity_instance.entity_instance
:return: None
:rtype: None
Example:
.. code:: python
classification = model.by_type("IfcClassification")[0]
ifcopenshell.api.run("classification.remove_classification", model,
classification=classification)
"""
self.file = file
self.settings = {"classification": classification}
def execute(self):
references = self.get_references(self.settings["classification"])
for reference in references:
@@ -21,107 +21,102 @@ import ifcopenshell.api
import ifcopenshell.util.element
class Usecase:
def __init__(
self,
file: ifcopenshell.file,
reference: ifcopenshell.entity_instance,
products: list[ifcopenshell.entity_instance],
):
"""Removes a classification reference from the list of products
def remove_reference(
file: ifcopenshell.file,
reference: ifcopenshell.entity_instance,
products: list[ifcopenshell.entity_instance],
) -> None:
"""Removes a classification reference from the list of products
If the classification reference is no longer associated to any products,
the classification reference itself is also removed.
If the classification reference is no longer associated to any products,
the classification reference itself is also removed.
:param reference: The IfcClassificationReference entity of the
relationship you want to remove.
:type reference: ifcopenshell.entity_instance.entity_instance
:param product: The list fo object entities of the relationship you want to
remove.
:type product: list[ifcopenshell.entity_instance.entity_instance]
:param reference: The IfcClassificationReference entity of the
relationship you want to remove.
:type reference: ifcopenshell.entity_instance
:param product: The list fo object entities of the relationship you want to
remove.
:type product: list[ifcopenshell.entity_instance]
:raises TypeError: If file is IFC2X3 and `products` has non-IfcRoot elements.
:raises TypeError: If file is IFC2X3 and `products` has non-IfcRoot elements.
:return: None
:rtype: None
:return: None
:rtype: None
Example:
Example:
.. code:: python
.. code:: python
wall_type = model.by_type("IfcWallType")[0]
classification = ifcopenshell.api.run("classification.add_classification",
model, classification="MyCustomClassification")
reference = ifcopenshell.api.run("classification.add_reference", model,
products=[wall_type], classification=classification,
identification="W_01", name="Interior Walls")
ifcopenshell.api.run("classification.remove_reference", model,
reference=reference, products=[wall_type])
"""
self.file = file
self.settings = {"reference": reference, "products": products}
wall_type = model.by_type("IfcWallType")[0]
classification = ifcopenshell.api.run("classification.add_classification",
model, classification="MyCustomClassification")
reference = ifcopenshell.api.run("classification.add_reference", model,
products=[wall_type], classification=classification,
identification="W_01", name="Interior Walls")
ifcopenshell.api.run("classification.remove_reference", model,
reference=reference, products=[wall_type])
"""
settings = {"reference": reference, "products": products}
def execute(self) -> None:
is_ifc2x3 = self.file.schema == "IFC2X3"
products = set(self.settings["products"])
referenced = ifcopenshell.util.element.get_referenced_elements(self.settings["reference"])
products -= products.difference(referenced)
is_ifc2x3 = file.schema == "IFC2X3"
products = set(settings["products"])
referenced = ifcopenshell.util.element.get_referenced_elements(settings["reference"])
products -= products.difference(referenced)
# all products are already unassigned from a reference
if not products:
return
# all products are already unassigned from a reference
if not products:
return
rooted_products: set[ifcopenshell.entity_instance] = set()
non_rooted_products: set[ifcopenshell.entity_instance] = set()
for product in self.settings["products"]:
if product.is_a("IfcRoot"):
rooted_products.add(product)
rooted_products: set[ifcopenshell.entity_instance] = set()
non_rooted_products: set[ifcopenshell.entity_instance] = set()
for product in settings["products"]:
if product.is_a("IfcRoot"):
rooted_products.add(product)
else:
non_rooted_products.add(product)
if non_rooted_products and is_ifc2x3:
raise TypeError(f"Cannot add reference to non-IfcRoot element in IFC2X3: {non_rooted_products}.")
if rooted_products:
reference_rels: set[ifcopenshell.entity_instance] = set()
for product in rooted_products:
reference_rels.update(product.HasAssociations)
reference_rels = {
rel
for rel in reference_rels
if rel.is_a("IfcRelAssociatesClassification") and rel.RelatingClassification == settings["reference"]
}
for rel in reference_rels:
related_objects = set(rel.RelatedObjects) - rooted_products
if related_objects:
rel.RelatedObjects = list(related_objects)
ifcopenshell.api.run("owner.update_owner_history", file, **{"element": rel})
else:
non_rooted_products.add(product)
history = rel.OwnerHistory
file.remove(rel)
if history:
ifcopenshell.util.element.remove_deep2(file, history)
if non_rooted_products and is_ifc2x3:
raise TypeError(f"Cannot add reference to non-IfcRoot element in IFC2X3: {non_rooted_products}.")
if non_rooted_products:
reference_rels: set[ifcopenshell.entity_instance] = set()
for product in non_rooted_products:
rels = getattr(product, "HasExternalReferences", None)
if rels is None:
rels = getattr(product, "HasExternalReference", [])
reference_rels.update(rels)
if rooted_products:
reference_rels: set[ifcopenshell.entity_instance] = set()
for product in rooted_products:
reference_rels.update(product.HasAssociations)
reference_rels = {rel for rel in reference_rels if rel.RelatingReference == settings["reference"]}
for rel in reference_rels:
related_objects = set(rel.RelatedResourceObjects) - non_rooted_products
if related_objects:
rel.RelatedResourceObjects = list(related_objects)
else:
file.remove(rel)
reference_rels = {
rel
for rel in reference_rels
if rel.is_a("IfcRelAssociatesClassification")
and rel.RelatingClassification == self.settings["reference"]
}
for rel in reference_rels:
related_objects = set(rel.RelatedObjects) - rooted_products
if related_objects:
rel.RelatedObjects = list(related_objects)
ifcopenshell.api.run("owner.update_owner_history", self.file, **{"element": rel})
else:
history = rel.OwnerHistory
self.file.remove(rel)
if history:
ifcopenshell.util.element.remove_deep2(self.file, history)
if non_rooted_products:
reference_rels: set[ifcopenshell.entity_instance] = set()
for product in non_rooted_products:
rels = getattr(product, "HasExternalReferences", None)
if rels is None:
rels = getattr(product, "HasExternalReference", [])
reference_rels.update(rels)
reference_rels = {rel for rel in reference_rels if rel.RelatingReference == self.settings["reference"]}
for rel in reference_rels:
related_objects = set(rel.RelatedResourceObjects) - non_rooted_products
if related_objects:
rel.RelatedResourceObjects = list(related_objects)
else:
self.file.remove(rel)
# TODO: we only handle lightweight classifications here
referenced_elements = ifcopenshell.util.element.get_referenced_elements(self.settings["reference"])
if not referenced_elements:
self.file.remove(self.settings["reference"])
# TODO: we only handle lightweight classifications here
referenced_elements = ifcopenshell.util.element.get_referenced_elements(settings["reference"])
if not referenced_elements:
file.remove(settings["reference"])
@@ -15,3 +15,13 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
from .add_metric import add_metric
from .add_metric_reference import add_metric_reference
from .add_objective import add_objective
from .assign_constraint import assign_constraint
from .edit_metric import edit_metric
from .edit_objective import edit_objective
from .remove_constraint import remove_constraint
from .remove_metric import remove_metric
from .unassign_constraint import unassign_constraint
@@ -19,44 +19,41 @@
import ifcopenshell
class Usecase:
def __init__(self, file, objective=None):
"""Add a new metric benchmark
def add_metric(file, objective=None) -> None:
"""Add a new metric benchmark
Qualitative constraints may have a series of quantitative benchmarks
linked to it known as metrics. Metrics may be parametrically linked to
computed model properties or quantities. Metrics need to be satisfied
to meet the objective of the constraint.
Qualitative constraints may have a series of quantitative benchmarks
linked to it known as metrics. Metrics may be parametrically linked to
computed model properties or quantities. Metrics need to be satisfied
to meet the objective of the constraint.
:param objective: The IfcObjective that this metric is a benchmark of.
:type objective: ifcopenshell.entity_instance.entity_instance
:return: The newly created IfcMetric entity
:rtype: ifcopenshell.entity_instance.entity_instance
:param objective: The IfcObjective that this metric is a benchmark of.
:type objective: ifcopenshell.entity_instance
:return: The newly created IfcMetric entity
:rtype: ifcopenshell.entity_instance
Example:
Example:
.. code:: python
.. code:: python
objective = ifcopenshell.api.run("constraint.add_objective", model)
metric = ifcopenshell.api.run("constraint.add_metric", model,
objective=objective)
"""
self.file = file
self.settings = {
"objective": objective,
objective = ifcopenshell.api.run("constraint.add_objective", model)
metric = ifcopenshell.api.run("constraint.add_metric", model,
objective=objective)
"""
settings = {
"objective": objective,
}
metric = file.create_entity(
"IfcMetric",
**{
"Name": "Unnamed",
"ConstraintGrade": "NOTDEFINED",
"Benchmark": "EQUALTO",
}
def execute(self):
metric = self.file.create_entity(
"IfcMetric",
**{
"Name": "Unnamed",
"ConstraintGrade": "NOTDEFINED",
"Benchmark": "EQUALTO",
}
)
if self.settings["objective"]:
benchmark_values = list(self.settings["objective"].BenchmarkValues or [])
benchmark_values.append(metric)
self.settings["objective"].BenchmarkValues = benchmark_values
return metric
)
if settings["objective"]:
benchmark_values = list(settings["objective"].BenchmarkValues or [])
benchmark_values.append(metric)
settings["objective"].BenchmarkValues = benchmark_values
return metric
@@ -18,28 +18,26 @@
import ifcopenshell
class Usecase:
def __init__(self, file, metric=None, reference_path=None):
"""
Adds a chain of references to a metric. The reference path is a string of the form "attribute.attribute.attribute"
Used to reference a value of an attribute of an instance through a metric objective entity.
"""
self.file = file
self.settings = {"metric": metric, "reference_path": reference_path}
def execute(self):
if self.settings["reference_path"]:
attributes = self.settings["reference_path"].split(".")
references_created = []
for i in range(len(attributes)):
if i == 0:
reference = self.file.create_entity("IfcReference")
reference.AttributeIdentifier = attributes[i]
self.settings["metric"].ReferencePath = reference
references_created.append(reference)
else:
reference = self.file.create_entity("IfcReference")
reference.AttributeIdentifier = attributes[i]
references_created[i-1].InnerReference = reference
references_created.append(reference)
return references_created
def add_metric_reference(file, metric=None, reference_path=None) -> None:
"""
Adds a chain of references to a metric. The reference path is a string of the form "attribute.attribute.attribute"
Used to reference a value of an attribute of an instance through a metric objective entity.
"""
settings = {"metric": metric, "reference_path": reference_path}
if settings["reference_path"]:
attributes = settings["reference_path"].split(".")
references_created = []
for i in range(len(attributes)):
if i == 0:
reference = file.create_entity("IfcReference")
reference.AttributeIdentifier = attributes[i]
settings["metric"].ReferencePath = reference
references_created.append(reference)
else:
reference = file.create_entity("IfcReference")
reference.AttributeIdentifier = attributes[i]
references_created[i - 1].InnerReference = reference
references_created.append(reference)
return references_created
@@ -19,34 +19,31 @@
import ifcopenshell
class Usecase:
def __init__(self, file):
"""Add a new objective constraint
def add_objective(file) -> None:
"""Add a new objective constraint
Parametric constraints may be defined by the user. The constraint is defined
by first creating an objective describing the purpose of the constraint and
whether it is a hard or soft constraint. Later on, metrics may be added to
check whether the constraint has been met by connecting it to properties and
quantities. See ifcopenshell.api.constraint.add_metric for more information.
Parametric constraints may be defined by the user. The constraint is defined
by first creating an objective describing the purpose of the constraint and
whether it is a hard or soft constraint. Later on, metrics may be added to
check whether the constraint has been met by connecting it to properties and
quantities. See ifcopenshell.api.constraint.add_metric for more information.
:return: The newly created IfcObjective entity
:rtype: ifcopenshell.entity_instance.entity_instance
:return: The newly created IfcObjective entity
:rtype: ifcopenshell.entity_instance
Example:
Example:
.. code:: python
.. code:: python
# Create a new objective for code compliance requirements
objective = ifcopenshell.api.run("constraint.add_objective", model)
objective.ConstraintGrade = "ADVISORY"
objective.ObjectiveQualifier = "CODECOMPLIANCE"
# Note: the objective right now is purely qualitative and for
# information purposes. You may wish to add quantiative metrics.
"""
self.file = file
self.settings = {}
# Create a new objective for code compliance requirements
objective = ifcopenshell.api.run("constraint.add_objective", model)
objective.ConstraintGrade = "ADVISORY"
objective.ObjectiveQualifier = "CODECOMPLIANCE"
# Note: the objective right now is purely qualitative and for
# information purposes. You may wish to add quantiative metrics.
"""
settings = {}
def execute(self):
return self.file.create_entity(
"IfcObjective", **{"Name": "Unnamed", "ConstraintGrade": "NOTDEFINED", "ObjectiveQualifier": "NOTDEFINED"}
)
return file.create_entity(
"IfcObjective", **{"Name": "Unnamed", "ConstraintGrade": "NOTDEFINED", "ObjectiveQualifier": "NOTDEFINED"}
)
@@ -21,39 +21,41 @@ import ifcopenshell.api
from typing import Union
def assign_constraint(
file: ifcopenshell.file,
products: list[ifcopenshell.entity_instance],
constraint: ifcopenshell.entity_instance,
) -> Union[ifcopenshell.entity_instance, None]:
"""Assigns a constraint to a list of products
This assigns a relationship between a product and a constraint, so that
when a product's properties and quantities do not match the requirements
of the constraint's metrics, results can be flagged.
It is assumed (but not explicit in the IFC documentation) that
constraints are inherited from the type. This way, it is not necessary
to create lots of constraint assignments.
:param products: The list of products the constraint applies to. This is anything
which can have properties or quantities.
:type products: list[ifcopenshell.entity_instance]
:param constraint: The IfcObjective constraint
:type constraint: ifcopenshell.entity_instance
:return: The new or updated IfcRelAssociatesConstraint relationship
or `None` if `products` was an empty list.
:rtype: ifcopenshell.entity_instance
"""
usecase = Usecase()
usecase.file = file
usecase.settings = {
"products": products,
"constraint": constraint,
}
return usecase.execute()
class Usecase:
def __init__(
self,
file: ifcopenshell.file,
products: list[ifcopenshell.entity_instance],
constraint: ifcopenshell.entity_instance,
):
"""Assigns a constraint to a list of products
This assigns a relationship between a product and a constraint, so that
when a product's properties and quantities do not match the requirements
of the constraint's metrics, results can be flagged.
It is assumed (but not explicit in the IFC documentation) that
constraints are inherited from the type. This way, it is not necessary
to create lots of constraint assignments.
:param products: The list of products the constraint applies to. This is anything
which can have properties or quantities.
:type products: list[ifcopenshell.entity_instance.entity_instance]
:param constraint: The IfcObjective constraint
:type constraint: ifcopenshell.entity_instance.entity_instance
:return: The new or updated IfcRelAssociatesConstraint relationship
or `None` if `products` was an empty list.
:rtype: ifcopenshell.entity_instance.entity_instance
"""
self.file = file
self.settings = {
"products": products,
"constraint": constraint,
}
def execute(self) -> Union[ifcopenshell.entity_instance, None]:
def execute(self):
products = set(self.settings["products"])
if not products:
return
@@ -17,33 +17,30 @@
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
class Usecase:
def __init__(self, file, metric=None, attributes=None):
"""Edit the attributes of a metric
def edit_metric(file, metric=None, attributes=None) -> None:
"""Edit the attributes of a metric
For more information about the attributes and data types of an
IfcMetric, consult the IFC documentation.
For more information about the attributes and data types of an
IfcMetric, consult the IFC documentation.
:param metric: The IfcMetric you want to edit.
:type metric: ifcopenshell.entity_instance.entity_instance
:param attributes: a dictionary of attribute names and values.
:type attributes: dict, optional
:return: None
:rtype: None
:param metric: The IfcMetric you want to edit.
:type metric: ifcopenshell.entity_instance
:param attributes: a dictionary of attribute names and values.
:type attributes: dict, optional
:return: None
:rtype: None
Example:
Example:
.. code:: python
.. code:: python
objective = ifcopenshell.api.run("constraint.add_objective", model)
metric = ifcopenshell.api.run("constraint.add_metric", model,
objective=objective)
ifcopenshell.api.run("constraint.edit_metric", model,
metric=metric, attributes={"ConstraintGrade": "HARD"})
"""
self.file = file
self.settings = {"metric": metric, "attributes": attributes or {}}
objective = ifcopenshell.api.run("constraint.add_objective", model)
metric = ifcopenshell.api.run("constraint.add_metric", model,
objective=objective)
ifcopenshell.api.run("constraint.edit_metric", model,
metric=metric, attributes={"ConstraintGrade": "HARD"})
"""
settings = {"metric": metric, "attributes": attributes or {}}
def execute(self):
for name, value in self.settings["attributes"].items():
setattr(self.settings["metric"], name, value)
for name, value in settings["attributes"].items():
setattr(settings["metric"], name, value)
@@ -17,31 +17,28 @@
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
class Usecase:
def __init__(self, file, objective=None, attributes=None):
"""Edit the attributes of a objective
def edit_objective(file, objective=None, attributes=None) -> None:
"""Edit the attributes of a objective
For more information about the attributes and data types of an
IfcObjective, consult the IFC documentation.
For more information about the attributes and data types of an
IfcObjective, consult the IFC documentation.
:param objective: The IfcObjective you want to edit.
:type objective: ifcopenshell.entity_instance.entity_instance
:param attributes: a dictionary of attribute names and values.
:type attributes: dict, optional
:return: None
:rtype: None
:param objective: The IfcObjective you want to edit.
:type objective: ifcopenshell.entity_instance
:param attributes: a dictionary of attribute names and values.
:type attributes: dict, optional
:return: None
:rtype: None
Example:
Example:
.. code:: python
.. code:: python
objective = ifcopenshell.api.run("constraint.add_objective", model)
ifcopenshell.api.run("constraint.edit_objective", model,
objective=objective, attributes={"ConstraintGrade": "HARD"})
"""
self.file = file
self.settings = {"objective": objective, "attributes": attributes or {}}
objective = ifcopenshell.api.run("constraint.add_objective", model)
ifcopenshell.api.run("constraint.edit_objective", model,
objective=objective, attributes={"ConstraintGrade": "HARD"})
"""
settings = {"objective": objective, "attributes": attributes or {}}
def execute(self):
for name, value in self.settings["attributes"].items():
setattr(self.settings["objective"], name, value)
for name, value in settings["attributes"].items():
setattr(settings["objective"], name, value)
@@ -20,36 +20,33 @@ import ifcopenshell
import ifcopenshell.util.element
class Usecase:
def __init__(self, file, constraint=None):
"""Remove a constraint (typically an objective)
def remove_constraint(file, constraint=None) -> None:
"""Remove a constraint (typically an objective)
Removes a constraint definition and all of its associations to any
products. Typically this would be an IfcObjective, although technically
you can associate IfcMetrics ith products too, though the meaning may be
unclear.
Removes a constraint definition and all of its associations to any
products. Typically this would be an IfcObjective, although technically
you can associate IfcMetrics ith products too, though the meaning may be
unclear.
:param constraint: The IfcObjective you want to remove.
:type constraint: ifcopenshell.entity_instance.entity_instance
:return: None
:rtype: None
:param constraint: The IfcObjective you want to remove.
:type constraint: ifcopenshell.entity_instance
:return: None
:rtype: None
Example:
Example:
.. code:: python
.. code:: python
objective = ifcopenshell.api.run("constraint.add_objective", model)
ifcopenshell.api.run("constraint.remove_constraint", model,
constraint=objective)
"""
self.file = file
self.settings = {"constraint": constraint}
objective = ifcopenshell.api.run("constraint.add_objective", model)
ifcopenshell.api.run("constraint.remove_constraint", model,
constraint=objective)
"""
settings = {"constraint": constraint}
def execute(self):
self.file.remove(self.settings["constraint"])
for rel in self.file.by_type("IfcRelAssociatesConstraint"):
if not rel.RelatingConstraint:
history = rel.OwnerHistory
self.file.remove(rel)
if history:
ifcopenshell.util.element.remove_deep2(self.file, history)
file.remove(settings["constraint"])
for rel in file.by_type("IfcRelAssociatesConstraint"):
if not rel.RelatingConstraint:
history = rel.OwnerHistory
file.remove(rel)
if history:
ifcopenshell.util.element.remove_deep2(file, history)
@@ -17,31 +17,34 @@
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
def remove_metric(file, metric=None) -> None:
"""Remove a metric benchmark
Removes a metric benchmark and all of its associations to any products
and objectives.
:param metric: The IfcMetric you want to remove.
:type metric: ifcopenshell.entity_instance
:return: None
:rtype: None
Example:
.. code:: python
objective = ifcopenshell.api.run("constraint.add_objective", model)
metric = ifcopenshell.api.run("constraint.add_metric", model,
objective=objective)
ifcopenshell.api.run("constraint.remove_metric", model,
metric=metric)
"""
usecase = Usecase()
usecase.file = file
usecase.settings = {"metric": metric}
return usecase.execute()
class Usecase:
def __init__(self, file, metric=None):
"""Remove a metric benchmark
Removes a metric benchmark and all of its associations to any products
and objectives.
:param metric: The IfcMetric you want to remove.
:type metric: ifcopenshell.entity_instance.entity_instance
:return: None
:rtype: None
Example:
.. code:: python
objective = ifcopenshell.api.run("constraint.add_objective", model)
metric = ifcopenshell.api.run("constraint.add_metric", model,
objective=objective)
ifcopenshell.api.run("constraint.remove_metric", model,
metric=metric)
"""
self.file = file
self.settings = {"metric": metric}
def execute(self):
if self.settings["metric"].ReferencePath:
reference = self.settings["metric"].ReferencePath
@@ -21,31 +21,33 @@ import ifcopenshell.api
import ifcopenshell.util.element
def unassign_constraint(
file: ifcopenshell.file,
products: list[ifcopenshell.entity_instance],
constraint: ifcopenshell.entity_instance,
) -> None:
"""Unassigns a constraint from a list of products
The constraint will not be deleted and is available to be assigned to
other products.
:param products: The list of products the constraint applies to.
:type products: list[ifcopenshell.entity_instance]
:param constraint: The IfcObjective constraint
:type constraint: ifcopenshell.entity_instance
:return: None
:rtype: None
"""
usecase = Usecase()
usecase.file = file
usecase.settings = {
"products": products,
"constraint": constraint,
}
return usecase.execute()
class Usecase:
def __init__(
self,
file: ifcopenshell.file,
products: list[ifcopenshell.entity_instance],
constraint: ifcopenshell.entity_instance,
):
"""Unassigns a constraint from a list of products
The constraint will not be deleted and is available to be assigned to
other products.
:param products: The list of products the constraint applies to.
:type products: list[ifcopenshell.entity_instance.entity_instance]
:param constraint: The IfcObjective constraint
:type constraint: ifcopenshell.entity_instance.entity_instance
:return: None
:rtype: None
"""
self.file = file
self.settings = {
"products": products,
"constraint": constraint,
}
def execute(self):
products = set(self.settings["products"])
if not products:
@@ -15,3 +15,7 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
from .add_context import add_context
from .edit_context import edit_context
from .remove_context import remove_context
@@ -17,168 +17,171 @@
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
def add_context(file, context_type=None, context_identifier=None, target_view=None, parent=None) -> None:
"""Adds a new geometric representation context
In IFC, physical objects may have zero, one, or multiple geometric
representations associated with it. For example, a building storey might
not have any geometry, but simply be a coordinate in space.
Alternatively, a wall might have a 3D body representation in the form of
a cuboid. As a final example, a door might also have a 3D body
representation of a 3D door panel and door frame, but may additionally
have a 2D door plan view representation of the door swing, and even a 2D
elevation view of the door, a 3D box representing the disabled clearance
zone of the door, a 2D profile representing the profile of the door to
cut out in a wall, and so on. In this situation, a door will have
multiple geometric representations.
To distinguish between the different purposes of multiple geometric
representations, each geometric representation must belong to a
geometric representation "context". There are typically always 2
contexts, one for 3D representations and one for 2D representations.
These 2 contexts then have subcontexts for things like the 3D body
representation, clearance representations, annotation representations,
and so on. Each representation of a physical IFC product (e.g. a door)
must be assigned to one of these subcontexts. Therefore setting up
appropriate contexts is critical prior to authoring any IFC model which
contains geometry.
There are two steps to setting up appropriate subcontexts. First, a 2D
and/or 3D context must be added. These must be always called the "Model"
context for 3D and the "Plan" context for 2D (even if the 2D geometry is
not a plan view). Then, one or more subcontexts are added using either
the "Model" or "Plan" as their parent. These subcontexts are further
distinguished using an "identifier" and "target view". The "identifier"
describes the purpose of the representation, and the "target view"
describes the typical diagrammatic presentation that context's geometry
should be viewed in. The most common identifiers you might use are:
- Body: for the actual shape of the object
- Box: the bounding box of the object (useful for shape analytics)
- Axis: the parametric line determining the shape of the object
- Profile: the elevation silhouette of the object, useful for cutting
out holes for the object to fit into host elements
- Footprint: the plan view silhouette of the object, useful for certain
quantity take-off rules
- Clearance: the clearance zone of the object
- Annotation: symbolic annotations typically used in diagrams or
drawings
The most common "target views" you might use are:
- MODEL_VIEW: for 3D geometry you might see in a BIM viewer
- PLAN_VIEW: for 2D geometry you might see in a plan representation
- ELEVATION_VIEW: for 2D geometry you might see in an elevation representation
- SECTION_VIEW: for 2D geometry you might see in a section representation
- GRAPH_VIEW: for 2D or 3D line or frame or path connectivity diagrams
you might use for structural frame analysis, axis-based parametric
modeling
- SKETCH_VIEW: for viewing abstract high-level representations such as
in bubble diagrams of spatial topology
This may sound like a lot, but after a few typical contexts are set up
at the beginning, it becomes easy to navigate and isolate geometry for
different purposes. There is also the concept of a target scale, which
represents the zoom level detail of geometry, but this is not currently
supported by this API. Setting up all these contexts are also optional,
and you may only use a single Model context and Body subcontext for
simple models, but this simplification sacrifices the ability of more
parametric or analytical usecases.
:param context_type: The type of the context, must be one of "Model" or
"Plan" only.
:type context_type: str
:param context_identifier: The identifier of the context, chosen from
one of the common identifiers above or consult the IFC documentation
(under the IfcShapeRepresentation page) for more details. Optional
for contexts, but mandatory for subcontexts.
:type context_identifier: str, optional
:param target_view: the target view of the context, chosen from one of
the common target views above or consult the IFC documentation
(under the IfcShapeRepresentation page) for more details. Optional
for contexts, but mandatory for subcontexts.
:type target_view: str, optional
:param parent: the parent context. Must be left as None (the default)
for contexts, and only set for subcontexts. Note that there are only
contexts and subcontexts, a subcontext cannot have any children.
:type parent: ifcopenshell.entity_instance, optional
:return: the newly created IfcGeometricRepresentationContext or
IfcGeometricRepresentationSubContext entity
:rtype: ifcopenshell.entity_instance, optional
Example:
.. code:: python
# If we plan to store 3D geometry in our IFC model, we have to setup
# a "Model" context.
model3d = ifcopenshell.api.run("context.add_context", model, context_type="Model")
# And/Or, if we plan to store 2D geometry, we need a "Plan" context
plan = ifcopenshell.api.run("context.add_context", model, context_type="Plan")
# Now we setup the subcontexts with each of the geometric "purposes"
# we plan to store in our model. "Body" is by far the most important
# and common context, as most IFC models are assumed to be viewable
# in 3D.
body = ifcopenshell.api.run("context.add_context", model,
context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model3d)
# The 3D Axis subcontext is important if any "axis-based" parametric
# geometry is going to be created. For example, a beam, or column
# may be drawn using a single 3D axis line, and for this we need an
# Axis subcontext.
ifcopenshell.api.run("context.add_context", model,
context_type="Model", context_identifier="Axis", target_view="GRAPH_VIEW", parent=model3d)
# The 3D Box subcontext is useful for clash detection or shape
# analysis, or even lazy-loading of large models.
ifcopenshell.api.run("context.add_context", model,
context_type="Model", context_identifier="Box", target_view="MODEL_VIEW", parent=model3d)
# It's also important to have a 2D Axis subcontext for things like
# walls and claddings which can be drawn using a 2D axis line.
ifcopenshell.api.run("context.add_context", model,
context_type="Plan", context_identifier="Axis", target_view="GRAPH_VIEW", parent=plan)
# A 2D annotation subcontext for plan views are important for door
# swings, window cuts, and symbols for equipment like GPOs, fire
# extinguishers, and so on.
ifcopenshell.api.run("context.add_context", model,
context_type="Plan", context_identifier="Annotation", target_view="PLAN_VIEW", parent=plan)
# You may also create 2D annotation subcontexts for sections and
# elevation views.
ifcopenshell.api.run("context.add_context", model,
context_type="Plan", context_identifier="Annotation", target_view="SECTION_VIEW", parent=plan)
ifcopenshell.api.run("context.add_context", model,
context_type="Plan", context_identifier="Annotation", target_view="ELEVATION_VIEW", parent=plan)
# Let's create a new wall. The wall does not have any geometry yet.
wall = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcWall")
# Let's use the "3D Body" representation we created earlier to add a
# new wall-like body geometry, 5 meters long, 3 meters high, and
# 200mm thick
representation = ifcopenshell.api.run("geometry.add_wall_representation", model,
context=body, length=5, height=3, thickness=0.2)
# Assign our new body geometry back to our wall
ifcopenshell.api.run("geometry.assign_representation", model,
product=wall, representation=representation)
# Place our wall at the origin
ifcopenshell.api.run("geometry.edit_object_placement", model, product=wall)
"""
usecase = Usecase()
usecase.file = file
usecase.settings = {
"context_type": context_type,
"parent": parent,
"context_identifier": context_identifier,
"target_view": target_view,
}
return usecase.execute()
class Usecase:
def __init__(self, file, context_type=None, context_identifier=None, target_view=None, parent=None):
"""Adds a new geometric representation context
In IFC, physical objects may have zero, one, or multiple geometric
representations associated with it. For example, a building storey might
not have any geometry, but simply be a coordinate in space.
Alternatively, a wall might have a 3D body representation in the form of
a cuboid. As a final example, a door might also have a 3D body
representation of a 3D door panel and door frame, but may additionally
have a 2D door plan view representation of the door swing, and even a 2D
elevation view of the door, a 3D box representing the disabled clearance
zone of the door, a 2D profile representing the profile of the door to
cut out in a wall, and so on. In this situation, a door will have
multiple geometric representations.
To distinguish between the different purposes of multiple geometric
representations, each geometric representation must belong to a
geometric representation "context". There are typically always 2
contexts, one for 3D representations and one for 2D representations.
These 2 contexts then have subcontexts for things like the 3D body
representation, clearance representations, annotation representations,
and so on. Each representation of a physical IFC product (e.g. a door)
must be assigned to one of these subcontexts. Therefore setting up
appropriate contexts is critical prior to authoring any IFC model which
contains geometry.
There are two steps to setting up appropriate subcontexts. First, a 2D
and/or 3D context must be added. These must be always called the "Model"
context for 3D and the "Plan" context for 2D (even if the 2D geometry is
not a plan view). Then, one or more subcontexts are added using either
the "Model" or "Plan" as their parent. These subcontexts are further
distinguished using an "identifier" and "target view". The "identifier"
describes the purpose of the representation, and the "target view"
describes the typical diagrammatic presentation that context's geometry
should be viewed in. The most common identifiers you might use are:
- Body: for the actual shape of the object
- Box: the bounding box of the object (useful for shape analytics)
- Axis: the parametric line determining the shape of the object
- Profile: the elevation silhouette of the object, useful for cutting
out holes for the object to fit into host elements
- Footprint: the plan view silhouette of the object, useful for certain
quantity take-off rules
- Clearance: the clearance zone of the object
- Annotation: symbolic annotations typically used in diagrams or
drawings
The most common "target views" you might use are:
- MODEL_VIEW: for 3D geometry you might see in a BIM viewer
- PLAN_VIEW: for 2D geometry you might see in a plan representation
- ELEVATION_VIEW: for 2D geometry you might see in an elevation representation
- SECTION_VIEW: for 2D geometry you might see in a section representation
- GRAPH_VIEW: for 2D or 3D line or frame or path connectivity diagrams
you might use for structural frame analysis, axis-based parametric
modeling
- SKETCH_VIEW: for viewing abstract high-level representations such as
in bubble diagrams of spatial topology
This may sound like a lot, but after a few typical contexts are set up
at the beginning, it becomes easy to navigate and isolate geometry for
different purposes. There is also the concept of a target scale, which
represents the zoom level detail of geometry, but this is not currently
supported by this API. Setting up all these contexts are also optional,
and you may only use a single Model context and Body subcontext for
simple models, but this simplification sacrifices the ability of more
parametric or analytical usecases.
:param context_type: The type of the context, must be one of "Model" or
"Plan" only.
:type context_type: str
:param context_identifier: The identifier of the context, chosen from
one of the common identifiers above or consult the IFC documentation
(under the IfcShapeRepresentation page) for more details. Optional
for contexts, but mandatory for subcontexts.
:type context_identifier: str, optional
:param target_view: the target view of the context, chosen from one of
the common target views above or consult the IFC documentation
(under the IfcShapeRepresentation page) for more details. Optional
for contexts, but mandatory for subcontexts.
:type target_view: str, optional
:param parent: the parent context. Must be left as None (the default)
for contexts, and only set for subcontexts. Note that there are only
contexts and subcontexts, a subcontext cannot have any children.
:type parent: ifcopenshell.entity_instance.entity_instance, optional
:return: the newly created IfcGeometricRepresentationContext or
IfcGeometricRepresentationSubContext entity
:rtype: ifcopenshell.entity_instance.entity_instance, optional
Example:
.. code:: python
# If we plan to store 3D geometry in our IFC model, we have to setup
# a "Model" context.
model3d = ifcopenshell.api.run("context.add_context", model, context_type="Model")
# And/Or, if we plan to store 2D geometry, we need a "Plan" context
plan = ifcopenshell.api.run("context.add_context", model, context_type="Plan")
# Now we setup the subcontexts with each of the geometric "purposes"
# we plan to store in our model. "Body" is by far the most important
# and common context, as most IFC models are assumed to be viewable
# in 3D.
body = ifcopenshell.api.run("context.add_context", model,
context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model3d)
# The 3D Axis subcontext is important if any "axis-based" parametric
# geometry is going to be created. For example, a beam, or column
# may be drawn using a single 3D axis line, and for this we need an
# Axis subcontext.
ifcopenshell.api.run("context.add_context", model,
context_type="Model", context_identifier="Axis", target_view="GRAPH_VIEW", parent=model3d)
# The 3D Box subcontext is useful for clash detection or shape
# analysis, or even lazy-loading of large models.
ifcopenshell.api.run("context.add_context", model,
context_type="Model", context_identifier="Box", target_view="MODEL_VIEW", parent=model3d)
# It's also important to have a 2D Axis subcontext for things like
# walls and claddings which can be drawn using a 2D axis line.
ifcopenshell.api.run("context.add_context", model,
context_type="Plan", context_identifier="Axis", target_view="GRAPH_VIEW", parent=plan)
# A 2D annotation subcontext for plan views are important for door
# swings, window cuts, and symbols for equipment like GPOs, fire
# extinguishers, and so on.
ifcopenshell.api.run("context.add_context", model,
context_type="Plan", context_identifier="Annotation", target_view="PLAN_VIEW", parent=plan)
# You may also create 2D annotation subcontexts for sections and
# elevation views.
ifcopenshell.api.run("context.add_context", model,
context_type="Plan", context_identifier="Annotation", target_view="SECTION_VIEW", parent=plan)
ifcopenshell.api.run("context.add_context", model,
context_type="Plan", context_identifier="Annotation", target_view="ELEVATION_VIEW", parent=plan)
# Let's create a new wall. The wall does not have any geometry yet.
wall = ifcopenshell.api.run("root.create_entity", model, ifc_class="IfcWall")
# Let's use the "3D Body" representation we created earlier to add a
# new wall-like body geometry, 5 meters long, 3 meters high, and
# 200mm thick
representation = ifcopenshell.api.run("geometry.add_wall_representation", model,
context=body, length=5, height=3, thickness=0.2)
# Assign our new body geometry back to our wall
ifcopenshell.api.run("geometry.assign_representation", model,
product=wall, representation=representation)
# Place our wall at the origin
ifcopenshell.api.run("geometry.edit_object_placement", model, product=wall)
"""
self.file = file
self.settings = {
"context_type": context_type,
"parent": parent,
"context_identifier": context_identifier,
"target_view": target_view,
}
def execute(self):
if not self.settings["parent"]:
if self.settings["context_type"] == "Plan":
@@ -17,37 +17,34 @@
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
class Usecase:
def __init__(self, file, context, attributes):
"""Edits the attributes of an IfcGeometricRepresentationContext
def edit_context(file, context, attributes) -> None:
"""Edits the attributes of an IfcGeometricRepresentationContext
For more information about the attributes and data types of an
IfcGeometricRepresentationContext, consult the IFC documentation.
For more information about the attributes and data types of an
IfcGeometricRepresentationContext, consult the IFC documentation.
:param context: The IfcGeometricRepresentationContext entity you want to edit
:type context: ifcopenshell.entity_instance.entity_instance
:param attributes: a dictionary of attribute names and values.
:type attributes: dict, optional
:return: None
:rtype: None
:param context: The IfcGeometricRepresentationContext entity you want to edit
:type context: ifcopenshell.entity_instance
:param attributes: a dictionary of attribute names and values.
:type attributes: dict, optional
:return: None
:rtype: None
Example:
Example:
.. code:: python
.. code:: python
model = ifcopenshell.api.run("context.add_context", model, context_type="Model")
# Revit had a bug where they incorrectly called the body representation a "Facetation"
body = ifcopenshell.api.run("context.add_context", model,
context_type="Model", context_identifier="Facetation", target_view="MODEL_VIEW", parent=model
)
model = ifcopenshell.api.run("context.add_context", model, context_type="Model")
# Revit had a bug where they incorrectly called the body representation a "Facetation"
body = ifcopenshell.api.run("context.add_context", model,
context_type="Model", context_identifier="Facetation", target_view="MODEL_VIEW", parent=model
)
# Let's fix it!
ifcopenshell.api.run("context.edit_context", model,
context=body, attributes={"ContextIdentifier": "Body"})
"""
self.file = file
self.settings = {"context": context, "attributes": attributes or {}}
# Let's fix it!
ifcopenshell.api.run("context.edit_context", model,
context=body, attributes={"ContextIdentifier": "Body"})
"""
settings = {"context": context, "attributes": attributes or {}}
def execute(self):
for name, value in self.settings["attributes"].items():
setattr(self.settings["context"], name, value)
for name, value in settings["attributes"].items():
setattr(settings["context"], name, value)
@@ -19,49 +19,46 @@
import ifcopenshell
class Usecase:
def __init__(self, file, context=None):
"""Removes an IfcGeometricRepresentationContext
def remove_context(file: ifcopenshell.entity_instance, context: ifcopenshell.entity_instance) -> None:
"""Removes an IfcGeometricRepresentationContext
Any representation geometry that is assigned to the context is also
removed. If a context is removed, then any subcontexts are also removed.
Any representation geometry that is assigned to the context is also
removed. If a context is removed, then any subcontexts are also removed.
:param context: The IfcGeometricRepresentationContext entity to remove
:type context: ifcopenshell.entity_instance.entity_instance
:return: None
:rtype: None
:param context: The IfcGeometricRepresentationContext entity to remove
:type context: ifcopenshell.entity_instance
:return: None
:rtype: None
Example:
Example:
.. code:: python
.. code:: python
model = ifcopenshell.api.run("context.add_context", model, context_type="Model")
# Revit had a bug where they incorrectly called the body representation a "Facetation"
body = ifcopenshell.api.run("context.add_context", model,
context_type="Model", context_identifier="Facetation", target_view="MODEL_VIEW", parent=model
)
model = ifcopenshell.api.run("context.add_context", model, context_type="Model")
# Revit had a bug where they incorrectly called the body representation a "Facetation"
body = ifcopenshell.api.run("context.add_context", model,
context_type="Model", context_identifier="Facetation", target_view="MODEL_VIEW", parent=model
)
# Let's just get rid of it completely
ifcopenshell.api.run("context.remove_context", model, context=body)
"""
self.file = file
self.settings = {"context": context}
# Let's just get rid of it completely
ifcopenshell.api.run("context.remove_context", model, context=body)
"""
settings = {"context": context}
def execute(self):
for subcontext in self.settings["context"].HasSubContexts:
ifcopenshell.api.run("context.remove_context", self.file, context=subcontext)
for subcontext in settings["context"].HasSubContexts:
ifcopenshell.api.run("context.remove_context", file, context=subcontext)
if getattr(self.settings["context"], "ParentContext", None):
new = self.settings["context"].ParentContext
for inverse in self.file.get_inverse(self.settings["context"]):
if inverse.is_a("IfcCoordinateOperation"):
inverse.SourceCRS = inverse.TargetCRS
ifcopenshell.util.element.remove_deep(self.file, inverse)
else:
ifcopenshell.util.element.replace_attribute(inverse, self.settings["context"], new)
self.file.remove(self.settings["context"])
else:
representations_in_context = self.settings["context"].RepresentationsInContext
self.file.remove(self.settings["context"])
for element in representations_in_context:
ifcopenshell.api.run("geometry.remove_representation", self.file, representation=element)
if getattr(settings["context"], "ParentContext", None):
new = settings["context"].ParentContext
for inverse in file.get_inverse(settings["context"]):
if inverse.is_a("IfcCoordinateOperation"):
inverse.SourceCRS = inverse.TargetCRS
ifcopenshell.util.element.remove_deep(file, inverse)
else:
ifcopenshell.util.element.replace_attribute(inverse, settings["context"], new)
file.remove(settings["context"])
else:
representations_in_context = settings["context"].RepresentationsInContext
file.remove(settings["context"])
for element in representations_in_context:
ifcopenshell.api.run("geometry.remove_representation", file, representation=element)

Some files were not shown because too many files have changed in this diff Show More