| 1 |
# Bonsai - OpenBIM Blender Add-on |
| 2 |
# Copyright (C) 2021 Dion Moult <[email protected]> |
| 3 |
# |
| 4 |
# This file is part of Bonsai. |
| 5 |
# |
| 6 |
# Bonsai is free software: you can redistribute it and/or modify |
| 7 |
# it under the terms of the GNU General Public License as published by |
| 8 |
# the Free Software Foundation, either version 3 of the License, or |
| 9 |
# (at your option) any later version. |
| 10 |
# |
| 11 |
# Bonsai is distributed in the hope that it will be useful, |
| 12 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 |
# GNU General Public License for more details. |
| 15 |
# |
| 16 |
# You should have received a copy of the GNU General Public License |
| 17 |
# along with Bonsai. If not, see <http://www.gnu.org/licenses/>. |
| 18 |
|
| 19 |
import os |
| 20 |
import bpy |
| 21 |
import numpy as np |
| 22 |
import ifcopenshell.api |
| 23 |
import ifcopenshell.ifcopenshell_wrapper as ifcopenshell_wrapper |
| 24 |
import ifcopenshell.util.element |
| 25 |
import ifcopenshell.util.schema |
| 26 |
import bonsai.core.tool |
| 27 |
import bonsai.bim.handler |
| 28 |
import bonsai.tool as tool |
| 29 |
from pathlib import Path |
| 30 |
from bonsai.bim.ifc import IfcStore, IFC_CONNECTED_TYPE |
| 31 |
from typing import Optional, Union, Any, final, Literal |
| 32 |
|
| 33 |
|
| 34 |
class Ifc(bonsai.core.tool.Ifc): |
| 35 |
OBJECT_TYPE = Literal[ |
| 36 |
"Object", |
| 37 |
"Material", |
| 38 |
"MaterialSetItem", |
| 39 |
"Task", |
| 40 |
"Cost", |
| 41 |
"Resource", |
| 42 |
"Profile", |
| 43 |
"WorkSchedule", |
| 44 |
"Group", |
| 45 |
] |
| 46 |
|
| 47 |
@classmethod |
| 48 |
def run(cls, command: str, **kwargs) -> Any: |
| 49 |
return ifcopenshell.api.run(command, IfcStore.get_file(), **kwargs) |
| 50 |
|
| 51 |
@classmethod |
| 52 |
def set(cls, ifc: ifcopenshell.file) -> None: |
| 53 |
IfcStore.file = ifc |
| 54 |
|
| 55 |
@classmethod |
| 56 |
def get(cls) -> ifcopenshell.file: |
| 57 |
return IfcStore.get_file() |
| 58 |
|
| 59 |
@classmethod |
| 60 |
def set_path(cls, value: str) -> None: |
| 61 |
bim_props = tool.Blender.get_bim_props() |
| 62 |
bim_props.ifc_file = value |
| 63 |
IfcStore.set_path(value) |
| 64 |
|
| 65 |
@classmethod |
| 66 |
def get_path(cls) -> str: |
| 67 |
"""Get absolute filepath to the IFC file, return empty string if file is not saved.""" |
| 68 |
return IfcStore.path |
| 69 |
|
| 70 |
@classmethod |
| 71 |
def get_schema(cls) -> ifcopenshell.util.schema.IFC_SCHEMA: |
| 72 |
if IfcStore.get_file(): |
| 73 |
return IfcStore.get_file().schema |
| 74 |
|
| 75 |
@classmethod |
| 76 |
def clear_history(cls) -> None: |
| 77 |
IfcStore.last_transaction = "" |
| 78 |
IfcStore.history = [] |
| 79 |
IfcStore.future = [] |
| 80 |
|
| 81 |
@classmethod |
| 82 |
def is_edited(cls, obj: bpy.types.Object, *, ignore_scale: bool = False) -> bool: |
| 83 |
return (not ignore_scale and tool.Geometry.is_scaled(obj)) or obj in IfcStore.edited_objs |
| 84 |
|
| 85 |
@classmethod |
| 86 |
def is_moved(cls, obj: bpy.types.Object, ifc_only: bool = True) -> bool: |
| 87 |
if ifc_only: |
| 88 |
element = cls.get_entity(obj) |
| 89 |
if not element and not tool.Geometry.is_representation_item(obj): |
| 90 |
return False |
| 91 |
if element and (element.is_a("IfcTypeProduct") or element.is_a("IfcProject")): |
| 92 |
return False |
| 93 |
oprops = tool.Blender.get_object_bim_props(obj) |
| 94 |
if not oprops.location_checksum: |
| 95 |
return True # Let's be conservative |
| 96 |
loc_check = np.frombuffer(eval(oprops.location_checksum)) |
| 97 |
loc_real = np.array(obj.matrix_world.translation).flatten() |
| 98 |
if not np.allclose(loc_check, loc_real, atol=1e-4): # 0.1 mm |
| 99 |
return True |
| 100 |
rot_check = np.frombuffer(eval(oprops.rotation_checksum)).reshape(3, 3) |
| 101 |
rot_real = np.array(obj.matrix_world.to_3x3()) |
| 102 |
rot_dot = np.dot(rot_check, rot_real.T) |
| 103 |
angle_rad = np.arccos(np.clip((np.trace(rot_dot) - 1) / 2, -1, 1)) |
| 104 |
if angle_rad > 0.0017453292519943296: # 0.1 degrees |
| 105 |
return True |
| 106 |
return False |
| 107 |
|
| 108 |
@classmethod |
| 109 |
def schema(cls) -> ifcopenshell_wrapper.schema_definition: |
| 110 |
return IfcStore.get_schema() |
| 111 |
|
| 112 |
@classmethod |
| 113 |
def get_entity(cls, obj: IFC_CONNECTED_TYPE) -> Union[ifcopenshell.entity_instance, None]: |
| 114 |
"""Get linked IFC entity based on obj's ifc_definition_id. |
| 115 |
|
| 116 |
Return None if object is not linked to IFC or it's linked to non-existent element. |
| 117 |
""" |
| 118 |
ifc = IfcStore.get_file() |
| 119 |
if not ifc or not obj: |
| 120 |
return |
| 121 |
|
| 122 |
props = None |
| 123 |
if isinstance(obj, bpy.types.Object): |
| 124 |
props = tool.Blender.get_object_bim_props(obj) |
| 125 |
elif isinstance(obj, bpy.types.Material): |
| 126 |
props = tool.Style.get_material_style_props(obj) |
| 127 |
else: |
| 128 |
props = tool.Geometry.get_mesh_props(obj) |
| 129 |
|
| 130 |
if props and (ifc_definition_id := props.ifc_definition_id): |
| 131 |
try: |
| 132 |
return ifc.by_id(ifc_definition_id) |
| 133 |
except RuntimeError: |
| 134 |
pass |
| 135 |
|
| 136 |
@classmethod |
| 137 |
def get_entity_by_id(cls, entity_id: int) -> Union[ifcopenshell.entity_instance, None]: |
| 138 |
"""useful to check whether entity_id is still exists in IFC""" |
| 139 |
ifc_file = tool.Ifc.get() |
| 140 |
try: |
| 141 |
return ifc_file.by_id(entity_id) |
| 142 |
except RuntimeError: |
| 143 |
return None |
| 144 |
|
| 145 |
@classmethod |
| 146 |
def get_object(cls, element: ifcopenshell.entity_instance) -> Union[IFC_CONNECTED_TYPE, None]: |
| 147 |
return IfcStore.get_element(element.id()) |
| 148 |
|
| 149 |
@classmethod |
| 150 |
def get_object_by_identifier(cls, id_or_guid: Union[int, str]) -> Union[IFC_CONNECTED_TYPE, None]: |
| 151 |
return IfcStore.get_element(id_or_guid) |
| 152 |
|
| 153 |
@classmethod |
| 154 |
def rebuild_element_maps(cls) -> None: |
| 155 |
"""Rebuilds the id_map and guid_map |
| 156 |
|
| 157 |
When any Blender object is stored outside a Blender PointerProperty, |
| 158 |
such as in a regular Python list, there is the likely probability that |
| 159 |
the object will be invalidated when undo or redo occurs. Object |
| 160 |
invalidation seems to occur whenever an object is affected during an |
| 161 |
operation, or selected, or has a related modifier, and so on ... to |
| 162 |
cover all bases, this completely rebuilds the element maps. |
| 163 |
""" |
| 164 |
|
| 165 |
IfcStore.id_map = {} |
| 166 |
IfcStore.guid_map = {} |
| 167 |
|
| 168 |
if not cls.get(): |
| 169 |
return |
| 170 |
|
| 171 |
for obj in bpy.data.objects: |
| 172 |
if obj.library: |
| 173 |
continue |
| 174 |
|
| 175 |
bpy.msgbus.clear_by_owner(obj) |
| 176 |
|
| 177 |
element = cls.get_entity(obj) |
| 178 |
if not element: |
| 179 |
continue |
| 180 |
IfcStore.id_map[element.id()] = obj |
| 181 |
global_id = getattr(element, "GlobalId", None) |
| 182 |
if global_id: |
| 183 |
IfcStore.guid_map[global_id] = obj |
| 184 |
|
| 185 |
cls.setup_listeners(obj) |
| 186 |
|
| 187 |
for obj in bpy.data.materials: |
| 188 |
if obj.library: |
| 189 |
continue |
| 190 |
|
| 191 |
bpy.msgbus.clear_by_owner(obj) |
| 192 |
|
| 193 |
style = cls.get_entity(obj) |
| 194 |
if not style: |
| 195 |
continue |
| 196 |
|
| 197 |
IfcStore.id_map[style.id()] = obj |
| 198 |
cls.setup_listeners(obj) |
| 199 |
|
| 200 |
IfcStore.edited_objs = set() |
| 201 |
edited_objs = tool.Project.get_project_props().edited_objs |
| 202 |
for i in range(len(edited_objs))[::-1]: |
| 203 |
obj = edited_objs[i].obj |
| 204 |
if obj: |
| 205 |
IfcStore.edited_objs.add(obj) |
| 206 |
else: |
| 207 |
# Object was removed. |
| 208 |
edited_objs.remove(i) |
| 209 |
|
| 210 |
@classmethod |
| 211 |
def setup_listeners(cls, obj: IFC_CONNECTED_TYPE) -> None: |
| 212 |
if isinstance(obj, bpy.types.Object): |
| 213 |
bonsai.bim.handler.subscribe_to( |
| 214 |
obj, "active_material_index", bonsai.bim.handler.active_material_index_callback |
| 215 |
) |
| 216 |
bonsai.bim.handler.subscribe_to(obj, "name", bonsai.bim.handler.name_callback) |
| 217 |
|
| 218 |
@classmethod |
| 219 |
def link( |
| 220 |
cls, |
| 221 |
element: ifcopenshell.entity_instance, |
| 222 |
obj: Union[IFC_CONNECTED_TYPE, tool.Geometry.TYPES_WITH_MESH_PROPERTIES], |
| 223 |
) -> None: |
| 224 |
IfcStore.link_element(element, obj) |
| 225 |
|
| 226 |
@classmethod |
| 227 |
def edit(cls, obj: bpy.types.Object) -> None: |
| 228 |
"""Mark object as edited. |
| 229 |
|
| 230 |
Marking object as edited is an optimization mechanism - instead of saving |
| 231 |
changed geometry to IFC, we mark it as changed and then it's saved later |
| 232 |
(typically during project save or switch_representation(should_sync_changes_first=True)). |
| 233 |
|
| 234 |
Other caveat of using edited objects is that it won't have an effect for objects with openings, |
| 235 |
since we can't deduce non-openings representation from edited representation with openings. |
| 236 |
|
| 237 |
So, it's preferable not to use edited objects if object can have an opening. It's still can be used for spaces. |
| 238 |
""" |
| 239 |
if obj in IfcStore.edited_objs: |
| 240 |
return |
| 241 |
edited_objs = tool.Project.get_project_props().edited_objs |
| 242 |
edited_objs.add().obj = obj |
| 243 |
IfcStore.edited_objs.add(obj) |
| 244 |
IfcStore.history_edit_object(obj, finish_editing=False) |
| 245 |
|
| 246 |
@classmethod |
| 247 |
def finish_edit(cls, obj: bpy.types.Object) -> None: |
| 248 |
"""Unmark object as edited. |
| 249 |
|
| 250 |
Method is safe to use on an object that wasn't marked as edited before. |
| 251 |
""" |
| 252 |
if obj not in IfcStore.edited_objs: |
| 253 |
return |
| 254 |
edited_objs = tool.Project.get_project_props().edited_objs |
| 255 |
edited_objs.remove(next(i for i, o in enumerate(edited_objs) if o.obj == obj)) |
| 256 |
IfcStore.edited_objs.discard(obj) |
| 257 |
IfcStore.history_edit_object(obj, finish_editing=True) |
| 258 |
|
| 259 |
@classmethod |
| 260 |
def resolve_uri(cls, uri: str) -> str: |
| 261 |
if os.path.isabs(uri): |
| 262 |
return uri |
| 263 |
ifc_path = cls.get_path() |
| 264 |
if os.path.isfile(ifc_path): |
| 265 |
ifc_path = os.path.dirname(ifc_path) |
| 266 |
return (uri if not uri else os.path.join(ifc_path, uri)).replace("\\", "/") |
| 267 |
|
| 268 |
@classmethod |
| 269 |
def get_uri(cls, uri: str | Path, use_relative_path: bool = False) -> str: |
| 270 |
if not use_relative_path: |
| 271 |
return Path(uri).absolute().resolve().as_posix() |
| 272 |
uri = Path(uri) |
| 273 |
if not os.path.isabs(uri) or not (ifc_path := cls.get_path()): |
| 274 |
return uri.as_posix().replace("\\", "/") |
| 275 |
if Path(uri).drive != Path(ifc_path).drive: |
| 276 |
return uri.as_posix().replace("\\", "/") |
| 277 |
if os.path.isfile(ifc_path): |
| 278 |
ifc_path = os.path.dirname(ifc_path) |
| 279 |
return Path(os.path.relpath(uri, ifc_path)).as_posix().replace("\\", "/") |
| 280 |
|
| 281 |
@classmethod |
| 282 |
def unlink( |
| 283 |
cls, element: Optional[ifcopenshell.entity_instance] = None, obj: Optional[IFC_CONNECTED_TYPE] = None |
| 284 |
) -> None: |
| 285 |
"""See IfcStore.unlink_element doc for details.""" |
| 286 |
IfcStore.unlink_element(element, obj) |
| 287 |
|
| 288 |
@classmethod |
| 289 |
def get_all_element_occurrences(cls, element: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: |
| 290 |
if element.is_a("IfcElementType"): |
| 291 |
element_type = element |
| 292 |
occurrences = ifcopenshell.util.element.get_types(element_type) |
| 293 |
else: |
| 294 |
element_type = ifcopenshell.util.element.get_type(element) |
| 295 |
if element_type: |
| 296 |
occurrences = ifcopenshell.util.element.get_types(element_type) |
| 297 |
else: |
| 298 |
occurrences = [element] |
| 299 |
return occurrences |
| 300 |
|
| 301 |
class Operator: |
| 302 |
"""IFC Operator class. |
| 303 |
|
| 304 |
Operators that edit any IFC data should inherit from this class |
| 305 |
and implement `_execute` method. |
| 306 |
|
| 307 |
`execute` method is already reserved by this class to keep track of the |
| 308 |
IFC changes for Undo system. |
| 309 |
""" |
| 310 |
|
| 311 |
transaction_key = "" |
| 312 |
transaction_data: Union[Any, None] = None |
| 313 |
|
| 314 |
@final |
| 315 |
def execute(self, context): |
| 316 |
IfcStore.execute_ifc_operator(self, context) |
| 317 |
return {"FINISHED"} |
| 318 |
|
| 319 |
# NOTE: this class can't inherit from abc.ABC to use abc.abstractmethod |
| 320 |
# because it conflicts with bpy.types.Operator. |
| 321 |
def _execute(self, context: bpy.types.Context) -> None: |
| 322 |
raise NotImplementedError("IFC operator must implement _execute method.") |