/
ArchWall.py
1672 lines (1439 loc) · 76.3 KB
/
ArchWall.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
#***************************************************************************
#* Copyright (c) 2011 Yorik van Havre <yorik@uncreated.net> *
#* *
#* 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 provides tools to build Wall objects. Walls are simple
objects, usually vertical, typically obtained by giving a thickness to a base
line, then extruding it vertically.
Examples
--------
TODO put examples here.
"""
import FreeCAD,Draft,ArchComponent,DraftVecUtils,ArchCommands,math
from FreeCAD import Vector
if FreeCAD.GuiUp:
import FreeCADGui
from PySide import QtCore, QtGui
from DraftTools import translate
from PySide.QtCore import QT_TRANSLATE_NOOP
import draftguitools.gui_trackers as DraftTrackers
else:
# \cond
def translate(ctxt,txt, utf8_decode=False):
return txt
def QT_TRANSLATE_NOOP(ctxt,txt):
return txt
# \endcond
## @package ArchWall
# \ingroup ARCH
# \brief The Wall object and tools
#
# This module provides tools to build Wall objects. Walls are simple objects,
# usually vertical, typically obtained by giving a thickness to a base line,
# then extruding it vertically.
__title__="FreeCAD Wall"
__author__ = "Yorik van Havre"
__url__ = "http://www.freecadweb.org"
def makeWall(baseobj=None,height=None,length=None,width=None,align="Center",face=None,name="Wall"):
"""Create a wall based on a given object, and returns the generated wall.
TODO: It is unclear what defines which units this function uses.
Parameters
----------
baseobj: <Part::PartFeature>, optional
The base object with which to build the wall. This can be a sketch, a
draft object, a face, or a solid. It can also be left as None.
height: float, optional
The height of the wall.
length: float, optional
The length of the wall. Not used if the wall is based off an object.
Will use Arch default if left empty.
width: float, optional
The width of the wall. Not used if the base object is a face. Will use
Arch default if left empty.
align: str, optional
Either "Center", "Left", or "Right". Effects the alignment of the wall
on its baseline.
face: int, optional
The index number of a face on the given baseobj, to base the wall on.
name: str, optional
The name to give to the created wall.
Returns
-------
<Part::FeaturePython>
Returns the generated wall.
Notes
-----
Creates a new <Part::FeaturePython> object, and turns it into a parametric wall
object. This <Part::FeaturePython> object does not yet have any shape.
The wall then uses the baseobj.Shape as the basis to extrude out a wall shape,
giving the new <Part::FeaturePython> object a shape.
It then hides the original baseobj.
"""
if not FreeCAD.ActiveDocument:
FreeCAD.Console.PrintError("No active document. Aborting\n")
return
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch")
obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Wall")
obj.Label = translate("Arch",name)
_Wall(obj)
if FreeCAD.GuiUp:
_ViewProviderWall(obj.ViewObject)
if baseobj:
if hasattr(baseobj,'Shape') or baseobj.isDerivedFrom("Mesh::Feature"):
obj.Base = baseobj
else:
FreeCAD.Console.PrintWarning(str(translate("Arch","Walls can only be based on Part or Mesh objects")))
if face:
obj.Face = face
if length:
obj.Length = length
if width:
obj.Width = width
else:
obj.Width = p.GetFloat("WallWidth",200)
if height:
obj.Height = height
else:
obj.Height = p.GetFloat("WallHeight",3000)
obj.Align = align
if obj.Base and FreeCAD.GuiUp:
if Draft.getType(obj.Base) != "Space":
obj.Base.ViewObject.hide()
return obj
def joinWalls(walls,delete=False):
"""Join the given list of walls into one sketch-based wall.
Take the first wall in the list, and adds on the other walls in the list.
Return the modified first wall.
Setting delete to True, will delete the other walls. Only join walls
if the walls have the same width, height and alignment.
Parameters
----------
walls: list of <Part::FeaturePython>
List containing the walls to add to the first wall in the list. Walls must
be based off a base object.
delete: bool, optional
If True, deletes the other walls in the list.
Returns
-------
<Part::FeaturePython>
"""
import Part
if not walls:
return None
if not isinstance(walls,list):
walls = [walls]
if not areSameWallTypes(walls):
return None
deleteList = []
base = walls.pop()
if base.Base:
if base.Base.Shape.Faces:
return None
if Draft.getType(base.Base) == "Sketch":
sk = base.Base
else:
sk = Draft.makeSketch(base.Base,autoconstraints=True)
if sk:
base.Base = sk
for w in walls:
if w.Base:
if not w.Base.Shape.Faces:
for e in w.Base.Shape.Edges:
l = e.Curve
if isinstance(l,Part.Line):
l = Part.LineSegment(e.Vertexes[0].Point,e.Vertexes[-1].Point)
sk.addGeometry(l)
deleteList.append(w.Name)
if delete:
for n in deleteList:
FreeCAD.ActiveDocument.removeObject(n)
FreeCAD.ActiveDocument.recompute()
base.ViewObject.show()
return base
def mergeShapes(w1,w2):
"""Not currently implemented.
Return a Shape built on two walls that share same properties and have a
coincident endpoint.
"""
if not areSameWallTypes([w1,w2]):
return None
if (not hasattr(w1.Base,"Shape")) or (not hasattr(w2.Base,"Shape")):
return None
if w1.Base.Shape.Faces or w2.Base.Shape.Faces:
return None
# TODO fix this
return None
eds = w1.Base.Shape.Edges + w2.Base.Shape.Edges
import DraftGeomUtils
w = DraftGeomUtils.findWires(eds)
if len(w) == 1:
#print("found common wire")
normal,length,width,height = w1.Proxy.getDefaultValues(w1)
print(w[0].Edges)
sh = w1.Proxy.getBase(w1,w[0],normal,width,height)
print(sh)
return sh
return None
def areSameWallTypes(walls):
"""Check if a list of walls have the same height, width and alignment.
Parameters
----------
walls: list of <ArchComponent.Component>
Returns
-------
bool
True if the walls have the same height, width and alignment, False if
otherwise.
"""
for att in ["Width","Height","Align"]:
value = None
for w in walls:
if not hasattr(w,att):
return False
if not value:
value = getattr(w,att)
else:
if type(value) == float:
if round(value,Draft.precision()) != round(getattr(w,att),Draft.precision()):
return False
else:
if value != getattr(w,att):
return False
return True
class _CommandWall:
"""The command definition for the Arch workbench's gui tool, Arch Wall.
A tool for creating Arch walls.
Create a wall from the object selected by the user. If no objects are
selected, enter an interactive mode to create a wall using selected points
to create a base.
Find documentation on the end user usage of Arch Wall here:
https://wiki.freecadweb.org/Arch_Wall
"""
def GetResources(self):
"""Returns a dictionary with the visual aspects of the Arch Wall tool."""
return {'Pixmap' : 'Arch_Wall',
'MenuText': QT_TRANSLATE_NOOP("Arch_Wall","Wall"),
'Accel': "W, A",
'ToolTip': QT_TRANSLATE_NOOP("Arch_Wall","Creates a wall object from scratch or from a selected object (wire, face or solid)")}
def IsActive(self):
"""Determines whether or not the Arch Wall tool is active.
Inactive commands are indicated by a greyed-out icon in the menus and
toolbars.
"""
return not FreeCAD.ActiveDocument is None
def Activated(self):
"""Executed when Arch Wall is called.
Creates a wall from the object selected by the user. If no objects are
selected, enters an interactive mode to create a wall using selected
points to create a base.
"""
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch")
self.Align = ["Center","Left","Right"][p.GetInt("WallAlignment",0)]
self.MultiMat = None
self.Length = None
self.lengthValue = 0
self.continueCmd = False
self.Width = p.GetFloat("WallWidth",200)
self.Height = p.GetFloat("WallHeight",3000)
self.JOIN_WALLS_SKETCHES = p.GetBool("joinWallSketches",False)
self.AUTOJOIN = p.GetBool("autoJoinWalls",True)
sel = FreeCADGui.Selection.getSelectionEx()
done = False
self.existing = []
if sel:
# automatic mode
import Draft
if Draft.getType(sel[0].Object) != "Wall":
FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Wall"))
FreeCADGui.addModule("Arch")
for selobj in sel:
if Draft.getType(selobj.Object) == "Space":
spacedone = False
if selobj.HasSubObjects:
if "Face" in selobj.SubElementNames[0]:
idx = int(selobj.SubElementNames[0][4:])
FreeCADGui.doCommand("obj = Arch.makeWall(FreeCAD.ActiveDocument."+selobj.Object.Name+",face="+str(idx)+")")
spacedone = True
if not spacedone:
FreeCADGui.doCommand('obj = Arch.makeWall(FreeCAD.ActiveDocument.'+selobj.Object.Name+')')
else:
FreeCADGui.doCommand('obj = Arch.makeWall(FreeCAD.ActiveDocument.'+selobj.Object.Name+')')
FreeCADGui.addModule("Draft")
FreeCADGui.doCommand("Draft.autogroup(obj)")
FreeCAD.ActiveDocument.commitTransaction()
FreeCAD.ActiveDocument.recompute()
done = True
if not done:
# interactive mode
self.points = []
self.tracker = DraftTrackers.boxTracker()
if hasattr(FreeCAD,"DraftWorkingPlane"):
FreeCAD.DraftWorkingPlane.setup()
FreeCADGui.Snapper.getPoint(callback=self.getPoint,
extradlg=self.taskbox(),
title=translate("Arch","First point of wall")+":")
def getPoint(self,point=None,obj=None):
"""Callback for clicks during interactive mode.
When method _CommandWall.Activated() has entered the interactive mode,
this callback runs when the user clicks.
Parameters
----------
point: <class 'Base.Vector'>
The point the user has selected.
obj: <Part::PartFeature>, optional
The object the user's cursor snapped to, if any.
"""
if obj:
if Draft.getType(obj) == "Wall":
if not obj in self.existing:
self.existing.append(obj)
if point is None:
self.tracker.finalize()
return
self.points.append(point)
if len(self.points) == 1:
self.tracker.width(self.Width)
self.tracker.height(self.Height)
self.tracker.on()
FreeCADGui.Snapper.getPoint(last=self.points[0],
callback=self.getPoint,
movecallback=self.update,
extradlg=self.taskbox(),
title=translate("Arch","Next point")+":",mode="line")
elif len(self.points) == 2:
import Part
l = Part.LineSegment(FreeCAD.DraftWorkingPlane.getLocalCoords(self.points[0]),
FreeCAD.DraftWorkingPlane.getLocalCoords(self.points[1]))
self.tracker.finalize()
FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Wall"))
FreeCADGui.addModule("Arch")
FreeCADGui.doCommand('import Part')
FreeCADGui.doCommand('trace=Part.LineSegment(FreeCAD.'+str(l.StartPoint)+',FreeCAD.'+str(l.EndPoint)+')')
if not self.existing:
# no existing wall snapped, just add a default wall
self.addDefault()
else:
if self.JOIN_WALLS_SKETCHES:
# join existing subwalls first if possible, then add the new one
w = joinWalls(self.existing)
if w:
if areSameWallTypes([w,self]):
FreeCADGui.doCommand('FreeCAD.ActiveDocument.'+w.Name+'.Base.addGeometry(trace)')
else:
# if not possible, add new wall as addition to the existing one
self.addDefault()
if self.AUTOJOIN:
FreeCADGui.doCommand('Arch.addComponents(FreeCAD.ActiveDocument.'+FreeCAD.ActiveDocument.Objects[-1].Name+',FreeCAD.ActiveDocument.'+w.Name+')')
else:
self.addDefault()
else:
# add new wall as addition to the first existing one
self.addDefault()
if self.AUTOJOIN:
FreeCADGui.doCommand('Arch.addComponents(FreeCAD.ActiveDocument.'+FreeCAD.ActiveDocument.Objects[-1].Name+',FreeCAD.ActiveDocument.'+self.existing[0].Name+')')
FreeCAD.ActiveDocument.commitTransaction()
FreeCAD.ActiveDocument.recompute()
if self.continueCmd:
self.Activated()
def addDefault(self):
"""Create a wall using a line segment, with all parameters as the default.
Used solely by _CommandWall.getPoint() when the interactive mode has
selected two points.
Relies on the assumption that FreeCADGui.doCommand() has already
created a Part.LineSegment assigned as the variable "trace"
"""
FreeCADGui.addModule("Draft")
if FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetBool("WallSketches",True):
FreeCADGui.doCommand('base=FreeCAD.ActiveDocument.addObject("Sketcher::SketchObject","WallTrace")')
FreeCADGui.doCommand('base.Placement = FreeCAD.DraftWorkingPlane.getPlacement()')
FreeCADGui.doCommand('base.addGeometry(trace)')
else:
FreeCADGui.doCommand('base=Draft.makeLine(trace)')
FreeCADGui.doCommand('FreeCAD.ActiveDocument.recompute()')
FreeCADGui.doCommand('wall = Arch.makeWall(base,width='+str(self.Width)+',height='+str(self.Height)+',align="'+str(self.Align)+'")')
FreeCADGui.doCommand('wall.Normal = FreeCAD.DraftWorkingPlane.getNormal()')
if self.MultiMat:
FreeCADGui.doCommand("wall.Material = FreeCAD.ActiveDocument."+self.MultiMat.Name)
FreeCADGui.doCommand("Draft.autogroup(wall)")
def update(self,point,info):
# info parameter is not used but needed for compatibility with the snapper
"""Callback for the mouse moving during the interactive mode.
Update the active dialog box to show the coordinates of the location of
the cursor. Also show the length the line would take, if the user
selected that point.
Parameters
----------
point: <class 'Base.Vector'>
The point the cursor is currently at, or has snapped to.
"""
if FreeCADGui.Control.activeDialog():
b = self.points[0]
n = FreeCAD.DraftWorkingPlane.axis
bv = point.sub(b)
dv = bv.cross(n)
dv = DraftVecUtils.scaleTo(dv,self.Width/2)
if self.Align == "Center":
self.tracker.update([b,point])
elif self.Align == "Left":
self.tracker.update([b.add(dv),point.add(dv)])
else:
dv = dv.negative()
self.tracker.update([b.add(dv),point.add(dv)])
if self.Length:
self.Length.setText(FreeCAD.Units.Quantity(bv.Length,FreeCAD.Units.Length).UserString)
def taskbox(self):
"""Set up a simple gui widget for the interactive mode."""
w = QtGui.QWidget()
ui = FreeCADGui.UiLoader()
w.setWindowTitle(translate("Arch","Wall options"))
grid = QtGui.QGridLayout(w)
matCombo = QtGui.QComboBox()
matCombo.addItem(translate("Arch","Wall Presets..."))
matCombo.setToolTip(translate("Arch","This list shows all the MultiMaterials objects of this document. Create some to define wall types."))
self.multimats = []
self.MultiMat = None
for o in FreeCAD.ActiveDocument.Objects:
if Draft.getType(o) == "MultiMaterial":
self.multimats.append(o)
matCombo.addItem(o.Label)
if hasattr(FreeCAD,"LastArchMultiMaterial"):
for i,o in enumerate(self.multimats):
if o.Name == FreeCAD.LastArchMultiMaterial:
matCombo.setCurrentIndex(i+1)
self.MultiMat = o
grid.addWidget(matCombo,0,0,1,2)
label5 = QtGui.QLabel(translate("Arch","Length"))
self.Length = ui.createWidget("Gui::InputField")
self.Length.setText("0.00 mm")
grid.addWidget(label5,1,0,1,1)
grid.addWidget(self.Length,1,1,1,1)
label1 = QtGui.QLabel(translate("Arch","Width"))
value1 = ui.createWidget("Gui::InputField")
value1.setText(FreeCAD.Units.Quantity(self.Width,FreeCAD.Units.Length).UserString)
grid.addWidget(label1,2,0,1,1)
grid.addWidget(value1,2,1,1,1)
label2 = QtGui.QLabel(translate("Arch","Height"))
value2 = ui.createWidget("Gui::InputField")
value2.setText(FreeCAD.Units.Quantity(self.Height,FreeCAD.Units.Length).UserString)
grid.addWidget(label2,3,0,1,1)
grid.addWidget(value2,3,1,1,1)
label3 = QtGui.QLabel(translate("Arch","Alignment"))
value3 = QtGui.QComboBox()
items = [translate("Arch","Center"),translate("Arch","Left"),translate("Arch","Right")]
value3.addItems(items)
value3.setCurrentIndex(["Center","Left","Right"].index(self.Align))
grid.addWidget(label3,4,0,1,1)
grid.addWidget(value3,4,1,1,1)
label4 = QtGui.QLabel(translate("Arch","Con&tinue"))
value4 = QtGui.QCheckBox()
value4.setObjectName("ContinueCmd")
value4.setLayoutDirection(QtCore.Qt.RightToLeft)
label4.setBuddy(value4)
if hasattr(FreeCADGui,"draftToolBar"):
value4.setChecked(FreeCADGui.draftToolBar.continueMode)
self.continueCmd = FreeCADGui.draftToolBar.continueMode
grid.addWidget(label4,5,0,1,1)
grid.addWidget(value4,5,1,1,1)
label5 = QtGui.QLabel(translate("Arch","Use sketches"))
value5 = QtGui.QCheckBox()
value5.setObjectName("UseSketches")
value5.setLayoutDirection(QtCore.Qt.RightToLeft)
label5.setBuddy(value5)
value5.setChecked(FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetBool("WallSketches",True))
grid.addWidget(label5,6,0,1,1)
grid.addWidget(value5,6,1,1,1)
QtCore.QObject.connect(self.Length,QtCore.SIGNAL("valueChanged(double)"),self.setLength)
QtCore.QObject.connect(value1,QtCore.SIGNAL("valueChanged(double)"),self.setWidth)
QtCore.QObject.connect(value2,QtCore.SIGNAL("valueChanged(double)"),self.setHeight)
QtCore.QObject.connect(value3,QtCore.SIGNAL("currentIndexChanged(int)"),self.setAlign)
QtCore.QObject.connect(value4,QtCore.SIGNAL("stateChanged(int)"),self.setContinue)
QtCore.QObject.connect(value5,QtCore.SIGNAL("stateChanged(int)"),self.setUseSketch)
QtCore.QObject.connect(self.Length,QtCore.SIGNAL("returnPressed()"),value1.setFocus)
QtCore.QObject.connect(self.Length,QtCore.SIGNAL("returnPressed()"),value1.selectAll)
QtCore.QObject.connect(value1,QtCore.SIGNAL("returnPressed()"),value2.setFocus)
QtCore.QObject.connect(value1,QtCore.SIGNAL("returnPressed()"),value2.selectAll)
QtCore.QObject.connect(value2,QtCore.SIGNAL("returnPressed()"),self.createFromGUI)
QtCore.QObject.connect(matCombo,QtCore.SIGNAL("currentIndexChanged(int)"),self.setMat)
return w
def setMat(self,d):
"""Simple callback for the interactive mode gui widget to set material."""
if d == 0:
self.MultiMat = None
del FreeCAD.LastArchMultiMaterial
elif d <= len(self.multimats):
self.MultiMat = self.multimats[d-1]
FreeCAD.LastArchMultiMaterial = self.MultiMat.Name
def setLength(self,d):
"""Simple callback for the interactive mode gui widget to set length."""
self.lengthValue = d
def setWidth(self,d):
"""Simple callback for the interactive mode gui widget to set width."""
self.Width = d
self.tracker.width(d)
FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").SetFloat("WallWidth",d)
def setHeight(self,d):
"""Simple callback for the interactive mode gui widget to set height."""
self.Height = d
self.tracker.height(d)
FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").SetFloat("WallHeight",d)
def setAlign(self,i):
"""Simple callback for the interactive mode gui widget to set alignment."""
self.Align = ["Center","Left","Right"][i]
FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").SetInt("WallAlignment",i)
def setContinue(self,i):
"""Simple callback to set if the interactive mode will restart when finished.
This allows for several walls to be placed one after another.
"""
self.continueCmd = bool(i)
if hasattr(FreeCADGui,"draftToolBar"):
FreeCADGui.draftToolBar.continueMode = bool(i)
def setUseSketch(self,i):
"""Simple callback to set if walls should join their base sketches when possible."""
FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").SetBool("joinWallSketches",bool(i))
def createFromGUI(self):
"""Callback to create wall by using the _CommandWall.taskbox()"""
FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Wall"))
FreeCADGui.addModule("Arch")
FreeCADGui.doCommand('wall = Arch.makeWall(length='+str(self.lengthValue)+',width='+str(self.Width)+',height='+str(self.Height)+',align="'+str(self.Align)+'")')
if self.MultiMat:
FreeCADGui.doCommand("wall.Material = FreeCAD.ActiveDocument."+self.MultiMat.Name)
FreeCAD.ActiveDocument.commitTransaction()
FreeCAD.ActiveDocument.recompute()
if hasattr(FreeCADGui,"draftToolBar"):
FreeCADGui.draftToolBar.escape()
class _CommandMergeWalls:
"""The command definition for the Arch workbench's gui tool, Arch MergeWalls.
A tool for merging walls.
Join two or more walls by using the ArchWall.joinWalls() function.
Find documentation on the end user usage of Arch Wall here:
https://wiki.freecadweb.org/Arch_MergeWalls
"""
def GetResources(self):
"""Returns a dictionary with the visual aspects of the Arch MergeWalls tool."""
return {'Pixmap' : 'Arch_MergeWalls',
'MenuText': QT_TRANSLATE_NOOP("Arch_MergeWalls","Merge Walls"),
'ToolTip': QT_TRANSLATE_NOOP("Arch_MergeWalls","Merges the selected walls, if possible")}
def IsActive(self):
"""Determines whether or not the Arch MergeWalls tool is active.
Inactive commands are indicated by a greyed-out icon in the menus and
toolbars.
"""
return bool(FreeCADGui.Selection.getSelection())
def Activated(self):
"""Executed when Arch MergeWalls is called.
Call ArchWall.joinWalls() on walls selected by the user, with the
delete option enabled. If the user has selected a single wall, check to
see if the wall has any Additions that are walls. If so, merges these
additions to the wall, deleting the additions.
"""
walls = FreeCADGui.Selection.getSelection()
if len(walls) == 1:
if Draft.getType(walls[0]) == "Wall":
ostr = "FreeCAD.ActiveDocument."+ walls[0].Name
ok = False
for o in walls[0].Additions:
if Draft.getType(o) == "Wall":
ostr += ",FreeCAD.ActiveDocument." + o.Name
ok = True
if ok:
FreeCAD.ActiveDocument.openTransaction(translate("Arch","Merge Wall"))
FreeCADGui.addModule("Arch")
FreeCADGui.doCommand("Arch.joinWalls(["+ostr+"],delete=True)")
FreeCAD.ActiveDocument.commitTransaction()
return
else:
FreeCAD.Console.PrintWarning(translate("Arch","The selected wall contains no subwall to merge"))
return
else:
FreeCAD.Console.PrintWarning(translate("Arch","Please select only wall objects"))
return
for w in walls:
if Draft.getType(w) != "Wall":
FreeCAD.Console.PrintMessage(translate("Arch","Please select only wall objects"))
return
FreeCAD.ActiveDocument.openTransaction(translate("Arch","Merge Walls"))
FreeCADGui.addModule("Arch")
FreeCADGui.doCommand("Arch.joinWalls(FreeCADGui.Selection.getSelection(),delete=True)")
FreeCAD.ActiveDocument.commitTransaction()
class _Wall(ArchComponent.Component):
"""The Wall object.
Turns a <App::FeaturePython> into a wall object, then uses a
<Part::Feature> to create the wall's shape.
Walls are simple objects, usually vertical, typically obtained by giving a
thickness to a base line, then extruding it vertically.
Parameters
----------
obj: <App::FeaturePython>
The object to turn into a wall. Note that this is not the object that
forms the basis for the new wall's shape. That is given later.
"""
def __init__(self, obj):
ArchComponent.Component.__init__(self, obj)
self.setProperties(obj)
obj.IfcType = "Wall"
def setProperties(self, obj):
"""Give the wall its wall specific properties, such as its alignment.
You can learn more about properties here:
https://wiki.freecadweb.org/property
parameters
----------
obj: <part::featurepython>
The object to turn into a wall.
"""
lp = obj.PropertiesList
if not "Length" in lp:
obj.addProperty("App::PropertyLength","Length","Wall",QT_TRANSLATE_NOOP("App::Property","The length of this wall. Not used if this wall is based on an underlying object"))
if not "Width" in lp:
obj.addProperty("App::PropertyLength","Width","Wall",QT_TRANSLATE_NOOP("App::Property","The width of this wall. Not used if this wall is based on a face"))
# To be combined into Width when PropertyLengthList is available
if not "OverrideWidth" in lp:
obj.addProperty("App::PropertyFloatList","OverrideWidth","Wall",QT_TRANSLATE_NOOP("App::Property","This overrides Width attribute to set width of each segment of wall. Ignored if Base object provides Widths information, with getWidths() method. (The 1st value override 'Width' attribute for 1st segment of wall; if a value is zero, 1st value of 'OverrideWidth' will be followed)")) # see DraftGeomUtils.offsetwire()
if not "OverrideAlign" in lp:
obj.addProperty("App::PropertyStringList","OverrideAlign","Wall",QT_TRANSLATE_NOOP("App::Property","This overrides Align attribute to set Align of each segment of wall. Ignored if Base object provides Aligns information, with getAligns() method. (The 1st value override 'Align' attribute for 1st segment of wall; if a value is not 'Left, Right, Center', 1st value of 'OverrideAlign' will be followed)")) # see DraftGeomUtils.offsetwire()
if not "Height" in lp:
obj.addProperty("App::PropertyLength","Height","Wall",QT_TRANSLATE_NOOP("App::Property","The height of this wall. Keep 0 for automatic. Not used if this wall is based on a solid"))
if not "Area" in lp:
obj.addProperty("App::PropertyArea","Area","Wall",QT_TRANSLATE_NOOP("App::Property","The area of this wall as a simple Height * Length calculation"))
obj.setEditorMode("Area",1)
if not "Align" in lp:
obj.addProperty("App::PropertyEnumeration","Align","Wall",QT_TRANSLATE_NOOP("App::Property","The alignment of this wall on its base object, if applicable"))
obj.Align = ['Left','Right','Center']
if not "Normal" in lp:
obj.addProperty("App::PropertyVector","Normal","Wall",QT_TRANSLATE_NOOP("App::Property","The normal extrusion direction of this object (keep (0,0,0) for automatic normal)"))
if not "Face" in lp:
obj.addProperty("App::PropertyInteger","Face","Wall",QT_TRANSLATE_NOOP("App::Property","The face number of the base object used to build this wall"))
if not "Offset" in lp:
obj.addProperty("App::PropertyDistance","Offset","Wall",QT_TRANSLATE_NOOP("App::Property","The offset between this wall and its baseline (only for left and right alignments)"))
# See getExtrusionData(), removeSplitters are no longer used
#if not "Refine" in lp:
# obj.addProperty("App::PropertyEnumeration","Refine","Wall",QT_TRANSLATE_NOOP("App::Property","Select whether or not and the method to remove splitter of the Wall. Currently Draft removeSplitter and Part removeSplitter available but may not work on complex sketch."))
# obj.Refine = ['No','DraftRemoveSplitter','PartRemoveSplitter']
# TODO - To implement in Arch Component ?
if not "MakeBlocks" in lp:
obj.addProperty("App::PropertyBool","MakeBlocks","Blocks",QT_TRANSLATE_NOOP("App::Property","Enable this to make the wall generate blocks"))
if not "BlockLength" in lp:
obj.addProperty("App::PropertyLength","BlockLength","Blocks",QT_TRANSLATE_NOOP("App::Property","The length of each block"))
if not "BlockHeight" in lp:
obj.addProperty("App::PropertyLength","BlockHeight","Blocks",QT_TRANSLATE_NOOP("App::Property","The height of each block"))
if not "OffsetFirst" in lp:
obj.addProperty("App::PropertyLength","OffsetFirst","Blocks",QT_TRANSLATE_NOOP("App::Property","The horizontal offset of the first line of blocks"))
if not "OffsetSecond" in lp:
obj.addProperty("App::PropertyLength","OffsetSecond","Blocks",QT_TRANSLATE_NOOP("App::Property","The horizontal offset of the second line of blocks"))
if not "Joint" in lp:
obj.addProperty("App::PropertyLength","Joint","Blocks",QT_TRANSLATE_NOOP("App::Property","The size of the joints between each block"))
if not "CountEntire" in lp:
obj.addProperty("App::PropertyInteger","CountEntire","Blocks",QT_TRANSLATE_NOOP("App::Property","The number of entire blocks"))
obj.setEditorMode("CountEntire",1)
if not "CountBroken" in lp:
obj.addProperty("App::PropertyInteger","CountBroken","Blocks",QT_TRANSLATE_NOOP("App::Property","The number of broken blocks"))
obj.setEditorMode("CountBroken",1)
self.Type = "Wall"
def onDocumentRestored(self,obj):
"""Method run when the document is restored. Re-adds the Arch component, and Arch wall properties."""
ArchComponent.Component.onDocumentRestored(self,obj)
self.setProperties(obj)
def execute(self,obj):
"""Method run when the object is recomputed.
Extrude the wall from the Base shape if possible. Processe additions
and subtractions. Assign the resulting shape as the shape of the wall.
Add blocks if the MakeBlocks property is assigned. If the Base shape is
a mesh, just copy the mesh.
"""
if self.clone(obj):
return
import Part, DraftGeomUtils
base = None
pl = obj.Placement
extdata = self.getExtrusionData(obj)
if extdata:
bplates = extdata[0]
extv = extdata[2].Rotation.multVec(extdata[1])
if isinstance(bplates,list):
shps = []
# Test : if base is Sketch, then fuse all solid; otherwise, makeCompound
sketchBaseToFuse = obj.Base.getLinkedObject().isDerivedFrom("Sketcher::SketchObject")
# but turn this off if we have layers, otherwise layers get merged
if hasattr(obj,"Material") and obj.Material \
and hasattr(obj.Material,"Materials") and obj.Material.Materials:
sketchBaseToFuse = False
for b in bplates:
b.Placement = extdata[2].multiply(b.Placement)
b = b.extrude(extv)
# See getExtrusionData() - not fusing baseplates there - fuse solids here
# Remarks - If solids are fused, but exportIFC.py use underlying baseplates w/o fuse, the result in ifc look slightly different from in FC.
if sketchBaseToFuse:
if shps:
shps = shps.fuse(b) #shps.fuse(b)
else:
shps=b
else:
shps.append(b)
# TODO - To let user to select whether to fuse (slower) or to do a compound (faster) only ?
if sketchBaseToFuse:
base = shps
else:
base = Part.makeCompound(shps)
else:
bplates.Placement = extdata[2].multiply(bplates.Placement)
base = bplates.extrude(extv)
if obj.Base:
if hasattr(obj.Base,'Shape'):
if obj.Base.Shape.isNull():
return
if not obj.Base.Shape.isValid():
if not obj.Base.Shape.Solids:
# let pass invalid objects if they have solids...
return
elif obj.Base.Shape.Solids:
base = obj.Base.Shape.copy()
# blocks calculation
elif hasattr(obj,"MakeBlocks") and hasattr(self,"basewires"):
if obj.MakeBlocks and self.basewires and extdata and obj.Width and obj.Height:
#print "calculating blocks"
if len(self.basewires) == 1:
blocks = []
n = FreeCAD.Vector(extv)
n.normalize()
cuts1 = []
cuts2 = []
if obj.BlockLength.Value:
for i in range(2):
if i == 0:
offset = obj.OffsetFirst.Value
else:
offset = obj.OffsetSecond.Value
for edge in self.basewires[0].Edges:
while offset < (edge.Length-obj.Joint.Value):
#print i," Edge ",edge," : ",edge.Length," - ",offset
if offset:
t = edge.tangentAt(offset)
p = t.cross(n)
p.multiply(1.1*obj.Width.Value+obj.Offset.Value)
p1 = edge.valueAt(offset).add(p)
p2 = edge.valueAt(offset).add(p.negative())
sh = Part.LineSegment(p1,p2).toShape()
if obj.Joint.Value:
sh = sh.extrude(t.multiply(obj.Joint.Value))
sh = sh.extrude(n)
if i == 0:
cuts1.append(sh)
else:
cuts2.append(sh)
offset += (obj.BlockLength.Value + obj.Joint.Value)
else:
offset -= (edge.Length - obj.Joint.Value)
if isinstance(bplates,list):
bplates = bplates[0]
if obj.BlockHeight.Value:
fsize = obj.BlockHeight.Value + obj.Joint.Value
bh = obj.BlockHeight.Value
else:
fsize = obj.Height.Value
bh = obj.Height.Value
bvec = FreeCAD.Vector(n)
bvec.multiply(bh)
svec = FreeCAD.Vector(n)
svec.multiply(fsize)
if cuts1:
plate1 = bplates.cut(cuts1).Faces
else:
plate1 = bplates.Faces
blocks1 = Part.makeCompound([f.extrude(bvec) for f in plate1])
if cuts2:
plate2 = bplates.cut(cuts2).Faces
else:
plate2 = bplates.Faces
blocks2 = Part.makeCompound([f.extrude(bvec) for f in plate2])
interval = extv.Length/(fsize)
entires = int(interval)
rest = (interval - entires)
for i in range(entires):
if i % 2: # odd
b = blocks2.copy()
else:
b = blocks1.copy()
if i:
t = FreeCAD.Vector(svec)
t.multiply(i)
b.translate(t)
blocks.append(b)
if rest:
rest = extv.Length-(entires*fsize)
rvec = FreeCAD.Vector(n)
rvec.multiply(rest)
if entires % 2:
b = Part.makeCompound([f.extrude(rvec) for f in plate2])
else:
b = Part.makeCompound([f.extrude(rvec) for f in plate1])
t = FreeCAD.Vector(svec)
t.multiply(entires)
b.translate(t)
blocks.append(b)
if blocks:
base = Part.makeCompound(blocks)
else:
FreeCAD.Console.PrintWarning(translate("Arch","Cannot compute blocks for wall")+obj.Label+"\n")
elif obj.Base.isDerivedFrom("Mesh::Feature"):
if obj.Base.Mesh.isSolid():
if obj.Base.Mesh.countComponents() == 1:
sh = ArchCommands.getShapeFromMesh(obj.Base.Mesh)
if sh.isClosed() and sh.isValid() and sh.Solids and (not sh.isNull()):
base = sh
else:
FreeCAD.Console.PrintWarning(translate("Arch","This mesh is an invalid solid")+"\n")
obj.Base.ViewObject.show()
if not base:
#FreeCAD.Console.PrintError(translate("Arch","Error: Invalid base object")+"\n")
#return
# walls can be made of only a series of additions and have no base shape
base = Part.Shape()
base = self.processSubShapes(obj,base,pl)
self.applyShape(obj,base,pl)
# count blocks
if hasattr(obj,"MakeBlocks"):
if obj.MakeBlocks:
fvol = obj.BlockLength.Value * obj.BlockHeight.Value * obj.Width.Value
if fvol:
#print("base volume:",fvol)
#for s in base.Solids:
#print(abs(s.Volume - fvol))
ents = [s for s in base.Solids if abs(s.Volume - fvol) < 1]
obj.CountEntire = len(ents)
obj.CountBroken = len(base.Solids) - len(ents)
else:
obj.CountEntire = 0
obj.CountBroken = 0
# set the length property
if obj.Base:
if hasattr(obj.Base,'Shape'):
if obj.Base.Shape.Edges:
if not obj.Base.Shape.Faces:
if hasattr(obj.Base.Shape,"Length"):
l = obj.Base.Shape.Length
if obj.Length.Value != l:
obj.Length = l
self.oldLength = None # delete the stored value to prevent triggering base change below
# set the Area property
obj.Area = obj.Length.Value * obj.Height.Value
def onBeforeChange(self,obj,prop):
"""Method called before the object has a property changed.
Specifically, this method is called before the value changes.
If "Length" has changed, record the old length so that .onChanged() can
be sure that the base needs to be changed.
Parameters
----------
prop: string
The name of the property that has changed.
"""
if prop == "Length":
self.oldLength = obj.Length.Value
def onChanged(self, obj, prop):
"""Method called when the object has a property changed.
If length has changed, extend the length of the Base object, if the
Base object only has a single edge to extend.
Also hide subobjects.
Also call ArchComponent.Component.onChanged().
Parameters
----------
prop: string
The name of the property that has changed.
"""