-
-
Notifications
You must be signed in to change notification settings - Fork 77
/
BimViews.py
605 lines (517 loc) · 23.2 KB
/
BimViews.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
# ***************************************************************************
# * *
# * Copyright (c) 2018 Yorik van Havre <[email protected]> *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program 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 Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
"""This module contains FreeCAD commands for the BIM workbench"""
import os
import sys
import FreeCAD
import FreeCADGui
from BimTranslateUtils import *
UPDATEINTERVAL = 2000 # number of milliseconds between BIM Views window update
PREFS = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/BIM")
class BIM_Views:
def GetResources(self):
return {
"Pixmap": os.path.join(os.path.dirname(__file__), "icons", "BIM_Views.svg"),
"MenuText": QT_TRANSLATE_NOOP("BIM_Views", "Views manager"),
"ToolTip": QT_TRANSLATE_NOOP(
"BIM_Views", "Shows or hides the views manager"
),
"Accel": "Ctrl+9",
}
def Activated(self):
from PySide import QtCore, QtGui
vm = findWidget()
bimviewsbutton = None
mw = FreeCADGui.getMainWindow()
st = mw.statusBar()
statuswidget = st.findChild(QtGui.QToolBar, "BIMStatusWidget")
if statuswidget:
if hasattr(statuswidget, "bimviewsbutton"):
bimviewsbutton = statuswidget.bimviewsbutton
if vm:
if vm.isVisible():
vm.hide()
if bimviewsbutton:
bimviewsbutton.setChecked(False)
PREFS.SetBool("RestoreBimViews", False)
else:
vm.show()
if bimviewsbutton:
bimviewsbutton.setChecked(True)
PREFS.SetBool("RestoreBimViews", True)
self.update()
else:
vm = QtGui.QDockWidget()
# create the dialog
dialog = FreeCADGui.PySideUic.loadUi(
os.path.join(os.path.dirname(__file__), "dialogViews.ui")
)
vm.setWidget(dialog)
vm.tree = dialog.tree
# set button sizes
size = FreeCAD.ParamGet(
"User parameter:BaseApp/Preferences/General"
).GetInt("ToolbarIconSize", 24)
toolbar = QtGui.QToolBar()
toolbar.setIconSize(QtCore.QSize(size, size))
dialog.horizontalLayout.addWidget(toolbar)
for button in [
"AddLevel",
"AddProxy",
"Delete",
"Toggle",
"Isolate",
"SaveView",
"Rename",
]:
action = QtGui.QAction()
toolbar.addAction(action)
setattr(dialog, "button" + button, action)
# # set button icons
dialog.buttonAddLevel.setIcon(QtGui.QIcon(":/icons/Arch_Floor_Tree.svg"))
dialog.buttonAddProxy.setIcon(QtGui.QIcon(":/icons/Draft_SelectPlane.svg"))
dialog.buttonDelete.setIcon(QtGui.QIcon(":/icons/delete.svg"))
dialog.buttonToggle.setIcon(QtGui.QIcon(":/icons/dagViewVisible.svg"))
dialog.buttonIsolate.setIcon(QtGui.QIcon(":/icons/view-refresh.svg"))
dialog.buttonSaveView.setIcon(QtGui.QIcon(":/icons/view-perspective.svg"))
dialog.buttonRename.setIcon(
QtGui.QIcon(":/icons/accessories-text-editor.svg")
)
# set tooltips
dialog.buttonAddLevel.setToolTip(translate("BIM", "Creates a new level"))
dialog.buttonAddProxy.setToolTip(
translate("BIM", "Creates a new Working Plane Proxy")
)
dialog.buttonDelete.setToolTip(
translate("BIM", "Deletes the selected item")
)
dialog.buttonToggle.setToolTip(
translate("BIM", "Toggles selected items on/off")
)
dialog.buttonIsolate.setToolTip(
translate("BIM", "Turns all items off except the selected ones")
)
dialog.buttonSaveView.setToolTip(
translate(
"BIM", "Saves the current camera position to the selected items"
)
)
dialog.buttonRename.setToolTip(
translate("BIM", "Renames the selected item")
)
# connect signals
dialog.buttonAddLevel.triggered.connect(self.addLevel)
dialog.buttonAddProxy.triggered.connect(self.addProxy)
dialog.buttonDelete.triggered.connect(self.delete)
dialog.buttonToggle.triggered.connect(self.toggle)
dialog.buttonIsolate.triggered.connect(self.isolate)
dialog.buttonSaveView.triggered.connect(self.saveView)
dialog.buttonRename.triggered.connect(self.rename)
dialog.tree.itemClicked.connect(self.select)
dialog.tree.itemDoubleClicked.connect(show)
dialog.tree.itemChanged.connect(self.editObject)
# delay connecting after FreeCAD finishes setting up
QtCore.QTimer.singleShot(UPDATEINTERVAL, self.connectDock)
# set the dock widget
area = PREFS.GetInt("BimViewArea", 1)
floating = PREFS.GetBool("BimViewFloat", True)
height = PREFS.GetBool("BimViewWidth", 200)
width = PREFS.GetBool("BimViewHeight", 300)
tabs = PREFS.GetString("BimViewTabs", "")
vm.setObjectName("BIM Views Manager")
vm.setWindowTitle(translate("BIM", "BIM"))
mw = FreeCADGui.getMainWindow()
vm.setFloating(floating)
vm.setGeometry(vm.x(), vm.y(), width, height)
mw.addDockWidget(self.getDockArea(area), vm)
if tabs:
tabs = tabs.split("+")
for tab in tabs:
dw = mw.findChild(QtGui.QDockWidget, tab)
if dw:
mw.tabifyDockWidget(dw, vm)
break
# restore saved settings
vm.tree.setColumnWidth(0, PREFS.GetInt("ViewManagerColumnWidth", 100))
vm.setFloating(PREFS.GetBool("ViewManagerFloating", False))
# check the status bar button
if bimviewsbutton:
bimviewsbutton.setChecked(True)
PREFS.SetBool("RestoreBimViews", True)
self.update()
def connectDock(self):
"watch for dock location"
vm = findWidget()
if vm:
vm.dockLocationChanged.connect(self.onDockLocationChanged)
def update(self, retrigger=True):
"updates the view manager"
from PySide import QtCore
vm = findWidget()
if vm and FreeCAD.ActiveDocument:
if vm.isVisible() and (vm.tree.state() != vm.tree.EditingState):
vm.tree.clear()
import Draft
treeViewItems = [] # QTreeWidgetItem to Display in tree
lvHold = [] # temporary keep all the level items in the same building
soloProxyHold = []
for obj in FreeCAD.ActiveDocument.Objects:
t = Draft.getType(obj)
if obj and (
t
in [
"Building",
"BuildingPart",
"IfcBuilding",
"IfcBuildingStorey",
]
):
if (
t in ["Building", "IfcBuilding"]
or getattr(obj, "IfcType", "") == "Building"
):
building, _ = getTreeViewItem(obj)
subObjs = obj.Group
# find every levels belongs to the building
for subObj in subObjs:
if Draft.getType(subObj) in [
"BuildingPart",
"Building Storey",
"IfcBuildingStorey",
]:
lv, lvH = getTreeViewItem(subObj)
subSubObjs = subObj.Group
# find every working plane proxy belongs to the level
for subSubObj in subSubObjs:
if (
Draft.getType(subSubObj)
== "WorkingPlaneProxy"
):
wp, _ = getTreeViewItem(subSubObj)
lv.addChild(wp)
lvHold.append((lv, lvH))
sortLvHold = sorted(lvHold, key=lambda x: x[1])
sortLvItems = [item[0] for item in sortLvHold]
for lvItem in sortLvItems:
building.addChild(lvItem)
treeViewItems.append(building)
lvHold.clear()
if (
t in ["Building Storey", "IfcBuildingStorey"]
or getattr(obj, "IfcType", "") == "Building Storey"
):
if (
Draft.getType(getParent(obj))
in ["Building", "IfcBuilding"]
or getattr(getParent(obj), "IfcType", "") == "Building"
):
continue
lv, lvH = getTreeViewItem(obj)
subObjs = obj.Group
# find every working plane proxy belongs to the level
for subObj in subObjs:
if Draft.getType(subObj) == "WorkingPlaneProxy":
wp, _ = getTreeViewItem(subObj)
lv.addChild(wp)
lvHold.append((lv, lvH))
if obj and (t == "WorkingPlaneProxy"):
if (
obj.getParent()
and obj.getParent().IfcType == "Building Storey"
):
continue
wp, _ = getTreeViewItem(obj)
soloProxyHold.append(wp)
sortLvHold = sorted(lvHold, key=lambda x: x[1])
sortLvItems = [item[0] for item in sortLvHold]
treeViewItems = treeViewItems + sortLvItems + soloProxyHold
vm.tree.addTopLevelItems(treeViewItems)
# set TreeVinew Item selected if obj is selected
objSelected = FreeCADGui.Selection.getSelection()
objNameSelected = [obj.Label for obj in objSelected]
allItemsInTree = getAllItemsInTree(vm.tree)
for item in allItemsInTree:
if item.text(0) in objNameSelected:
item.setSelected(True)
if retrigger:
QtCore.QTimer.singleShot(UPDATEINTERVAL, self.update)
# save state
PREFS.SetInt("ViewManagerColumnWidth", vm.tree.columnWidth(0))
PREFS.SetBool("ViewManagerFloating", vm.isFloating())
# expand
vm.tree.expandAll()
def select(self, item, column=None):
"selects a doc object corresponding to an item"
item.setSelected(True)
name = item.toolTip(0)
obj = FreeCAD.ActiveDocument.getObject(name)
if obj:
FreeCADGui.Selection.clearSelection()
FreeCADGui.Selection.addSelection(obj)
def addLevel(self):
"adds a building part"
import Arch
FreeCAD.ActiveDocument.openTransaction("Create BuildingPart")
Arch.makeFloor()
FreeCAD.ActiveDocument.commitTransaction()
FreeCAD.ActiveDocument.recompute()
self.update(False)
def addProxy(self):
"adds a WP proxy"
import Draft
FreeCAD.ActiveDocument.openTransaction("Create WP Proxy")
Draft.makeWorkingPlaneProxy(FreeCAD.DraftWorkingPlane.getPlacement())
FreeCAD.ActiveDocument.commitTransaction()
FreeCAD.ActiveDocument.recompute()
self.update(False)
def delete(self):
"deletes the selected object"
vm = findWidget()
if vm:
if vm.tree.selectedItems():
FreeCAD.ActiveDocument.openTransaction("Delete")
for item in vm.tree.selectedItems():
obj = FreeCAD.ActiveDocument.getObject(item.toolTip(0))
if obj:
FreeCAD.ActiveDocument.removeObject(obj.Name)
FreeCAD.ActiveDocument.commitTransaction()
FreeCAD.ActiveDocument.recompute()
self.update(False)
def rename(self):
"renames the selected object"
vm = findWidget()
if vm:
if vm.tree.selectedItems():
if vm.tree.selectedItems():
item = vm.tree.selectedItems()[-1]
vm.tree.editItem(item, 0)
def editObject(self, item, column):
"renames or edit height of the actual object"
obj = FreeCAD.ActiveDocument.getObject(item.toolTip(0))
if obj:
if column == 0:
obj.Label = item.text(column)
if column == 1:
obj.Height = FreeCAD.Units.parseQuantity(item.text(column))
# update every floors level which above the edited floor
_updateFloorLevel(obj)
if column == 2:
obj.Placement.Base.z = FreeCAD.Units.parseQuantity(item.text(column))
# update the floor height which 1 floor below the edited floor and self
_updateFloorHeight(obj)
FreeCAD.ActiveDocument.recompute()
def toggle(self):
"toggle selected item on/off"
vm = findWidget()
if vm:
for item in vm.tree.selectedItems():
obj = FreeCAD.ActiveDocument.getObject(item.toolTip(0))
if obj:
obj.ViewObject.Visibility = not (obj.ViewObject.Visibility)
FreeCAD.ActiveDocument.recompute()
def isolate(self):
"turns all items off except the selected ones"
vm = findWidget()
if vm:
onnames = [item.toolTip(0) for item in vm.tree.selectedItems()]
for i in range(vm.tree.topLevelItemCount()):
item = vm.tree.topLevelItem(i)
if item.toolTip(0) not in onnames:
obj = FreeCAD.ActiveDocument.getObject(item.toolTip(0))
if obj:
obj.ViewObject.Visibility = False
FreeCAD.ActiveDocument.recompute()
def saveView(self):
"save the current camera angle to the selected item"
vm = findWidget()
if vm:
for item in vm.tree.selectedItems():
obj = FreeCAD.ActiveDocument.getObject(item.toolTip(0))
if obj:
if hasattr(obj.ViewObject.Proxy, "writeCamera"):
obj.ViewObject.Proxy.writeCamera()
FreeCAD.ActiveDocument.recompute()
def onDockLocationChanged(self, area):
"""Saves dock widget size and location"""
PREFS.SetInt("BimViewArea", int(area))
mw = FreeCADGui.getMainWindow()
vm = findWidget()
if vm:
PREFS.SetBool("BimViewFloat", vm.isFloating())
PREFS.SetInt("BimViewWidth", vm.width())
PREFS.SetInt("BimViewHeight", vm.height())
tabs = "+".join([o.objectName() for o in mw.tabifiedDockWidgets(vm)])
PREFS.SetString("BimViewTabs", tabs)
def getDockArea(self, area):
"""Turns an int into a qt dock area"""
from PySide import QtCore
if area == 1:
return QtCore.Qt.LeftDockWidgetArea
elif area == 4:
return QtCore.Qt.TopDockWidgetArea
elif area == 8:
return QtCore.Qt.BottomDockWidgetArea
else:
return QtCore.Qt.RightDockWidgetArea
# These functions need to be localized outside the command class, as they are used outside this module
def findWidget():
"finds the manager widget, if present"
from PySide import QtGui
mw = FreeCADGui.getMainWindow()
vm = mw.findChild(QtGui.QDockWidget, "BIM Views Manager")
if vm:
return vm
return None
def show(item, column=None):
"item has been double-clicked"
obj = None
vm = findWidget()
if isinstance(item, str) or (
(sys.version_info.major < 3) and isinstance(item, unicode)
):
# called from Python code
obj = FreeCAD.ActiveDocument.getObject(item)
else:
# called from GUI
if column != 0:
# user clicked all field (except the name field
if vm:
vm.tree.editItem(item, column)
return
else:
# TODO find a way to not edit the object name
obj = FreeCAD.ActiveDocument.getObject(item.toolTip(0))
if obj:
FreeCADGui.Selection.clearSelection()
FreeCADGui.Selection.addSelection(obj)
FreeCADGui.runCommand("Draft_SelectPlane")
if vm:
# store the last double-clicked item for the BIM WPView command
if isinstance(item, str) or (
(sys.version_info.major < 3) and isinstance(item, unicode)
):
vm.lastSelected = item
else:
vm.lastSelected = item.toolTip(0)
def getTreeViewItem(obj):
"""
from FreeCAD object make the TreeWidgetItem including icon Label and LevelHeight
and also make a level height in number to sort the order after
"""
from PySide import QtCore, QtGui
z = FreeCAD.Units.Quantity(obj.Placement.Base.z, FreeCAD.Units.Length)
h = ""
if hasattr(obj, "Height"):
h = FreeCAD.Units.Quantity(obj.Height, FreeCAD.Units.Length).UserString
lvHStr = z.UserString
if z.Value == 0:
# override with Elevation property if available
if hasattr(obj, "Elevation"):
z = FreeCAD.Units.Quantity(obj.Elevation, FreeCAD.Units.Length)
lvHStr = z.UserString
lvH = z.Value
it = QtGui.QTreeWidgetItem([obj.Label, h, lvHStr])
it.setFlags(it.flags() | QtCore.Qt.ItemIsEditable)
it.setToolTip(0, obj.Name)
it.setToolTip(1, "Double-Click or Press F2 to edit")
it.setToolTip(2, "Double-Click or Press F2 to edit")
if obj.ViewObject:
if hasattr(obj.ViewObject, "Proxy") and hasattr(
obj.ViewObject.Proxy, "getIcon"
):
it.setIcon(0, QtGui.QIcon(obj.ViewObject.Proxy.getIcon()))
return (it, lvH)
def getAllItemsInTree(tree_widget):
"return list of all items in QtreeWidget"
def get_child_items(parent_item):
child_items = []
# get how many sub items
child_count = parent_item.childCount()
for j in range(child_count):
child_item = parent_item.child(j)
child_items.append(child_item)
child_items.extend(get_child_items(child_item))
return child_items
all_items = []
# get top level items
top_level_item_count = tree_widget.topLevelItemCount()
for i in range(top_level_item_count):
top_level_item = tree_widget.topLevelItem(i)
all_items.append(top_level_item)
# iterate sub-items
all_items.extend(get_child_items(top_level_item))
return all_items
def getParent(obj):
"return the first parent of this object"
if obj.getParent():
return obj.getParent()
else:
for parent in obj.InList:
if hasattr(parent, "Group") and obj in parent.Group:
return parent
def _updateFloorLevel(obj):
"update every floors level which above the edited floor"
floors = _getSiblingFloors(obj)
editedFloorIndex = floors.index(obj)
for i in range(editedFloorIndex + 1, len(floors)):
updateFloor = floors[i]
updateFloor.Placement.Base.z = FreeCAD.Units.Quantity(
floors[i - 1].Placement.Base.z, FreeCAD.Units.Length
) + FreeCAD.Units.Quantity(floors[i - 1].Height, FreeCAD.Units.Length)
def _updateFloorHeight(obj):
"update the floor height which 1 floor below the edited floor and self"
floors = _getSiblingFloors(obj)
editedFloorIndex = floors.index(obj)
floorEdited = floors[editedFloorIndex]
if editedFloorIndex > 0:
floorBelow = floors[editedFloorIndex - 1]
floorBelow.Height = FreeCAD.Units.Quantity(
floorEdited.Placement.Base.z, FreeCAD.Units.Length
) - FreeCAD.Units.Quantity(floorBelow.Placement.Base.z, FreeCAD.Units.Length)
if editedFloorIndex < (len(floors) - 1):
floorAbove = floors[editedFloorIndex + 1]
floorEdited.Height = FreeCAD.Units.Quantity(
floorAbove.Placement.Base.z, FreeCAD.Units.Length
) - FreeCAD.Units.Quantity(floorEdited.Placement.Base.z, FreeCAD.Units.Length)
def _getSiblingFloors(obj):
"get all floors from the same building and sort by the Placement z"
import Draft
if (
Draft.getType(getParent(obj)) in ["Building", "IfcBuilding"]
or getattr(getParent(obj), "IfcType", "") == "Building"
):
# find all floors belongs to the same building and sorted by its level
building = getParent(obj)
floors = []
for floor in building.Group:
if (
Draft.getType(floor) in ["Building Storey", "IfcBuildingStorey"]
or getattr(floor, "IfcType", "") == "Building Storey"
):
floors.append(floor)
sortedFloors = _sortFloorsByLevel(floors)
return sortedFloors
else:
return []
def _sortFloorsByLevel(floors):
sortFloors = sorted(floors, key=lambda floor: floor.Placement.Base.z)
return sortFloors