-
-
Notifications
You must be signed in to change notification settings - Fork 4k
/
ArchComponent.py
2376 lines (2023 loc) · 95.5 KB
/
ArchComponent.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 the base Arch component class, that is shared
by all of the Arch BIM objects.
Examples
--------
TODO put examples here.
"""
__title__="FreeCAD Arch Component"
__author__ = "Yorik van Havre"
__url__ = "http://www.freecadweb.org"
import FreeCAD,Draft,ArchCommands,math,sys,json,os,ArchIFC,ArchIFCSchema
from FreeCAD import Vector
if FreeCAD.GuiUp:
import FreeCADGui
from PySide import QtGui,QtCore
from draftutils.translate import translate
from PySide.QtCore import QT_TRANSLATE_NOOP
else:
# \cond
def translate(ctxt,txt):
return txt
def QT_TRANSLATE_NOOP(ctxt,txt):
return txt
# \endcond
## @package ArchComponent
# \ingroup ARCH
# \brief The base class of all Arch objects
#
# This module provides the base Arch component class, that
# is shared by all of the Arch BIM objects
def addToComponent(compobject,addobject,mod=None):
"""Add an object to a component's properties.
Does not run if the addobject already exists in the component's properties.
Adds the object to the first property found of Base, Group, or Hosts.
If mod is provided, adds the object to that property instead.
Parameters
----------
compobject: <ArchComponent.Component>
The component object to add the object to.
addobject: <App::DocumentObject>
The object to add to the component.
mod: str, optional
The property to add the object to.
"""
import Draft
if compobject == addobject: return
# first check zis already there
found = False
attribs = ["Additions","Objects","Components","Subtractions","Base","Group","Hosts"]
for a in attribs:
if hasattr(compobject,a):
if a == "Base":
if addobject == getattr(compobject,a):
found = True
else:
if addobject in getattr(compobject,a):
found = True
if not found:
if mod:
if hasattr(compobject,mod):
if mod == "Base":
setattr(compobject,mod,addobject)
addobject.ViewObject.hide()
elif mod == "Axes":
if Draft.getType(addobject) == "Axis":
l = getattr(compobject,mod)
l.append(addobject)
setattr(compobject,mod,l)
else:
l = getattr(compobject,mod)
l.append(addobject)
setattr(compobject,mod,l)
if mod != "Objects":
addobject.ViewObject.hide()
if Draft.getType(compobject) == "PanelSheet":
addobject.Placement.move(compobject.Placement.Base.negative())
else:
for a in attribs[:3]:
if hasattr(compobject,a):
l = getattr(compobject,a)
l.append(addobject)
setattr(compobject,a,l)
addobject.ViewObject.hide()
break
def removeFromComponent(compobject,subobject):
"""Remove the object from the given component.
Try to find the object in the component's properties. If found, remove the
object.
If the object is not found, add the object in the component's Subtractions
property.
Parameters
----------
compobject: <ArchComponent.Component>
The component to remove the object from.
subobject: <App::DocumentObject>
The object to remove from the component.
"""
if compobject == subobject: return
found = False
attribs = ["Additions","Subtractions","Objects","Components","Base","Axes","Fixtures","Group","Hosts"]
for a in attribs:
if hasattr(compobject,a):
if a == "Base":
if subobject == getattr(compobject,a):
setattr(compobject,a,None)
subobject.ViewObject.show()
found = True
else:
if subobject in getattr(compobject,a):
l = getattr(compobject,a)
l.remove(subobject)
setattr(compobject,a,l)
subobject.ViewObject.show()
if Draft.getType(compobject) == "PanelSheet":
subobject.Placement.move(compobject.Placement.Base)
found = True
if not found:
if hasattr(compobject,"Subtractions"):
l = compobject.Subtractions
l.append(subobject)
compobject.Subtractions = l
if (Draft.getType(subobject) != "Window") and (not Draft.isClone(subobject,"Window",True)):
ArchCommands.setAsSubcomponent(subobject)
class Component(ArchIFC.IfcProduct):
"""The Arch Component object.
Acts as a base for all other Arch objects, such as Arch walls and Arch
structures. Its properties and behaviours are common to all Arch objects.
You can learn more about Arch Components, and the purpose of Arch
Components here: https://wiki.freecadweb.org/Arch_Component
Parameters
----------
obj: <App::FeaturePython>
The object to turn into an Arch Component
"""
def __init__(self, obj):
obj.Proxy = self
Component.setProperties(self, obj)
self.Type = "Component"
def setProperties(self, obj):
"""Give the component its component specific properties, such as material.
You can learn more about properties here:
https://wiki.freecadweb.org/property
"""
ArchIFC.IfcProduct.setProperties(self, obj)
pl = obj.PropertiesList
if not "Base" in pl:
obj.addProperty("App::PropertyLink","Base","Component",QT_TRANSLATE_NOOP("App::Property","The base object this component is built upon"))
if not "CloneOf" in pl:
obj.addProperty("App::PropertyLink","CloneOf","Component",QT_TRANSLATE_NOOP("App::Property","The object this component is cloning"))
if not "Additions" in pl:
obj.addProperty("App::PropertyLinkList","Additions","Component",QT_TRANSLATE_NOOP("App::Property","Other shapes that are appended to this object"))
if not "Subtractions" in pl:
obj.addProperty("App::PropertyLinkList","Subtractions","Component",QT_TRANSLATE_NOOP("App::Property","Other shapes that are subtracted from this object"))
if not "Description" in pl:
obj.addProperty("App::PropertyString","Description","Component",QT_TRANSLATE_NOOP("App::Property","An optional description for this component"))
if not "Tag" in pl:
obj.addProperty("App::PropertyString","Tag","Component",QT_TRANSLATE_NOOP("App::Property","An optional tag for this component"))
if not "StandardCode" in pl:
obj.addProperty("App::PropertyString","StandardCode","Component",QT_TRANSLATE_NOOP("App::Property","An optional standard (OmniClass, etc...) code for this component"))
if not "Material" in pl:
obj.addProperty("App::PropertyLink","Material","Component",QT_TRANSLATE_NOOP("App::Property","A material for this object"))
if "BaseMaterial" in pl:
obj.Material = obj.BaseMaterial
obj.removeProperty("BaseMaterial")
FreeCAD.Console.PrintMessage("Upgrading "+obj.Label+" BaseMaterial property to Material\n")
if not "MoveBase" in pl:
obj.addProperty("App::PropertyBool","MoveBase","Component",QT_TRANSLATE_NOOP("App::Property","Specifies if moving this object moves its base instead"))
obj.MoveBase = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetBool("MoveBase",False)
if not "MoveWithHost" in pl:
obj.addProperty("App::PropertyBool","MoveWithHost","Component",QT_TRANSLATE_NOOP("App::Property","Specifies if this object must move together when its host is moved"))
obj.MoveWithHost = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetBool("MoveWithHost",False)
if not "VerticalArea" in pl:
obj.addProperty("App::PropertyArea","VerticalArea","Component",QT_TRANSLATE_NOOP("App::Property","The area of all vertical faces of this object"))
obj.setEditorMode("VerticalArea",1)
if not "HorizontalArea" in pl:
obj.addProperty("App::PropertyArea","HorizontalArea","Component",QT_TRANSLATE_NOOP("App::Property","The area of the projection of this object onto the XY plane"))
obj.setEditorMode("HorizontalArea",1)
if not "PerimeterLength" in pl:
obj.addProperty("App::PropertyLength","PerimeterLength","Component",QT_TRANSLATE_NOOP("App::Property","The perimeter length of the horizontal area"))
obj.setEditorMode("PerimeterLength",1)
if not "HiRes" in pl:
obj.addProperty("App::PropertyLink","HiRes","Component",QT_TRANSLATE_NOOP("App::Property","An optional higher-resolution mesh or shape for this object"))
if not "Axis" in pl:
obj.addProperty("App::PropertyLink","Axis","Component",QT_TRANSLATE_NOOP("App::Property","An optional axis or axis system on which this object should be duplicated"))
self.Subvolume = None
#self.MoveWithHost = False
self.Type = "Component"
def onDocumentRestored(self, obj):
"""Method run when the document is restored. Re-add the Arch component properties.
Parameters
----------
obj: <App::FeaturePython>
The component object.
"""
Component.setProperties(self, obj)
def execute(self,obj):
"""Method run when the object is recomputed.
If the object is a clone, just copy the shape it's cloned from.
Process subshapes of the object to add additions, and subtract
subtractions from the object's shape.
Parameters
----------
obj: <App::FeaturePython>
The component object.
"""
if self.clone(obj):
return
if obj.Base:
shape = self.spread(obj,obj.Base.Shape)
if obj.Additions or obj.Subtractions:
shape = self.processSubShapes(obj,shape)
obj.Shape = shape
def __getstate__(self):
# for compatibility with 0.17
if hasattr(self,"Type"):
return self.Type
return "Component"
def __setstate__(self,state):
return None
def onBeforeChange(self,obj,prop):
"""Method called before the object has a property changed.
Specifically, this method is called before the value changes.
If "Placement" has changed, record the old placement, so that
.onChanged() can compare between the old and new placement, and move
its children accordingly.
Parameters
----------
obj: <App::FeaturePython>
The component object.
prop: string
The name of the property that has changed.
"""
if prop == "Placement":
self.oldPlacement = FreeCAD.Placement(obj.Placement)
def onChanged(self, obj, prop):
"""Method called when the object has a property changed.
If "Placement" has changed, move any children components that have been
set to move with their host, such that they stay in the same location
to this component.
Also call ArchIFC.IfcProduct.onChanged().
Parameters
----------
obj: <App::FeaturePython>
The component object.
prop: string
The name of the property that has changed.
"""
ArchIFC.IfcProduct.onChanged(self, obj, prop)
if prop == "Placement":
if hasattr(self,"oldPlacement"):
if self.oldPlacement:
import DraftVecUtils
deltap = obj.Placement.Base.sub(self.oldPlacement.Base)
if deltap.Length == 0:
deltap = None
v = FreeCAD.Vector(0,0,1)
deltar = FreeCAD.Rotation(self.oldPlacement.Rotation.multVec(v),obj.Placement.Rotation.multVec(v))
#print "Rotation",deltar.Axis,deltar.Angle
if deltar.Angle < 0.0001:
deltar = None
for child in self.getMovableChildren(obj):
#print "moving ",child.Label
if deltar:
#child.Placement.Rotation = child.Placement.Rotation.multiply(deltar) - not enough, child must also move
# use shape methods to obtain a correct placement
import Part,math
shape = Part.Shape()
shape.Placement = child.Placement
#print("angle before rotation:",shape.Placement.Rotation.Angle)
#print("rotation angle:",math.degrees(deltar.Angle))
shape.rotate(DraftVecUtils.tup(self.oldPlacement.Base), DraftVecUtils.tup(deltar.Axis), math.degrees(deltar.Angle))
#print("angle after rotation:",shape.Placement.Rotation.Angle)
child.Placement = shape.Placement
if deltap:
child.Placement.move(deltap)
def getMovableChildren(self,obj):
"""Find the component's children set to move with their host.
In this case, children refer to Additions, Subtractions, and objects
linked to this object that refer to it as a host in the "Host" or
"Hosts" properties. Objects are set to move with their host via the
MoveWithHost property.
Parameters
----------
obj: <App::FeaturePython>
The component object.
Returns
-------
list of <App::FeaturePython>
List of child objects set to move with their host.
"""
ilist = obj.Additions + obj.Subtractions
for o in obj.InList:
if hasattr(o,"Hosts"):
if obj in o.Hosts:
ilist.append(o)
elif hasattr(o,"Host"):
if obj == o.Host:
ilist.append(o)
ilist2 = []
for o in ilist:
if hasattr(o,"MoveWithHost"):
if o.MoveWithHost:
ilist2.append(o)
else:
ilist2.append(o)
return ilist2
def getParentHeight(self,obj):
"""Get a height value from hosts.
Recursively crawl hosts until a Floor or BuildingPart is found, then
return the value of its Height property.
Parameters
---------
obj: <App::FeaturePython>
The component object.
Returns
-------
<App::PropertyLength>
The Height value of the found Floor or BuildingPart.
"""
for parent in obj.InList:
if Draft.getType(parent) in ["Floor","BuildingPart"]:
if obj in parent.Group:
if parent.HeightPropagate:
if parent.Height.Value:
return parent.Height.Value
# not found? get one level higher
for parent in obj.InList:
if hasattr(parent,"Group"):
if obj in parent.Group:
return self.getParentHeight(parent)
return 0
def clone(self,obj):
"""If the object is a clone, copy the shape.
If the object is a clone according to the "CloneOf" property, copy the
object's shape and several properties relating to shape, such as
"Length" and "Thickness".
Only perform the copy if this object and the object it's a clone of are
of the same type, or if the object has the type "Component" or
"BuildingPart".
Parameters
----------
obj: <App::FeaturePython>
The component object.
Returns
-------
bool
True if the copy occurs, False if otherwise.
"""
if hasattr(obj,"CloneOf"):
if obj.CloneOf:
if (Draft.getType(obj.CloneOf) == Draft.getType(obj)) or (Draft.getType(obj) in ["Component","BuildingPart"]):
pl = obj.Placement
obj.Shape = obj.CloneOf.Shape.copy()
obj.Placement = pl
for prop in ["Length","Width","Height","Thickness","Area","PerimeterLength","HorizontalArea","VerticalArea"]:
if hasattr(obj,prop) and hasattr(obj.CloneOf,prop):
setattr(obj,prop,getattr(obj.CloneOf,prop))
return True
return False
def getSiblings(self,obj):
"""Find objects that have the same Base object, and type.
Look to base object, and find other objects that are based off this
base object. If these objects are the same type, return them.
Parameters
----------
obj: <App::FeaturePython>
The component object.
Returns
-------
list of <App::FeaturePython>
List of objects that have the same Base and type as this component.
"""
if not hasattr(obj,"Base"):
return []
if not obj.Base:
return []
siblings = []
for o in obj.Base.InList:
if hasattr(o,"Base"):
if o.Base:
if o.Base.Name == obj.Base.Name:
if o.Name != obj.Name:
if Draft.getType(o) == Draft.getType(obj):
siblings.append(o)
return siblings
def getExtrusionData(self,obj):
"""Get the object's extrusion data.
Recursively scrape the Bases of the object, until a Base that is
derived from a <Part::Extrusion> is found. From there, copy the
extrusion to the (0,0,0) origin.
With this copy, get the <Part.Face> the shape was originally
extruded from, the <Base.Vector> of the extrusion, and the
<Base.Placement> needed to move the copy back to its original
location/orientation. Return this data as a tuple.
If an object derived from a <Part::Multifuse> is encountered, return
this data as a tuple containing lists. The lists will contain the same
data as above, from each of the objects within the multifuse.
Parameters
----------
obj: <App::FeaturePython>
The component object.
Returns
-------
tuple
Tuple containing:
1) The <Part.Face> the object was extruded from.
2) The <Base.Vector> of the extrusion.
3) The <Base.Placement> of the extrusion.
"""
if hasattr(obj,"CloneOf"):
if obj.CloneOf:
if hasattr(obj.CloneOf,"Proxy"):
if hasattr(obj.CloneOf.Proxy,"getExtrusionData"):
data = obj.CloneOf.Proxy.getExtrusionData(obj.CloneOf)
if data:
return data
if obj.Base:
# the base is another arch object which can provide extrusion data
if hasattr(obj.Base,"Proxy") and hasattr(obj.Base.Proxy,"getExtrusionData") and (not obj.Additions) and (not obj.Subtractions):
if obj.Base.Base:
if obj.Placement.Rotation.Angle < 0.0001:
# if the final obj is rotated, this will screw all our IFC orientation. Better leave it like that then...
data = obj.Base.Proxy.getExtrusionData(obj.Base)
if data:
return data
# TODO above doesn't work if underlying shape is not at (0,0,0). But code below doesn't work well yet
# add the displacement of the final object
disp = obj.Shape.CenterOfMass.sub(obj.Base.Shape.CenterOfMass)
if isinstance(data[2],(list,tuple)):
ndata2 = []
for p in data[2]:
p.move(disp)
ndata2.append(p)
return (data[0],data[1],ndata2)
else:
ndata2 = data[2]
ndata2.move(disp)
return (data[0],data[1],ndata2)
# the base is a Part Extrusion
elif obj.Base.isDerivedFrom("Part::Extrusion"):
if obj.Base.Base:
base,placement = self.rebase(obj.Base.Base.Shape)
extrusion = FreeCAD.Vector(obj.Base.Dir)
if extrusion.Length == 0:
extrusion = FreeCAD.Vector(0,0,1)
else:
extrusion = placement.inverse().Rotation.multVec(extrusion)
if hasattr(obj.Base,"LengthFwd"):
if obj.Base.LengthFwd.Value:
extrusion = extrusion.multiply(obj.Base.LengthFwd.Value)
if not self.isIdentity(obj.Base.Placement):
placement = placement.multiply(obj.Base.Placement)
return (base,extrusion,placement)
elif obj.Base.isDerivedFrom("Part::MultiFuse"):
rshapes = []
revs = []
rpls = []
for sub in obj.Base.Shapes:
if sub.isDerivedFrom("Part::Extrusion"):
if sub.Base:
base,placement = self.rebase(sub.Base.Shape)
extrusion = FreeCAD.Vector(sub.Dir)
if extrusion.Length == 0:
extrusion = FreeCAD.Vector(0,0,1)
else:
extrusion = placement.inverse().Rotation.multVec(extrusion)
if hasattr(sub,"LengthFwd"):
if sub.LengthFwd.Value:
extrusion = extrusion.multiply(sub.LengthFwd.Value)
placement = obj.Placement.multiply(placement)
rshapes.append(base)
revs.append(extrusion)
rpls.append(placement)
else:
exdata = ArchCommands.getExtrusionData(sub.Shape)
if exdata:
base,placement = self.rebase(exdata[0])
extrusion = placement.inverse().Rotation.multVec(exdata[1])
placement = obj.Placement.multiply(placement)
rshapes.append(base)
revs.append(extrusion)
rpls.append(placement)
if rshapes and revs and rpls:
return (rshapes,revs,rpls)
return None
def rebase(self,shape,hint=None):
"""Copy a shape to the (0,0,0) origin.
Create a copy of a shape, such that its center of mass is in the
(0,0,0) origin.
TODO Determine the way the shape is rotated by this method.
Return the copy of the shape, and the <Base.Placement> needed to move
the copy back to its original location/orientation.
Parameters
----------
shape: <Part.Shape>
The shape to copy.
hint: <Base.Vector>, optional
If the angle between the normal vector of the shape, and the hint
vector is greater than 90 degrees, the normal will be reversed
before being rotated.
"""
import DraftGeomUtils,math
# Get the object's center.
if not isinstance(shape,list):
shape = [shape]
if hasattr(shape[0],"CenterOfMass"):
v = shape[0].CenterOfMass
else:
v = shape[0].BoundBox.Center
# Get the object's normal.
n = DraftGeomUtils.getNormal(shape[0])
# Reverse the normal if the hint vector and the normal vector have more
# than a 90 degree angle between them.
if hint and hint.getAngle(n) > 1.58:
n = n.negative()
r = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), n)
if round(abs(r.Angle),8) == round(math.pi,8):
r = FreeCAD.Rotation()
shapes = []
for s in shape:
s = s.copy()
s.translate(v.negative())
s.rotate(FreeCAD.Vector(0, 0, 0),
r.Axis,
math.degrees(-r.Angle))
shapes.append(s)
p = FreeCAD.Placement()
p.Base = v
p.Rotation = r
if len(shapes) == 1:
return (shapes[0],p)
else:
return(shapes,p)
def hideSubobjects(self,obj,prop):
"""Hides Additions and Subtractions of this Component when that list changes.
Intended to be used in conjunction with the .onChanged() method, to
access the property that has changed.
When an object loses or gains an Addition, this method hides all
Additions. When it gains or loses a Subtraction, this method hides all
Subtractions.
Does not effect objects of type Window, or clones of Windows.
Parameters
----------
obj: <App::FeaturePython>
The component object.
prop: string
The name of the property that has changed.
"""
if FreeCAD.GuiUp:
if prop in ["Additions","Subtractions"]:
if hasattr(obj,prop):
for o in getattr(obj,prop):
if (Draft.getType(o) != "Window") and (not Draft.isClone(o,"Window",True)):
if (Draft.getType(obj) == "Wall"):
if (Draft.getType(o) == "Roof"):
continue
o.ViewObject.hide()
elif prop in ["Mesh"]:
if hasattr(obj,prop):
o = getattr(obj,prop)
if o:
o.ViewObject.hide()
def processSubShapes(self,obj,base,placement=None):
"""Add Additions and Subtractions to a base shape.
If Additions exist, fuse them to the base shape. If no base is
provided, just fuse other additions to the first addition.
If Subtractions exist, cut them from the base shape. Roofs and Windows
are treated uniquely, as they define their own Shape to subtract from
parent shapes using their .getSubVolume() methods.
TODO determine what the purpose of the placement argument is.
Parameters
----------
obj: <App::FeaturePython>
The component object.
base: <Part.Shape>, optional
The base shape to add Additions and Subtractions to.
placement: <Base.Placement>, optional
Prior to adding or subtracting subshapes, the <Base.Placement> of
the subshapes are multiplied by the inverse of this parameter.
Returns
-------
<Part.Shape>
The base shape, with the additions and subtractions performed.
"""
import Draft,Part
#print("Processing subshapes of ",obj.Label, " : ",obj.Additions)
if placement:
if self.isIdentity(placement):
placement = None
else:
placement = FreeCAD.Placement(placement)
placement = placement.inverse()
# treat additions
for o in obj.Additions:
if not base:
if hasattr(o,'Shape'):
base = o.Shape
else:
if base.isNull():
if hasattr(o,'Shape'):
base = o.Shape
else:
# special case, both walls with coinciding endpoints
import ArchWall
js = ArchWall.mergeShapes(o,obj)
if js:
add = js.cut(base)
if placement:
add.Placement = add.Placement.multiply(placement)
base = base.fuse(add)
elif hasattr(o,'Shape'):
if o.Shape:
if not o.Shape.isNull():
if o.Shape.Solids:
s = o.Shape.copy()
if placement:
s.Placement = s.Placement.multiply(placement)
if base:
if base.Solids:
try:
base = base.fuse(s)
except Part.OCCError:
print("Arch: unable to fuse object ", obj.Name, " with ", o.Name)
else:
base = s
# treat subtractions
subs = obj.Subtractions
for link in obj.InList:
if hasattr(link,"Hosts"):
for host in link.Hosts:
if host == obj:
subs.append(link)
for o in subs:
if base:
if base.isNull():
base = None
if base:
if (Draft.getType(o) == "Window") or (Draft.isClone(o,"Window",True)):
# windows can be additions or subtractions, treated the same way
f = o.Proxy.getSubVolume(o)
if f:
if base.Solids and f.Solids:
if placement:
f.Placement = f.Placement.multiply(placement)
if len(base.Solids) > 1:
base = Part.makeCompound([sol.cut(f) for sol in base.Solids])
else:
base = base.cut(f)
elif (Draft.getType(o) == "Roof") or (Draft.isClone(o,"Roof")):
# roofs define their own special subtraction volume
f = o.Proxy.getSubVolume(o)
if f:
if base.Solids and f.Solids:
if len(base.Solids) > 1:
base = Part.makeCompound([sol.cut(f) for sol in base.Solids])
else:
base = base.cut(f)
elif hasattr(o,'Shape'):
if o.Shape:
if not o.Shape.isNull():
if o.Shape.Solids and base.Solids:
s = o.Shape.copy()
if placement:
s.Placement = s.Placement.multiply(placement)
try:
if len(base.Solids) > 1:
base = Part.makeCompound([sol.cut(s) for sol in base.Solids])
else:
base = base.cut(s)
except Part.OCCError:
print("Arch: unable to cut object ",o.Name, " from ", obj.Name)
return base
def spread(self,obj,shape,placement=None):
"""Copy the object to its Axis's points.
If the object has the "Axis" property assigned, create a copy of the
shape for each point on the object assigned as the "Axis". Translate
each of these copies equal to the displacement of the points from the
(0,0,0) origin.
If the object's "Axis" is unassigned, return the original shape
unchanged.
Parameters
----------
obj: <App::FeaturePython>
The component object.
shape: <Part.Shape>
The shape to copy.
placement:
Does nothing.
Returns
-------
<Part.Shape>
The shape, either spread to the axis points, or unchanged.
"""
points = None
if hasattr(obj,"Axis"):
if obj.Axis:
if hasattr(obj.Axis,"Proxy"):
if hasattr(obj.Axis.Proxy,"getPoints"):
points = obj.Axis.Proxy.getPoints(obj.Axis)
if not points:
if hasattr(obj.Axis,'Shape'):
points = [v.Point for v in obj.Axis.Shape.Vertexes]
if points:
shps = []
for p in points:
sh = shape.copy()
sh.translate(p)
shps.append(sh)
import Part
shape = Part.makeCompound(shps)
return shape
def isIdentity(self,placement):
"""Check if a placement is *almost* zero.
Check if a <Base.Placement>'s displacement from (0,0,0) is almost zero,
and if the angle of its rotation about its axis is almost zero.
Parameters
----------
placement: <Base.Placement>
The placement to examine.
Returns
-------
bool
Returns true if angle and displacement are almost zero, false it
otherwise.
"""
if (placement.Base.Length < 0.000001) and (placement.Rotation.Angle < 0.000001):
return True
return False
def applyShape(self,obj,shape,placement,allowinvalid=False,allownosolid=False):
"""Check the given shape, then assign it to the object.
Check if the shape is valid, isn't null, and if it has volume. Remove
redundant edges from the shape. Spread the shape to the "Axis" with
method .spread().
Set the object's Shape and Placement to the values given, if
successful.
Finally, run .computeAreas() method, to calculate the horizontal and
vertical area of the shape.
Parameters
----------
obj: <App::FeaturePython>
The component object.
shape: <Part.Shape>
The shape to check and apply to the object.
placement: <Base.Placement>
The placement to apply to the object.
allowinvalid: bool, optional
Whether to allow invalid shapes, or to throw an error.
allownosolid: bool, optional
Whether to allow non-solid shapes, or to throw an error.
"""
if shape:
if not shape.isNull():
if shape.isValid():
if shape.Solids:
if shape.Volume < 0:
shape.reverse()
if shape.Volume < 0:
FreeCAD.Console.PrintError(translate("Arch","Error computing the shape of this object")+"\n")
return
import Part
try:
r = shape.removeSplitter()
except Part.OCCError:
pass
else:
shape = r
p = self.spread(obj,shape,placement).Placement.copy() # for some reason this gets zeroed in next line
obj.Shape = self.spread(obj,shape,placement)
if not self.isIdentity(placement):
obj.Placement = placement
else:
obj.Placement = p
else:
if allownosolid:
obj.Shape = self.spread(obj,shape,placement)
if not self.isIdentity(placement):
obj.Placement = placement
else:
FreeCAD.Console.PrintWarning(obj.Label + " " + translate("Arch","has no solid")+"\n")
else:
if allowinvalid:
obj.Shape = self.spread(obj,shape,placement)
if not self.isIdentity(placement):
obj.Placement = placement
else:
FreeCAD.Console.PrintWarning(obj.Label + " " + translate("Arch","has an invalid shape")+"\n")
else:
FreeCAD.Console.PrintWarning(obj.Label + " " + translate("Arch","has a null shape")+"\n")
self.computeAreas(obj)
def computeAreas(self,obj):
"""Compute the area properties of the object's shape.
Compute the vertical area, horizontal area, and perimeter length of
the object's shape.
The vertical area is the surface area of the faces perpendicular to the
ground.
The horizontal area is the area of the shape, when projected onto a
hyperplane across the XY axes, IE: the area when viewed from a bird's
eye view.
The perimeter length is the length of the outside edges of this bird's
eye view.
Assign these values to the object's "VerticalArea", "HorizontalArea",
and "PerimeterLength" properties.
Parameters
----------
obj: <App::FeaturePython>
The component object.
"""
if (not obj.Shape) or obj.Shape.isNull() or (not obj.Shape.isValid()) or (not obj.Shape.Faces):
obj.VerticalArea = 0
obj.HorizontalArea = 0
obj.PerimeterLength = 0
return
import Drawing,Part
fmax = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetInt("MaxComputeAreas",20)
if len(obj.Shape.Faces) > fmax:
obj.VerticalArea = 0
obj.HorizontalArea = 0
obj.PerimeterLength = 0
return
a = 0
fset = []
for i,f in enumerate(obj.Shape.Faces):
try:
ang = f.normalAt(0,0).getAngle(FreeCAD.Vector(0,0,1))
except Part.OCCError:
print("Debug: Error computing areas for ",obj.Label,": normalAt() Face ",i)
obj.VerticalArea = 0
obj.HorizontalArea = 0
obj.PerimeterLength = 0
return
else:
if (ang > 1.57) and (ang < 1.571):
a += f.Area
if ang < 1.5707:
fset.append(f)
if a and hasattr(obj,"VerticalArea"):
if obj.VerticalArea.Value != a:
obj.VerticalArea = a
if fset and hasattr(obj,"HorizontalArea"):