-
-
Notifications
You must be signed in to change notification settings - Fork 681
/
drawing.py
2091 lines (1799 loc) · 87.1 KB
/
drawing.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# BlenderBIM Add-on - OpenBIM Blender Add-on
# Copyright (C) 2021 Dion Moult <dion@thinkmoult.com>
#
# This file is part of BlenderBIM Add-on.
#
# BlenderBIM Add-on is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# BlenderBIM Add-on is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# 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/>.
import os
import re
import collections
import bpy
import math
import json
import lark
import bmesh
import shutil
import logging
import shapely
import platform
import mathutils
import subprocess
import numpy as np
import blenderbim.core.tool
import blenderbim.core.geometry
import blenderbim.tool as tool
import ifcopenshell.api
import ifcopenshell.geom
import ifcopenshell.util.representation
import ifcopenshell.util.element
import ifcopenshell.util.selector
import blenderbim.bim.import_ifc
import blenderbim.bim.module.drawing.sheeter as sheeter
import blenderbim.bim.module.drawing.scheduler as scheduler
import blenderbim.bim.module.drawing.annotation as annotation
import blenderbim.bim.module.drawing.helper as helper
import blenderbim.core.root
from shapely.ops import unary_union
from blenderbim.bim.module.drawing.data import FONT_SIZES, DecoratorData
from blenderbim.bim.module.drawing.prop import get_diagram_scales, BOX_ALIGNMENT_POSITIONS, ANNOTATION_TYPES_DATA
from lxml import etree
from mathutils import Vector, Matrix
from fractions import Fraction
from typing import Optional, Union, Iterable, Any
from pathlib import Path
class Drawing(blenderbim.core.tool.Drawing):
@classmethod
def canonicalise_class_name(cls, name):
return re.sub("[^0-9a-zA-Z]+", "", name)
@classmethod
def copy_representation(cls, source, dest):
if source.Representation:
dest.Representation = ifcopenshell.util.element.copy_deep(
tool.Ifc.get(), source.Representation, exclude=["IfcGeometricRepresentationContext"]
)
@classmethod
def get_annotation_data_type(cls, object_type):
return ANNOTATION_TYPES_DATA[object_type][3]
@classmethod
def create_annotation_object(cls, drawing, object_type):
data_type = cls.get_annotation_data_type(object_type)
obj = annotation.Annotator.get_annotation_obj(drawing, object_type, data_type)
if object_type == "FILL_AREA":
obj = annotation.Annotator.add_plane_to_annotation(obj)
elif object_type == "REVISION_CLOUD":
obj = annotation.Annotator.add_plane_to_annotation(obj, remove_face=True)
elif object_type == "MULTI_SYMBOL":
obj = annotation.Annotator.add_vertex_to_annotation(obj)
elif object_type == "TEXT_LEADER":
co1, _, co2, _ = annotation.Annotator.get_placeholder_coords()
obj = annotation.Annotator.add_line_to_annotation(obj, co2, co1)
elif object_type != "TEXT":
obj = annotation.Annotator.add_line_to_annotation(obj)
return obj
@classmethod
def ensure_annotation_in_drawing_plane(cls, obj, camera=None):
"""Make sure annotation object is going to be visible in the camera view"""
def get_camera_from_annotation_object(obj):
entity = tool.Ifc.get_entity(obj)
if not entity:
return
for rel in entity.HasAssignments:
if rel.is_a("IfcRelAssignsToGroup"):
for e in rel.RelatedObjects:
if e.ObjectType == "DRAWING":
return tool.Ifc.get_object(e)
if not camera:
camera = get_camera_from_annotation_object(obj) or bpy.context.scene.camera
current_pos = camera.matrix_world.inverted() @ obj.location
current_pos.z = -camera.data.clip_start - 0.05
current_pos = camera.matrix_world @ current_pos
obj.location = current_pos
ANNOTATION_TYPES_SUPPORT_SETUP = ("STAIR_ARROW", "TEXT", "REVISION_CLOUD", "FILL_AREA")
@classmethod
def setup_annotation_object(cls, obj, object_type, related_object=None):
"""Finish object's adjustments after both object and entity are created"""
if not related_object:
related_object = bpy.context.active_object
related_entity = tool.Ifc.get_entity(related_object)
if not related_entity:
return
obj_entity = tool.Ifc.get_entity(obj)
assign_product = False
if object_type == "STAIR_ARROW":
if related_entity.is_a("IfcStairFlight"):
stair, arrow = related_object, obj
# place the arrow
# NOTE: may not work correctly in EDIT mode
bbox = tool.Blender.get_object_bounding_box(stair)
arrow.location = stair.matrix_world @ Vector(
(bbox["min_x"], (bbox["max_y"] - bbox["min_y"]) / 2, bbox["max_z"])
)
last_step_x = max(v.co.x for v in stair.data.vertices if tool.Cad.is_x(v.co.z - bbox["max_z"], 0))
arrow.data.splines[0].points[0].co = Vector((0, 0, 0, 1))
arrow.data.splines[0].points[1].co = Vector((last_step_x, 0, 0, 1))
cls.ensure_annotation_in_drawing_plane(obj)
assign_product = True
elif object_type == "TEXT":
bbox = tool.Blender.get_object_bounding_box(related_object)
obj.location = related_object.matrix_world @ bbox["center"]
cls.ensure_annotation_in_drawing_plane(obj)
assign_product = True
elif object_type == "REVISION_CLOUD":
revised_object, cloud = related_object, obj
verts = [np.array(revised_object.matrix_world @ v.co) for v in revised_object.data.vertices]
verts = [(np.around(v[[0, 1]], decimals=3)).tolist() for v in verts]
edges = [e.vertices for e in revised_object.data.edges]
# shapely magic
boundary_lines = [shapely.LineString([verts[v] for v in e]) for e in edges]
unioned_boundaries = shapely.union_all(shapely.GeometryCollection(boundary_lines))
all_polygons = shapely.polygonize(unioned_boundaries.geoms).geoms
outer_shell = unary_union(all_polygons)
bm = tool.Blender.get_bmesh_for_mesh(obj.data, clean=True)
new_verts = list(outer_shell.exterior.coords)
bm_verts = [bm.verts.new(v + (0,)) for v in new_verts]
bm_edges = [bm.edges.new([bm_verts[i], bm_verts[i + 1]]) for i in range(len(new_verts) - 1)]
bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.0001)
tool.Blender.apply_bmesh(obj.data, bm, obj)
cloud.location = Vector((0, 0, 0))
cls.ensure_annotation_in_drawing_plane(cloud)
assign_product = True
if assign_product and not cls.get_assigned_product(obj_entity):
tool.Ifc.run("drawing.assign_product", relating_product=related_entity, related_object=obj_entity)
if object_type == "TEXT":
tool.Drawing.update_text_value(obj)
@classmethod
def is_annotation_object_type(cls, element, object_types):
if not isinstance(object_types, collections.abc.Iterable):
object_types = [object_types]
element_type = element.is_a()
if element_type == "IfcAnnotation" and element.ObjectType in object_types:
return True
if (
element_type == "IfcTypeProduct"
and element.ApplicableOccurrence
and element.ApplicableOccurrence.startswith("IfcAnnotation/")
):
applicable_object_type = element.ApplicableOccurrence.split("/")[1]
if applicable_object_type in object_types:
return True
return False
@classmethod
def get_annotation_representation(cls, element):
rep = ifcopenshell.util.representation.get_representation(
element, "Plan", "Annotation"
) or ifcopenshell.util.representation.get_representation(element, "Model", "Annotation")
if not rep:
return None
rep = tool.Geometry.resolve_mapped_representation(rep)
return rep
@classmethod
def create_camera(cls, name, matrix, location_hint):
camera = bpy.data.objects.new(name, bpy.data.cameras.new(name))
camera.location = (0, 0, 1.5) # The view shall be 1.5m above the origin
camera.data.show_limits = True
if location_hint == "PERSPECTIVE":
camera.data.type = "PERSP"
else:
camera.data.type = "ORTHO"
camera.data.ortho_scale = 50 # The default of 6m is too small
camera.data.clip_start = 0.002 # 2mm is close to zero but allows any GPU-drawn lines to be visible.
camera.data.clip_end = 10 # A slightly more reasonable default
if bpy.context.scene.unit_settings.system == "IMPERIAL":
camera.data.BIMCameraProperties.diagram_scale = '1/8"=1\'-0"|1/96'
else:
camera.data.BIMCameraProperties.diagram_scale = "1:100|1/100"
camera.matrix_world = matrix
bpy.context.scene.collection.objects.link(camera)
return camera
@classmethod
def create_svg_schedule(cls, schedule):
schedule_creator = scheduler.Scheduler()
schedule_creator.schedule(
cls.get_document_uri(schedule), cls.get_path_with_ext(cls.get_document_uri(schedule), "svg")
)
@classmethod
def create_svg_sheet(cls, document, titleblock):
sheet_builder = sheeter.SheetBuilder()
sheet_builder.data_dir = bpy.context.scene.BIMProperties.data_dir
uri = cls.get_document_uri(document, "LAYOUT")
sheet_builder.create(uri, titleblock)
return uri
@classmethod
def add_drawings(cls, sheet):
sheet_builder = sheeter.SheetBuilder()
sheet_builder.data_dir = bpy.context.scene.BIMProperties.data_dir
sheet_reference = None
drawing_names = []
for reference in cls.get_document_references(sheet):
if reference.Description == "LAYOUT":
sheet_reference = reference
elif reference.Description == "DRAWING":
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)
@classmethod
def delete_collection(cls, collection):
bpy.data.collections.remove(collection, do_unlink=True)
@classmethod
def delete_drawing_elements(cls, elements: Iterable[ifcopenshell.entity_instance]) -> None:
for element in elements:
obj = tool.Ifc.get_object(element)
ifcopenshell.api.run("root.remove_product", tool.Ifc.get(), product=element)
if obj:
obj_data = obj.data
bpy.data.objects.remove(obj)
if obj_data and obj_data.users == 0: # in case we have drawing element types
tool.Blender.remove_data_block(obj_data)
@classmethod
def delete_object(cls, obj: bpy.types.Object) -> None:
bpy.data.objects.remove(obj)
@classmethod
def disable_editing_drawings(cls):
bpy.context.scene.DocProperties.is_editing_drawings = False
@classmethod
def disable_editing_schedules(cls):
bpy.context.scene.DocProperties.is_editing_schedules = False
@classmethod
def disable_editing_references(cls):
bpy.context.scene.DocProperties.is_editing_references = False
@classmethod
def disable_editing_sheets(cls):
bpy.context.scene.DocProperties.is_editing_sheets = False
@classmethod
def disable_editing_text(cls, obj):
obj.BIMTextProperties.is_editing = False
@classmethod
def disable_editing_assigned_product(cls, obj):
obj.BIMAssignedProductProperties.is_editing_product = False
@classmethod
def enable_editing(cls, obj):
bpy.ops.object.select_all(action="DESELECT")
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
if obj.data:
bpy.ops.object.mode_set(mode="EDIT")
@classmethod
def enable_editing_drawings(cls):
bpy.context.scene.DocProperties.is_editing_drawings = True
@classmethod
def enable_editing_schedules(cls):
bpy.context.scene.DocProperties.is_editing_schedules = True
@classmethod
def enable_editing_references(cls):
bpy.context.scene.DocProperties.is_editing_references = True
@classmethod
def enable_editing_sheets(cls):
bpy.context.scene.DocProperties.is_editing_sheets = True
@classmethod
def enable_editing_text(cls, obj):
obj.BIMTextProperties.is_editing = True
@classmethod
def enable_editing_assigned_product(cls, obj):
obj.BIMAssignedProductProperties.is_editing_product = True
@classmethod
def ensure_unique_drawing_name(cls, name):
names = [e.Name for e in tool.Ifc.get().by_type("IfcAnnotation") if e.ObjectType == "DRAWING"]
while name in names:
name += "-X"
return name
@classmethod
def ensure_unique_identification(cls, identification):
if tool.Ifc.get_schema() == "IFC2X3":
ids = [d.DocumentId for d in tool.Ifc.get().by_type("IfcDocumentInformation") if d.Scope == "DOCUMENTATION"]
else:
ids = [
d.Identification for d in tool.Ifc.get().by_type("IfcDocumentInformation") if d.Scope == "DOCUMENTATION"
]
while identification in ids:
identification += "-X"
return identification
@classmethod
def export_text_literal_attributes(cls, obj: bpy.types.Object) -> list[dict[str, Any]]:
literals = []
for literal_props in obj.BIMTextProperties.literals:
literal_data = blenderbim.bim.helper.export_attributes(literal_props.attributes)
literals.append(literal_data)
return literals
@classmethod
def create_annotation_context(
cls, target_view: str, object_type: Optional[str] = None
) -> ifcopenshell.entity_instance:
# checking PLAN target view and annotation type that doesn't require 3d
if target_view in ("PLAN_VIEW", "REFLECTED_PLAN_VIEW") and object_type not in (
"FALL",
"SECTION_LEVEL",
"PLAN_LEVEL",
):
parent = ifcopenshell.util.representation.get_context(tool.Ifc.get(), "Plan")
else:
parent = ifcopenshell.util.representation.get_context(tool.Ifc.get(), "Model")
return ifcopenshell.api.run(
"context.add_context",
tool.Ifc.get(),
context_type=parent.ContextType,
context_identifier="Annotation",
target_view=target_view,
parent=parent,
)
@classmethod
def get_annotation_context(
cls, target_view: str, object_type: Optional[str] = None
) -> Union[ifcopenshell.entity_instance, None]:
# checking PLAN target view and annotation type that doesn't require 3d
if target_view in ("PLAN_VIEW", "REFLECTED_PLAN_VIEW") and object_type not in (
"FALL",
"SECTION_LEVEL",
"PLAN_LEVEL",
):
return ifcopenshell.util.representation.get_context(tool.Ifc.get(), "Plan", "Annotation", target_view)
return ifcopenshell.util.representation.get_context(tool.Ifc.get(), "Model", "Annotation", target_view)
@classmethod
def get_body_context(cls):
return ifcopenshell.util.representation.get_context(tool.Ifc.get(), "Model", "Body", "MODEL_VIEW")
@classmethod
def get_document_uri(
cls, document: ifcopenshell.entity_instance, description: Optional[str] = None
) -> Union[str, None]:
if getattr(document, "Location", None):
if os.path.isabs(document.Location):
return document.Location
ifc_path = tool.Ifc.get_path()
if os.path.isfile(ifc_path):
ifc_path = os.path.dirname(ifc_path)
return os.path.abspath(os.path.join(ifc_path, document.Location))
if document.is_a("IfcDocumentInformation"):
if tool.Ifc.get_schema() == "IFC2X3":
references = document.DocumentReferences
else:
references = document.HasDocumentReferences
for reference in references:
if description and reference.Description != description:
continue
location = cls.get_document_uri(reference)
if location:
return location
@classmethod
def get_path_filename(cls, path):
return os.path.splitext(os.path.basename(path))[0]
@classmethod
def get_path_with_ext(cls, path, ext):
return os.path.splitext(path)[0] + f".{ext}"
@classmethod
def get_unit_system(cls):
return bpy.context.scene.unit_settings.system
@classmethod
def get_drawing_collection(cls, drawing):
obj = tool.Ifc.get_object(drawing)
if obj:
return obj.BIMObjectProperties.collection
@classmethod
def get_drawing_group(cls, drawing: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance:
for rel in drawing.HasAssignments or []:
if rel.is_a("IfcRelAssignsToGroup") and rel.RelatingGroup.ObjectType == "DRAWING":
return rel.RelatingGroup
@classmethod
def get_drawing_document(cls, drawing: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance:
for rel in drawing.HasAssociations:
if rel.is_a("IfcRelAssociatesDocument"):
return rel.RelatingDocument
@classmethod
def get_drawing_references(cls, drawing):
results = set()
for inverse in tool.Ifc.get().get_inverse(drawing):
if inverse.is_a("IfcRelAssignsToProduct") and inverse.RelatingProduct == drawing:
results.update(inverse.RelatedObjects)
return results
@classmethod
def get_drawing_target_view(cls, drawing: ifcopenshell.entity_instance) -> str:
return ifcopenshell.util.element.get_psets(drawing).get("EPset_Drawing", {}).get("TargetView", "MODEL_VIEW")
@classmethod
def get_group_elements(cls, group: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]:
for rel in group.IsGroupedBy or []:
return rel.RelatedObjects
@classmethod
def get_ifc_representation_class(cls, object_type):
if object_type == "TEXT":
return "IfcTextLiteral"
elif object_type == "TEXT_LEADER":
return "IfcGeometricCurveSet/IfcTextLiteral"
return ""
@classmethod
def get_name(cls, element):
return element.Name
@classmethod
def generate_drawing_matrix(cls, target_view, location_hint):
x, y, z = (0, 0, 0) if location_hint == 0 else bpy.context.scene.cursor.matrix.translation
if target_view == "PLAN_VIEW":
if location_hint:
z = tool.Ifc.get_object(tool.Ifc.get().by_id(location_hint)).matrix_world.translation.z
return mathutils.Matrix(((1, 0, 0, x), (0, 1, 0, y), (0, 0, 1, z + 1.6), (0, 0, 0, 1)))
elif target_view == "REFLECTED_PLAN_VIEW":
if location_hint:
z = tool.Ifc.get_object(tool.Ifc.get().by_id(location_hint)).matrix_world.translation.z
m = mathutils.Matrix()
m[2][2] = -1
m.translation = (x, y, z + 1.6)
return m
return mathutils.Matrix(((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, -1, 0), (0, 0, 0, 1)))
elif target_view == "ELEVATION_VIEW":
if location_hint == "NORTH":
return mathutils.Matrix(((-1, 0, 0, x), (0, 0, 1, y), (0, 1, 0, z), (0, 0, 0, 1)))
elif location_hint == "SOUTH":
return mathutils.Matrix(((1, 0, 0, x), (0, 0, -1, y), (0, 1, 0, z), (0, 0, 0, 1)))
elif location_hint == "EAST":
return mathutils.Matrix(((0, 0, 1, x), (1, 0, 0, y), (0, 1, 0, z), (0, 0, 0, 1)))
elif location_hint == "WEST":
return mathutils.Matrix(((0, 0, -1, x), (-1, 0, 0, y), (0, 1, 0, z), (0, 0, 0, 1)))
elif target_view == "SECTION_VIEW":
if location_hint == "NORTH":
return mathutils.Matrix(((1, 0, 0, x), (0, 0, -1, y), (0, 1, 0, z), (0, 0, 0, 1)))
elif location_hint == "SOUTH":
return mathutils.Matrix(((-1, 0, 0, x), (0, 0, 1, y), (0, 1, 0, z), (0, 0, 0, 1)))
elif location_hint == "EAST":
return mathutils.Matrix(((0, 0, -1, x), (-1, 0, 0, y), (0, 1, 0, z), (0, 0, 0, 1)))
elif location_hint == "WEST":
return mathutils.Matrix(((0, 0, 1, x), (1, 0, 0, y), (0, 1, 0, z), (0, 0, 0, 1)))
elif target_view == "MODEL_VIEW":
return mathutils.Matrix(((1, 0, 0, x), (0, 1, 0, y), (0, 0, 1, z), (0, 0, 0, 1)))
return mathutils.Matrix()
@classmethod
def generate_sheet_identification(cls):
number = len([d for d in tool.Ifc.get().by_type("IfcDocumentInformation") if d.Scope == "DOCUMENTATION"])
return "A" + str(number).zfill(2)
@classmethod
def get_text_literal(cls, obj, return_list=False):
element = tool.Ifc.get_entity(obj)
if not element:
return
rep = cls.get_annotation_representation(element)
if not rep:
return [] if return_list else None
items = [i for i in rep.Items if i.is_a("IfcTextLiteral")]
if not items:
return [] if return_list else None
if return_list:
return items
return items[0]
@classmethod
def is_editing_sheets(cls):
return bpy.context.scene.DocProperties.is_editing_sheets
@classmethod
def remove_literal_from_annotation(cls, obj, literal):
element = tool.Ifc.get_entity(obj)
if not element:
return
rep = cls.get_annotation_representation(element)
if not rep:
return
ifc_file = tool.Ifc.get()
rep.Items = [l for l in rep.Items if l != literal]
ifcopenshell.util.element.remove_deep2(ifc_file, literal)
@classmethod
def synchronise_ifc_and_text_attributes(cls, obj):
literals = cls.get_text_literal(obj, return_list=True)
literals_attributes = cls.export_text_literal_attributes(obj)
defined_ifc_ids = [l.ifc_definition_id for l in obj.BIMTextProperties.literals]
ifc_file = tool.Ifc.get()
for ifc_definition_id, attributes in zip(defined_ifc_ids, literals_attributes):
# making sure all literals from text edit exist in ifc
if ifc_definition_id == 0:
literal = cls.add_literal_to_annotation(obj, **attributes)
else:
literal = ifc_file.by_id(ifc_definition_id)
tool.Ifc.run(
"drawing.edit_text_literal",
text_literal=literal,
attributes=attributes,
)
# remove from ifc the literals that were removed during the edit
for literal in literals:
if literal.id() not in defined_ifc_ids:
cls.remove_literal_from_annotation(obj, literal)
@classmethod
def add_literal_to_annotation(cls, obj, Literal="Literal", Path="RIGHT", BoxAlignment="bottom-left"):
element = tool.Ifc.get_entity(obj)
if not element:
return
rep = cls.get_annotation_representation(element)
if not rep:
return
ifc_file = tool.Ifc.get()
origin = ifc_file.createIfcAxis2Placement3D(
ifc_file.createIfcCartesianPoint((0.0, 0.0, 0.0)),
ifc_file.createIfcDirection((0.0, 0.0, 1.0)),
ifc_file.createIfcDirection((1.0, 0.0, 0.0)),
)
ifc_literal = ifc_file.createIfcTextLiteralWithExtent(
Literal, origin, Path, ifc_file.createIfcPlanarExtent(1000, 1000), BoxAlignment
)
rep.Items = rep.Items + (ifc_literal,)
return ifc_literal
@classmethod
def get_assigned_product(cls, element: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]:
for rel in element.HasAssignments:
if rel.is_a("IfcRelAssignsToProduct"):
return rel.RelatingProduct
@classmethod
def import_annotations_in_group(cls, group: ifcopenshell.entity_instance) -> None:
elements = set(
[e for e in cls.get_group_elements(group) if e.is_a("IfcAnnotation") and e.ObjectType != "DRAWING"]
)
logger = logging.getLogger("ImportIFC")
ifc_import_settings = blenderbim.bim.import_ifc.IfcImportSettings.factory(bpy.context, None, logger)
ifc_importer = blenderbim.bim.import_ifc.IfcImporter(ifc_import_settings)
ifc_importer.file = tool.Ifc.get()
ifc_importer.calculate_unit_scale()
ifc_importer.process_context_filter()
ifc_importer.load_existing_meshes()
ifc_importer.material_creator.load_existing_materials()
ifc_importer.create_generic_elements(elements)
for obj in ifc_importer.added_data.values():
tool.Collector.assign(obj)
# NOTE: EPsetDrawing pset is completely synced with BIMCameraProperties
# but BIMCameraProperties are only synced with EPsetDrawing at drawing import
# therefore camera props can differ from pset if the user changed them from pset.
@classmethod
def import_drawing(cls, drawing: ifcopenshell.entity_instance) -> bpy.types.Object:
settings = ifcopenshell.geom.settings()
settings.set(settings.STRICT_TOLERANCE, True)
camera_type = "ORTHO"
body = ifcopenshell.util.representation.get_representation(drawing, "Model", "Body", "MODEL_VIEW")
if "IfcRectangularPyramid" in {e.is_a() for e in tool.Ifc.get().traverse(body)}:
camera_type = "PERSP"
shape = ifcopenshell.geom.create_shape(settings, drawing)
geometry = shape.geometry
v = geometry.verts
x = [v[i] for i in range(0, len(v), 3)]
y = [v[i + 1] for i in range(0, len(v), 3)]
z = [v[i + 2] for i in range(0, len(v), 3)]
width = max(x) - min(x)
height = max(y) - min(y)
depth = max(z) - min(z)
camera = bpy.data.cameras.new(tool.Loader.get_mesh_name(geometry))
camera.type = camera_type
camera.show_limits = True
if camera_type == "ORTHO":
camera.clip_start = 0.002 # Technically 0, but Blender doesn't allow this, so 2mm it is!
camera.clip_end = depth
camera.BIMCameraProperties.width = width
camera.BIMCameraProperties.height = height
elif camera_type == "PERSP":
abs_min_z = abs(min(z))
abs_max_z = abs(max(z))
camera.clip_start = abs_max_z
camera.clip_end = abs_min_z
max_res = 1000
camera.BIMCameraProperties.width = width
camera.BIMCameraProperties.height = height
if width > height:
fov = 2 * math.atan(width / (2 * abs_min_z))
else:
fov = 2 * math.atan(height / (2 * abs_min_z))
camera.angle = fov
tool.Loader.link_mesh(shape, camera)
obj = bpy.data.objects.new(tool.Loader.get_name(drawing), camera)
cls.import_camera_props(drawing, obj)
tool.Ifc.link(drawing, obj)
m = shape.transformation.matrix.data
mat = mathutils.Matrix(
([m[0], m[3], m[6], m[9]], [m[1], m[4], m[7], m[10]], [m[2], m[5], m[8], m[11]], [0, 0, 0, 1])
)
obj.matrix_world = mat
if cls.get_drawing_target_view(drawing) == "REFLECTED_PLAN_VIEW":
obj.matrix_world[1][1] *= -1
tool.Geometry.record_object_position(obj)
tool.Collector.assign(obj)
return obj
@classmethod
def import_camera_props(cls, drawing, obj):
# Temporarily clear the definition id to prevent prop update callbacks to IFC.
ifc_definition_id = obj.BIMObjectProperties.ifc_definition_id
obj.BIMObjectProperties.ifc_definition_id = 0
camera = obj.data
camera.BIMCameraProperties.has_underlay = False
camera.BIMCameraProperties.has_linework = True
camera.BIMCameraProperties.has_annotation = True
camera.BIMCameraProperties.target_view = "PLAN_VIEW"
camera.BIMCameraProperties.is_nts = False
pset = ifcopenshell.util.element.get_pset(drawing, "EPset_Drawing")
if pset:
if "TargetView" in pset:
camera.BIMCameraProperties.target_view = pset["TargetView"]
if "Scale" in pset:
valid_scales = [
i[0] for i in get_diagram_scales(None, bpy.context) if pset["Scale"] == i[0].split("|")[-1]
]
if valid_scales:
camera.BIMCameraProperties.diagram_scale = valid_scales[0]
else:
camera.BIMCameraProperties.diagram_scale = "CUSTOM"
if ":" in pset["HumanScale"]:
numerator, denominator = pset["HumanScale"].split(":")
else:
numerator, denominator = pset["HumanScale"].split("=")
camera.BIMCameraProperties.custom_scale_numerator = numerator
camera.BIMCameraProperties.custom_scale_denominator = denominator
if "HasUnderlay" in pset:
camera.BIMCameraProperties.has_underlay = bool(pset["HasUnderlay"])
if "HasLinework" in pset:
camera.BIMCameraProperties.has_linework = bool(pset["HasLinework"])
if "HasAnnotation" in pset:
camera.BIMCameraProperties.has_annotation = bool(pset["HasAnnotation"])
if "IsNTS" in pset:
camera.BIMCameraProperties.is_nts = bool(pset["IsNTS"])
obj.BIMObjectProperties.ifc_definition_id = ifc_definition_id
@classmethod
def import_drawings(cls):
props = bpy.context.scene.DocProperties
expanded_target_views = {d.target_view for d in props.drawings if d.is_expanded}
current_drawings_selection = {d.ifc_definition_id: d.is_selected for d in props.drawings}
props.drawings.clear()
drawings = [e for e in tool.Ifc.get().by_type("IfcAnnotation") if e.ObjectType == "DRAWING"]
grouped_drawings = {
"MODEL_VIEW": [],
"PLAN_VIEW": [],
"SECTION_VIEW": [],
"ELEVATION_VIEW": [],
"REFLECTED_PLAN_VIEW": [],
}
for drawing in drawings:
target_view = cls.get_drawing_target_view(drawing)
grouped_drawings.setdefault(target_view, []).append(drawing)
for target_view, drawings in grouped_drawings.items():
new = props.drawings.add()
new.name = target_view.replace("_", " ").title() + f" ({len(drawings)})"
new.target_view = target_view
new.is_drawing = False
new.is_expanded = target_view in expanded_target_views
if not new.is_expanded:
continue
for drawing in sorted(drawings, key=lambda x: x.Name or "Unnamed"):
new = props.drawings.add()
new.name = drawing.Name or "Unnamed"
new.is_selected = current_drawings_selection.get(drawing.id(), True)
new.is_drawing = True
new.ifc_definition_id = drawing.id() # Last, to prevent unnecessary prop callbacks
@classmethod
def import_documents(cls, document_type):
dprops = bpy.context.scene.DocProperties
if document_type == "SCHEDULE":
documents_collection = dprops.schedules
elif document_type == "REFERENCE":
documents_collection = dprops.references
documents_collection.clear()
schedules = [d for d in tool.Ifc.get().by_type("IfcDocumentInformation") if d.Scope == document_type]
for schedule in schedules:
new = documents_collection.add()
new.ifc_definition_id = schedule.id()
new.name = schedule.Name or "Unnamed"
if tool.Ifc.get_schema() == "IFC2X3":
new.identification = schedule.DocumentId
else:
new.identification = schedule.Identification
@classmethod
def import_sheets(cls):
props = bpy.context.scene.DocProperties
expanded_sheets = {s.ifc_definition_id for s in props.sheets if s.is_expanded}
props.sheets.clear()
sheets = [d for d in tool.Ifc.get().by_type("IfcDocumentInformation") if d.Scope == "SHEET"]
for sheet in sorted(sheets, key=lambda s: getattr(s, "Identification", getattr(s, "DocumentId", None))):
new = props.sheets.add()
new.ifc_definition_id = sheet.id()
if tool.Ifc.get_schema() == "IFC2X3":
new.identification = sheet.DocumentId
else:
new.identification = sheet.Identification
new.name = sheet.Name
new.is_sheet = True
new.is_expanded = sheet.id() in expanded_sheets
if not new.is_expanded:
continue
for reference in cls.get_document_references(sheet):
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()
new.ifc_definition_id = reference.id()
new.is_sheet = False
if tool.Ifc.get_schema() == "IFC2X3":
new.identification = reference.ItemReference or ""
else:
new.identification = reference.Identification or ""
new.name = os.path.basename(reference.Location)
new.reference_type = reference.Description
@classmethod
def get_active_sheet(cls, context):
props = context.scene.DocProperties
return next(s for s in props.sheets[: props.active_sheet_index + 1][::-1] if s.is_sheet)
@classmethod
def import_text_attributes(cls, obj):
props = obj.BIMTextProperties
props.literals.clear()
for ifc_literal in cls.get_text_literal(obj, return_list=True):
literal_props = props.literals.add()
blenderbim.bim.helper.import_attributes2(ifc_literal, literal_props.attributes)
box_alignment_mask = [False] * 9
position_string = literal_props.attributes["BoxAlignment"].string_value
box_alignment_mask[BOX_ALIGNMENT_POSITIONS.index(position_string)] = True
literal_props.box_alignment = box_alignment_mask
literal_props.ifc_definition_id = ifc_literal.id()
text_data = DecoratorData.get_ifc_text_data(obj)
props.font_size = str(text_data["FontSize"])
@classmethod
def import_assigned_product(cls, obj):
element = tool.Ifc.get_entity(obj)
product = cls.get_assigned_product(element)
if product:
obj.BIMAssignedProductProperties.relating_product = tool.Ifc.get_object(product)
else:
obj.BIMAssignedProductProperties.relating_product = None
@classmethod
def open_with_user_command(cls, user_command, path):
if user_command:
commands = json.loads(user_command)
replacements = {"path": path}
for command in commands:
command[0] = shutil.which(command[0]) or command[0]
subprocess.Popen([replacements.get(c, c) for c in command])
else:
if platform.system() == "Darwin":
subprocess.call(("open", path))
elif platform.system() == "Windows":
os.startfile(os.path.normpath(path))
else:
subprocess.call(("xdg-open", path))
@classmethod
def open_spreadsheet(cls, uri):
cls.open_with_user_command(bpy.context.preferences.addons["blenderbim"].preferences.spreadsheet_command, uri)
@classmethod
def open_svg(cls, uri):
cls.open_with_user_command(bpy.context.preferences.addons["blenderbim"].preferences.svg_command, uri)
@classmethod
def open_layout_svg(cls, uri):
cls.open_with_user_command(bpy.context.preferences.addons["blenderbim"].preferences.layout_svg_command, uri)
@classmethod
def run_root_assign_class(
cls,
obj=None,
ifc_class=None,
predefined_type=None,
should_add_representation=True,
context=None,
ifc_representation_class=None,
) -> Union[ifcopenshell.entity_instance, None]:
return blenderbim.core.root.assign_class(
tool.Ifc,
tool.Collector,
tool.Root,
obj=obj,
ifc_class=ifc_class,
predefined_type=predefined_type,
should_add_representation=should_add_representation,
context=context,
ifc_representation_class=ifc_representation_class,
)
@classmethod
def set_drawing_collection_name(cls, drawing, collection):
collection.name = tool.Loader.get_name(drawing)
@classmethod
def set_name(cls, element, name):
element.Name = name
@classmethod
def show_decorations(cls):
bpy.context.scene.DocProperties.should_draw_decorations = True
@classmethod
def update_text_value(cls, obj):
element = tool.Ifc.get_entity(obj)
if element.is_a("IfcTypeProduct"):
objs = [obj]
for occurrence in ifcopenshell.util.element.get_types(element):
obj = tool.Ifc.get_object(occurrence)
if obj:
objs.append(obj)
else:
objs = []
element_type = ifcopenshell.util.element.get_type(element)
if element_type and element_type.RepresentationMaps:
obj = tool.Ifc.get_object(element_type)
if obj:
objs.append(obj)
for occurrence in ifcopenshell.util.element.get_types(element_type):
obj = tool.Ifc.get_object(occurrence)
if obj:
objs.append(obj)
else:
objs = [obj]
for obj in objs:
props = obj.BIMTextProperties
literals = cls.get_text_literal(obj, return_list=True)
cls.import_text_attributes(obj)
for i, literal in enumerate(literals):
product = cls.get_assigned_product(tool.Ifc.get_entity(obj)) or tool.Ifc.get_entity(obj)
props.literals[i].value = cls.replace_text_literal_variables(literal.Literal, product)
@classmethod
def update_text_size_pset(cls, obj):
"""updates pset `EPset_Annotation.Classes` value
based on current font size from `obj.BIMTextProperties.font_size`
"""
props = obj.BIMTextProperties
element = tool.Ifc.get_entity(obj)
# updating text font size in EPset_Annotation.Classes
font_size = float(props.font_size)
font_size_str = next((key for key in FONT_SIZES if FONT_SIZES[key] == font_size), None)
classes = ifcopenshell.util.element.get_pset(element, "EPset_Annotation", "Classes")
classes_split = classes.split() if classes else []
different_font_sizes = [c for c in classes_split if c in FONT_SIZES and c != font_size_str]
# we do need to change pset value in ifc
# only if there are different font sizes in classes already
# or if the current font size is not present in classes
# (except regular font size because it's default)
if different_font_sizes or (font_size_str not in classes_split and font_size_str != "regular"):
classes_split = [c for c in classes_split if c not in FONT_SIZES] + [font_size_str]
classes = " ".join(classes_split)
ifc_file = tool.Ifc.get()
pset = tool.Pset.get_element_pset(element, "EPset_Annotation")
if not pset:
pset = ifcopenshell.api.run("pset.add_pset", ifc_file, product=element, name="EPset_Annotation")
ifcopenshell.api.run(
"pset.edit_pset",
ifc_file,
pset=pset,
properties={"Classes": classes},
)
# TODO below this point is highly experimental prototype code with no tests